From 58e080470009470c8bcc8f053abe56d5b8296206 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:27:01 +0000 Subject: [PATCH 1/9] ref(cli): Add mapBounded and lint against await in loops Add `mapBounded(items, fn, concurrency)` in `src/lib/fan-out.ts`, a thin wrapper over `pLimit(concurrency).map` that keeps input order, and turn on Oxlint's `no-await-in-loop` for `packages/cli/src`. The 82 files that already await in a loop are listed in an override that turns the rule off for them, so new code is checked while existing loops get fixed file by file. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .oxlintrc.json | 92 ++++++++++++++++++++++++++- packages/cli/AGENTS.md | 1 + packages/cli/src/lib/fan-out.ts | 23 +++++++ packages/cli/test/lib/fan-out.test.ts | 74 +++++++++++++++++++++ 4 files changed, 189 insertions(+), 1 deletion(-) create mode 100644 packages/cli/src/lib/fan-out.ts create mode 100644 packages/cli/test/lib/fan-out.test.ts diff --git a/.oxlintrc.json b/.oxlintrc.json index 152a664fbd..7a416d0fc7 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -252,7 +252,8 @@ "files": ["packages/cli/src/**/*.ts"], "rules": { "typescript/no-explicit-any": "error", - "typescript/no-non-null-assertion": "error" + "typescript/no-non-null-assertion": "error", + "no-await-in-loop": "error" } }, { @@ -508,6 +509,95 @@ "no-restricted-imports": "off", "no-restricted-globals": "off" } + }, + { + "files": [ + "packages/cli/src/commands/alert/issues/rule-resolve.ts", + "packages/cli/src/commands/alert/metrics/rule-resolve.ts", + "packages/cli/src/commands/alert/metrics/view.ts", + "packages/cli/src/commands/auth/default.ts", + "packages/cli/src/commands/auth/logout.ts", + "packages/cli/src/commands/build/upload.ts", + "packages/cli/src/commands/cli/setup.ts", + "packages/cli/src/commands/cli/uninstall.ts", + "packages/cli/src/commands/cli/upgrade.ts", + "packages/cli/src/commands/dashboard/list.ts", + "packages/cli/src/commands/dashboard/resolve.ts", + "packages/cli/src/commands/dashboard/view.ts", + "packages/cli/src/commands/event/send.ts", + "packages/cli/src/commands/issue/view.ts", + "packages/cli/src/commands/local/daemon.ts", + "packages/cli/src/commands/local/receiver-ingest.ts", + "packages/cli/src/commands/local/run.ts", + "packages/cli/src/commands/local/server.ts", + "packages/cli/src/commands/log/tail.ts", + "packages/cli/src/commands/log/view.ts", + "packages/cli/src/commands/proguard/upload.ts", + "packages/cli/src/commands/project/create.ts", + "packages/cli/src/commands/project/list.ts", + "packages/cli/src/commands/react-native/gradle.ts", + "packages/cli/src/commands/react-native/xcode.ts", + "packages/cli/src/commands/sourcemap/upload.ts", + "packages/cli/src/lib/agent-skills.ts", + "packages/cli/src/lib/api/attribute-pagination.ts", + "packages/cli/src/lib/api/chunk-upload.ts", + "packages/cli/src/lib/api/code-mappings.ts", + "packages/cli/src/lib/api/conversations.ts", + "packages/cli/src/lib/api/dart-symbols.ts", + "packages/cli/src/lib/api/dashboards.ts", + "packages/cli/src/lib/api/debug-files.ts", + "packages/cli/src/lib/api/explore.ts", + "packages/cli/src/lib/api/infrastructure.ts", + "packages/cli/src/lib/api/issue-app-links.ts", + "packages/cli/src/lib/api/preprod-artifacts.ts", + "packages/cli/src/lib/api/proguard.ts", + "packages/cli/src/lib/api/releases.ts", + "packages/cli/src/lib/api/replays.ts", + "packages/cli/src/lib/bash-hook/traceback.ts", + "packages/cli/src/lib/build/asset-catalog-extract.ts", + "packages/cli/src/lib/build/dsyms.ts", + "packages/cli/src/lib/build/index.ts", + "packages/cli/src/lib/build/zip-writer.ts", + "packages/cli/src/lib/command.ts", + "packages/cli/src/lib/complete.ts", + "packages/cli/src/lib/db/dsn-cache.ts", + "packages/cli/src/lib/detect-agent.ts", + "packages/cli/src/lib/dev-script.ts", + "packages/cli/src/lib/dif/find.ts", + "packages/cli/src/lib/dif/scan.ts", + "packages/cli/src/lib/docs-context.ts", + "packages/cli/src/lib/dsn/env-file.ts", + "packages/cli/src/lib/dsn/project-root.ts", + "packages/cli/src/lib/dsn/resolver.ts", + "packages/cli/src/lib/dsn/scanner.ts", + "packages/cli/src/lib/fs-utils.ts", + "packages/cli/src/lib/ghcr.ts", + "packages/cli/src/lib/jvm-bundle.ts", + "packages/cli/src/lib/oauth.ts", + "packages/cli/src/lib/polling.ts", + "packages/cli/src/lib/scan/concurrent.ts", + "packages/cli/src/lib/scan/grep.ts", + "packages/cli/src/lib/scan/walker.ts", + "packages/cli/src/lib/sentryclirc-import.ts", + "packages/cli/src/lib/sentryclirc.ts", + "packages/cli/src/lib/snapshots/archive.ts", + "packages/cli/src/lib/sourcemap/inject.ts", + "packages/cli/src/lib/sourcemap/zip.ts", + "packages/cli/src/lib/target-scope.ts", + "packages/cli/src/lib/upgrade.ts", + "packages/cli/src/lib/walk-up.ts", + "packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts", + "packages/cli/src/lib/wizard/nuxt/sdk-setup.ts", + "packages/cli/src/lib/wizard/react-native/javascript.ts", + "packages/cli/src/lib/wizard/remix/codemods/express-server.ts", + "packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts", + "packages/cli/src/lib/wizard/utils/clack/index.ts", + "packages/cli/src/lib/wizard/utils/clack/mcp-config.ts", + "packages/cli/src/lib/wrangler.ts" + ], + "rules": { + "no-await-in-loop": "off" + } } ] } diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.md index 9373450b51..132c957772 100644 --- a/packages/cli/AGENTS.md +++ b/packages/cli/AGENTS.md @@ -1078,6 +1078,7 @@ Don't copy a pattern from a neighboring file without this check. The wizards wer | Absolute date/time display | `src/lib/formatters/time-utils.ts` (`formatLocalDateTime` and `formatLocalTime` for epoch ms or ISO strings, `formatUtcTimestamp`, `formatAxisTimestamp` for chart axes). `sentry-cli/no-inline-date-format` rejects `new Date(x).toLocale*String()` elsewhere in `src/`. | | Table/markdown output | `src/lib/formatters/` directory | | Pagination | `src/lib/db/pagination.ts`, `src/lib/list-command.ts` | +| Independent async work over a list (instead of `await` in a loop) | `src/lib/fan-out.ts` (`mapBounded(items, fn, concurrency)`): pass `ORG_FANOUT_CONCURRENCY` for API calls, `CONCURRENCY_LIMIT` (`src/lib/scan/constants.ts`) for local files. Oxlint's `no-await-in-loop` is on in `src/`, except for the files listed in its `"off"` override in `/.oxlintrc.json`; a file comes off that list once its loops are fixed. | | Error classes | `src/lib/errors.ts` (never create ad-hoc error types) | | Search query building | `src/lib/search-query.ts` (wraps `@sentry/toolkit-core/search-query`), `src/lib/arg-parsing.ts` | diff --git a/packages/cli/src/lib/fan-out.ts b/packages/cli/src/lib/fan-out.ts new file mode 100644 index 0000000000..acac027090 --- /dev/null +++ b/packages/cli/src/lib/fan-out.ts @@ -0,0 +1,23 @@ +/** + * Bounded fan-out over a list: run independent async work with a cap on how + * many calls are in flight, and keep the results in input order. + */ + +import pLimit from "p-limit"; + +/** + * Map each item through `fn`, with at most `concurrency` calls in flight. + * Results keep the order of `items`, and the first rejection rejects the + * whole map, as with `Promise.all`. + * + * Use it for independent work over a list whose length the code does not + * fix, instead of an `await` in a loop or an unbounded `Promise.all`. Pass + * the cap the work needs, such as `ORG_FANOUT_CONCURRENCY` for API calls. + */ +export async function mapBounded( + items: Iterable, + fn: (item: T, index: number) => PromiseLike | R, + concurrency: number, +): Promise { + return await pLimit(concurrency).map(items, fn); +} diff --git a/packages/cli/test/lib/fan-out.test.ts b/packages/cli/test/lib/fan-out.test.ts new file mode 100644 index 0000000000..681abe6fda --- /dev/null +++ b/packages/cli/test/lib/fan-out.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, test } from "vitest"; +import { mapBounded } from "../../src/lib/fan-out.js"; + +function deferred(): { promise: Promise; resolve: () => void } { + let resolve = () => {}; + const promise = new Promise((r) => { + resolve = r; + }); + return { promise, resolve }; +} + +describe("mapBounded", () => { + test("keeps input order when calls finish out of order", async () => { + const gates = [deferred(), deferred(), deferred()]; + const result = mapBounded( + [0, 1, 2], + async (item) => { + await gates[item]?.promise; + return item * 10; + }, + 3, + ); + gates[2]?.resolve(); + gates[0]?.resolve(); + gates[1]?.resolve(); + expect(await result).toEqual([0, 10, 20]); + }); + + test("runs at most `concurrency` calls at once", async () => { + let inFlight = 0; + let peak = 0; + const result = await mapBounded( + Array.from({ length: 10 }, (_, i) => i), + async (item) => { + inFlight += 1; + peak = Math.max(peak, inFlight); + await new Promise((r) => setTimeout(r, 1)); + inFlight -= 1; + return item; + }, + 3, + ); + expect(result).toHaveLength(10); + expect(peak).toBe(3); + }); + + test("passes the index and accepts any iterable and sync results", async () => { + const result = await mapBounded( + new Set(["a", "b"]), + (item, index) => `${item}${index}`, + 2, + ); + expect(result).toEqual(["a0", "b1"]); + }); + + test("rejects with the first error", async () => { + await expect( + mapBounded( + [1, 2], + async (item) => { + if (item === 2) { + throw new Error("boom"); + } + return await Promise.resolve(item); + }, + 2, + ), + ).rejects.toThrow("boom"); + }); + + test("resolves an empty list to an empty array", async () => { + expect(await mapBounded([], () => 1, 2)).toEqual([]); + }); +}); From cb82197d5e7256bb6b2859f7588e7b26356c77e5 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:38:50 +0000 Subject: [PATCH 2/9] ref: Turn on no-await-in-loop for the whole repo and fix its sites Move `no-await-in-loop` from the `packages/cli/src` override to the root rules and drop the per-file off list. Test files keep the rule off, by glob: their loops are table-driven assertions that run in order. Independent work now fans out with `mapBounded` or `Promise.all`: CLI lookups across orgs and projects, dashboard widget queries, assemble batches, local file reads and hashes, alert rule detector lookups in mcp-core, and file reads and writes in build and check scripts. Loops that must stay sequential (cursor pages, polling, retries, ordered writes, first match wins, prompts, scope checks) keep their await with a disable comment that gives the reason. --- .../verify-toolkit/scripts/mcp-call.mjs | 1 + .oxlintrc.json | 91 ++---------------- apps/docs-mcp/src/agent/features-agent.ts | 1 + apps/docs-mcp/src/agent/model-fallback.ts | 2 + apps/local/scripts/replay.ts | 5 + packages/cli/AGENTS.md | 2 +- packages/cli/script/bench-sweep.ts | 2 + packages/cli/script/bench.ts | 3 + packages/cli/script/build.ts | 1 + packages/cli/script/check-doc-examples.ts | 16 +++- packages/cli/script/check-env-coverage.ts | 30 ++++-- packages/cli/script/check-error-patterns.ts | 11 ++- packages/cli/script/check-fragments.ts | 57 ++++++++---- packages/cli/script/check-patches.ts | 2 + packages/cli/script/check-stale-references.ts | 20 ++-- packages/cli/script/eval-skill.ts | 3 + packages/cli/script/generate-command-api.ts | 9 +- packages/cli/script/generate-command-docs.ts | 25 ++--- packages/cli/script/generate-docs-sections.ts | 2 + .../cli/script/generate-output-schemas.ts | 36 +++---- packages/cli/script/generate-skill.ts | 14 +-- packages/cli/script/generate.ts | 1 + packages/cli/script/lib/chunk-build.ts | 5 +- packages/cli/script/lib/split-bundle.ts | 41 ++++---- packages/cli/script/preview-selectors.ts | 1 + .../src/commands/alert/issues/rule-resolve.ts | 46 ++++++--- .../commands/alert/metrics/rule-resolve.ts | 43 ++++++--- .../cli/src/commands/alert/metrics/view.ts | 40 +++++--- packages/cli/src/commands/auth/default.ts | 1 + packages/cli/src/commands/auth/logout.ts | 1 + packages/cli/src/commands/build/upload.ts | 1 + packages/cli/src/commands/cli/setup.ts | 1 + packages/cli/src/commands/cli/uninstall.ts | 1 + packages/cli/src/commands/cli/upgrade.ts | 2 + packages/cli/src/commands/dashboard/list.ts | 1 + .../cli/src/commands/dashboard/resolve.ts | 1 + packages/cli/src/commands/dashboard/view.ts | 2 + packages/cli/src/commands/event/send.ts | 2 + packages/cli/src/commands/issue/view.ts | 1 + packages/cli/src/commands/local/daemon.ts | 12 +++ .../cli/src/commands/local/receiver-ingest.ts | 2 + packages/cli/src/commands/local/run.ts | 1 + packages/cli/src/commands/local/server.ts | 2 + packages/cli/src/commands/log/tail.ts | 2 + packages/cli/src/commands/log/view.ts | 1 + packages/cli/src/commands/proguard/upload.ts | 17 ++-- packages/cli/src/commands/project/create.ts | 1 + packages/cli/src/commands/project/list.ts | 20 ++-- .../cli/src/commands/react-native/gradle.ts | 1 + .../cli/src/commands/react-native/xcode.ts | 3 + packages/cli/src/commands/sourcemap/upload.ts | 27 +++--- packages/cli/src/lib/agent-skills.ts | 2 + .../cli/src/lib/api/attribute-pagination.ts | 1 + packages/cli/src/lib/api/chunk-upload.ts | 13 ++- packages/cli/src/lib/api/code-mappings.ts | 1 + packages/cli/src/lib/api/conversations.ts | 1 + packages/cli/src/lib/api/dart-symbols.ts | 2 + packages/cli/src/lib/api/dashboards.ts | 59 ++++-------- packages/cli/src/lib/api/debug-files.ts | 14 ++- packages/cli/src/lib/api/explore.ts | 1 + packages/cli/src/lib/api/infrastructure.ts | 1 + packages/cli/src/lib/api/issue-app-links.ts | 1 + packages/cli/src/lib/api/preprod-artifacts.ts | 5 + packages/cli/src/lib/api/proguard.ts | 5 +- packages/cli/src/lib/api/releases.ts | 1 + packages/cli/src/lib/api/replays.ts | 1 + packages/cli/src/lib/bash-hook/traceback.ts | 38 +++++--- .../src/lib/build/asset-catalog-extract.ts | 56 ++++++----- packages/cli/src/lib/build/dsyms.ts | 3 + packages/cli/src/lib/build/index.ts | 16 +++- packages/cli/src/lib/build/zip-writer.ts | 5 + packages/cli/src/lib/command.ts | 1 + packages/cli/src/lib/complete.ts | 1 + packages/cli/src/lib/db/dsn-cache.ts | 30 +++--- packages/cli/src/lib/detect-agent.ts | 1 + packages/cli/src/lib/dev-script.ts | 1 + packages/cli/src/lib/dif/find.ts | 1 + packages/cli/src/lib/dif/scan.ts | 4 + packages/cli/src/lib/docs-context.ts | 51 ++++++---- packages/cli/src/lib/dsn/env-file.ts | 74 +++++++++------ packages/cli/src/lib/dsn/project-root.ts | 2 + packages/cli/src/lib/dsn/resolver.ts | 34 +++---- packages/cli/src/lib/dsn/scanner.ts | 2 + packages/cli/src/lib/fs-utils.ts | 1 + packages/cli/src/lib/ghcr.ts | 2 + packages/cli/src/lib/jvm-bundle.ts | 41 ++++---- packages/cli/src/lib/oauth.ts | 2 + packages/cli/src/lib/polling.ts | 2 + packages/cli/src/lib/scan/concurrent.ts | 1 + packages/cli/src/lib/scan/grep.ts | 1 + packages/cli/src/lib/scan/walker.ts | 6 ++ packages/cli/src/lib/sentryclirc-import.ts | 28 +++--- packages/cli/src/lib/sentryclirc.ts | 1 + packages/cli/src/lib/snapshots/archive.ts | 1 + packages/cli/src/lib/sourcemap/inject.ts | 93 +++++++++++-------- packages/cli/src/lib/sourcemap/zip.ts | 2 + packages/cli/src/lib/target-scope.ts | 4 + packages/cli/src/lib/upgrade.ts | 4 + packages/cli/src/lib/walk-up.ts | 1 + .../src/lib/wizard/nextjs/nextjs-wizard.ts | 1 + packages/cli/src/lib/wizard/nuxt/sdk-setup.ts | 1 + .../src/lib/wizard/react-native/javascript.ts | 1 + .../wizard/remix/codemods/express-server.ts | 2 + .../lib/wizard/sourcemaps/tools/sentry-cli.ts | 2 + .../cli/src/lib/wizard/utils/clack/index.ts | 1 + .../src/lib/wizard/utils/clack/mcp-config.ts | 2 + packages/cli/src/lib/wrangler.ts | 1 + packages/cli/test/lib/dsn/errors.test.ts | 1 + packages/cli/test/lib/dsn/resolver.test.ts | 1 + packages/http/src/policy.ts | 8 +- packages/http/src/retry.ts | 3 + .../scripts/generate-otel-namespaces.ts | 1 + .../scripts/generate-platform-setup.ts | 1 + packages/mcp-core/scripts/measure-ui-views.ts | 1 + .../scripts/validate-skills-mapping.ts | 17 ++-- packages/mcp-core/src/api-client/client.ts | 2 + packages/mcp-core/src/internal/fetch-utils.ts | 2 + .../tools/catalog/analyze-issue-with-seer.ts | 2 + .../mcp-core/src/tools/catalog/get-doc.ts | 1 + .../tools/support/alert-rule-connections.ts | 3 + .../src/tools/support/alert-rule-details.ts | 92 +++++++++--------- .../src/tools/support/issue-linking/app.ts | 1 + .../src/tools/support/search-events/seer.ts | 2 + packages/mcp-test-client/src/index.ts | 2 + packages/toolkit-core/src/mcp-limits.ts | 2 + scripts/cli-nightly-verify.mjs | 1 + scripts/cloudflare-deployment.mjs | 4 + scripts/generate-parsers.mjs | 45 ++++----- 128 files changed, 865 insertions(+), 569 deletions(-) diff --git a/.agents/skills/verify-toolkit/scripts/mcp-call.mjs b/.agents/skills/verify-toolkit/scripts/mcp-call.mjs index ff23ed21dc..56f8e6bdf8 100755 --- a/.agents/skills/verify-toolkit/scripts/mcp-call.mjs +++ b/.agents/skills/verify-toolkit/scripts/mcp-call.mjs @@ -113,6 +113,7 @@ try { ); for (const [n, [name, toolArgs]] of opts.calls.entries()) { const file = `call-${n + 1}-${name}.json`; + // oxlint-disable-next-line no-await-in-loop -- calls run in the order given, since a later call can depend on an earlier one's side effects const result = await client.callTool({ name, arguments: toolArgs }); write(file, { request: { name, arguments: toolArgs }, result }); const shape = result.structuredContent diff --git a/.oxlintrc.json b/.oxlintrc.json index 7a416d0fc7..a78ef22902 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -50,6 +50,7 @@ ], "typescript/no-unnecessary-type-constraint": "error", "prefer-const": "error", + "no-await-in-loop": "error", "no-else-return": ["error", { "allowElseIf": false }], "no-new-wrappers": "error", "no-new": "error", @@ -252,8 +253,7 @@ "files": ["packages/cli/src/**/*.ts"], "rules": { "typescript/no-explicit-any": "error", - "typescript/no-non-null-assertion": "error", - "no-await-in-loop": "error" + "typescript/no-non-null-assertion": "error" } }, { @@ -512,88 +512,11 @@ }, { "files": [ - "packages/cli/src/commands/alert/issues/rule-resolve.ts", - "packages/cli/src/commands/alert/metrics/rule-resolve.ts", - "packages/cli/src/commands/alert/metrics/view.ts", - "packages/cli/src/commands/auth/default.ts", - "packages/cli/src/commands/auth/logout.ts", - "packages/cli/src/commands/build/upload.ts", - "packages/cli/src/commands/cli/setup.ts", - "packages/cli/src/commands/cli/uninstall.ts", - "packages/cli/src/commands/cli/upgrade.ts", - "packages/cli/src/commands/dashboard/list.ts", - "packages/cli/src/commands/dashboard/resolve.ts", - "packages/cli/src/commands/dashboard/view.ts", - "packages/cli/src/commands/event/send.ts", - "packages/cli/src/commands/issue/view.ts", - "packages/cli/src/commands/local/daemon.ts", - "packages/cli/src/commands/local/receiver-ingest.ts", - "packages/cli/src/commands/local/run.ts", - "packages/cli/src/commands/local/server.ts", - "packages/cli/src/commands/log/tail.ts", - "packages/cli/src/commands/log/view.ts", - "packages/cli/src/commands/proguard/upload.ts", - "packages/cli/src/commands/project/create.ts", - "packages/cli/src/commands/project/list.ts", - "packages/cli/src/commands/react-native/gradle.ts", - "packages/cli/src/commands/react-native/xcode.ts", - "packages/cli/src/commands/sourcemap/upload.ts", - "packages/cli/src/lib/agent-skills.ts", - "packages/cli/src/lib/api/attribute-pagination.ts", - "packages/cli/src/lib/api/chunk-upload.ts", - "packages/cli/src/lib/api/code-mappings.ts", - "packages/cli/src/lib/api/conversations.ts", - "packages/cli/src/lib/api/dart-symbols.ts", - "packages/cli/src/lib/api/dashboards.ts", - "packages/cli/src/lib/api/debug-files.ts", - "packages/cli/src/lib/api/explore.ts", - "packages/cli/src/lib/api/infrastructure.ts", - "packages/cli/src/lib/api/issue-app-links.ts", - "packages/cli/src/lib/api/preprod-artifacts.ts", - "packages/cli/src/lib/api/proguard.ts", - "packages/cli/src/lib/api/releases.ts", - "packages/cli/src/lib/api/replays.ts", - "packages/cli/src/lib/bash-hook/traceback.ts", - "packages/cli/src/lib/build/asset-catalog-extract.ts", - "packages/cli/src/lib/build/dsyms.ts", - "packages/cli/src/lib/build/index.ts", - "packages/cli/src/lib/build/zip-writer.ts", - "packages/cli/src/lib/command.ts", - "packages/cli/src/lib/complete.ts", - "packages/cli/src/lib/db/dsn-cache.ts", - "packages/cli/src/lib/detect-agent.ts", - "packages/cli/src/lib/dev-script.ts", - "packages/cli/src/lib/dif/find.ts", - "packages/cli/src/lib/dif/scan.ts", - "packages/cli/src/lib/docs-context.ts", - "packages/cli/src/lib/dsn/env-file.ts", - "packages/cli/src/lib/dsn/project-root.ts", - "packages/cli/src/lib/dsn/resolver.ts", - "packages/cli/src/lib/dsn/scanner.ts", - "packages/cli/src/lib/fs-utils.ts", - "packages/cli/src/lib/ghcr.ts", - "packages/cli/src/lib/jvm-bundle.ts", - "packages/cli/src/lib/oauth.ts", - "packages/cli/src/lib/polling.ts", - "packages/cli/src/lib/scan/concurrent.ts", - "packages/cli/src/lib/scan/grep.ts", - "packages/cli/src/lib/scan/walker.ts", - "packages/cli/src/lib/sentryclirc-import.ts", - "packages/cli/src/lib/sentryclirc.ts", - "packages/cli/src/lib/snapshots/archive.ts", - "packages/cli/src/lib/sourcemap/inject.ts", - "packages/cli/src/lib/sourcemap/zip.ts", - "packages/cli/src/lib/target-scope.ts", - "packages/cli/src/lib/upgrade.ts", - "packages/cli/src/lib/walk-up.ts", - "packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts", - "packages/cli/src/lib/wizard/nuxt/sdk-setup.ts", - "packages/cli/src/lib/wizard/react-native/javascript.ts", - "packages/cli/src/lib/wizard/remix/codemods/express-server.ts", - "packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts", - "packages/cli/src/lib/wizard/utils/clack/index.ts", - "packages/cli/src/lib/wizard/utils/clack/mcp-config.ts", - "packages/cli/src/lib/wrangler.ts" + "**/*.test.ts", + "**/*.test.tsx", + "**/*.test.mjs", + "**/test-utils/**", + "packages/cli/test/**" ], "rules": { "no-await-in-loop": "off" diff --git a/apps/docs-mcp/src/agent/features-agent.ts b/apps/docs-mcp/src/agent/features-agent.ts index 45ce82cd29..24a7e904cf 100644 --- a/apps/docs-mcp/src/agent/features-agent.ts +++ b/apps/docs-mcp/src/agent/features-agent.ts @@ -237,6 +237,7 @@ export async function parseFeaturesOutput( `Structured output was truncated because the model finished with reason "${finishReason}".`, ); } + // oxlint-disable-next-line no-await-in-loop -- steps parse in order: a cut-off step throws before later steps are read, and the last valid output wins const { value } = await parsePartialJson(preprocessJsonText(text)); const parsed = featuresOutputSchema.safeParse(value); if (!parsed.success) { diff --git a/apps/docs-mcp/src/agent/model-fallback.ts b/apps/docs-mcp/src/agent/model-fallback.ts index 299e65f210..516205264e 100644 --- a/apps/docs-mcp/src/agent/model-fallback.ts +++ b/apps/docs-mcp/src/agent/model-fallback.ts @@ -187,6 +187,7 @@ function createFallbackModel( for (const [index, model] of models.entries()) { for (;;) { try { + // oxlint-disable-next-line no-await-in-loop -- tries one model at a time and falls back only after it fails return { model, result: await call(model) }; } catch (error) { lastError = error; @@ -202,6 +203,7 @@ function createFallbackModel( break; } retryCount++; + // oxlint-disable-next-line no-await-in-loop -- backs off before retrying the same model await wait(delay, signal); } } diff --git a/apps/local/scripts/replay.ts b/apps/local/scripts/replay.ts index 88d8e68959..1ffbd25adc 100644 --- a/apps/local/scripts/replay.ts +++ b/apps/local/scripts/replay.ts @@ -24,6 +24,7 @@ async function envelopeFiles(path: string): Promise { const files: string[] = []; for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) { const child = join(path, entry.name); + // oxlint-disable-next-line no-await-in-loop -- walks directories in sorted order so envelopes replay in a stable order if (entry.isDirectory()) files.push(...(await envelopeFiles(child))); else if ( entry.isFile() && @@ -69,7 +70,9 @@ export async function replayEnvelopes({ let sent = 0; for (let cycle = 0; cycle < repeat; cycle++) for (const file of files) { + // oxlint-disable-next-line no-await-in-loop -- replays envelopes one at a time, spaced by --interval if (sent && interval) await delay(interval); + // oxlint-disable-next-line no-await-in-loop -- replays envelopes one at a time, spaced by --interval const raw = await readFile(file); const body = compression === "gzip" @@ -77,6 +80,7 @@ export async function replayEnvelopes({ : compression === "br" ? brotliCompressSync(raw) : raw; + // oxlint-disable-next-line no-await-in-loop -- replays envelopes one at a time, spaced by --interval const response = await fetch(target, { method: "POST", headers: { @@ -89,6 +93,7 @@ export async function replayEnvelopes({ redirect: "error", signal: AbortSignal.timeout(10_000), }); + // oxlint-disable-next-line no-await-in-loop -- replays envelopes one at a time, spaced by --interval await response.body?.cancel(); if (!response.ok) throw new Error(`Receiver rejected ${file}: HTTP ${response.status}`); diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.md index 132c957772..f07a5f31f6 100644 --- a/packages/cli/AGENTS.md +++ b/packages/cli/AGENTS.md @@ -1078,7 +1078,7 @@ Don't copy a pattern from a neighboring file without this check. The wizards wer | Absolute date/time display | `src/lib/formatters/time-utils.ts` (`formatLocalDateTime` and `formatLocalTime` for epoch ms or ISO strings, `formatUtcTimestamp`, `formatAxisTimestamp` for chart axes). `sentry-cli/no-inline-date-format` rejects `new Date(x).toLocale*String()` elsewhere in `src/`. | | Table/markdown output | `src/lib/formatters/` directory | | Pagination | `src/lib/db/pagination.ts`, `src/lib/list-command.ts` | -| Independent async work over a list (instead of `await` in a loop) | `src/lib/fan-out.ts` (`mapBounded(items, fn, concurrency)`): pass `ORG_FANOUT_CONCURRENCY` for API calls, `CONCURRENCY_LIMIT` (`src/lib/scan/constants.ts`) for local files. Oxlint's `no-await-in-loop` is on in `src/`, except for the files listed in its `"off"` override in `/.oxlintrc.json`; a file comes off that list once its loops are fixed. | +| Independent async work over a list (instead of `await` in a loop) | `src/lib/fan-out.ts` (`mapBounded(items, fn, concurrency)`): pass `ORG_FANOUT_CONCURRENCY` for API calls, `CONCURRENCY_LIMIT` (`src/lib/scan/constants.ts`) for local files. Oxlint's `no-await-in-loop` is on for the whole repo except test files. A loop that must stay sequential (cursor pages, polling, retries, ordered writes, first match wins) gets `// oxlint-disable-next-line no-await-in-loop -- `. | | Error classes | `src/lib/errors.ts` (never create ad-hoc error types) | | Search query building | `src/lib/search-query.ts` (wraps `@sentry/toolkit-core/search-query`), `src/lib/arg-parsing.ts` | diff --git a/packages/cli/script/bench-sweep.ts b/packages/cli/script/bench-sweep.ts index 06190f1ced..5372cff827 100644 --- a/packages/cli/script/bench-sweep.ts +++ b/packages/cli/script/bench-sweep.ts @@ -245,6 +245,7 @@ async function runSweep(args: SweepArgs): Promise { if (!args.json) { logger.log(`\n${fx.label} (${fx.rootDir})`); } + // oxlint-disable-next-line no-await-in-loop -- benchmarks run one fixture at a time so runs do not skew each other's timings await withBenchDb(async () => { await sweepFixture(fx, ops, args, results); }); @@ -263,6 +264,7 @@ async function sweepFixture( for (const op of ops) { for (const concurrency of args.values) { const setup = op.setup; + // oxlint-disable-next-line no-await-in-loop -- benchmarks run one sample at a time so runs do not skew each other's timings const samples = await measure(() => op.run(fx.rootDir, concurrency), { runs: args.runs, warmup: args.warmup, diff --git a/packages/cli/script/bench.ts b/packages/cli/script/bench.ts index 2492bed6ac..c40949097d 100644 --- a/packages/cli/script/bench.ts +++ b/packages/cli/script/bench.ts @@ -303,6 +303,7 @@ async function roughFileCount(root: string): Promise { for (const entry of entries) { if (entry.isDirectory()) { if (!skip.has(entry.name)) { + // oxlint-disable-next-line no-await-in-loop -- builds the fixture file list in a stable order await walk(join(dir, entry.name)); } } else if (entry.isFile()) { @@ -541,9 +542,11 @@ async function runAll( if (!args.json) { logger.log(`${fx.label} (${fx.fileCount} files @ ${fx.rootDir})`); } + // oxlint-disable-next-line no-await-in-loop -- benchmarks run one fixture at a time so runs do not skew each other's timings await withBenchDb(async () => { for (const op of ops) { const setup = op.setup; + // oxlint-disable-next-line no-await-in-loop -- benchmarks run one operation at a time so runs do not skew each other's timings const samples = await measure( async () => { await op.run(fx.rootDir); diff --git a/packages/cli/script/build.ts b/packages/cli/script/build.ts index e487891947..b68cf2a374 100644 --- a/packages/cli/script/build.ts +++ b/packages/cli/script/build.ts @@ -422,6 +422,7 @@ async function compileAllTargets( let failures = 0; for (const target of targets) { try { + // oxlint-disable-next-line no-await-in-loop -- each target compresses a full binary; one at a time keeps memory bounded await postProcessTarget(target); successes += 1; } catch (error) { diff --git a/packages/cli/script/check-doc-examples.ts b/packages/cli/script/check-doc-examples.ts index bf5149283c..d407c0d9e8 100644 --- a/packages/cli/script/check-doc-examples.ts +++ b/packages/cli/script/check-doc-examples.ts @@ -54,6 +54,8 @@ import { } from "./sdk-run-calls.js"; import { shellCommands } from "./shell-words.js"; import { logger } from "../src/lib/logger.js"; +import { mapBounded } from "../src/lib/fan-out.js"; +import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; await writeRouteTreeStubs(); @@ -399,8 +401,11 @@ for (const { source, invocation } of commandExamples( findings.push({ file: source, example: invocation, problem }); } } -for (const file of [...files, ...SDK_EXAMPLE_FILES]) { - const content = await readFile(file, "utf-8"); +for (const { file, content } of await mapBounded( + [...files, ...SDK_EXAMPLE_FILES], + async (file) => ({ file, content: await readFile(file, "utf-8") }), + CONCURRENCY_LIMIT, +)) { const invocations = file.endsWith(".ts") ? [] : extractInvocations(content); for (const invocation of invocations) { checked += 1; @@ -418,8 +423,11 @@ for (const file of [...files, ...SDK_EXAMPLE_FILES]) { } const sourceFiles = listSource(SOURCE_DIR); -for (const file of sourceFiles) { - const content = await readFile(file, "utf-8"); +for (const { file, content } of await mapBounded( + sourceFiles, + async (file) => ({ file, content: await readFile(file, "utf-8") }), + CONCURRENCY_LIMIT, +)) { if (!content.includes("sentry`")) { continue; } diff --git a/packages/cli/script/check-env-coverage.ts b/packages/cli/script/check-env-coverage.ts index 890b9e2eb3..2e13d382ae 100644 --- a/packages/cli/script/check-env-coverage.ts +++ b/packages/cli/script/check-env-coverage.ts @@ -33,6 +33,8 @@ import { readFile } from "node:fs/promises"; import { join } from "node:path"; import { ENV_VAR_REGISTRY } from "../src/lib/env-registry.js"; import { logger } from "../src/lib/logger.js"; +import { mapBounded } from "../src/lib/fan-out.js"; +import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; /** * Well-known env vars that don't start with `SENTRY_` but are still part of the @@ -134,8 +136,11 @@ const files = globSync("src/**/*.ts", { // bracket reads indexed by a constant can be mapped back to a literal name. const constMap = new Map(); const fileContents = new Map(); -for (const file of files) { - const content = await readFile(file, "utf-8"); +for (const { file, content } of await mapBounded( + files, + async (file) => ({ file, content: await readFile(file, "utf-8") }), + CONCURRENCY_LIMIT, +)) { fileContents.set(file, content); for (const match of content.matchAll(ENV_CONST_RE)) { const [, name] = match; @@ -192,8 +197,11 @@ const INSTALLERS: readonly { file: string; read: RegExp; assign?: RegExp }[] = [ /** name -> first "file:line" where an installer reads it. */ const installerReads = new Map(); -for (const { file, read, assign } of INSTALLERS) { - const content = await readFile(file, "utf-8"); +const installerContents = await Promise.all( + INSTALLERS.map(({ file }) => readFile(file, "utf-8")), +); +for (const [index, { file, read, assign }] of INSTALLERS.entries()) { + const content = installerContents[index] ?? ""; const assigned = new Set( assign ? [...content.matchAll(assign)].map((m) => m[1]) : [], ); @@ -252,12 +260,14 @@ for (const name of INTERNAL_ENV_VARS.keys()) { // Every file type under src/, generated files included, not just the env // reads above: a retired name in a string or a comment fails too. -for (const entry of globSync("src/**/*", { withFileTypes: true })) { - if (!entry.isFile()) { - continue; - } - const file = join(entry.parentPath, entry.name); - const content = await readFile(file, "utf-8"); +const srcFiles = globSync("src/**/*", { withFileTypes: true }) + .filter((entry) => entry.isFile()) + .map((entry) => join(entry.parentPath, entry.name)); +for (const { file, content } of await mapBounded( + srcFiles, + async (file) => ({ file, content: await readFile(file, "utf-8") }), + CONCURRENCY_LIMIT, +)) { for (const [prefix, reason] of RETIRED_ENV_PREFIXES) { const index = content.indexOf(prefix); if (index !== -1) { diff --git a/packages/cli/script/check-error-patterns.ts b/packages/cli/script/check-error-patterns.ts index 9360893887..f939bc854a 100644 --- a/packages/cli/script/check-error-patterns.ts +++ b/packages/cli/script/check-error-patterns.ts @@ -26,6 +26,8 @@ import { globSync } from "node:fs"; import { readFile } from "node:fs/promises"; import { logger } from "../src/lib/logger.js"; +import { mapBounded } from "../src/lib/fan-out.js"; +import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; export type Violation = { file: string; line: number; message: string }; @@ -271,8 +273,13 @@ export function findAdHocTryPatterns( /** Scan the given files and collect violations. */ export async function scanFiles(files: string[]): Promise { const violations: Violation[] = []; - for (const filePath of files) { - const content = await readFile(filePath, "utf-8"); + const contents = await mapBounded( + files, + (filePath) => readFile(filePath, "utf-8"), + CONCURRENCY_LIMIT, + ); + for (const [index, filePath] of files.entries()) { + const content = contents[index] ?? ""; violations.push(...findContextErrorNewlines(content, filePath)); violations.push(...findAdHocTryPatterns(content, filePath)); } diff --git a/packages/cli/script/check-fragments.ts b/packages/cli/script/check-fragments.ts index e21c244702..b34283122b 100644 --- a/packages/cli/script/check-fragments.ts +++ b/packages/cli/script/check-fragments.ts @@ -27,6 +27,8 @@ import { writeRouteTreeStubs } from "./lib/route-tree-stubs.js"; import { markdownHeadings } from "./markdown.js"; import { DOCS_FRAGMENTS } from "./paths.js"; import { logger } from "../src/lib/logger.js"; +import { mapBounded } from "../src/lib/fan-out.js"; +import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; await writeRouteTreeStubs(); @@ -90,9 +92,14 @@ for (const name of actualFragments) { const EXAMPLES_HEADING_RE = /^examples?\b/i; // Check 3: Fragment content validation -for (const file of fragmentFiles) { - const content = await readFile(`${FRAGMENTS_DIR}/${file}`, "utf-8"); - +for (const { file, content } of await mapBounded( + fragmentFiles, + async (file) => ({ + file, + content: await readFile(`${FRAGMENTS_DIR}/${file}`, "utf-8"), + }), + CONCURRENCY_LIMIT, +)) { if (content.includes("---\ntitle:") || content.startsWith("---\n")) { errors.push( `Fragment contains frontmatter: ${FRAGMENTS_DIR}/${file} (fragments should only contain custom content, not YAML frontmatter)`, @@ -129,13 +136,17 @@ const TOP_LEVEL_FRAGMENTS_DIR = DOCS_FRAGMENTS; /** Top-level fragment files that must exist (for generated doc pages) */ const REQUIRED_TOP_LEVEL_FRAGMENTS = ["configuration"]; -for (const name of REQUIRED_TOP_LEVEL_FRAGMENTS) { +const requiredFragmentsExist = await Promise.all( + REQUIRED_TOP_LEVEL_FRAGMENTS.map((name) => + access(`${TOP_LEVEL_FRAGMENTS_DIR}/${name}.md`).then( + () => true, + () => false, + ), + ), +); +for (const [index, name] of REQUIRED_TOP_LEVEL_FRAGMENTS.entries()) { const path = `${TOP_LEVEL_FRAGMENTS_DIR}/${name}.md`; - const exists = await access(path).then( - () => true, - () => false, - ); - if (!exists) { + if (!requiredFragmentsExist[index]) { errors.push( `Missing top-level fragment: ${path} (required for generated ${name}.md page)`, ); @@ -253,13 +264,27 @@ function getDefaultCommandName(routeName: string): string | undefined { const multiCommandRoutes = getMultiCommandRoutes(); -for (const [routeName, route] of multiCommandRoutes) { - const fragmentPath = `${FRAGMENTS_DIR}/${routeName}.md`; - let content: string; - try { - content = await readFile(fragmentPath, "utf-8"); - } catch { - // Fragment doesn't exist — already caught by Check 1 +const multiCommandFragments = await mapBounded( + multiCommandRoutes, + async ([routeName, route]) => ({ + routeName, + route, + fragmentPath: `${FRAGMENTS_DIR}/${routeName}.md`, + // A missing fragment is already caught by Check 1. + content: await readFile(`${FRAGMENTS_DIR}/${routeName}.md`, "utf-8").catch( + () => undefined, + ), + }), + CONCURRENCY_LIMIT, +); + +for (const { + routeName, + route, + fragmentPath, + content, +} of multiCommandFragments) { + if (content === undefined) { continue; } diff --git a/packages/cli/script/check-patches.ts b/packages/cli/script/check-patches.ts index 36d678d70c..a931298d49 100644 --- a/packages/cli/script/check-patches.ts +++ b/packages/cli/script/check-patches.ts @@ -207,6 +207,7 @@ for (const [key, patchPath] of Object.entries(patches)) { throw new Error("unresolved"); } const installed: { version: string } = JSON.parse( + // oxlint-disable-next-line no-await-in-loop -- reports each patch's result in patch order await readFile(pkgJsonPath, "utf-8"), ); if (installed.version !== patchVersion) { @@ -343,6 +344,7 @@ for (const assertion of CONTENT_ASSERTIONS) { if (!assertionPath) { throw new Error("unresolved"); } + // oxlint-disable-next-line no-await-in-loop -- reports each assertion's result in assertion order const contents = await readFile(assertionPath, "utf-8"); if (assertion.staleMarker && contents.includes(assertion.staleMarker)) { errors.push( diff --git a/packages/cli/script/check-stale-references.ts b/packages/cli/script/check-stale-references.ts index ae83400232..f9e05cf111 100644 --- a/packages/cli/script/check-stale-references.ts +++ b/packages/cli/script/check-stale-references.ts @@ -24,6 +24,8 @@ import { readFile } from "node:fs/promises"; import { blankCodeBlocks } from "./markdown.js"; import { DOCS_CONTENT } from "./paths.js"; import { logger } from "../src/lib/logger.js"; +import { mapBounded } from "../src/lib/fan-out.js"; +import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; const pkg = JSON.parse(await readFile("package.json", "utf-8")); const currentPM: string = (pkg.packageManager ?? "").split("@")[0]; @@ -112,12 +114,18 @@ type Finding = { const findings: Finding[] = []; -for (const filePath of FILES_TO_SCAN) { - let content: string; - try { - content = await readFile(filePath, "utf-8"); - } catch { - // File doesn't exist — skip silently (e.g., optional doc files) +const scanned = await mapBounded( + FILES_TO_SCAN, + async (filePath) => ({ + filePath, + // A file that doesn't exist is skipped silently (e.g., optional doc files). + content: await readFile(filePath, "utf-8").catch(() => undefined), + }), + CONCURRENCY_LIMIT, +); + +for (const { filePath, content } of scanned) { + if (content === undefined) { continue; } diff --git a/packages/cli/script/eval-skill.ts b/packages/cli/script/eval-skill.ts index 0e9b8ef786..a44a47ba26 100644 --- a/packages/cli/script/eval-skill.ts +++ b/packages/cli/script/eval-skill.ts @@ -67,12 +67,14 @@ async function evalModel( for (const testCase of testCases) { logger.start(`${testCase.id}...`); + // oxlint-disable-next-line no-await-in-loop -- eval cases run one at a time to stay inside the model provider's rate limits const plan = await generatePlan( client, model, skillContent, testCase.prompt, ); + // oxlint-disable-next-line no-await-in-loop -- the judge needs the plan from the step before const result = await judgePlan(client, testCase, plan); results.push(result); @@ -130,6 +132,7 @@ async function main(): Promise { const models: ModelResult[] = []; for (const model of client.agentModels) { + // oxlint-disable-next-line no-await-in-loop -- models run one at a time to stay inside the model provider's rate limits const result = await evalModel(client, model, skillContent, testCases); models.push(result); } diff --git a/packages/cli/script/generate-command-api.ts b/packages/cli/script/generate-command-api.ts index 05fe23fea0..e6d96f0cc8 100644 --- a/packages/cli/script/generate-command-api.ts +++ b/packages/cli/script/generate-command-api.ts @@ -28,8 +28,13 @@ export async function emit(): Promise { { commands: Set; reason: string } >(); - for (const { file, name } of analysis.commands) { - const module = await import(pathToFileURL(resolve(file)).href); + const modules = await Promise.all( + analysis.commands.map( + ({ file }) => import(pathToFileURL(resolve(file)).href), + ), + ); + for (const [index, { file, name }] of analysis.commands.entries()) { + const module = modules[index]; const target = module[name] as RouteTarget | undefined; const path = target && paths.get(target); if (!target || !path || !isCommand(target)) continue; diff --git a/packages/cli/script/generate-command-docs.ts b/packages/cli/script/generate-command-docs.ts index a9c92d9bb8..0d9df7df4a 100644 --- a/packages/cli/script/generate-command-docs.ts +++ b/packages/cli/script/generate-command-docs.ts @@ -389,17 +389,20 @@ export async function emit(): Promise { } // Generate command doc pages - for (const route of routeInfos) { - const filePath = `${DOCS_DIR}/${route.name}.md`; - const pageContent = generatePage(route); - const customContent = await readCustomContent(route.name); - const fullContent = customContent - ? pageContent + customContent - : `${pageContent}\n`; - - await writeFile(filePath, fullContent); - generatedFiles.push(filePath); - } + const pagePaths = await Promise.all( + routeInfos.map(async (route) => { + const filePath = `${DOCS_DIR}/${route.name}.md`; + const pageContent = generatePage(route); + const customContent = await readCustomContent(route.name); + const fullContent = customContent + ? pageContent + customContent + : `${pageContent}\n`; + + await writeFile(filePath, fullContent); + return filePath; + }), + ); + generatedFiles.push(...pagePaths); // Update commands/index.md const indexCustomContent = await readCustomContent("index"); diff --git a/packages/cli/script/generate-docs-sections.ts b/packages/cli/script/generate-docs-sections.ts index 15d9446379..1e4b488ac9 100644 --- a/packages/cli/script/generate-docs-sections.ts +++ b/packages/cli/script/generate-docs-sections.ts @@ -1144,6 +1144,7 @@ export async function emit({ check }: { check: boolean }): Promise { let staleCount = 0; for (const section of sections) { + // oxlint-disable-next-line no-await-in-loop -- several sections live in one file, so each read-modify-write must finish before the next const original = await readFile(section.filePath, "utf-8"); const generated = section.generate(); const updated = replaceMarkerSection( @@ -1158,6 +1159,7 @@ export async function emit({ check }: { check: boolean }): Promise { logger.error(`STALE: ${section.filePath} [${section.sectionName}]`); staleCount += 1; } else { + // oxlint-disable-next-line no-await-in-loop -- several sections live in one file, so each read-modify-write must finish before the next await writeFile(section.filePath, updated); logger.info(`Updated: ${section.filePath} [${section.sectionName}]`); } diff --git a/packages/cli/script/generate-output-schemas.ts b/packages/cli/script/generate-output-schemas.ts index a5d9ed1d5a..8b5f2b5e30 100644 --- a/packages/cli/script/generate-output-schemas.ts +++ b/packages/cli/script/generate-output-schemas.ts @@ -84,22 +84,26 @@ export async function emit(): Promise { await rm(OUTPUT_DIR, { recursive: true, force: true }); await mkdir(OUTPUT_DIR, { recursive: true }); - let count = 0; - for (const file of files) { - const name = basename(file, ".ts"); - const exports: Record = await import( - pathToFileURL(resolve(SOURCE_DIR, file)).href - ); - const schemas = Object.entries(exports).filter( - (entry): entry is [string, GenericSchema] => - entry[0].endsWith("Schema") && isSchema(entry[1]), - ); - if (schemas.length === 0) { - continue; - } - count += schemas.length; - await writeFile(`${OUTPUT_DIR}/${name}.ts`, renderModule(name, schemas)); - } + const counts = await Promise.all( + files.map(async (file) => { + const name = basename(file, ".ts"); + const exports: Record = await import( + pathToFileURL(resolve(SOURCE_DIR, file)).href + ); + const schemas = Object.entries(exports).filter( + (entry): entry is [string, GenericSchema] => + entry[0].endsWith("Schema") && isSchema(entry[1]), + ); + if (schemas.length > 0) { + await writeFile( + `${OUTPUT_DIR}/${name}.ts`, + renderModule(name, schemas), + ); + } + return schemas.length; + }), + ); + const count = counts.reduce((sum, n) => sum + n, 0); logger.success(`Generated ${OUTPUT_DIR}/ (${count} output schemas)`); } diff --git a/packages/cli/script/generate-skill.ts b/packages/cli/script/generate-skill.ts index f0e50445df..d47d352e4b 100644 --- a/packages/cli/script/generate-skill.ts +++ b/packages/cli/script/generate-skill.ts @@ -687,12 +687,14 @@ export async function emit(): Promise { // The public references are a symlink to these generated plugin references. rmSync(`${SKILL_DIR}/references`, { recursive: true, force: true }); - for (const [relativePath, content] of files) { - const fullPath = `${SKILL_DIR}/${relativePath}`; - const dir = fullPath.substring(0, fullPath.lastIndexOf("/")); - mkdirSync(dir, { recursive: true }); - await writeFile(fullPath, content); - } + await Promise.all( + [...files].map(([relativePath, content]) => { + const fullPath = `${SKILL_DIR}/${relativePath}`; + const dir = fullPath.substring(0, fullPath.lastIndexOf("/")); + mkdirSync(dir, { recursive: true }); + return writeFile(fullPath, content); + }), + ); const publicSkill = files.get("SKILL.md"); if (publicSkill === undefined) { diff --git a/packages/cli/script/generate.ts b/packages/cli/script/generate.ts index 74723249f8..ffad84fe02 100644 --- a/packages/cli/script/generate.ts +++ b/packages/cli/script/generate.ts @@ -258,6 +258,7 @@ if (treeSteps.length > 0) { await writeRouteTreeStubs(); await import("../src/app.js"); for (const step of treeSteps) { + // oxlint-disable-next-line no-await-in-loop -- steps emit in order because later steps read files that earlier ones write await (await step.load()).emit(options); if (process.exitCode) { break; diff --git a/packages/cli/script/lib/chunk-build.ts b/packages/cli/script/lib/chunk-build.ts index a3274f9c19..d8e1243353 100644 --- a/packages/cli/script/lib/chunk-build.ts +++ b/packages/cli/script/lib/chunk-build.ts @@ -105,12 +105,13 @@ export async function chunkBuild( entries: MainChunkBuild["entries"], ): Promise { const sorted = [...files].sort(); + const contents = await Promise.all(sorted.map((file) => readFile(file))); const hash = createHash("sha256"); - for (const file of sorted) { + for (const [index, file] of sorted.entries()) { hash .update(basename(file)) .update("\0") - .update(await readFile(file)); + .update(contents[index] ?? ""); } return { id: hash.digest("hex").slice(0, 16), diff --git a/packages/cli/script/lib/split-bundle.ts b/packages/cli/script/lib/split-bundle.ts index 5e40db6c43..f27284ecaa 100644 --- a/packages/cli/script/lib/split-bundle.ts +++ b/packages/cli/script/lib/split-bundle.ts @@ -187,6 +187,7 @@ async function buildEsmChunks(options: SplitBundleOptions): Promise<{ `${LAZY_ENTRY_PREFIX}${path}`, ]), ); + // oxlint-disable-next-line no-await-in-loop -- each build pass adds the lazy entries the previous pass discovered const result = await build({ ...options.options, entryPoints: { ...options.entryPoints, ...lazyPoints }, @@ -268,20 +269,21 @@ async function writeEsmChunks( ]), ); await mkdir(scratch, { recursive: true }); - const files: string[] = []; - for (const file of result.outputFiles) { - const target = join(scratch, relative(outdir, file.path)); - if (file.path.endsWith(".map")) { - await writeFile(target, file.contents); - continue; - } - await writeFile( - target, - lowerChunkImports(file.path, file.text, outputs.get(file.path)), - ); - files.push(target); - } - return files; + const targets = await Promise.all( + result.outputFiles.map(async (file) => { + const target = join(scratch, relative(outdir, file.path)); + if (file.path.endsWith(".map")) { + await writeFile(target, file.contents); + return undefined; + } + await writeFile( + target, + lowerChunkImports(file.path, file.text, outputs.get(file.path)), + ); + return target; + }), + ); + return targets.filter((target) => target !== undefined); } /** Pass 2 of a CommonJS build: convert the ESM chunks in `files` to CommonJS. */ @@ -328,11 +330,12 @@ function jsOutputs(metafile: Metafile): string[] { * their content, so a build does not overwrite the chunks of the last one. */ export async function removeBundleOutputs(dir: string): Promise { - for (const entry of await readdir(dir).catch(() => [])) { - if (BUNDLE_OUTPUT_RE.test(entry)) { - await rm(join(dir, entry), { force: true }); - } - } + const entries = await readdir(dir).catch(() => []); + await Promise.all( + entries + .filter((entry) => BUNDLE_OUTPUT_RE.test(entry)) + .map((entry) => rm(join(dir, entry), { force: true })), + ); } /** Build `options.entryPoints` into split chunks, see the module comment. */ diff --git a/packages/cli/script/preview-selectors.ts b/packages/cli/script/preview-selectors.ts index 0d88a77950..8d91b1c1f1 100644 --- a/packages/cli/script/preview-selectors.ts +++ b/packages/cli/script/preview-selectors.ts @@ -32,6 +32,7 @@ async function preview(): Promise { } const chosen: string[] = []; for (const prompt of [organization, project]) { + // oxlint-disable-next-line no-await-in-loop -- interactive prompts run one after another const value = await selectWithFilter(prompt); if (value === null) { return; diff --git a/packages/cli/src/commands/alert/issues/rule-resolve.ts b/packages/cli/src/commands/alert/issues/rule-resolve.ts index 7192121ca7..0af9abf829 100644 --- a/packages/cli/src/commands/alert/issues/rule-resolve.ts +++ b/packages/cli/src/commands/alert/issues/rule-resolve.ts @@ -2,7 +2,10 @@ * Shared issue alert rule reference parsing and resolution (view / delete / edit). */ -import { MAX_PAGINATION_PAGES } from "../../../lib/api/infrastructure.js"; +import { + MAX_PAGINATION_PAGES, + ORG_FANOUT_CONCURRENCY, +} from "../../../lib/api/infrastructure.js"; import { API_MAX_PER_PAGE, getIssueAlertRule, @@ -13,6 +16,7 @@ import { import { type LazyCommand, sentry } from "../../../lib/app-identity.js"; import { ORG_PROJECT_TARGET } from "../../../lib/completion-target.js"; import { ResolutionError, ValidationError } from "../../../lib/errors.js"; +import { mapBounded } from "../../../lib/fan-out.js"; import { fuzzyMatch } from "../../../lib/fuzzy.js"; import { logger } from "../../../lib/logger.js"; import type { ResolvedTarget } from "../../../lib/resolve-target.js"; @@ -91,6 +95,7 @@ export async function listAllIssueRulesForTarget( const all: IssueAlertRule[] = []; let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await listIssueAlertsPaginated( target.org, target.project, @@ -115,18 +120,24 @@ export async function resolveIssueAlertRule( usageHint: string, ): Promise { if (isAllDigits(ref)) { - const hits: IssueRuleResolution[] = []; - for (const target of targets) { - try { - const rule = await getIssueAlertRule(target.org, target.project, ref); - hits.push({ target, rule }); - } catch (e) { - if (isNotFoundApiError(e)) { - continue; + const lookups = await mapBounded( + targets, + async (target): Promise => { + try { + return { + target, + rule: await getIssueAlertRule(target.org, target.project, ref), + }; + } catch (e) { + if (isNotFoundApiError(e)) { + return null; + } + throw e; } - throw e; - } - } + }, + ORG_FANOUT_CONCURRENCY, + ); + const hits = lookups.filter((hit) => hit !== null); if (hits.length === 1) { return hits[0] as IssueRuleResolution; @@ -147,8 +158,15 @@ export async function resolveIssueAlertRule( const hits: IssueRuleResolution[] = []; const allRuleNames: string[] = []; - for (const target of targets) { - const rules = await listAllIssueRulesForTarget(target); + const targetRules = await mapBounded( + targets, + async (target) => ({ + target, + rules: await listAllIssueRulesForTarget(target), + }), + ORG_FANOUT_CONCURRENCY, + ); + for (const { target, rules } of targetRules) { for (const r of rules) { if (r.name) { allRuleNames.push(r.name); diff --git a/packages/cli/src/commands/alert/metrics/rule-resolve.ts b/packages/cli/src/commands/alert/metrics/rule-resolve.ts index dd0fb473b5..9cd5ffbc9c 100644 --- a/packages/cli/src/commands/alert/metrics/rule-resolve.ts +++ b/packages/cli/src/commands/alert/metrics/rule-resolve.ts @@ -2,7 +2,10 @@ * Shared metric alert rule reference parsing and resolution (view / delete / edit). */ -import { MAX_PAGINATION_PAGES } from "../../../lib/api/infrastructure.js"; +import { + MAX_PAGINATION_PAGES, + ORG_FANOUT_CONCURRENCY, +} from "../../../lib/api/infrastructure.js"; import { API_MAX_PER_PAGE, getMetricAlertRule, @@ -13,6 +16,7 @@ import { import { type LazyCommand, sentry } from "../../../lib/app-identity.js"; import { ORG_TARGET } from "../../../lib/completion-target.js"; import { ResolutionError, ValidationError } from "../../../lib/errors.js"; +import { mapBounded } from "../../../lib/fan-out.js"; import { fuzzyMatch } from "../../../lib/fuzzy.js"; import { logger } from "../../../lib/logger.js"; import { countChar, isAllDigits } from "../../../lib/utils.js"; @@ -88,6 +92,7 @@ export async function listAllMetricRulesForOrg( const all: MetricAlertRule[] = []; let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await listMetricAlertsPaginated(orgSlug, { perPage: API_MAX_PER_PAGE, cursor, @@ -111,18 +116,21 @@ export async function resolveMetricAlertRule( usageHint: string, ): Promise { if (isAllDigits(ref)) { - const hits: MetricRuleResolution[] = []; - for (const orgSlug of orgSlugs) { - try { - const rule = await getMetricAlertRule(orgSlug, ref); - hits.push({ orgSlug, rule }); - } catch (e) { - if (isNotFoundApiError(e)) { - continue; + const lookups = await mapBounded( + orgSlugs, + async (orgSlug): Promise => { + try { + return { orgSlug, rule: await getMetricAlertRule(orgSlug, ref) }; + } catch (e) { + if (isNotFoundApiError(e)) { + return null; + } + throw e; } - throw e; - } - } + }, + ORG_FANOUT_CONCURRENCY, + ); + const hits = lookups.filter((hit) => hit !== null); if (hits.length === 1) { return hits[0] as MetricRuleResolution; @@ -143,8 +151,15 @@ export async function resolveMetricAlertRule( const hits: MetricRuleResolution[] = []; const allNames: string[] = []; - for (const orgSlug of orgSlugs) { - const rules = await listAllMetricRulesForOrg(orgSlug); + const orgRules = await mapBounded( + orgSlugs, + async (orgSlug) => ({ + orgSlug, + rules: await listAllMetricRulesForOrg(orgSlug), + }), + ORG_FANOUT_CONCURRENCY, + ); + for (const { orgSlug, rules } of orgRules) { for (const r of rules) { if (r.name) { allNames.push(r.name); diff --git a/packages/cli/src/commands/alert/metrics/view.ts b/packages/cli/src/commands/alert/metrics/view.ts index fe7bec4248..ccbe99224b 100644 --- a/packages/cli/src/commands/alert/metrics/view.ts +++ b/packages/cli/src/commands/alert/metrics/view.ts @@ -6,6 +6,8 @@ import { import { openInBrowser } from "../../../lib/browser.js"; import { buildCommand } from "../../../lib/command.js"; import { ApiError } from "../../../lib/errors.js"; +import { mapBounded } from "../../../lib/fan-out.js"; +import { ORG_FANOUT_CONCURRENCY } from "../../../lib/api/infrastructure.js"; import { formatMetricAlertView, type MetricAlertViewResult, @@ -119,22 +121,32 @@ export const viewCommand = buildCommand({ workflows: [], workflowErrors: [], }; - for (const id of new Set(rule.workflowIds ?? [])) { - try { - data.workflows.push( - await getIssueAlertWorkflowDocument(result.orgSlug, id), - ); - } catch (error) { - // A missing or inaccessible link must not hide the readable detector - // or be mistaken for an alert with no notification configuration. - if ( - error instanceof ApiError && - (error.status === 403 || error.status === 404) - ) { - data.workflowErrors.push({ id, status: error.status }); - } else { + const lookups = await mapBounded( + new Set(rule.workflowIds ?? []), + async (id) => { + try { + return { + workflow: await getIssueAlertWorkflowDocument(result.orgSlug, id), + }; + } catch (error) { + // A missing or inaccessible link must not hide the readable detector + // or be mistaken for an alert with no notification configuration. + if ( + error instanceof ApiError && + (error.status === 403 || error.status === 404) + ) { + return { error: { id, status: error.status } }; + } throw error; } + }, + ORG_FANOUT_CONCURRENCY, + ); + for (const lookup of lookups) { + if ("workflow" in lookup) { + data.workflows.push(lookup.workflow); + } else { + data.workflowErrors.push(lookup.error); } } yield new CommandOutput(data); diff --git a/packages/cli/src/commands/auth/default.ts b/packages/cli/src/commands/auth/default.ts index 2fb9c0f6d8..ca105c8085 100644 --- a/packages/cli/src/commands/auth/default.ts +++ b/packages/cli/src/commands/auth/default.ts @@ -190,6 +190,7 @@ export const authDefaultCommand = buildCommand({ if (step.value instanceof CommandOutput) { yield step.value; } + // oxlint-disable-next-line no-await-in-loop -- drives the generator one step at a time step = await generator.next(); } return step.value as { hint?: string } | undefined; diff --git a/packages/cli/src/commands/auth/logout.ts b/packages/cli/src/commands/auth/logout.ts index 04f81099f1..f39d8ed37a 100644 --- a/packages/cli/src/commands/auth/logout.ts +++ b/packages/cli/src/commands/auth/logout.ts @@ -204,6 +204,7 @@ async function removeAccounts(accounts: AccountSummary[]): Promise { (a, b) => Number(a.active) - Number(b.active), ); for (const account of ordered) { + // oxlint-disable-next-line no-await-in-loop -- each removal promotes the next account, so accounts are removed in order await removeAccount(account.id, { promoteNext: true }); } } diff --git a/packages/cli/src/commands/build/upload.ts b/packages/cli/src/commands/build/upload.ts index 14a19c8cca..ba069fc83a 100644 --- a/packages/cli/src/commands/build/upload.ts +++ b/packages/cli/src/commands/build/upload.ts @@ -372,6 +372,7 @@ export const uploadCommand = buildCommand({ const builds: BuildUploadEntry[] = []; for (const path of paths) { try { + // oxlint-disable-next-line no-await-in-loop -- each build upload already sends its chunks in parallel; one build at a time keeps that cap const artifactUrl = await uploadOne( this, path, diff --git a/packages/cli/src/commands/cli/setup.ts b/packages/cli/src/commands/cli/setup.ts index 40a6556335..cbc4ccafd9 100644 --- a/packages/cli/src/commands/cli/setup.ts +++ b/packages/cli/src/commands/cli/setup.ts @@ -144,6 +144,7 @@ async function migrateLegacyConfig( for (const name of configFiles) { const from = join(legacyDir, name); if (existsSync(from)) { + // oxlint-disable-next-line no-await-in-loop -- moves the config files one at a time; a failure stops before the next move await rename(from, join(targetConfigDir, name)); } } diff --git a/packages/cli/src/commands/cli/uninstall.ts b/packages/cli/src/commands/cli/uninstall.ts index 778db99f60..72f7f037b6 100644 --- a/packages/cli/src/commands/cli/uninstall.ts +++ b/packages/cli/src/commands/cli/uninstall.ts @@ -361,6 +361,7 @@ async function executeRemovals( for (const artifact of existing) { try { + // oxlint-disable-next-line no-await-in-loop -- removes artifacts in the listed order and records each outcome await artifact.remove(); result.removed.push(`${artifact.label} (${artifact.path})`); } catch (error) { diff --git a/packages/cli/src/commands/cli/upgrade.ts b/packages/cli/src/commands/cli/upgrade.ts index c17fa2a45f..6fa2c369c0 100644 --- a/packages/cli/src/commands/cli/upgrade.ts +++ b/packages/cli/src/commands/cli/upgrade.ts @@ -670,6 +670,7 @@ async function spawnWithRetry( env, windowsVerbatimArguments: target.windowsVerbatimArguments, }); + // oxlint-disable-next-line no-await-in-loop -- retries the spawn one attempt at a time, with a backoff between attempts return await new Promise((resolve, reject) => { proc.on("close", (code, signal) => { // SIGKILL on macOS typically means AMFI killed the binary due to @@ -713,6 +714,7 @@ async function spawnWithRetry( log.warn( `Binary is locked (antivirus scan?), retrying in ${delay}ms... (attempt ${attempt}/${SPAWN_MAX_ATTEMPTS})`, ); + // oxlint-disable-next-line no-await-in-loop -- retries the spawn one attempt at a time, with a backoff between attempts await setTimeout(delay); } } diff --git a/packages/cli/src/commands/dashboard/list.ts b/packages/cli/src/commands/dashboard/list.ts index 7db12ec732..7343b963c3 100644 --- a/packages/cli/src/commands/dashboard/list.ts +++ b/packages/cli/src/commands/dashboard/list.ts @@ -300,6 +300,7 @@ async function fetchDashboards( // always uses one page size and resumes mid-page via afterId bookmarks. // oxlint-disable-next-line sentry-cli/no-manual-pagination for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await listDashboardsPaginated(orgSlug, { perPage: opts.perPage, cursor: serverCursor, diff --git a/packages/cli/src/commands/dashboard/resolve.ts b/packages/cli/src/commands/dashboard/resolve.ts index 6c46a20876..11de786e49 100644 --- a/packages/cli/src/commands/dashboard/resolve.ts +++ b/packages/cli/src/commands/dashboard/resolve.ts @@ -129,6 +129,7 @@ export async function resolveDashboardId( let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await withDashboardErrors( { orgSlug, operation: "list" }, () => diff --git a/packages/cli/src/commands/dashboard/view.ts b/packages/cli/src/commands/dashboard/view.ts index 259768bcac..507ecf286a 100644 --- a/packages/cli/src/commands/dashboard/view.ts +++ b/packages/cli/src/commands/dashboard/view.ts @@ -309,6 +309,7 @@ export const viewCommand = buildCommand({ try { while (!controller.signal.aborted) { + // oxlint-disable-next-line no-await-in-loop -- refreshes the dashboard on an interval until aborted const [widgetData, droppedData] = await Promise.all([ queryAllWidgets(regionUrl, orgSlug, dashboard, { ...widgetTimeOpts, @@ -333,6 +334,7 @@ export const viewCommand = buildCommand({ yield new CommandOutput(viewData); + // oxlint-disable-next-line no-await-in-loop -- refreshes the dashboard on an interval until aborted await abortableSleep(interval * 1000, controller.signal); } } finally { diff --git a/packages/cli/src/commands/event/send.ts b/packages/cli/src/commands/event/send.ts index 969e248bc7..f0692f81e1 100644 --- a/packages/cli/src/commands/event/send.ts +++ b/packages/cli/src/commands/event/send.ts @@ -361,11 +361,13 @@ built entirely from the file contents. if (eventFiles.length > 0) { for (const file of eventFiles) { + // oxlint-disable-next-line no-await-in-loop -- sends each file and yields its result before the next one const { body, eventId } = await buildFilePayload( file, flags.raw ?? false, dsnComponents, ); + // oxlint-disable-next-line no-await-in-loop -- sends each file and yields its result before the next one await sendEnvelopeRequest(dsn, body); yield new CommandOutput({ eventId, file }); } diff --git a/packages/cli/src/commands/issue/view.ts b/packages/cli/src/commands/issue/view.ts index 44cfb0d743..7538af2496 100644 --- a/packages/cli/src/commands/issue/view.ts +++ b/packages/cli/src/commands/issue/view.ts @@ -310,6 +310,7 @@ async function openIssuesInBrowser( ); for (const issue of issues) { + // oxlint-disable-next-line no-await-in-loop -- opens browser tabs one at a time, in order await openInBrowser(issue.permalink, "issue"); } } diff --git a/packages/cli/src/commands/local/daemon.ts b/packages/cli/src/commands/local/daemon.ts index 7a7ce358a1..9dcf709a32 100644 --- a/packages/cli/src/commands/local/daemon.ts +++ b/packages/cli/src/commands/local/daemon.ts @@ -224,6 +224,7 @@ async function withDaemonOwnershipGuard( action: () => Promise, ): Promise { const path = join(directory, "local-control-plane.owner.guard"); + // oxlint-disable no-await-in-loop -- retries the guard file until it is free; each attempt waits for the one before for (let attempt = 0; attempt < 40; attempt += 1) { let guard: Awaited>; try { @@ -252,6 +253,7 @@ async function withDaemonOwnershipGuard( await rm(path, { force: true }); } } + // oxlint-enable no-await-in-loop throw new Error( "Timed out waiting for Local daemon ownership arbitration; active ownership has been preserved.", ); @@ -283,6 +285,7 @@ export async function claimDaemonOwnership( }); }; for (let attempt = 0; attempt < 40; attempt += 1) { + // oxlint-disable-next-line no-await-in-loop -- retries the ownership claim until it is free; each attempt waits for the one before const release = await withDaemonOwnershipGuard(directory, async () => { const claimed = await tryClaim(); if (claimed) return claimed; @@ -325,6 +328,7 @@ export async function claimDaemonOwnership( return undefined; }); if (release) return release; + // oxlint-disable-next-line no-await-in-loop -- waits between checks of the daemon state until the deadline await sleep(125); } throw new Error("Timed out waiting for Sentry Local daemon ownership."); @@ -351,6 +355,7 @@ function isProcessRunning(pid: number): boolean { async function readOwnerPid(path: string): Promise { for (let attempt = 0; ; attempt += 1) { try { + // oxlint-disable-next-line no-await-in-loop -- retries the read only while Windows briefly denies it return Number(await readFile(path, "utf8")); } catch (error) { if (error instanceof Error && "code" in error) { @@ -358,6 +363,7 @@ async function readOwnerPid(path: string): Promise { // Windows may briefly deny reads while the previous owner removes its // file. Retry without interpreting an unreadable owner as absent. if (error.code === "EPERM" && attempt < 4) { + // oxlint-disable-next-line no-await-in-loop -- waits between checks of the daemon state until the deadline await sleep(125); continue; } @@ -491,7 +497,9 @@ export async function waitForLocalDaemonShutdown( const directory = getConfigDir(); const deadline = Date.now() + 5_000; while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls the daemon state until the deadline const current = await readLocalDaemonState(directory); + // oxlint-disable-next-line no-await-in-loop -- polls the daemon state until the deadline const owner = await readOwnerPid( join(directory, "local-control-plane.owner"), ); @@ -499,6 +507,7 @@ export async function waitForLocalDaemonShutdown( current?.pid === state.pid && current.token === state.token; if ((!ownsState && owner !== state.pid) || !isProcessRunning(state.pid)) return; + // oxlint-disable-next-line no-await-in-loop -- waits between checks of the daemon state until the deadline await sleep(125); } throw new Error( @@ -512,11 +521,14 @@ async function waitForLocalDaemon( startupError?: () => Error | undefined, ): Promise { while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- waits between checks of the daemon state until the deadline await sleep(125); + // oxlint-disable-next-line no-await-in-loop -- polls the daemon state until the deadline const state = await discoverLocalDaemon(true); if (state) return state; const error = startupError?.(); if (error) { + // oxlint-disable-next-line no-await-in-loop -- polls the daemon state until the deadline const owner = await readOwnerPid( join(getConfigDir(), "local-control-plane.owner"), ); diff --git a/packages/cli/src/commands/local/receiver-ingest.ts b/packages/cli/src/commands/local/receiver-ingest.ts index 8d7f8a0aa9..6f7ee61ab2 100644 --- a/packages/cli/src/commands/local/receiver-ingest.ts +++ b/packages/cli/src/commands/local/receiver-ingest.ts @@ -95,10 +95,12 @@ export async function readReceiverBody( let size = 0; try { for (;;) { + // oxlint-disable-next-line no-await-in-loop -- reads the request body in order, one chunk at a time const { done, value } = await reader.read(); if (done) return Buffer.concat(chunks, size); size += value.byteLength; if (size > maxBytes) { + // oxlint-disable-next-line no-await-in-loop -- reads the request body in order, one chunk at a time await reader .cancel() .catch(() => logger.debug("Local request body was already closed.")); diff --git a/packages/cli/src/commands/local/run.ts b/packages/cli/src/commands/local/run.ts index c8f11dc9c8..4ec7541409 100644 --- a/packages/cli/src/commands/local/run.ts +++ b/packages/cli/src/commands/local/run.ts @@ -1163,6 +1163,7 @@ async function waitForAppExit(pid: number, ms: number): Promise { if (Date.now() >= deadline) { return false; } + // oxlint-disable-next-line no-await-in-loop -- waits for the app process to exit await new Promise((r) => setTimeout(r, GROUP_POLL_MS)); } return true; diff --git a/packages/cli/src/commands/local/server.ts b/packages/cli/src/commands/local/server.ts index b7e7a30a68..314ff263fa 100644 --- a/packages/cli/src/commands/local/server.ts +++ b/packages/cli/src/commands/local/server.ts @@ -986,6 +986,7 @@ async function consumeSSEWithWarning( const replays = createReplayTracker(); while (!signal.aborted) { + // oxlint-disable-next-line no-await-in-loop -- reconnects one attempt at a time until aborted const result = await attemptSSEConnection({ url, streamUrl, @@ -1045,6 +1046,7 @@ async function consumeSSEWithWarning( logger.info( `SSE connection lost, reconnecting in ${retryDelay / 1000}s...`, ); + // oxlint-disable-next-line no-await-in-loop -- reconnects one attempt at a time until aborted await sleepUnlessAborted(retryDelay, signal); retryDelay = Math.min(retryDelay * 2, SSE_MAX_RETRY_MS); } diff --git a/packages/cli/src/commands/log/tail.ts b/packages/cli/src/commands/log/tail.ts index 4a9bec685b..9633135114 100644 --- a/packages/cli/src/commands/log/tail.ts +++ b/packages/cli/src/commands/log/tail.ts @@ -197,11 +197,13 @@ async function* generateFollowLogs( // Poll loop — exits when SIGINT fires for (;;) { + // oxlint-disable-next-line no-await-in-loop -- polls for new logs; each request starts after the last timestamp await abortableSleep(pollIntervalMs, controller.signal); if (controller.signal.aborted) { break; } + // oxlint-disable-next-line no-await-in-loop -- polls for new logs; each request starts after the last timestamp const newLogs = await fetchPoll(config, lastTimestamp); if (newLogs && newLogs.length > 0) { yield [...newLogs].reverse(); diff --git a/packages/cli/src/commands/log/view.ts b/packages/cli/src/commands/log/view.ts index 0a1f86f115..7291739717 100644 --- a/packages/cli/src/commands/log/view.ts +++ b/packages/cli/src/commands/log/view.ts @@ -319,6 +319,7 @@ async function handleWebOpen(orgSlug: string, logIds: string[]): Promise { } } for (const id of logIds) { + // oxlint-disable-next-line no-await-in-loop -- opens browser tabs one at a time, in order await openInBrowser(buildLogsUrl(orgSlug, id), "log"); } } diff --git a/packages/cli/src/commands/proguard/upload.ts b/packages/cli/src/commands/proguard/upload.ts index 63d85f5f1a..b14527b245 100644 --- a/packages/cli/src/commands/proguard/upload.ts +++ b/packages/cli/src/commands/proguard/upload.ts @@ -15,11 +15,13 @@ import { uploadProguardMappings } from "../../lib/api/proguard.js"; import { buildCommand } from "../../lib/command.js"; import { parseFilePath, parseText } from "../../lib/completion-target.js"; import { ContextError, ValidationError } from "../../lib/errors.js"; +import { mapBounded } from "../../lib/fan-out.js"; import { mdKvTable, renderMarkdown } from "../../lib/formatters/markdown.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { logger } from "../../lib/logger.js"; import { computeProguardUuid } from "../../lib/proguard.js"; import { resolveOrgAndProject } from "../../lib/resolve-target.js"; +import { CONCURRENCY_LIMIT } from "../../lib/scan/constants.js"; import { sentry } from "../../lib/app-identity.js"; const log = logger.withTag("proguard.upload"); @@ -251,12 +253,15 @@ export const uploadCommand = buildCommand({ } // 4. Read each file and compute UUID - const mappings: ProguardMapping[] = []; - for (const path of paths) { - const content = await readMappingFile(path); - const uuid = flags.uuid ?? computeProguardUuid(content); - mappings.push({ path, uuid, content }); - } + const mappings = await mapBounded( + paths, + async (path): Promise => { + const content = await readMappingFile(path); + const uuid = flags.uuid ?? computeProguardUuid(content); + return { path, uuid, content }; + }, + CONCURRENCY_LIMIT, + ); // 5. Deduplicate mappings with identical content (same UUID = same content) const uniqueMappings = deduplicateMappings(mappings); diff --git a/packages/cli/src/commands/project/create.ts b/packages/cli/src/commands/project/create.ts index c17d0f7311..1c0e5a3b68 100644 --- a/packages/cli/src/commands/project/create.ts +++ b/packages/cli/src/commands/project/create.ts @@ -764,6 +764,7 @@ export const createCommand = buildCommand({ try { for (const { name, platform } of parsed) { results.push( + // oxlint-disable-next-line no-await-in-loop -- creates projects one at a time to respect rate limits await createOneProject({ orgSlug, name, diff --git a/packages/cli/src/commands/project/list.ts b/packages/cli/src/commands/project/list.ts index 7ba8a9a6d5..e2d8ccda13 100644 --- a/packages/cli/src/commands/project/list.ts +++ b/packages/cli/src/commands/project/list.ts @@ -37,6 +37,8 @@ import { resolveCursor, } from "../../lib/db/pagination.js"; import { ResolutionError, withAuthGuard } from "../../lib/errors.js"; +import { mapBounded } from "../../lib/fan-out.js"; +import { ORG_FANOUT_CONCURRENCY } from "../../lib/api/infrastructure.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { type Column, formatTable } from "../../lib/formatters/table.js"; import { @@ -155,18 +157,12 @@ export async function fetchOrgProjectsByName( */ export async function fetchAllOrgProjects(): Promise { const orgs = await listOrganizations(); - const results: ProjectWithOrg[] = []; - - for (const org of orgs) { - const projectsResult = await withAuthGuard(() => - fetchOrgProjects(org.slug), - ); - if (projectsResult.ok) { - results.push(...projectsResult.value); - } - } - - return results; + const orgResults = await mapBounded( + orgs, + (org) => withAuthGuard(() => fetchOrgProjects(org.slug)), + ORG_FANOUT_CONCURRENCY, + ); + return orgResults.flatMap((result) => (result.ok ? result.value : [])); } /** diff --git a/packages/cli/src/commands/react-native/gradle.ts b/packages/cli/src/commands/react-native/gradle.ts index 23f022edd6..1baf243b9a 100644 --- a/packages/cli/src/commands/react-native/gradle.ts +++ b/packages/cli/src/commands/react-native/gradle.ts @@ -217,6 +217,7 @@ export const gradleCommand = buildCommand({ log.info( `Uploading sourcemaps for release ${flags.release} distribution ${dist}`, ); + // oxlint-disable-next-line no-await-in-loop -- each upload already sends its chunks in parallel; one dist at a time keeps that cap await uploadSourcemaps({ org, project, diff --git a/packages/cli/src/commands/react-native/xcode.ts b/packages/cli/src/commands/react-native/xcode.ts index 8ab1707bdf..c94d18c806 100644 --- a/packages/cli/src/commands/react-native/xcode.ts +++ b/packages/cli/src/commands/react-native/xcode.ts @@ -151,6 +151,7 @@ async function waitUntilAvailable( const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { try { + // oxlint-disable-next-line no-await-in-loop -- polls the URL until it answers or the deadline passes const res = await fetch(url, { method: "GET" }); if (res.status < 500) { return true; @@ -158,6 +159,7 @@ async function waitUntilAvailable( } catch (err) { log.debug("Packager not up yet", err); } + // oxlint-disable-next-line no-await-in-loop -- polls the URL until it answers or the deadline passes await sleep(500); } return false; @@ -359,6 +361,7 @@ async function uploadPair( let uploads = 0; if (dists.length > 0) { for (const d of dists) { + // oxlint-disable-next-line no-await-in-loop -- each upload already sends its chunks in parallel; one dist at a time keeps that cap await uploadSourcemaps({ org, project, diff --git a/packages/cli/src/commands/sourcemap/upload.ts b/packages/cli/src/commands/sourcemap/upload.ts index f93e3f377e..4f1045a848 100644 --- a/packages/cli/src/commands/sourcemap/upload.ts +++ b/packages/cli/src/commands/sourcemap/upload.ts @@ -28,9 +28,11 @@ import { parseText, } from "../../lib/completion-target.js"; import { ContextError, ValidationError } from "../../lib/errors.js"; +import { mapBounded } from "../../lib/fan-out.js"; import { mdKvTable, renderMarkdown } from "../../lib/formatters/markdown.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { resolveOrgAndProject } from "../../lib/resolve-target.js"; +import { CONCURRENCY_LIMIT } from "../../lib/scan/constants.js"; import { assertDirectoryReadable, buildEmptyDiscoveryError, @@ -264,18 +266,19 @@ async function stripUploadedSources( files: ArtifactFile[], strip: SourcesStrip, ): Promise { - for (const file of files) { - if (file.type !== "source_map") { - continue; - } - const json = file.content - ? file.content.toString("utf-8") - : await readFile(file.path, "utf-8"); - const stripped = stripSourcemapSources(json, strip); - if (stripped !== undefined) { - file.content = Buffer.from(stripped); - } - } + await mapBounded( + files.filter((file) => file.type === "source_map"), + async (file) => { + const json = file.content + ? file.content.toString("utf-8") + : await readFile(file.path, "utf-8"); + const stripped = stripSourcemapSources(json, strip); + if (stripped !== undefined) { + file.content = Buffer.from(stripped); + } + }, + CONCURRENCY_LIMIT, + ); } export const uploadCommand = buildCommand({ diff --git a/packages/cli/src/lib/agent-skills.ts b/packages/cli/src/lib/agent-skills.ts index 09feaf3dd1..b663450aa4 100644 --- a/packages/cli/src/lib/agent-skills.ts +++ b/packages/cli/src/lib/agent-skills.ts @@ -116,6 +116,7 @@ async function writeSkillFiles( if (!existsSync(dir)) { mkdirSync(dir, { recursive: true, mode: 0o755 }); } + // oxlint-disable-next-line no-await-in-loop -- writes the skill files one at a time; a failure stops before the next write await atomicWriteFile(fullPath, content); if (relativePath.startsWith("references/")) { referenceCount += 1; @@ -180,6 +181,7 @@ export async function installAgentSkills( continue; } + // oxlint-disable-next-line no-await-in-loop -- writes the skill files one at a time; a failure stops before the next write const location = await writeSkillFiles( getSkillInstallPath(homeDir, target.rootDir), ); diff --git a/packages/cli/src/lib/api/attribute-pagination.ts b/packages/cli/src/lib/api/attribute-pagination.ts index 4f70eb8e9c..70e6f908e5 100644 --- a/packages/cli/src/lib/api/attribute-pagination.ts +++ b/packages/cli/src/lib/api/attribute-pagination.ts @@ -96,6 +96,7 @@ export async function fetchAttributeTypePage( // coordinate system, so paginate()'s row-count bookmarks do not apply. // oxlint-disable-next-line sentry-cli/no-manual-pagination -- requires key bookmarks and cross-page deduplication for (let pageIndex = 0; pageIndex < MAX_PAGINATION_PAGES; pageIndex++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const page = await listTraceItemAttributes(org, { ...options, attributeTypes: [type], diff --git a/packages/cli/src/lib/api/chunk-upload.ts b/packages/cli/src/lib/api/chunk-upload.ts index 9cc5d3877b..4a93b422b4 100644 --- a/packages/cli/src/lib/api/chunk-upload.ts +++ b/packages/cli/src/lib/api/chunk-upload.ts @@ -374,6 +374,7 @@ export async function hashChunks( for (let offset = 0; offset < fileSize; offset += chunkSize) { const size = Math.min(chunkSize, fileSize - offset); const buf = Buffer.alloc(size); + // oxlint-disable-next-line no-await-in-loop -- reads the file into one reused buffer, one chunk at a time await fh.read(buf, 0, size, offset); const sha1 = createHash("sha1").update(buf).digest("hex"); overallHasher.update(buf); @@ -582,8 +583,14 @@ async function uploadChunkBatch(params: { const fieldName = encoding === "gzip" ? "file_gzip" : "file"; const form = new FormData(); - for (const chunk of batch) { - const payload = await encodeChunk(chunk.data, encoding); + // The batch is capped by the server's chunksPerRequest, so encode it at once. + const encoded = await Promise.all( + batch.map(async (chunk) => ({ + chunk, + payload: await encodeChunk(chunk.data, encoding), + })), + ); + for (const { chunk, payload } of encoded) { form.append( fieldName, new Blob([payload], { type: "application/octet-stream" }), @@ -779,8 +786,10 @@ export async function pollAssembly(params: { const deadline = Date.now() + deadlineMs; while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done const pollResult = await assemble(); if (pollResult.state === "ok") { diff --git a/packages/cli/src/lib/api/code-mappings.ts b/packages/cli/src/lib/api/code-mappings.ts index 4df974f603..caf918176e 100644 --- a/packages/cli/src/lib/api/code-mappings.ts +++ b/packages/cli/src/lib/api/code-mappings.ts @@ -119,6 +119,7 @@ export async function uploadCodeMappings( ); } + // oxlint-disable-next-line no-await-in-loop -- batches upsert into one project and repository, one request at a time const result = await bulkUpsertOrganizationCodeMappings({ ...config, path: { organization_id_or_slug: org }, diff --git a/packages/cli/src/lib/api/conversations.ts b/packages/cli/src/lib/api/conversations.ts index c785747fc4..f1fd2f5427 100644 --- a/packages/cli/src/lib/api/conversations.ts +++ b/packages/cli/src/lib/api/conversations.ts @@ -135,6 +135,7 @@ export async function getConversationSpans( let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const result = await retrieveOrganizationAiConversation({ ...config, path: { diff --git a/packages/cli/src/lib/api/dart-symbols.ts b/packages/cli/src/lib/api/dart-symbols.ts index a982b81bee..d17c02c875 100644 --- a/packages/cli/src/lib/api/dart-symbols.ts +++ b/packages/cli/src/lib/api/dart-symbols.ts @@ -166,8 +166,10 @@ export async function uploadDartSymbolMap( // Step 6: Poll assemble endpoint until done const deadline = Date.now() + ASSEMBLE_MAX_WAIT_MS; while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done const pollResult = await assembleDebugFiles(org, project, assembleBody); const { allDone: done } = checkAssembleResponse( diff --git a/packages/cli/src/lib/api/dashboards.ts b/packages/cli/src/lib/api/dashboards.ts index 498ece60d9..3e64899632 100644 --- a/packages/cli/src/lib/api/dashboards.ts +++ b/packages/cli/src/lib/api/dashboards.ts @@ -52,6 +52,7 @@ import { import type { EventsDataset } from "../datasets.js"; import { reportCliError } from "../error-reporting.js"; import { ApiError, stringifyUnknown } from "../errors.js"; +import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; import { getSdkClientConfig } from "../sentry-sdk-client.js"; @@ -581,6 +582,7 @@ async function queryWidgetTimeseries( const aggregates = query.aggregates ?? []; const columns = query.columns ?? []; + // oxlint-disable-next-line no-await-in-loop -- widgets already fan out at ORG_FANOUT_CONCURRENCY; a widget's queries run in turn so the total stays at that cap const result = await listOrganizationEventsTimeseries({ ...getSdkClientConfig(regionUrl), path: { organization_id_or_slug: orgSlug }, @@ -799,28 +801,6 @@ function widgetErrorMessage(error: unknown): string { * @param options - Query options (period override, environment filter) * @returns Map of widget index → query result */ -/** Collect settled results from a batch into the results map. */ -function collectBatchResults( - batchResults: PromiseSettledResult[], - startIndex: number, - results: Map, -): void { - for (let j = 0; j < batchResults.length; j++) { - const result = batchResults[j]; - const idx = startIndex + j; - if (result?.status === "fulfilled") { - results.set(idx, result.value); - } else { - results.set(idx, { - type: "error", - message: result?.reason - ? stringifyUnknown(result.reason) - : "Unknown error", - }); - } - } -} - export async function queryAllWidgets( regionUrl: string, orgSlug: string, @@ -842,18 +822,11 @@ export async function queryAllWidgets( project: options.project ?? dashboard.projects ?? undefined, }; - const results = new Map(); - if (widgets.length === 0) { - return results; - } - - // Process in batches to respect concurrency limit - const batchSize = ORG_FANOUT_CONCURRENCY; - for (let i = 0; i < widgets.length; i += batchSize) { - const batch = widgets.slice(i, i + batchSize); - const batchResults = await Promise.allSettled( - batch.map((widget) => - queryWidgetData({ + const widgetResults = await mapBounded( + widgets, + async (widget): Promise => { + try { + return await queryWidgetData({ regionUrl, orgSlug, widget, @@ -862,13 +835,17 @@ export async function queryAllWidgets( end: options.end, periodSeconds: options.periodSeconds, options: mergedOptions, - }), - ), - ); - collectBatchResults(batchResults, i, results); - } - - return results; + }); + } catch (error) { + return { + type: "error", + message: error ? stringifyUnknown(error) : "Unknown error", + }; + } + }, + ORG_FANOUT_CONCURRENCY, + ); + return new Map(widgetResults.entries()); } /** Material unintentional drops for one dataset of a dashboard's widgets. */ diff --git a/packages/cli/src/lib/api/debug-files.ts b/packages/cli/src/lib/api/debug-files.ts index 923349d322..bcd996e08c 100644 --- a/packages/cli/src/lib/api/debug-files.ts +++ b/packages/cli/src/lib/api/debug-files.ts @@ -19,6 +19,7 @@ */ import { ApiError, ValidationError } from "../errors.js"; +import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; import { resolveOrgRegion } from "../region.js"; import { @@ -37,6 +38,7 @@ import { type UploadEncoding, uploadChunkPayloads, } from "./chunk-upload.js"; +import { ORG_FANOUT_CONCURRENCY } from "./infrastructure.js"; const log = logger.withTag("api.debug-files"); @@ -359,9 +361,14 @@ async function postAssemble( project: string, bodies: readonly Record[], ): Promise { + const responses = await mapBounded( + bodies, + (body) => assembleDebugFiles(org, project, body), + ORG_FANOUT_CONCURRENCY, + ); const merged: DifAssembleResponse = {}; - for (const body of bodies) { - Object.assign(merged, await assembleDebugFiles(org, project, body)); + for (const response of responses) { + Object.assign(merged, response); } return merged; } @@ -584,11 +591,14 @@ export async function uploadDebugFiles( break; } + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done response = await postAssemble(org, project, bodies); evaluation = evaluateAssembly(response, chunked, wait); reportProcessing(); // Re-sends report progress too, so a long retry does not look hung. + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await uploadMissing({ chunked, missingChecksums: evaluation.missingChecksums, diff --git a/packages/cli/src/lib/api/explore.ts b/packages/cli/src/lib/api/explore.ts index b72a38dce1..8cdf87b220 100644 --- a/packages/cli/src/lib/api/explore.ts +++ b/packages/cli/src/lib/api/explore.ts @@ -225,6 +225,7 @@ export async function queryMetricsMeta( let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page += 1) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const result = await fetchEventsPage( regionUrl, orgSlug, diff --git a/packages/cli/src/lib/api/infrastructure.ts b/packages/cli/src/lib/api/infrastructure.ts index 0fd9924744..2878d4f1e5 100644 --- a/packages/cli/src/lib/api/infrastructure.ts +++ b/packages/cli/src/lib/api/infrastructure.ts @@ -856,6 +856,7 @@ export async function autoPaginate( let cursor: string | undefined = initialCursor; for (let page = 0; page < MAX_PAGINATION_PAGES; page += 1) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const result = await fetchPage(cursor); allRows.push(...result.data); diff --git a/packages/cli/src/lib/api/issue-app-links.ts b/packages/cli/src/lib/api/issue-app-links.ts index 8986b147ef..b8b206334c 100644 --- a/packages/cli/src/lib/api/issue-app-links.ts +++ b/packages/cli/src/lib/api/issue-app-links.ts @@ -514,6 +514,7 @@ async function resolveFields( ); } pending.splice(index, 1); + // oxlint-disable-next-line no-await-in-loop -- a field resolves only after the fields it depends on values[field.name] = await resolveFieldValue({ field, targetField, diff --git a/packages/cli/src/lib/api/preprod-artifacts.ts b/packages/cli/src/lib/api/preprod-artifacts.ts index 21e49876ac..7c1d8f9cf9 100644 --- a/packages/cli/src/lib/api/preprod-artifacts.ts +++ b/packages/cli/src/lib/api/preprod-artifacts.ts @@ -305,6 +305,7 @@ export async function uploadBuild( const deadline = Date.now() + ASSEMBLE_MAX_WAIT_MS; while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done const result = await assembleProjectPreprodArtifact({ ...config, path: { organization_id_or_slug: org, project_id_or_slug: project }, @@ -342,6 +343,7 @@ export async function uploadBuild( const missing = new Set(data.missingChunks ?? []); if (missing.size > 0) { + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await uploadMissingChunks({ chunks, missingChecksums: missing, @@ -354,6 +356,7 @@ export async function uploadBuild( // Always pace between assemble POSTs (matches the legacy poll loop and // avoids a busy loop should the server keep reporting the same chunks). + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); } @@ -601,6 +604,7 @@ export async function waitForSnapshotArchive( onBuildStarted?.(); const deadline = Date.now() + SNAPSHOT_ARCHIVE_TIMEOUT_MS; + // oxlint-disable-next-line no-await-in-loop -- polls until the snapshot archive is ready while (!(await getSnapshotArchiveReady(org, snapshotId))) { if (Date.now() >= deadline) { throw new TimeoutError( @@ -609,6 +613,7 @@ export async function waitForSnapshotArchive( }s. The build may still be running; try again shortly.`, ); } + // oxlint-disable-next-line no-await-in-loop -- polls until the snapshot archive is ready await new Promise((r) => setTimeout(r, SNAPSHOT_ARCHIVE_POLL_MS)); } } diff --git a/packages/cli/src/lib/api/proguard.ts b/packages/cli/src/lib/api/proguard.ts index 1beee0dac9..ded82e9e3b 100644 --- a/packages/cli/src/lib/api/proguard.ts +++ b/packages/cli/src/lib/api/proguard.ts @@ -170,8 +170,9 @@ export async function uploadProguardMappings( return; } - // Step 5: Upload missing chunks in parallel across all mappings + // Step 5: Upload missing chunks, one mapping at a time for (const cm of chunkedMappings) { + // oxlint-disable-next-line no-await-in-loop -- each call already uploads its chunks at serverOptions.concurrency; one mapping at a time keeps that cap await uploadMissingBufferChunks({ chunks: cm.chunks, missingChecksums, @@ -205,8 +206,10 @@ async function pollDifAssembly(params: { const deadline = Date.now() + ASSEMBLE_MAX_WAIT_MS; while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done const pollResult = await assemble(); const { allDone } = checkAssembleResponse(pollResult, checksums, endpoint); diff --git a/packages/cli/src/lib/api/releases.ts b/packages/cli/src/lib/api/releases.ts index 4b712f9998..bc5bd61b95 100644 --- a/packages/cli/src/lib/api/releases.ts +++ b/packages/cli/src/lib/api/releases.ts @@ -636,6 +636,7 @@ async function findSentryRepository( for (const query of queries) { let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const result = await listRepositoriesPaginated(orgSlug, { cursor, perPage: API_MAX_PER_PAGE, diff --git a/packages/cli/src/lib/api/replays.ts b/packages/cli/src/lib/api/replays.ts index cfd0ae7f5c..4a6b9d0f46 100644 --- a/packages/cli/src/lib/api/replays.ts +++ b/packages/cli/src/lib/api/replays.ts @@ -344,6 +344,7 @@ export async function getReplayRecordingSegments( let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page += 1) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await fetchReplayRecordingSegmentsPage({ orgSlug, projectSlugOrId, diff --git a/packages/cli/src/lib/bash-hook/traceback.ts b/packages/cli/src/lib/bash-hook/traceback.ts index 9ff018d4aa..8b43b4ad0b 100644 --- a/packages/cli/src/lib/bash-hook/traceback.ts +++ b/packages/cli/src/lib/bash-hook/traceback.ts @@ -12,8 +12,10 @@ import { readFile } from "node:fs/promises"; import type { Breadcrumb, Event, StackFrame } from "@sentry/core"; import { uuid4 } from "@sentry/core"; import { ValidationError } from "../errors.js"; +import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; import { omitUndefined } from "../omit-undefined.js"; +import { CONCURRENCY_LIMIT } from "../scan/constants.js"; const log = logger.withTag("bash-hook.traceback"); @@ -120,30 +122,38 @@ export function parseTracebackContent(content: string): TracebackData { * Enrich stack frames with source context from the original files. * * Reads each frame's source file and attaches ±5 lines of context around - * the error line. File contents are cached to avoid redundant reads. + * the error line. Each distinct file is read once. */ async function enrichFramesWithSourceContext( frames: StackFrame[], ): Promise { - const sourceCache = new Map(); + const filenames = new Set( + frames.flatMap((frame) => + frame.filename && frame.lineno ? [frame.filename] : [], + ), + ); + const sources = new Map( + await mapBounded( + filenames, + async (filename) => { + try { + const content = await readFile(filename, "utf-8"); + return [filename, content.split("\n")] as const; + } catch (err) { + log.debug(`Could not read source file ${filename}`, err); + return [filename, null] as const; + } + }, + CONCURRENCY_LIMIT, + ), + ); for (const frame of frames) { if (!(frame.filename && frame.lineno)) { continue; } - let lines = sourceCache.get(frame.filename); - if (lines === undefined) { - try { - const content = await readFile(frame.filename, "utf-8"); - lines = content.split("\n"); - } catch (err) { - log.debug(`Could not read source file ${frame.filename}`, err); - lines = null; - } - sourceCache.set(frame.filename, lines); - } - + const lines = sources.get(frame.filename); if (!lines) { continue; } diff --git a/packages/cli/src/lib/build/asset-catalog-extract.ts b/packages/cli/src/lib/build/asset-catalog-extract.ts index b725227428..ee45ea3e18 100644 --- a/packages/cli/src/lib/build/asset-catalog-extract.ts +++ b/packages/cli/src/lib/build/asset-catalog-extract.ts @@ -32,7 +32,9 @@ import { strictObject, string, } from "valibot"; +import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; +import { CONCURRENCY_LIMIT } from "../scan/constants.js"; import { getSeaRawAsset } from "../sea-assets.js"; const log = logger.withTag("build.asset-catalog"); @@ -166,35 +168,33 @@ async function canonicalizeOutput( const manifest: unknown = JSON.parse(await readFile(manifestPath, "utf8")); const assets = parse(array(AssetCatalogEntrySchema), manifest); const seenIds = new Set(); - const renditions = []; - for (const { imageId, ...asset } of assets) { + for (const { imageId } of assets) { if (imageId && seenIds.has(imageId)) { throw new Error("Asset-catalog manifest contains duplicate image IDs"); } seenIds.add(imageId); - // NSString.pathExtension treats a trailing dot as an empty extension. - const extension = `.${ - posix - .extname(asset.filename ?? "") - .slice(1) - .toLowerCase() || "png" - }`; - const sourcePath = join(outputDirectory, `${imageId}${extension}`); - const hasImage = - imageId !== "" && - IMAGE_EXTENSIONS.has(extension) && - (await regularFile(sourcePath)); - const hash = hasImage ? await imageHash(sourcePath) : ""; - const identity = `${catalogRelativePath}\0${JSON.stringify(asset)}\0${hash}`; - renditions.push({ - imageId, - asset, - extension, - sourcePath, - hasImage, - identity, - }); } + const renditions = await mapBounded( + assets, + async ({ imageId, ...asset }) => { + // NSString.pathExtension treats a trailing dot as an empty extension. + const extension = `.${ + posix + .extname(asset.filename ?? "") + .slice(1) + .toLowerCase() || "png" + }`; + const sourcePath = join(outputDirectory, `${imageId}${extension}`); + const hasImage = + imageId !== "" && + IMAGE_EXTENSIONS.has(extension) && + (await regularFile(sourcePath)); + const hash = hasImage ? await imageHash(sourcePath) : ""; + const identity = `${catalogRelativePath}\0${JSON.stringify(asset)}\0${hash}`; + return { imageId, asset, extension, sourcePath, hasImage, identity }; + }, + CONCURRENCY_LIMIT, + ); renditions.sort((a, b) => a.identity < b.identity ? -1 : a.identity > b.identity ? 1 : 0, ); @@ -203,6 +203,7 @@ async function canonicalizeOutput( const occurrences = new Map(); const canonicalAssets: AssetCatalogEntry[] = []; const files: AssetCatalogExtraction["files"] = []; + const copies: { from: string; to: string }[] = []; for (const rendition of renditions) { const occurrence = occurrences.get(rendition.identity) ?? 0; occurrences.set(rendition.identity, occurrence + 1); @@ -213,10 +214,15 @@ async function canonicalizeOutput( if (rendition.hasImage) { const name = `${imageId}${rendition.extension}`; const sourcePath = join(canonicalDirectory, name); - await copyFile(rendition.sourcePath, sourcePath, COPY_FILE_FLAGS); + copies.push({ from: rendition.sourcePath, to: sourcePath }); files.push({ name, sourcePath }); } } + await mapBounded( + copies, + ({ from, to }) => copyFile(from, to, COPY_FILE_FLAGS), + CONCURRENCY_LIMIT, + ); const sourcePath = join(canonicalDirectory, "Assets.json"); await writeFile(sourcePath, `${JSON.stringify(canonicalAssets)}\n`); files.push({ name: "Assets.json", sourcePath }); diff --git a/packages/cli/src/lib/build/dsyms.ts b/packages/cli/src/lib/build/dsyms.ts index 68aa605aae..6fe2ff1454 100644 --- a/packages/cli/src/lib/build/dsyms.ts +++ b/packages/cli/src/lib/build/dsyms.ts @@ -49,6 +49,7 @@ async function collectBundle( ); } if (dirent.isDirectory()) { + // oxlint-disable-next-line no-await-in-loop -- walks the bundle depth-first so entries keep their order entries.push(...(await collectBundle(sourcePath, relPath))); } else if (dirent.isFile()) { entries.push({ relPath, sourcePath }); @@ -174,6 +175,7 @@ export async function collectDsymEntries( ): Promise { const entries: DsymEntry[] = []; const seenBundles = new Set(); + // oxlint-disable no-await-in-loop -- inputs are staged in argument order, and bundle names must be unique across them for (const input of paths) { // resolve strips trailing separators before lstat and extension detection. // lstat("link.dSYM/") would otherwise follow a directory symlink on POSIX. @@ -219,5 +221,6 @@ export async function collectDsymEntries( entries.push(...files); } } + // oxlint-enable no-await-in-loop return entries; } diff --git a/packages/cli/src/lib/build/index.ts b/packages/cli/src/lib/build/index.ts index 2c8bab5082..d5117ce9b6 100644 --- a/packages/cli/src/lib/build/index.ts +++ b/packages/cli/src/lib/build/index.ts @@ -173,6 +173,7 @@ export async function detectBuildFormatFromFile( const size = (await src.stat()).size; let position = 0; while (position < size) { + // oxlint-disable-next-line no-await-in-loop -- reads the file into one reused buffer, one chunk at a time const read = await src.read(buf, 0, buf.length, position); if (read.bytesRead === 0) { break; @@ -367,8 +368,10 @@ async function collectArchiveEntries(root: string): Promise { // not descended into (matching Rust's WalkDir with follow_links = false). let payload: { sourcePath: string } | { linkTarget: Uint8Array }; if (dirent.isSymbolicLink()) { + // oxlint-disable-next-line no-await-in-loop -- walks the tree depth-first so archive entries keep a stable order payload = { linkTarget: strToU8(await readlink(full)) }; } else if (dirent.isDirectory()) { + // oxlint-disable-next-line no-await-in-loop -- walks the tree depth-first so archive entries keep a stable order await walk(full, relPath); continue; } else if (dirent.isFile()) { @@ -380,6 +383,7 @@ async function collectArchiveEntries(root: string): Promise { // Encode the full Unix mode (type + permission bits) into the upper 16 // bits of the ZIP external attributes so symlinks and exec bits survive. + // oxlint-disable-next-line no-await-in-loop -- walks the tree depth-first so archive entries keep a stable order const { mode } = await lstat(full); const attrs = ((mode & 0xff_ff) << 16) >>> 0; entries.push({ relPath, attrs, ...payload }); @@ -429,8 +433,10 @@ export async function normalizeBuildDirectory( const name = `${dirName}/${entry.relPath}`; const options = { os: ZIP_OS_UNIX, attrs: entry.attrs }; if ("sourcePath" in entry) { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addFile(name, entry.sourcePath, options); } else { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addData(name, entry.linkTarget, options); } } @@ -463,6 +469,7 @@ async function addParsedAssetCatalogs( const files = new Map(); try { for (const catalog of catalogs) { + // oxlint-disable-next-line no-await-in-loop -- each extraction runs the asset-catalog helper; the finally block cleans up only the extractions that finished const extraction = await extractAssetCatalogImages( catalog.relPath, catalog.sourcePath, @@ -498,12 +505,11 @@ async function addParsedAssetCatalogs( for (const [name, sourcePath] of [...files].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0, )) { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addFile(name, sourcePath); } } finally { - for (const extraction of extractions) { - await extraction.cleanup(); - } + await Promise.all(extractions.map((extraction) => extraction.cleanup())); } } @@ -713,7 +719,9 @@ async function stageIpaPayload( const staged: StagedIpaEntry[] = []; for (const { name, entry } of await readIpaPayloadEntries(ipaPath, zip)) { const stagePath = join(stageDir, `e${staged.length}`); + // oxlint-disable-next-line no-await-in-loop -- copies IPA entries in archive order from one open zip await pipeline( + // oxlint-disable-next-line no-await-in-loop -- copies IPA entries in archive order from one open zip await zip.openReadStreamPromise(entry), createWriteStream(stagePath), ); @@ -818,8 +826,10 @@ export async function normalizeIpa( try { for (const item of items) { if (item.stagePath !== undefined) { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addFile(item.name, item.stagePath, item.options); } else if (item.data !== undefined) { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addData(item.name, item.data); } } diff --git a/packages/cli/src/lib/build/zip-writer.ts b/packages/cli/src/lib/build/zip-writer.ts index b9c34687a5..3bfa649f96 100644 --- a/packages/cli/src/lib/build/zip-writer.ts +++ b/packages/cli/src/lib/build/zip-writer.ts @@ -203,6 +203,7 @@ export class DeterministicZipWriter { let size = 0; const buf = Buffer.allocUnsafe(STREAM_CHUNK_SIZE); for (;;) { + // oxlint-disable-next-line no-await-in-loop -- reads the source into one reused buffer, one chunk at a time const { bytesRead } = await src.read(buf, 0, buf.length, null); if (bytesRead === 0) { break; @@ -217,10 +218,12 @@ export class DeterministicZipWriter { // Pass 2: copy the stored bytes. let position = 0; while (position < size) { + // oxlint-disable-next-line no-await-in-loop -- reads the source into one reused buffer, one chunk at a time const { bytesRead } = await src.read(buf, 0, buf.length, position); if (bytesRead === 0) { break; } + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await this.fh.write(buf, 0, bytesRead); position += bytesRead; } @@ -258,7 +261,9 @@ export class DeterministicZipWriter { rec.writeUInt32LE(entry.attrs, 38); // external attributes rec.writeUInt32LE(entry.localHeaderOffset, 42); + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await this.fh.write(rec, 0, rec.length); + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await this.fh.write(entry.nameBytes, 0, entry.nameBytes.length); this.offset += CENTRAL_HEADER_FIXED_SIZE + entry.nameBytes.length; } diff --git a/packages/cli/src/lib/command.ts b/packages/cli/src/lib/command.ts index 63060f0098..af2f98ce4e 100644 --- a/packages/cli/src/lib/command.ts +++ b/packages/cli/src/lib/command.ts @@ -928,6 +928,7 @@ export function buildCommand< let result = await generator.next(); while (!result.done) { handleYieldedValue(stdout, result.value, cleanFlags, renderer); + // oxlint-disable-next-line no-await-in-loop -- drives the generator one step at a time result = await generator.next(); } return result.value as CommandReturn | undefined; diff --git a/packages/cli/src/lib/complete.ts b/packages/cli/src/lib/complete.ts index 0b0e16fc84..a7639d6d26 100644 --- a/packages/cli/src/lib/complete.ts +++ b/packages/cli/src/lib/complete.ts @@ -844,6 +844,7 @@ async function positionalOrg( positionals: readonly string[], ): Promise { for (const word of positionals) { + // oxlint-disable-next-line no-await-in-loop -- checks positionals in order and stops at the first that names an org const scope = await parseTargetScope(word); if (scope?.org) { return scope.org; diff --git a/packages/cli/src/lib/db/dsn-cache.ts b/packages/cli/src/lib/db/dsn-cache.ts index 538169fdda..da5722fd0c 100644 --- a/packages/cli/src/lib/db/dsn-cache.ts +++ b/packages/cli/src/lib/db/dsn-cache.ts @@ -14,6 +14,8 @@ import type { ResolvedProjectInfo, } from "../dsn/types.js"; import { invocationState } from "../env.js"; +import { mapBounded } from "../fan-out.js"; +import { CONCURRENCY_LIMIT } from "../scan/constants.js"; import { getDatabase, maybeCleanupCaches, recordCacheHit } from "./index.js"; import { safeParseJson } from "./json.js"; import { runUpsert, touchCacheEntry } from "./utils.js"; @@ -289,13 +291,13 @@ async function validateSourceMtimes( projectRoot: string, sourceMtimes: Record, ): Promise { - for (const [relativePath, cachedMtime] of Object.entries(sourceMtimes)) { - const fullPath = join(projectRoot, relativePath); - if (!(await validateFileMtime(fullPath, cachedMtime))) { - return false; - } - } - return true; + const matches = await mapBounded( + Object.entries(sourceMtimes), + ([relativePath, cachedMtime]) => + validateFileMtime(join(projectRoot, relativePath), cachedMtime), + CONCURRENCY_LIMIT, + ); + return matches.every(Boolean); } /** @@ -310,13 +312,13 @@ async function validateDirMtimes( projectRoot: string, dirMtimes: Record, ): Promise { - for (const [relativePath, cachedMtime] of Object.entries(dirMtimes)) { - const fullPath = join(projectRoot, relativePath); - if (!(await validateDirMtime(fullPath, cachedMtime))) { - return false; - } - } - return true; + const matches = await mapBounded( + Object.entries(dirMtimes), + ([relativePath, cachedMtime]) => + validateDirMtime(join(projectRoot, relativePath), cachedMtime), + CONCURRENCY_LIMIT, + ); + return matches.every(Boolean); } /** Type guard: value is a plain object with all-numeric values (mtimes record). */ diff --git a/packages/cli/src/lib/detect-agent.ts b/packages/cli/src/lib/detect-agent.ts index 1fa3519a90..81d3207d2b 100644 --- a/packages/cli/src/lib/detect-agent.ts +++ b/packages/cli/src/lib/detect-agent.ts @@ -326,6 +326,7 @@ export async function detectAgentFromProcessTree(): Promise< let pid = process.ppid; for (let depth = 0; depth < MAX_ANCESTOR_DEPTH && pid > 1; depth++) { + // oxlint-disable-next-line no-await-in-loop -- walks up the process tree; each parent comes from the step before const info = await _getProcessInfo(pid); if (!info) { break; diff --git a/packages/cli/src/lib/dev-script.ts b/packages/cli/src/lib/dev-script.ts index edf86e5b1c..ae362c2bc3 100644 --- a/packages/cli/src/lib/dev-script.ts +++ b/packages/cli/src/lib/dev-script.ts @@ -788,6 +788,7 @@ async function tryDockerCompose(cwd: string): Promise { for (const filename of ["docker-compose.yml", "compose.yml"]) { // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. try { + // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match await access(join(cwd, filename)); return { args: ["docker", "compose", "up"], source: filename }; } catch { diff --git a/packages/cli/src/lib/dif/find.ts b/packages/cli/src/lib/dif/find.ts index 7ca4c18786..133b58ac60 100644 --- a/packages/cli/src/lib/dif/find.ts +++ b/packages/cli/src/lib/dif/find.ts @@ -318,6 +318,7 @@ export async function findDebugFiles(opts: FindOptions): Promise { continue; } seen.add(abs); + // oxlint-disable-next-line no-await-in-loop -- walks the paths in order and stops once every requested ID is found for await (const entry of walkPath(path)) { if (state.remaining.size === 0) { break; diff --git a/packages/cli/src/lib/dif/scan.ts b/packages/cli/src/lib/dif/scan.ts index afc91af95e..467ff0771f 100644 --- a/packages/cli/src/lib/dif/scan.ts +++ b/packages/cli/src/lib/dif/scan.ts @@ -309,10 +309,12 @@ export async function scanPaths(paths: string[]): Promise { }; for (const path of paths) { + // oxlint-disable-next-line no-await-in-loop -- walks the paths in argument order so the deduplicated file list keeps it const info = await statExplicitPath(path); if (info.isFile()) { add(path); } else if (info.isDirectory()) { + // oxlint-disable-next-line no-await-in-loop -- walks the paths in argument order so the deduplicated file list keeps it for await (const entry of walkDebugFileDir(path)) { add(entry.absolutePath); } @@ -506,6 +508,7 @@ export async function prepareDifs( // means the path was a `.zip` and is fully handled. `null` means "not a // zip" — fall through to normal file handling. if (scanZips) { + // oxlint-disable-next-line no-await-in-loop -- zip inputs are inflated in memory; one path at a time keeps one archive in memory const zipPrepared = await prepareZipDifs( path, filters, @@ -525,6 +528,7 @@ export async function prepareDifs( } } + // oxlint-disable-next-line no-await-in-loop -- zip inputs are inflated in memory; one path at a time keeps one archive in memory const { difs, oversized } = await prepareFileDif( path, filters, diff --git a/packages/cli/src/lib/docs-context.ts b/packages/cli/src/lib/docs-context.ts index 5ce885daf2..197ea1c7d8 100644 --- a/packages/cli/src/lib/docs-context.ts +++ b/packages/cli/src/lib/docs-context.ts @@ -104,29 +104,40 @@ export async function detectDocsContextFromReader( const languages = new Set(); let sentryConfigured = false; - for (const manifest of DOCS_CONTEXT_MANIFESTS) { - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - try { - const contents = await reader.readManifest(manifest); - if (contents === undefined) { - continue; - } - addLanguageSignal(manifest, languages); - addFrameworkSignals(contents, frameworks); - sentryConfigured ||= containsSentrySdk(contents); - } catch { - // Missing/unreadable metadata is optional and must not block lookup. - } - } + const [manifests, configs] = await Promise.all([ + Promise.all( + DOCS_CONTEXT_MANIFESTS.map(async (manifest) => { + // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. + try { + return { manifest, contents: await reader.readManifest(manifest) }; + } catch { + // Missing/unreadable metadata is optional and must not block lookup. + return { manifest, contents: undefined }; + } + }), + ), + Promise.all( + DOCS_CONTEXT_CONFIGS.map(async (config) => { + // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. + try { + return await reader.hasConfig(config); + } catch { + // Config presence is an optional signal only. + return false; + } + }), + ), + ]); - for (const config of DOCS_CONTEXT_CONFIGS) { - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - try { - sentryConfigured ||= await reader.hasConfig(config); - } catch { - // Config presence is an optional signal only. + for (const { manifest, contents } of manifests) { + if (contents === undefined) { + continue; } + addLanguageSignal(manifest, languages); + addFrameworkSignals(contents, frameworks); + sentryConfigured ||= containsSentrySdk(contents); } + sentryConfigured ||= configs.includes(true); return { frameworks: [...frameworks].sort(), diff --git a/packages/cli/src/lib/dsn/env-file.ts b/packages/cli/src/lib/dsn/env-file.ts index e4409a560e..2f80eb9d32 100644 --- a/packages/cli/src/lib/dsn/env-file.ts +++ b/packages/cli/src/lib/dsn/env-file.ts @@ -199,43 +199,61 @@ export async function detectFromAllEnvFiles( export async function detectFromMonorepoEnvFiles( cwd: string, ): Promise { + const roots = await Promise.all( + MONOREPO_ROOTS.map((monorepoRoot) => + detectFromMonorepoRoot(cwd, monorepoRoot), + ), + ); const dsns: DetectedDsn[] = []; const sourceMtimes: Record = {}; let packagesScanned = 0; + for (const root of roots) { + dsns.push(...root.dsns); + Object.assign(sourceMtimes, root.sourceMtimes); + packagesScanned += root.packagesScanned; + } + return { dsns, sourceMtimes, packagesScanned }; +} - for (const monorepoRoot of MONOREPO_ROOTS) { - const rootDir = join(cwd, monorepoRoot); +/** Detect DSNs from .env files in the packages of one monorepo root. */ +async function detectFromMonorepoRoot( + cwd: string, + monorepoRoot: string, +): Promise> { + const dsns: DetectedDsn[] = []; + const sourceMtimes: Record = {}; + let packagesScanned = 0; + const rootDir = join(cwd, monorepoRoot); - // Bun's opendir() may not throw on a missing directory — the error - // surfaces when iterating. Wrap the full open+iterate in one try/catch. - // No explicit handle.close() needed: for-await-of auto-closes the Dir - // handle when the loop exits (including early return or break). - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - try { - for await (const entry of await opendir(rootDir)) { - // Skip hidden dirs (.git, .cache) and non-directories. Accept - // symlinks too — pnpm/Yarn workspaces can symlink packages, and - // detectDsnInPackage gracefully handles non-directory targets. - if ( - entry.name.startsWith(".") || - !(entry.isDirectory() || entry.isSymbolicLink()) - ) { - continue; - } + // Bun's opendir() may not throw on a missing directory — the error + // surfaces when iterating. Wrap the full open+iterate in one try/catch. + // No explicit handle.close() needed: for-await-of auto-closes the Dir + // handle when the loop exits (including early return or break). + // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. + try { + for await (const entry of await opendir(rootDir)) { + // Skip hidden dirs (.git, .cache) and non-directories. Accept + // symlinks too — pnpm/Yarn workspaces can symlink packages, and + // detectDsnInPackage gracefully handles non-directory targets. + if ( + entry.name.startsWith(".") || + !(entry.isDirectory() || entry.isSymbolicLink()) + ) { + continue; + } - packagesScanned += 1; - const pkgDir = join(rootDir, entry.name); - const packagePath = `${monorepoRoot}/${entry.name}`; + packagesScanned += 1; + const pkgDir = join(rootDir, entry.name); + const packagePath = `${monorepoRoot}/${entry.name}`; - const result = await detectDsnInPackage(pkgDir, packagePath); - if (result.dsn) { - dsns.push(result.dsn); - Object.assign(sourceMtimes, result.sourceMtimes); - } + const result = await detectDsnInPackage(pkgDir, packagePath); + if (result.dsn) { + dsns.push(result.dsn); + Object.assign(sourceMtimes, result.sourceMtimes); } - } catch { - // Directory doesn't exist or scan failed, skip this monorepo root } + } catch { + // Directory doesn't exist or scan failed, skip this monorepo root } return { dsns, sourceMtimes, packagesScanned }; diff --git a/packages/cli/src/lib/dsn/project-root.ts b/packages/cli/src/lib/dsn/project-root.ts index fa7542c70e..0373c065ba 100644 --- a/packages/cli/src/lib/dsn/project-root.ts +++ b/packages/cli/src/lib/dsn/project-root.ts @@ -373,9 +373,11 @@ function checkEnvForDsn(dir: string): Promise { // Guard: skip non-regular files (FIFOs, sockets, etc.) that would block. // 1Password streams secrets via symlinked named pipes; Bun.file().text() // blocks indefinitely on these. + // oxlint-disable-next-line no-await-in-loop -- checks env files in priority order and stops at the first DSN if (!(await isRegularFile(filePath, "checkEnvForDsn.stat"))) { continue; } + // oxlint-disable-next-line no-await-in-loop -- checks env files in priority order and stops at the first DSN const content = await readFile(filePath, "utf-8"); const dsn = extractDsnFromEnvContent(content); if (dsn) { diff --git a/packages/cli/src/lib/dsn/resolver.ts b/packages/cli/src/lib/dsn/resolver.ts index 27a9cc0ca1..1a8b87f393 100644 --- a/packages/cli/src/lib/dsn/resolver.ts +++ b/packages/cli/src/lib/dsn/resolver.ts @@ -9,10 +9,12 @@ import { findProjectByDsn, listOrganizations, listProjects, + ORG_FANOUT_CONCURRENCY, resolveOrgDisplayName, } from "../api-client.js"; import { sentry } from "../app-identity.js"; import { getCachedDsn, updateCachedResolution } from "../db/dsn-cache.js"; +import { mapBounded } from "../fan-out.js"; import { getDsnSourceDescription } from "./detector.js"; import type { DetectedDsn, @@ -157,32 +159,32 @@ type AccessibleProject = { * @returns Array of org/project pairs */ export async function getAccessibleProjects(): Promise { - const results: AccessibleProject[] = []; - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. try { const orgs = await listOrganizations(); - for (const org of orgs) { - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - try { - const projects = await listProjects(org.slug); - - for (const project of projects) { - results.push({ + const orgProjects = await mapBounded( + orgs, + async (org): Promise => { + // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. + try { + const projects = await listProjects(org.slug); + return projects.map((project) => ({ org: org.slug, project: project.slug, orgName: org.name, projectName: project.name, - }); + })); + } catch { + // Skip orgs we can't access + return []; } - } catch { - // Skip orgs we can't access - } - } + }, + ORG_FANOUT_CONCURRENCY, + ); + return orgProjects.flat(); } catch { // Not authenticated or API error + return []; } - - return results; } diff --git a/packages/cli/src/lib/dsn/scanner.ts b/packages/cli/src/lib/dsn/scanner.ts index a296a59dd4..adc7c726b5 100644 --- a/packages/cli/src/lib/dsn/scanner.ts +++ b/packages/cli/src/lib/dsn/scanner.ts @@ -67,6 +67,7 @@ export async function scanSpecificFiles( const dsns: DetectedDsn[] = []; const sourceMtimes: Record = {}; + // oxlint-disable no-await-in-loop -- files are checked in priority order, and stopOnFirst returns at the first DSN for (const filename of filenames) { const filepath = join(cwd, filename); @@ -112,6 +113,7 @@ export async function scanSpecificFiles( }); } } + // oxlint-enable no-await-in-loop return { dsns, sourceMtimes }; } diff --git a/packages/cli/src/lib/fs-utils.ts b/packages/cli/src/lib/fs-utils.ts index f58dba46c7..a7a5e49e8e 100644 --- a/packages/cli/src/lib/fs-utils.ts +++ b/packages/cli/src/lib/fs-utils.ts @@ -130,6 +130,7 @@ export async function findFile( ): Promise { for (const extension of extensions) { const candidate = `${basePath}${extension}`; + // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match if (await isRegularFile(candidate, "findFile")) { return candidate; } diff --git a/packages/cli/src/lib/ghcr.ts b/packages/cli/src/lib/ghcr.ts index 356bfb8a40..9f12e207e1 100644 --- a/packages/cli/src/lib/ghcr.ts +++ b/packages/cli/src/lib/ghcr.ts @@ -116,6 +116,7 @@ async function fetchWithRetry( for (let attempt = 0; attempt <= GHCR_MAX_RETRIES; attempt++) { try { + // oxlint-disable-next-line no-await-in-loop -- retries one attempt at a time, with a backoff between attempts const response = await customFetch(url, { ...init, signal: buildSignal(timeout, externalSignal), @@ -606,6 +607,7 @@ export async function listTags( let lastTag: string | undefined; for (;;) { + // oxlint-disable-next-line no-await-in-loop -- each tag page starts after the last tag of the page before const tags = await fetchTagPage(token, lastTag, signal, source); if (tags.length === 0) { break; diff --git a/packages/cli/src/lib/jvm-bundle.ts b/packages/cli/src/lib/jvm-bundle.ts index aa2c2a3e92..0f1653ade9 100644 --- a/packages/cli/src/lib/jvm-bundle.ts +++ b/packages/cli/src/lib/jvm-bundle.ts @@ -11,7 +11,9 @@ import { readdir, readFile, realpath, stat } from "node:fs/promises"; import { extname, join, relative } from "node:path"; +import { mapBounded } from "./fan-out.js"; import { logger } from "./logger.js"; +import { CONCURRENCY_LIMIT } from "./scan/constants.js"; import { ZipWriter } from "./sourcemap/zip.js"; const log = logger.withTag("jvm-bundle"); @@ -329,6 +331,7 @@ async function collectJvmSources( entries.sort((a, b) => a.name.localeCompare(b.name)); for (const entry of entries) { + // oxlint-disable-next-line no-await-in-loop -- walks the tree in sorted order so the bundle is deterministic await processEntry(entry, dir); } } @@ -352,26 +355,29 @@ type ValidatedEntry = { async function readAndValidateFiles( urlToAbsPath: Map, ): Promise { - const validated: ValidatedEntry[] = []; - - for (const [url, absPath] of urlToAbsPath) { - const bundlePath = `files/_/${url.replace(URL_PREFIX_RE, "")}`; - try { - const content = await readFile(absPath); - // Skip non-UTF-8 files (binary files that happen to have JVM extensions) + const entries = await mapBounded( + urlToAbsPath, + async ([url, absPath]): Promise => { + const bundlePath = `files/_/${url.replace(URL_PREFIX_RE, "")}`; try { - new TextDecoder("utf-8", { fatal: true }).decode(content); - } catch { - log.debug(`Skipping non-UTF-8 file: ${absPath}`); - continue; + const content = await readFile(absPath); + // Skip non-UTF-8 files (binary files that happen to have JVM extensions) + try { + new TextDecoder("utf-8", { fatal: true }).decode(content); + } catch { + log.debug(`Skipping non-UTF-8 file: ${absPath}`); + return null; + } + return { url, bundlePath, content }; + } catch (err) { + log.debug(`Failed to read source file: ${absPath}`, err); + return null; } - validated.push({ url, bundlePath, content }); - } catch (err) { - log.debug(`Failed to read source file: ${absPath}`, err); - } - } + }, + CONCURRENCY_LIMIT, + ); - return validated; + return entries.filter((entry) => entry !== null); } /** @@ -392,6 +398,7 @@ async function writeBundle( ); for (const { bundlePath, content } of validatedFiles) { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addEntry(bundlePath, content); } diff --git a/packages/cli/src/lib/oauth.ts b/packages/cli/src/lib/oauth.ts index 423287810e..e30d33b968 100644 --- a/packages/cli/src/lib/oauth.ts +++ b/packages/cli/src/lib/oauth.ts @@ -464,8 +464,10 @@ export async function performDeviceFlow( // Step 2: Poll for token while (Date.now() < timeoutAt) { + // oxlint-disable-next-line no-await-in-loop -- polls the device-code endpoint at the interval the server sets await sleep(pollInterval * 1000); + // oxlint-disable-next-line no-await-in-loop -- polls the device-code endpoint at the interval the server sets const result = await attemptPoll(device_code, pollInterval); switch (result.status) { diff --git a/packages/cli/src/lib/polling.ts b/packages/cli/src/lib/polling.ts index 6d66c41ee7..42c0778881 100644 --- a/packages/cli/src/lib/polling.ts +++ b/packages/cli/src/lib/polling.ts @@ -92,6 +92,7 @@ export async function poll(options: PollOptions): Promise { try { while (Date.now() - startTime < timeoutMs) { + // oxlint-disable-next-line no-await-in-loop -- polls until the state is done or the timeout passes const state = await fetchState(); if (state) { @@ -105,6 +106,7 @@ export async function poll(options: PollOptions): Promise { } } + // oxlint-disable-next-line no-await-in-loop -- polls until the state is done or the timeout passes await sleepMs(pollIntervalMs); } diff --git a/packages/cli/src/lib/scan/concurrent.ts b/packages/cli/src/lib/scan/concurrent.ts index e563032679..a1bf533f59 100644 --- a/packages/cli/src/lib/scan/concurrent.ts +++ b/packages/cli/src/lib/scan/concurrent.ts @@ -186,6 +186,7 @@ export async function* mapFilesConcurrentStream( if (producerDone) { break; } + // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await awake; resetAwake(); } diff --git a/packages/cli/src/lib/scan/grep.ts b/packages/cli/src/lib/scan/grep.ts index b26a6e23b9..7fcb37c9d2 100644 --- a/packages/cli/src/lib/scan/grep.ts +++ b/packages/cli/src/lib/scan/grep.ts @@ -508,6 +508,7 @@ async function* grepViaWorkers( notifyPending = false; continue; } + // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await new Promise((resolve) => { if (notifyPending) { notifyPending = false; diff --git a/packages/cli/src/lib/scan/walker.ts b/packages/cli/src/lib/scan/walker.ts index fa48dace5c..1472e58fca 100644 --- a/packages/cli/src/lib/scan/walker.ts +++ b/packages/cli/src/lib/scan/walker.ts @@ -201,6 +201,7 @@ async function processDir( if (isCancelled()) { return; } + // oxlint-disable-next-line no-await-in-loop -- entries are cheap to process and cancellation is checked between them; directories are the unit of concurrency const result = await processEntry(entry, frame, ctx); if (result !== null) { push(result); @@ -297,6 +298,7 @@ async function* walkFilesImpl(opts: WalkOptions): AsyncGenerator { */ async function* walkSerial(ctx: WalkContext): AsyncGenerator { const { cfg, matcher, stack } = ctx; + // oxlint-disable no-await-in-loop -- the serial walker visits one directory and one entry at a time; walkParallel is the concurrent path while (stack.length > 0) { checkAborted(cfg.signal); const frame = stack.pop() as DirFrame; @@ -325,6 +327,7 @@ async function* walkSerial(ctx: WalkContext): AsyncGenerator { } } } + // oxlint-enable no-await-in-loop } /** @@ -459,11 +462,13 @@ async function* walkParallel(ctx: WalkContext): AsyncGenerator { if (activeWorkers === 0) { return; } + // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await workerAwake; continue; } activeWorkers += 1; try { + // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await processDir(frame, ctx, push, () => cancelled); } finally { activeWorkers -= 1; @@ -522,6 +527,7 @@ async function* walkParallel(ctx: WalkContext): AsyncGenerator { if (stack.length === 0 && activeWorkers === 0) { break; } + // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await consumerAwake; resetConsumerAwake(); } diff --git a/packages/cli/src/lib/sentryclirc-import.ts b/packages/cli/src/lib/sentryclirc-import.ts index 793d5d6bc7..e95dea56b3 100644 --- a/packages/cli/src/lib/sentryclirc-import.ts +++ b/packages/cli/src/lib/sentryclirc-import.ts @@ -269,15 +269,13 @@ export async function discoverRcFiles( } // Check global fallback paths (config-dir first, then homedir) - for (const globalPath of globalPathSet) { - if (seen.has(globalPath)) { - continue; - } - seen.add(globalPath); - const file = await readRcFile( - globalPath, - classifyRcFileLocation(globalPath), - ); + const globalFiles = await Promise.all( + // The walk above skips these paths, so none of them is in `seen`. + [...globalPathSet].map((globalPath) => + readRcFile(globalPath, classifyRcFileLocation(globalPath)), + ), + ); + for (const file of globalFiles) { if (file) { files.push(file); } @@ -779,12 +777,12 @@ function clearImportRecord(): void { /** Verify all source files in a record still match their stored hashes */ async function verifyRecordHashes(record: ImportRecord): Promise { - for (const source of record.sources) { - if (!(await verifyFileHash(source.path, source.contentHash))) { - return false; - } - } - return true; + const matches = await Promise.all( + record.sources.map((source) => + verifyFileHash(source.path, source.contentHash), + ), + ); + return matches.every(Boolean); } /** diff --git a/packages/cli/src/lib/sentryclirc.ts b/packages/cli/src/lib/sentryclirc.ts index 8e26ae9a93..fc16aa5740 100644 --- a/packages/cli/src/lib/sentryclirc.ts +++ b/packages/cli/src/lib/sentryclirc.ts @@ -247,6 +247,7 @@ export async function applyGlobalFallbacks( if (isComplete(result)) { break; } + // oxlint-disable-next-line no-await-in-loop -- later global files fill only the keys the earlier ones left unset, and the loop stops once the config is complete await tryApplyFile(result, globalPath, true); } } diff --git a/packages/cli/src/lib/snapshots/archive.ts b/packages/cli/src/lib/snapshots/archive.ts index d1908fcebb..2356ca14e3 100644 --- a/packages/cli/src/lib/snapshots/archive.ts +++ b/packages/cli/src/lib/snapshots/archive.ts @@ -118,6 +118,7 @@ export async function extractZipStream( let current = await iterator.next(); while (!current.done) { const chunk = current.value; + // oxlint-disable-next-line no-await-in-loop -- drives the iterator one step at a time current = await iterator.next(); unzip.push(chunk, current.done === true); pushedAny = true; diff --git a/packages/cli/src/lib/sourcemap/inject.ts b/packages/cli/src/lib/sourcemap/inject.ts index 1491edfd4b..5a12e7a4d0 100644 --- a/packages/cli/src/lib/sourcemap/inject.ts +++ b/packages/cli/src/lib/sourcemap/inject.ts @@ -11,8 +11,10 @@ import ignore from "ignore"; import picomatch from "picomatch"; import { NODE_MODULES_DIRNAME } from "../constants.js"; import { ValidationError } from "../errors.js"; +import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; import { isLikelyBinary } from "../scan/binary.js"; +import { CONCURRENCY_LIMIT } from "../scan/constants.js"; import { walkFiles } from "../scan/index.js"; import { hasDebugIdRegistration, @@ -173,32 +175,39 @@ export async function injectDirectory( options.include, ); + if (options.dryRun) { + return await mapBounded( + filePairs, + async ({ jsPath, map }): Promise => { + // Match the real run's ID precedence and runtime registration check. + const jsBytes = await readFile(jsPath); + const js = jsBytes.toString("utf-8"); + const binary = isLikelyBinary(jsBytes); + const existing = await readPairDebugId(js, map); + // An ID the bundle only registers at runtime is reused; the file still + // changes, since the comment and the map ID are written. + const registered = + existing || binary ? undefined : readRegisteredDebugId(js); + return { + jsPath, + map, + mapPath: map.kind === "external" ? map.mapPath : undefined, + injected: !( + existing && + (binary || hasDebugIdRegistration(js, existing)) + ), + debugId: existing ?? registered ?? "(pending)", + }; + }, + CONCURRENCY_LIMIT, + ); + } + const results: InjectResult[] = []; for (const { jsPath, map } of filePairs) { const mapPath = map.kind === "external" ? map.mapPath : undefined; - if (options.dryRun) { - // Match the real run's ID precedence and runtime registration check. - const jsBytes = await readFile(jsPath); - const js = jsBytes.toString("utf-8"); - const binary = isLikelyBinary(jsBytes); - const existing = await readPairDebugId(js, map); - // An ID the bundle only registers at runtime is reused; the file still - // changes, since the comment and the map ID are written. - const registered = - existing || binary ? undefined : readRegisteredDebugId(js); - results.push({ - jsPath, - map, - mapPath, - injected: !( - existing && - (binary || hasDebugIdRegistration(js, existing)) - ), - debugId: existing ?? registered ?? "(pending)", - }); - continue; - } if (map.kind === "external") { + // oxlint-disable-next-line no-await-in-loop -- two bundles can reference one map file, so writes run one pair at a time const r = await injectDebugId(jsPath, map.mapPath); results.push({ jsPath, @@ -208,6 +217,7 @@ export async function injectDirectory( debugId: r.debugId, }); } else { + // oxlint-disable-next-line no-await-in-loop -- two bundles can reference one map file, so writes run one pair at a time const r = await injectInlineDebugId(jsPath, map.decoded); results.push({ jsPath, @@ -236,24 +246,26 @@ export async function injectDirectory( export async function readExistingDebugIds( pairs: FilePair[], ): Promise { - const results: InjectResult[] = []; - for (const { jsPath, map } of pairs) { - const jsBytes = await readFile(jsPath); - const js = jsBytes.toString("utf-8"); - const existing = await readPairDebugId(js, map); - const registered = - existing || isLikelyBinary(jsBytes) - ? undefined - : readRegisteredDebugId(js); - results.push({ - jsPath, - map, - mapPath: map.kind === "external" ? map.mapPath : undefined, - injected: false, - debugId: existing ?? registered ?? "", - }); - } - return results; + return await mapBounded( + pairs, + async ({ jsPath, map }): Promise => { + const jsBytes = await readFile(jsPath); + const js = jsBytes.toString("utf-8"); + const existing = await readPairDebugId(js, map); + const registered = + existing || isLikelyBinary(jsBytes) + ? undefined + : readRegisteredDebugId(js); + return { + jsPath, + map, + mapPath: map.kind === "external" ? map.mapPath : undefined, + injected: false, + debugId: existing ?? registered ?? "", + }; + }, + CONCURRENCY_LIMIT, + ); } /** @@ -386,6 +398,7 @@ async function readDirectiveTail(filePath: string): Promise { const readSize = Math.min(DIRECTIVE_CHUNK_BYTES, end); const offset = end - readSize; const buf = Buffer.alloc(readSize); + // oxlint-disable-next-line no-await-in-loop -- reads the file backwards into one reused buffer await fh.read(buf, 0, readSize, offset); chunks.unshift(buf); collected += readSize; diff --git a/packages/cli/src/lib/sourcemap/zip.ts b/packages/cli/src/lib/sourcemap/zip.ts index 69ca49f2f7..5291559184 100644 --- a/packages/cli/src/lib/sourcemap/zip.ts +++ b/packages/cli/src/lib/sourcemap/zip.ts @@ -283,10 +283,12 @@ export class ZipWriter { fill(); for (let result = inFlight.shift(); result; result = inFlight.shift()) { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order while later reads run ahead const settled = await result; if (!settled.ok) { throw settled.error; } + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order while later reads run ahead await this.writeEntry(settled.entry); bytesInFlight -= settled.entry.uncompressedSize; fill(); diff --git a/packages/cli/src/lib/target-scope.ts b/packages/cli/src/lib/target-scope.ts index 99d977d342..cba011bbbb 100644 --- a/packages/cli/src/lib/target-scope.ts +++ b/packages/cli/src/lib/target-scope.ts @@ -242,6 +242,7 @@ async function filterToProject( ...requested, ...url.searchParams.getAll("projectSlug"), ]) { + // oxlint-disable-next-line no-await-in-loop -- stops at the first project outside the scope, before more lookups are sent if (!(await anyScopeProject(context, [project]))) { throw outsideScope(subject, scope); } @@ -299,12 +300,14 @@ async function lookUpFirst( return; } for (const attempt of widerQuery ? [query, widerQuery] : [query]) { + // oxlint-disable-next-line no-await-in-loop -- sends the wider query only when the first one does not list the item const response = await context.send( `${context.api}${path}${attempt ? `?${attempt}` : ""}`, ); if (!response.ok) { return response; } + // oxlint-disable-next-line no-await-in-loop -- sends the wider query only when the first one does not list the item if (listed !== undefined && lists(await readJson(response), listed)) { foundInScope.add(key); } @@ -373,6 +376,7 @@ async function applyRule( throw outsideScope(subject, scope); } for (const target of targets) { + // oxlint-disable-next-line no-await-in-loop -- returns the first failed lookup, before more lookups are sent const failed = await lookUpFirst(context, target); if (failed) { return { input, response: failed, verify: NOTHING_TO_VERIFY }; diff --git a/packages/cli/src/lib/upgrade.ts b/packages/cli/src/lib/upgrade.ts index 9ad637e58f..ecdc178845 100644 --- a/packages/cli/src/lib/upgrade.ts +++ b/packages/cli/src/lib/upgrade.ts @@ -416,6 +416,7 @@ async function detectLegacyInstallationMethod(): Promise { const packageManagers: PackageManager[] = ["npm", "pnpm", "bun", "yarn"]; for (const pm of packageManagers) { + // oxlint-disable-next-line no-await-in-loop -- checks package managers in popularity order and stops at the first match if (await isInstalledWith(pm)) { return pm; } @@ -497,6 +498,7 @@ export async function fetchLatestFromGitHubWithSource( const visitedPages = new Set([firstPage]); const versions: string[] = []; for (;;) { + // oxlint-disable-next-line no-await-in-loop -- each release page comes from the Link header of the page before const data = await parseUpgradeJson( response, signal, @@ -521,6 +523,7 @@ export async function fetchLatestFromGitHubWithSource( ); } visitedPages.add(nextPage); + // oxlint-disable-next-line no-await-in-loop -- each release page comes from the Link header of the page before response = await fetchWithUpgradeError( nextPage, { headers: getGitHubHeaders(), ...(signal && { signal }) }, @@ -1173,6 +1176,7 @@ async function waitForBinaryVisible(path: string): Promise { log.debug( `Downloaded binary not yet visible at ${path}, retrying in ${delay}ms (attempt ${attempt}/${VERIFY_MAX_ATTEMPTS})`, ); + // oxlint-disable-next-line no-await-in-loop -- retries one attempt at a time, with a backoff between attempts await setTimeout(delay); } throw new UpgradeError( diff --git a/packages/cli/src/lib/walk-up.ts b/packages/cli/src/lib/walk-up.ts index 2516ff2d38..6df3a9cc5a 100644 --- a/packages/cli/src/lib/walk-up.ts +++ b/packages/cli/src/lib/walk-up.ts @@ -29,6 +29,7 @@ export async function* walkUpFrom(startDir: string): AsyncGenerator { for (;;) { let real: string; try { + // oxlint-disable-next-line no-await-in-loop -- walks up one parent directory at a time real = await realpath(current); } catch { // Can't resolve (broken symlink, permission denied) — stop walking diff --git a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts index ece063f07a..9e4cb70dc3 100644 --- a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts +++ b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts @@ -520,6 +520,7 @@ async function createOrMergeNextJsFiles( const configVariants = ["server", "edge"] as const; for (const configVariant of configVariants) { + // oxlint-disable-next-line no-await-in-loop -- each config step can prompt the user, so the steps run in turn await traceStep(`create-sentry-${configVariant}-config`, async () => { const jsConfig = `sentry.${configVariant}.config.js`; const tsConfig = `sentry.${configVariant}.config.ts`; diff --git a/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts b/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts index c0d43e6133..c6605284fb 100644 --- a/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts @@ -214,6 +214,7 @@ export async function createConfigFiles( const configVariants = ["server", "client"] as const; for (const configVariant of configVariants) { + // oxlint-disable-next-line no-await-in-loop -- each config step can prompt the user, so the steps run in turn await traceStep(`create-sentry-${configVariant}-config`, async () => { const jsConfig = `sentry.${configVariant}.config.js`; const tsConfig = `sentry.${configVariant}.config.ts`; diff --git a/packages/cli/src/lib/wizard/react-native/javascript.ts b/packages/cli/src/lib/wizard/react-native/javascript.ts index a4ab339717..6812905a84 100644 --- a/packages/cli/src/lib/wizard/react-native/javascript.ts +++ b/packages/cli/src/lib/wizard/react-native/javascript.ts @@ -261,6 +261,7 @@ export function getMainAppFilePath(): Promise { return traceStep("find-app-js-file", async () => { for (const dir of APP_FILE_DIRS) { for (const name of APP_FILE_NAMES) { + // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match const match = await findFile(path.join(dir, name), APP_FILE_EXTENSIONS); if (match) { return match; diff --git a/packages/cli/src/lib/wizard/remix/codemods/express-server.ts b/packages/cli/src/lib/wizard/remix/codemods/express-server.ts index 97b8227d4e..aa10298287 100644 --- a/packages/cli/src/lib/wizard/remix/codemods/express-server.ts +++ b/packages/cli/src/lib/wizard/remix/codemods/express-server.ts @@ -18,6 +18,7 @@ export async function findCustomExpressServerImplementation() { ]; for (const filePath of possiblePaths) { + // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match const filename = await findFile(filePath); if (!filename) { @@ -30,6 +31,7 @@ export async function findCustomExpressServerImplementation() { continue; } + // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match const fileMod = await loadFile(filename); const createRequestHandlerImport = fileMod.imports.$items.find( (imp) => diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts index bbff682d1d..a80c7a6aac 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -77,6 +77,7 @@ export async function configureSentryCLI( let validPath = false; let relativeArtifactPath: string | undefined; do { + // oxlint-disable-next-line no-await-in-loop -- prompts the user until they give a usable path const rawArtifactPath = await abortIfCancelled( clack.text({ message: "Where are your build artifacts located?", @@ -111,6 +112,7 @@ export async function configureSentryCLI( } const runBuildOrEnterPathOrProceed = + // oxlint-disable-next-line no-await-in-loop -- prompts the user until they give a usable path await askToRunBuildOrEnterPathOrProceed({ relativeArtifactPath, }); diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts index 44ba1f27d1..c371991504 100644 --- a/packages/cli/src/lib/wizard/utils/clack/index.ts +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -1628,6 +1628,7 @@ export async function featureSelectionPrompt>( const selectedFeatures: Record = {}; for (const feature of features) { + // oxlint-disable-next-line no-await-in-loop -- asks the feature questions one at a time selectedFeatures[feature.id] = await askFlagQuestion( feature.flag, feature, diff --git a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts index b63d30fd31..de7ed67a28 100644 --- a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts +++ b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts @@ -554,6 +554,7 @@ export async function offerProjectScopedMcpConfig( Sentry.setTag("mcp-editors-count", editors.length); // Configure each selected editor + // oxlint-disable no-await-in-loop -- configures one editor at a time; each step can prompt or print instructions for (const editor of editors) { // Track which editor is being configured Sentry.setTag("mcp-editor", editor); @@ -655,4 +656,5 @@ export async function offerProjectScopedMcpConfig( } } } + // oxlint-enable no-await-in-loop } diff --git a/packages/cli/src/lib/wrangler.ts b/packages/cli/src/lib/wrangler.ts index 89ef25737e..ccf7ae72be 100644 --- a/packages/cli/src/lib/wrangler.ts +++ b/packages/cli/src/lib/wrangler.ts @@ -391,6 +391,7 @@ async function hasWranglerConfig( for (const filename of WRANGLER_CONFIG_FILES) { // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. try { + // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match await access(join(cwd, filename)); return true; } catch { diff --git a/packages/cli/test/lib/dsn/errors.test.ts b/packages/cli/test/lib/dsn/errors.test.ts index cf1bae8277..1ac318f829 100644 --- a/packages/cli/test/lib/dsn/errors.test.ts +++ b/packages/cli/test/lib/dsn/errors.test.ts @@ -26,6 +26,7 @@ vi.mock("../../../src/lib/api-client.js", () => ({ listOrganizations: mockListOrganizations, listProjects: mockListProjects, findProjectByDsn: vi.fn(() => Promise.resolve(null)), + ORG_FANOUT_CONCURRENCY: 5, })); describe("formatConflictError", () => { diff --git a/packages/cli/test/lib/dsn/resolver.test.ts b/packages/cli/test/lib/dsn/resolver.test.ts index 00f49653f3..594061a024 100644 --- a/packages/cli/test/lib/dsn/resolver.test.ts +++ b/packages/cli/test/lib/dsn/resolver.test.ts @@ -35,6 +35,7 @@ vi.mock("../../../src/lib/api-client.js", () => ({ listProjects: mockListProjects, findProjectByDsn: mockFindProjectByDsn, resolveOrgDisplayName: mockResolveOrgDisplayName, + ORG_FANOUT_CONCURRENCY: 5, })); // Now import the resolver after mocking diff --git a/packages/http/src/policy.ts b/packages/http/src/policy.ts index 48c5f6bce8..93db35970c 100644 --- a/packages/http/src/policy.ts +++ b/packages/http/src/policy.ts @@ -157,9 +157,11 @@ async function policyRequestHeaders( // Lowercase names, as `http-cache-semantics` stores them and `Vary` // matching compares them. for (const [rawName, value] of Object.entries(headers)) { - const name = rawName.toLowerCase(); - result[name] = - name === "authorization" && value ? await sha256Hex(value) : value; + result[rawName.toLowerCase()] = value; + } + const authorization = result["authorization"]; + if (authorization) { + result["authorization"] = await sha256Hex(authorization); } return result; } diff --git a/packages/http/src/retry.ts b/packages/http/src/retry.ts index 4d5685d62d..5dc7d3bc5c 100644 --- a/packages/http/src/retry.ts +++ b/packages/http/src/retry.ts @@ -278,6 +278,7 @@ export async function fetchWithRetry( for (let attempt = 0; ; attempt++) { let response: Response; try { + // oxlint-disable-next-line no-await-in-loop -- retries are sequential by definition response = await send(attempt); } catch (error) { const delayMs = @@ -288,6 +289,7 @@ export async function fetchWithRetry( throw error; } options.onRetry?.({ attempt, delayMs, status: undefined, error }); + // oxlint-disable-next-line no-await-in-loop -- waits out the backoff before the next attempt await sleep(delayMs, signal); waitedMs += delayMs; continue; @@ -301,6 +303,7 @@ export async function fetchWithRetry( } response.body?.cancel().catch(() => undefined); options.onRetry?.({ attempt, delayMs, status: response.status }); + // oxlint-disable-next-line no-await-in-loop -- waits out the backoff before the next attempt await sleep(delayMs, signal); waitedMs += delayMs; } diff --git a/packages/mcp-core/scripts/generate-otel-namespaces.ts b/packages/mcp-core/scripts/generate-otel-namespaces.ts index 541ebcffbd..b976c016f2 100644 --- a/packages/mcp-core/scripts/generate-otel-namespaces.ts +++ b/packages/mcp-core/scripts/generate-otel-namespaces.ts @@ -343,6 +343,7 @@ async function generateNamespaceFiles() { } } + // oxlint-disable-next-line no-await-in-loop -- fetches one namespace at a time to stay under GitHub's raw-content rate limits const yamlContent = await fetchYamlContent(namespace); if (!yamlContent) { console.log(`⏭️ Skipping ${namespace} (no registry.yaml found)`); diff --git a/packages/mcp-core/scripts/generate-platform-setup.ts b/packages/mcp-core/scripts/generate-platform-setup.ts index 8cca97d436..5f964d17c1 100644 --- a/packages/mcp-core/scripts/generate-platform-setup.ts +++ b/packages/mcp-core/scripts/generate-platform-setup.ts @@ -208,6 +208,7 @@ async function main() { for (const platform of platforms) { const linkPath = DOCS_PATH_OVERRIDES[platform.id] ?? new URL(platform.link).pathname; + // oxlint-disable-next-line no-await-in-loop -- resolves one platform at a time to keep the load on docs.sentry.io low const path = normalizePath(await resolveRedirects(linkPath)); // The platform list page is not a setup guide (for example `other`). if (path === "platforms" || !index.has(path)) { diff --git a/packages/mcp-core/scripts/measure-ui-views.ts b/packages/mcp-core/scripts/measure-ui-views.ts index d074464fb9..6b81af293d 100644 --- a/packages/mcp-core/scripts/measure-ui-views.ts +++ b/packages/mcp-core/scripts/measure-ui-views.ts @@ -89,6 +89,7 @@ async function readViews(): Promise { if (budget === undefined) { throw new Error(`${uri} is not in UI_RESOURCES, so it has no budget`); } + // oxlint-disable-next-line no-await-in-loop -- reads go over one stdio MCP connection and report budgets in resource order const { contents } = await client.readResource({ uri }); for (const content of contents) { const body = diff --git a/packages/mcp-core/scripts/validate-skills-mapping.ts b/packages/mcp-core/scripts/validate-skills-mapping.ts index 93bb583bb8..8cebd6cc17 100644 --- a/packages/mcp-core/scripts/validate-skills-mapping.ts +++ b/packages/mcp-core/scripts/validate-skills-mapping.ts @@ -57,18 +57,13 @@ function getToolsForSkill(skill: Skill): string[] { * Validate skills-to-tools-to-scopes mapping */ async function validateMapping(): Promise { - const results: ValidationResult[] = []; - - for (const skillId of Object.keys(SKILLS) as Skill[]) { - const enabledTools = getToolsForSkill(skillId); - const requiredScopes = await getScopesForSkills(new Set([skillId])); - - results.push({ + const results: ValidationResult[] = await Promise.all( + (Object.keys(SKILLS) as Skill[]).map(async (skillId) => ({ skill: skillId, - enabledTools, - requiredScopes, - }); - } + enabledTools: getToolsForSkill(skillId), + requiredScopes: await getScopesForSkills(new Set([skillId])), + })), + ); return results; } diff --git a/packages/mcp-core/src/api-client/client.ts b/packages/mcp-core/src/api-client/client.ts index cd0d03ba10..accafd5d33 100644 --- a/packages/mcp-core/src/api-client/client.ts +++ b/packages/mcp-core/src/api-client/client.ts @@ -5117,12 +5117,14 @@ export class SentryApiService { queryParams.set("cursor", cursor); } + // oxlint-disable-next-line no-await-in-loop -- cursor pagination: each page needs the previous page's cursor const response = await this.request( apiPath`/organizations/${organizationSlug}/agents/conversations/${conversationId}/` + `?${queryParams.toString()}`, undefined, opts, ); + // oxlint-disable-next-line no-await-in-loop -- cursor pagination: each page needs the previous page's cursor const body = await readJsonResponse(response); const details = AIConversationDetailsResponseSchema.parse(body); // Pages repeat the same conversation-scoped title. diff --git a/packages/mcp-core/src/internal/fetch-utils.ts b/packages/mcp-core/src/internal/fetch-utils.ts index 1d04390295..a9e8f5dee3 100644 --- a/packages/mcp-core/src/internal/fetch-utils.ts +++ b/packages/mcp-core/src/internal/fetch-utils.ts @@ -91,6 +91,7 @@ export async function retryWithBackoff( for (let attempt = 0; attempt <= maxRetries; attempt++) { try { + // oxlint-disable-next-line no-await-in-loop -- retries are sequential by definition return await fn(); } catch (error) { lastError = error; @@ -103,6 +104,7 @@ export async function retryWithBackoff( } // Wait before retrying with exponential backoff + // oxlint-disable-next-line no-await-in-loop -- waits out the backoff before the next attempt await sleep(delay, signal); delay = Math.min(delay * 2, 30000); // Cap at 30 seconds } diff --git a/packages/mcp-core/src/tools/catalog/analyze-issue-with-seer.ts b/packages/mcp-core/src/tools/catalog/analyze-issue-with-seer.ts index 3526080805..250be51769 100644 --- a/packages/mcp-core/src/tools/catalog/analyze-issue-with-seer.ts +++ b/packages/mcp-core/src/tools/catalog/analyze-issue-with-seer.ts @@ -230,10 +230,12 @@ export default defineTool({ } // Wait before next poll + // oxlint-disable-next-line no-await-in-loop -- polls Seer until the run finishes await sleep(SEER_POLLING_INTERVAL, context.signal); // Refresh state with error handling try { + // oxlint-disable-next-line no-await-in-loop -- polls Seer until the run finishes autofixState = await retryWithBackoff( () => apiService.getAutofixState({ diff --git a/packages/mcp-core/src/tools/catalog/get-doc.ts b/packages/mcp-core/src/tools/catalog/get-doc.ts index fa9e3d7eaa..aa859e5726 100644 --- a/packages/mcp-core/src/tools/catalog/get-doc.ts +++ b/packages/mcp-core/src/tools/catalog/get-doc.ts @@ -87,6 +87,7 @@ export default defineTool({ // off the allowed hosts is reported as a missing page. let response: Response; for (let redirects = 0; ; redirects++) { + // oxlint-disable-next-line no-await-in-loop -- follows redirects one hop at a time so each hop is checked against the allowlist response = await fetchWithTimeout( docUrl, { diff --git a/packages/mcp-core/src/tools/support/alert-rule-connections.ts b/packages/mcp-core/src/tools/support/alert-rule-connections.ts index 5b9cc9b54a..66b2d99c52 100644 --- a/packages/mcp-core/src/tools/support/alert-rule-connections.ts +++ b/packages/mcp-core/src/tools/support/alert-rule-connections.ts @@ -76,6 +76,7 @@ export async function resolveAlertRuleConnections( [params.removeProjectSlugs, params.removeDetectorIds, removals], ] as const) { for (const projectSlug of new Set(projectSlugs ?? [])) { + // oxlint-disable-next-line no-await-in-loop -- the project scope check must stop before more lookups go out const project = await api.getProject({ organizationSlug: params.organizationSlug, projectSlugOrId: projectSlug, @@ -87,6 +88,7 @@ export async function resolveAlertRuleConnections( hasEvidence: projectId === params.scopedProject?.id, }); + // oxlint-disable-next-line no-await-in-loop -- the project scope check must stop before more lookups go out const detectors = await fetchEveryPage(async (cursor) => { const page = await api.listDetectorsPage({ organizationSlug: params.organizationSlug, @@ -128,6 +130,7 @@ export async function resolveAlertRuleConnections( removals.add(detectorId); continue; } + // oxlint-disable-next-line no-await-in-loop -- the project scope check must stop before more lookups go out const detector = await api.getDetector({ organizationSlug: params.organizationSlug, detectorId, diff --git a/packages/mcp-core/src/tools/support/alert-rule-details.ts b/packages/mcp-core/src/tools/support/alert-rule-details.ts index 7622728454..ba89bd31c6 100644 --- a/packages/mcp-core/src/tools/support/alert-rule-details.ts +++ b/packages/mcp-core/src/tools/support/alert-rule-details.ts @@ -217,51 +217,53 @@ export async function getAlertRuleDetails( projectSlugOrId: scopedProjectSlug, }) : undefined; - const sources: AlertRuleDetails["sources"] = []; - for (const id of rule.detectorIds ?? []) { - try { - const detector = await api.getDetector({ - organizationSlug, - detectorId: id, - }); - if ( - project && - detector.projectId !== null && - String(detector.projectId) !== String(project.id) - ) { - sources.push({ id: String(id), status: "outside_project_constraint" }); - continue; - } - sources.push({ - id: String(detector.id), - status: "available", - name: detector.name, - type: detector.type, - projectId: - detector.projectId === null ? null : String(detector.projectId), - enabled: detector.enabled, - config: toDetectorConfig(detector.type, detector.config), - conditionGroup: detector.conditionGroup - ? conditionGroupSchema.parse(detector.conditionGroup) - : null, - dataSources: (detector.dataSources ?? []).map(sourceDetails), - }); - } catch (error) { - if ( - !( - error instanceof ApiNotFoundError || - error instanceof ApiPermissionError - ) - ) { - throw error; - } - sources.push({ - id: String(id), - status: "unavailable", - reason: "Not found or not accessible.", - }); - } - } + const sources: AlertRuleDetails["sources"] = await Promise.all( + (rule.detectorIds ?? []).map( + async (id): Promise => { + try { + const detector = await api.getDetector({ + organizationSlug, + detectorId: id, + }); + if ( + project && + detector.projectId !== null && + String(detector.projectId) !== String(project.id) + ) { + return { id: String(id), status: "outside_project_constraint" }; + } + return { + id: String(detector.id), + status: "available", + name: detector.name, + type: detector.type, + projectId: + detector.projectId === null ? null : String(detector.projectId), + enabled: detector.enabled, + config: toDetectorConfig(detector.type, detector.config), + conditionGroup: detector.conditionGroup + ? conditionGroupSchema.parse(detector.conditionGroup) + : null, + dataSources: (detector.dataSources ?? []).map(sourceDetails), + }; + } catch (error) { + if ( + !( + error instanceof ApiNotFoundError || + error instanceof ApiPermissionError + ) + ) { + throw error; + } + return { + id: String(id), + status: "unavailable", + reason: "Not found or not accessible.", + }; + } + }, + ), + ); const projectIds = project ? scope.projectIds.filter((id) => id === String(project.id)) : scope.projectIds; diff --git a/packages/mcp-core/src/tools/support/issue-linking/app.ts b/packages/mcp-core/src/tools/support/issue-linking/app.ts index bac222abc2..53ec41098f 100644 --- a/packages/mcp-core/src/tools/support/issue-linking/app.ts +++ b/packages/mcp-core/src/tools/support/issue-linking/app.ts @@ -214,6 +214,7 @@ async function resolveFields( if (field.type === "select") { let choices = field.choices ?? field.options ?? []; if (field.uri) { + // oxlint-disable-next-line no-await-in-loop -- a field's options depend on the values chosen for earlier fields const options = await api.getSentryAppExternalRequestOptions({ installationUuid, uri: validateUri(field.uri), diff --git a/packages/mcp-core/src/tools/support/search-events/seer.ts b/packages/mcp-core/src/tools/support/search-events/seer.ts index 105559ac35..1d203cfe6a 100644 --- a/packages/mcp-core/src/tools/support/search-events/seer.ts +++ b/packages/mcp-core/src/tools/support/search-events/seer.ts @@ -304,6 +304,7 @@ async function runSearchAgent({ const deadline = Date.now() + SEER_SEARCH_AGENT_TIMEOUT; while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls the search agent until it finishes or times out const { session } = await apiService.getSearchAgentState({ organizationSlug, runId: run.sentry_run_id, @@ -325,6 +326,7 @@ async function runSearchAgent({ return null; } + // oxlint-disable-next-line no-await-in-loop -- polls the search agent until it finishes or times out await sleep(SEER_SEARCH_AGENT_POLLING_INTERVAL, apiService.signal); } diff --git a/packages/mcp-test-client/src/index.ts b/packages/mcp-test-client/src/index.ts index 87ce5d1430..55cf839e9c 100644 --- a/packages/mcp-test-client/src/index.ts +++ b/packages/mcp-test-client/src/index.ts @@ -201,6 +201,7 @@ program for (;;) { try { + // oxlint-disable-next-line no-await-in-loop -- interactive prompt: reads one line at a time const userInput = await rl.question(chalk.gray("> ")); if ( @@ -212,6 +213,7 @@ program } if (userInput.trim()) { + // oxlint-disable-next-line no-await-in-loop -- interactive prompt: answers one line at a time await runAgent(connection, userInput, agentConfig); // Add newline after response before next prompt console.log(); diff --git a/packages/toolkit-core/src/mcp-limits.ts b/packages/toolkit-core/src/mcp-limits.ts index 59ceaf4a66..fc9101a7cd 100644 --- a/packages/toolkit-core/src/mcp-limits.ts +++ b/packages/toolkit-core/src/mcp-limits.ts @@ -44,12 +44,14 @@ export async function readBoundedBody( const chunks: Uint8Array[] = []; let received = 0; for (;;) { + // oxlint-disable-next-line no-await-in-loop -- reads the request body stream chunk by chunk const { done, value } = await reader.read(); if (done) { break; } received += value.byteLength; if (received > MAX_MCP_REQUEST_BODY_BYTES) { + // oxlint-disable-next-line no-await-in-loop -- stops reading once the body is over the limit await reader.cancel(); return undefined; } diff --git a/scripts/cli-nightly-verify.mjs b/scripts/cli-nightly-verify.mjs index 20dd249f48..824f3c1a96 100644 --- a/scripts/cli-nightly-verify.mjs +++ b/scripts/cli-nightly-verify.mjs @@ -58,6 +58,7 @@ async function main() { ); let failed = false; for (const tag of ["nightly", `nightly-${version}`]) { + // oxlint-disable-next-line no-await-in-loop -- checks the two tags in order so the log lists them in order const manifest = await getJson( `https://ghcr.io/v2/${REPOSITORY}/manifests/${tag}`, { diff --git a/scripts/cloudflare-deployment.mjs b/scripts/cloudflare-deployment.mjs index 353683882f..6189614b19 100644 --- a/scripts/cloudflare-deployment.mjs +++ b/scripts/cloudflare-deployment.mjs @@ -258,7 +258,9 @@ export async function listSettled( attempt < SETTLE_ATTEMPTS && !settled(deployments); attempt++ ) { + // oxlint-disable-next-line no-await-in-loop -- polls until the deployments settle await sleep(SETTLE_DELAY_MS); + // oxlint-disable-next-line no-await-in-loop -- polls until the deployments settle deployments = await list(env); } return deployments; @@ -309,11 +311,13 @@ async function waitUntilReadable( const deadline = now() + READABLE_TIMEOUT_MS; let streak = 0; while (now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls until every version is readable const readable = await Promise.all( versionIds.map((versionId) => readVersion(env, versionId, worker)), ); streak = readable.every(Boolean) ? streak + 1 : 0; if (streak === READABLE_STREAK) return; + // oxlint-disable-next-line no-await-in-loop -- polls until every version is readable await sleep(SETTLE_DELAY_MS); } throw new DeploymentError( diff --git a/scripts/generate-parsers.mjs b/scripts/generate-parsers.mjs index 066e5b3b39..fcadd31c20 100644 --- a/scripts/generate-parsers.mjs +++ b/scripts/generate-parsers.mjs @@ -86,26 +86,29 @@ const grammars = (await readdir(grammarDir)).filter((file) => ); await mkdir(outputDir, { recursive: true }); -for (const file of grammars) { - const name = file.slice(0, -".pegjs".length); - const grammarPath = join(grammarDir, file); - const declarationsPath = join(grammarDir, `${name}.d.ts`); - if (!existsSync(declarationsPath)) { - throw new Error(`${declarationsPath} is missing`); - } +// Each grammar writes its own output files, so they generate concurrently. +await Promise.all( + grammars.map(async (file) => { + const name = file.slice(0, -".pegjs".length); + const grammarPath = join(grammarDir, file); + const declarationsPath = join(grammarDir, `${name}.d.ts`); + if (!existsSync(declarationsPath)) { + throw new Error(`${declarationsPath} is missing`); + } - const parserSource = peggy.generate(await readFile(grammarPath, "utf-8"), { - output: "source", - format: "es", - grammarSource: relative(packageDir, grammarPath).split(sep).join("/"), - }); - const declarations = rebaseDeclarations( - await readFile(declarationsPath, "utf-8"), - declarationsPath, - ); + const parserSource = peggy.generate(await readFile(grammarPath, "utf-8"), { + output: "source", + format: "es", + grammarSource: relative(packageDir, grammarPath).split(sep).join("/"), + }); + const declarations = rebaseDeclarations( + await readFile(declarationsPath, "utf-8"), + declarationsPath, + ); - const outputBase = join(outputDir, `${name}-grammar`); - await writeFile(`${outputBase}.js`, `${HEADER}\n${parserSource}\n`); - await writeFile(`${outputBase}.d.ts`, `${HEADER}\n${declarations}`); - console.log(`Generated ${relative(process.cwd(), outputBase)}.{js,d.ts}`); -} + const outputBase = join(outputDir, `${name}-grammar`); + await writeFile(`${outputBase}.js`, `${HEADER}\n${parserSource}\n`); + await writeFile(`${outputBase}.d.ts`, `${HEADER}\n${declarations}`); + console.log(`Generated ${relative(process.cwd(), outputBase)}.{js,d.ts}`); + }), +); From 8dfd11f52828306744b8afe69dc482eb68541beb Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:42:22 +0000 Subject: [PATCH 3/9] Revert "ref: Turn on no-await-in-loop for the whole repo and fix its sites" This reverts commit cb82197d5e7256bb6b2859f7588e7b26356c77e5. The same change follows as one commit per area, so each can be reviewed on its own. --- .../verify-toolkit/scripts/mcp-call.mjs | 1 - .oxlintrc.json | 91 ++++++++++++++++-- apps/docs-mcp/src/agent/features-agent.ts | 1 - apps/docs-mcp/src/agent/model-fallback.ts | 2 - apps/local/scripts/replay.ts | 5 - packages/cli/AGENTS.md | 2 +- packages/cli/script/bench-sweep.ts | 2 - packages/cli/script/bench.ts | 3 - packages/cli/script/build.ts | 1 - packages/cli/script/check-doc-examples.ts | 16 +--- packages/cli/script/check-env-coverage.ts | 30 ++---- packages/cli/script/check-error-patterns.ts | 11 +-- packages/cli/script/check-fragments.ts | 57 ++++-------- packages/cli/script/check-patches.ts | 2 - packages/cli/script/check-stale-references.ts | 20 ++-- packages/cli/script/eval-skill.ts | 3 - packages/cli/script/generate-command-api.ts | 9 +- packages/cli/script/generate-command-docs.ts | 25 +++-- packages/cli/script/generate-docs-sections.ts | 2 - .../cli/script/generate-output-schemas.ts | 36 ++++--- packages/cli/script/generate-skill.ts | 14 ++- packages/cli/script/generate.ts | 1 - packages/cli/script/lib/chunk-build.ts | 5 +- packages/cli/script/lib/split-bundle.ts | 41 ++++---- packages/cli/script/preview-selectors.ts | 1 - .../src/commands/alert/issues/rule-resolve.ts | 46 +++------ .../commands/alert/metrics/rule-resolve.ts | 43 +++------ .../cli/src/commands/alert/metrics/view.ts | 40 +++----- packages/cli/src/commands/auth/default.ts | 1 - packages/cli/src/commands/auth/logout.ts | 1 - packages/cli/src/commands/build/upload.ts | 1 - packages/cli/src/commands/cli/setup.ts | 1 - packages/cli/src/commands/cli/uninstall.ts | 1 - packages/cli/src/commands/cli/upgrade.ts | 2 - packages/cli/src/commands/dashboard/list.ts | 1 - .../cli/src/commands/dashboard/resolve.ts | 1 - packages/cli/src/commands/dashboard/view.ts | 2 - packages/cli/src/commands/event/send.ts | 2 - packages/cli/src/commands/issue/view.ts | 1 - packages/cli/src/commands/local/daemon.ts | 12 --- .../cli/src/commands/local/receiver-ingest.ts | 2 - packages/cli/src/commands/local/run.ts | 1 - packages/cli/src/commands/local/server.ts | 2 - packages/cli/src/commands/log/tail.ts | 2 - packages/cli/src/commands/log/view.ts | 1 - packages/cli/src/commands/proguard/upload.ts | 17 ++-- packages/cli/src/commands/project/create.ts | 1 - packages/cli/src/commands/project/list.ts | 20 ++-- .../cli/src/commands/react-native/gradle.ts | 1 - .../cli/src/commands/react-native/xcode.ts | 3 - packages/cli/src/commands/sourcemap/upload.ts | 27 +++--- packages/cli/src/lib/agent-skills.ts | 2 - .../cli/src/lib/api/attribute-pagination.ts | 1 - packages/cli/src/lib/api/chunk-upload.ts | 13 +-- packages/cli/src/lib/api/code-mappings.ts | 1 - packages/cli/src/lib/api/conversations.ts | 1 - packages/cli/src/lib/api/dart-symbols.ts | 2 - packages/cli/src/lib/api/dashboards.ts | 59 ++++++++---- packages/cli/src/lib/api/debug-files.ts | 14 +-- packages/cli/src/lib/api/explore.ts | 1 - packages/cli/src/lib/api/infrastructure.ts | 1 - packages/cli/src/lib/api/issue-app-links.ts | 1 - packages/cli/src/lib/api/preprod-artifacts.ts | 5 - packages/cli/src/lib/api/proguard.ts | 5 +- packages/cli/src/lib/api/releases.ts | 1 - packages/cli/src/lib/api/replays.ts | 1 - packages/cli/src/lib/bash-hook/traceback.ts | 38 +++----- .../src/lib/build/asset-catalog-extract.ts | 56 +++++------ packages/cli/src/lib/build/dsyms.ts | 3 - packages/cli/src/lib/build/index.ts | 16 +--- packages/cli/src/lib/build/zip-writer.ts | 5 - packages/cli/src/lib/command.ts | 1 - packages/cli/src/lib/complete.ts | 1 - packages/cli/src/lib/db/dsn-cache.ts | 30 +++--- packages/cli/src/lib/detect-agent.ts | 1 - packages/cli/src/lib/dev-script.ts | 1 - packages/cli/src/lib/dif/find.ts | 1 - packages/cli/src/lib/dif/scan.ts | 4 - packages/cli/src/lib/docs-context.ts | 51 ++++------ packages/cli/src/lib/dsn/env-file.ts | 74 ++++++--------- packages/cli/src/lib/dsn/project-root.ts | 2 - packages/cli/src/lib/dsn/resolver.ts | 34 ++++--- packages/cli/src/lib/dsn/scanner.ts | 2 - packages/cli/src/lib/fs-utils.ts | 1 - packages/cli/src/lib/ghcr.ts | 2 - packages/cli/src/lib/jvm-bundle.ts | 41 ++++---- packages/cli/src/lib/oauth.ts | 2 - packages/cli/src/lib/polling.ts | 2 - packages/cli/src/lib/scan/concurrent.ts | 1 - packages/cli/src/lib/scan/grep.ts | 1 - packages/cli/src/lib/scan/walker.ts | 6 -- packages/cli/src/lib/sentryclirc-import.ts | 28 +++--- packages/cli/src/lib/sentryclirc.ts | 1 - packages/cli/src/lib/snapshots/archive.ts | 1 - packages/cli/src/lib/sourcemap/inject.ts | 93 ++++++++----------- packages/cli/src/lib/sourcemap/zip.ts | 2 - packages/cli/src/lib/target-scope.ts | 4 - packages/cli/src/lib/upgrade.ts | 4 - packages/cli/src/lib/walk-up.ts | 1 - .../src/lib/wizard/nextjs/nextjs-wizard.ts | 1 - packages/cli/src/lib/wizard/nuxt/sdk-setup.ts | 1 - .../src/lib/wizard/react-native/javascript.ts | 1 - .../wizard/remix/codemods/express-server.ts | 2 - .../lib/wizard/sourcemaps/tools/sentry-cli.ts | 2 - .../cli/src/lib/wizard/utils/clack/index.ts | 1 - .../src/lib/wizard/utils/clack/mcp-config.ts | 2 - packages/cli/src/lib/wrangler.ts | 1 - packages/cli/test/lib/dsn/errors.test.ts | 1 - packages/cli/test/lib/dsn/resolver.test.ts | 1 - packages/http/src/policy.ts | 8 +- packages/http/src/retry.ts | 3 - .../scripts/generate-otel-namespaces.ts | 1 - .../scripts/generate-platform-setup.ts | 1 - packages/mcp-core/scripts/measure-ui-views.ts | 1 - .../scripts/validate-skills-mapping.ts | 17 ++-- packages/mcp-core/src/api-client/client.ts | 2 - packages/mcp-core/src/internal/fetch-utils.ts | 2 - .../tools/catalog/analyze-issue-with-seer.ts | 2 - .../mcp-core/src/tools/catalog/get-doc.ts | 1 - .../tools/support/alert-rule-connections.ts | 3 - .../src/tools/support/alert-rule-details.ts | 92 +++++++++--------- .../src/tools/support/issue-linking/app.ts | 1 - .../src/tools/support/search-events/seer.ts | 2 - packages/mcp-test-client/src/index.ts | 2 - packages/toolkit-core/src/mcp-limits.ts | 2 - scripts/cli-nightly-verify.mjs | 1 - scripts/cloudflare-deployment.mjs | 4 - scripts/generate-parsers.mjs | 45 +++++---- 128 files changed, 569 insertions(+), 865 deletions(-) diff --git a/.agents/skills/verify-toolkit/scripts/mcp-call.mjs b/.agents/skills/verify-toolkit/scripts/mcp-call.mjs index 56f8e6bdf8..ff23ed21dc 100755 --- a/.agents/skills/verify-toolkit/scripts/mcp-call.mjs +++ b/.agents/skills/verify-toolkit/scripts/mcp-call.mjs @@ -113,7 +113,6 @@ try { ); for (const [n, [name, toolArgs]] of opts.calls.entries()) { const file = `call-${n + 1}-${name}.json`; - // oxlint-disable-next-line no-await-in-loop -- calls run in the order given, since a later call can depend on an earlier one's side effects const result = await client.callTool({ name, arguments: toolArgs }); write(file, { request: { name, arguments: toolArgs }, result }); const shape = result.structuredContent diff --git a/.oxlintrc.json b/.oxlintrc.json index a78ef22902..7a416d0fc7 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -50,7 +50,6 @@ ], "typescript/no-unnecessary-type-constraint": "error", "prefer-const": "error", - "no-await-in-loop": "error", "no-else-return": ["error", { "allowElseIf": false }], "no-new-wrappers": "error", "no-new": "error", @@ -253,7 +252,8 @@ "files": ["packages/cli/src/**/*.ts"], "rules": { "typescript/no-explicit-any": "error", - "typescript/no-non-null-assertion": "error" + "typescript/no-non-null-assertion": "error", + "no-await-in-loop": "error" } }, { @@ -512,11 +512,88 @@ }, { "files": [ - "**/*.test.ts", - "**/*.test.tsx", - "**/*.test.mjs", - "**/test-utils/**", - "packages/cli/test/**" + "packages/cli/src/commands/alert/issues/rule-resolve.ts", + "packages/cli/src/commands/alert/metrics/rule-resolve.ts", + "packages/cli/src/commands/alert/metrics/view.ts", + "packages/cli/src/commands/auth/default.ts", + "packages/cli/src/commands/auth/logout.ts", + "packages/cli/src/commands/build/upload.ts", + "packages/cli/src/commands/cli/setup.ts", + "packages/cli/src/commands/cli/uninstall.ts", + "packages/cli/src/commands/cli/upgrade.ts", + "packages/cli/src/commands/dashboard/list.ts", + "packages/cli/src/commands/dashboard/resolve.ts", + "packages/cli/src/commands/dashboard/view.ts", + "packages/cli/src/commands/event/send.ts", + "packages/cli/src/commands/issue/view.ts", + "packages/cli/src/commands/local/daemon.ts", + "packages/cli/src/commands/local/receiver-ingest.ts", + "packages/cli/src/commands/local/run.ts", + "packages/cli/src/commands/local/server.ts", + "packages/cli/src/commands/log/tail.ts", + "packages/cli/src/commands/log/view.ts", + "packages/cli/src/commands/proguard/upload.ts", + "packages/cli/src/commands/project/create.ts", + "packages/cli/src/commands/project/list.ts", + "packages/cli/src/commands/react-native/gradle.ts", + "packages/cli/src/commands/react-native/xcode.ts", + "packages/cli/src/commands/sourcemap/upload.ts", + "packages/cli/src/lib/agent-skills.ts", + "packages/cli/src/lib/api/attribute-pagination.ts", + "packages/cli/src/lib/api/chunk-upload.ts", + "packages/cli/src/lib/api/code-mappings.ts", + "packages/cli/src/lib/api/conversations.ts", + "packages/cli/src/lib/api/dart-symbols.ts", + "packages/cli/src/lib/api/dashboards.ts", + "packages/cli/src/lib/api/debug-files.ts", + "packages/cli/src/lib/api/explore.ts", + "packages/cli/src/lib/api/infrastructure.ts", + "packages/cli/src/lib/api/issue-app-links.ts", + "packages/cli/src/lib/api/preprod-artifacts.ts", + "packages/cli/src/lib/api/proguard.ts", + "packages/cli/src/lib/api/releases.ts", + "packages/cli/src/lib/api/replays.ts", + "packages/cli/src/lib/bash-hook/traceback.ts", + "packages/cli/src/lib/build/asset-catalog-extract.ts", + "packages/cli/src/lib/build/dsyms.ts", + "packages/cli/src/lib/build/index.ts", + "packages/cli/src/lib/build/zip-writer.ts", + "packages/cli/src/lib/command.ts", + "packages/cli/src/lib/complete.ts", + "packages/cli/src/lib/db/dsn-cache.ts", + "packages/cli/src/lib/detect-agent.ts", + "packages/cli/src/lib/dev-script.ts", + "packages/cli/src/lib/dif/find.ts", + "packages/cli/src/lib/dif/scan.ts", + "packages/cli/src/lib/docs-context.ts", + "packages/cli/src/lib/dsn/env-file.ts", + "packages/cli/src/lib/dsn/project-root.ts", + "packages/cli/src/lib/dsn/resolver.ts", + "packages/cli/src/lib/dsn/scanner.ts", + "packages/cli/src/lib/fs-utils.ts", + "packages/cli/src/lib/ghcr.ts", + "packages/cli/src/lib/jvm-bundle.ts", + "packages/cli/src/lib/oauth.ts", + "packages/cli/src/lib/polling.ts", + "packages/cli/src/lib/scan/concurrent.ts", + "packages/cli/src/lib/scan/grep.ts", + "packages/cli/src/lib/scan/walker.ts", + "packages/cli/src/lib/sentryclirc-import.ts", + "packages/cli/src/lib/sentryclirc.ts", + "packages/cli/src/lib/snapshots/archive.ts", + "packages/cli/src/lib/sourcemap/inject.ts", + "packages/cli/src/lib/sourcemap/zip.ts", + "packages/cli/src/lib/target-scope.ts", + "packages/cli/src/lib/upgrade.ts", + "packages/cli/src/lib/walk-up.ts", + "packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts", + "packages/cli/src/lib/wizard/nuxt/sdk-setup.ts", + "packages/cli/src/lib/wizard/react-native/javascript.ts", + "packages/cli/src/lib/wizard/remix/codemods/express-server.ts", + "packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts", + "packages/cli/src/lib/wizard/utils/clack/index.ts", + "packages/cli/src/lib/wizard/utils/clack/mcp-config.ts", + "packages/cli/src/lib/wrangler.ts" ], "rules": { "no-await-in-loop": "off" diff --git a/apps/docs-mcp/src/agent/features-agent.ts b/apps/docs-mcp/src/agent/features-agent.ts index 24a7e904cf..45ce82cd29 100644 --- a/apps/docs-mcp/src/agent/features-agent.ts +++ b/apps/docs-mcp/src/agent/features-agent.ts @@ -237,7 +237,6 @@ export async function parseFeaturesOutput( `Structured output was truncated because the model finished with reason "${finishReason}".`, ); } - // oxlint-disable-next-line no-await-in-loop -- steps parse in order: a cut-off step throws before later steps are read, and the last valid output wins const { value } = await parsePartialJson(preprocessJsonText(text)); const parsed = featuresOutputSchema.safeParse(value); if (!parsed.success) { diff --git a/apps/docs-mcp/src/agent/model-fallback.ts b/apps/docs-mcp/src/agent/model-fallback.ts index 516205264e..299e65f210 100644 --- a/apps/docs-mcp/src/agent/model-fallback.ts +++ b/apps/docs-mcp/src/agent/model-fallback.ts @@ -187,7 +187,6 @@ function createFallbackModel( for (const [index, model] of models.entries()) { for (;;) { try { - // oxlint-disable-next-line no-await-in-loop -- tries one model at a time and falls back only after it fails return { model, result: await call(model) }; } catch (error) { lastError = error; @@ -203,7 +202,6 @@ function createFallbackModel( break; } retryCount++; - // oxlint-disable-next-line no-await-in-loop -- backs off before retrying the same model await wait(delay, signal); } } diff --git a/apps/local/scripts/replay.ts b/apps/local/scripts/replay.ts index 1ffbd25adc..88d8e68959 100644 --- a/apps/local/scripts/replay.ts +++ b/apps/local/scripts/replay.ts @@ -24,7 +24,6 @@ async function envelopeFiles(path: string): Promise { const files: string[] = []; for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) { const child = join(path, entry.name); - // oxlint-disable-next-line no-await-in-loop -- walks directories in sorted order so envelopes replay in a stable order if (entry.isDirectory()) files.push(...(await envelopeFiles(child))); else if ( entry.isFile() && @@ -70,9 +69,7 @@ export async function replayEnvelopes({ let sent = 0; for (let cycle = 0; cycle < repeat; cycle++) for (const file of files) { - // oxlint-disable-next-line no-await-in-loop -- replays envelopes one at a time, spaced by --interval if (sent && interval) await delay(interval); - // oxlint-disable-next-line no-await-in-loop -- replays envelopes one at a time, spaced by --interval const raw = await readFile(file); const body = compression === "gzip" @@ -80,7 +77,6 @@ export async function replayEnvelopes({ : compression === "br" ? brotliCompressSync(raw) : raw; - // oxlint-disable-next-line no-await-in-loop -- replays envelopes one at a time, spaced by --interval const response = await fetch(target, { method: "POST", headers: { @@ -93,7 +89,6 @@ export async function replayEnvelopes({ redirect: "error", signal: AbortSignal.timeout(10_000), }); - // oxlint-disable-next-line no-await-in-loop -- replays envelopes one at a time, spaced by --interval await response.body?.cancel(); if (!response.ok) throw new Error(`Receiver rejected ${file}: HTTP ${response.status}`); diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.md index f07a5f31f6..132c957772 100644 --- a/packages/cli/AGENTS.md +++ b/packages/cli/AGENTS.md @@ -1078,7 +1078,7 @@ Don't copy a pattern from a neighboring file without this check. The wizards wer | Absolute date/time display | `src/lib/formatters/time-utils.ts` (`formatLocalDateTime` and `formatLocalTime` for epoch ms or ISO strings, `formatUtcTimestamp`, `formatAxisTimestamp` for chart axes). `sentry-cli/no-inline-date-format` rejects `new Date(x).toLocale*String()` elsewhere in `src/`. | | Table/markdown output | `src/lib/formatters/` directory | | Pagination | `src/lib/db/pagination.ts`, `src/lib/list-command.ts` | -| Independent async work over a list (instead of `await` in a loop) | `src/lib/fan-out.ts` (`mapBounded(items, fn, concurrency)`): pass `ORG_FANOUT_CONCURRENCY` for API calls, `CONCURRENCY_LIMIT` (`src/lib/scan/constants.ts`) for local files. Oxlint's `no-await-in-loop` is on for the whole repo except test files. A loop that must stay sequential (cursor pages, polling, retries, ordered writes, first match wins) gets `// oxlint-disable-next-line no-await-in-loop -- `. | +| Independent async work over a list (instead of `await` in a loop) | `src/lib/fan-out.ts` (`mapBounded(items, fn, concurrency)`): pass `ORG_FANOUT_CONCURRENCY` for API calls, `CONCURRENCY_LIMIT` (`src/lib/scan/constants.ts`) for local files. Oxlint's `no-await-in-loop` is on in `src/`, except for the files listed in its `"off"` override in `/.oxlintrc.json`; a file comes off that list once its loops are fixed. | | Error classes | `src/lib/errors.ts` (never create ad-hoc error types) | | Search query building | `src/lib/search-query.ts` (wraps `@sentry/toolkit-core/search-query`), `src/lib/arg-parsing.ts` | diff --git a/packages/cli/script/bench-sweep.ts b/packages/cli/script/bench-sweep.ts index 5372cff827..06190f1ced 100644 --- a/packages/cli/script/bench-sweep.ts +++ b/packages/cli/script/bench-sweep.ts @@ -245,7 +245,6 @@ async function runSweep(args: SweepArgs): Promise { if (!args.json) { logger.log(`\n${fx.label} (${fx.rootDir})`); } - // oxlint-disable-next-line no-await-in-loop -- benchmarks run one fixture at a time so runs do not skew each other's timings await withBenchDb(async () => { await sweepFixture(fx, ops, args, results); }); @@ -264,7 +263,6 @@ async function sweepFixture( for (const op of ops) { for (const concurrency of args.values) { const setup = op.setup; - // oxlint-disable-next-line no-await-in-loop -- benchmarks run one sample at a time so runs do not skew each other's timings const samples = await measure(() => op.run(fx.rootDir, concurrency), { runs: args.runs, warmup: args.warmup, diff --git a/packages/cli/script/bench.ts b/packages/cli/script/bench.ts index c40949097d..2492bed6ac 100644 --- a/packages/cli/script/bench.ts +++ b/packages/cli/script/bench.ts @@ -303,7 +303,6 @@ async function roughFileCount(root: string): Promise { for (const entry of entries) { if (entry.isDirectory()) { if (!skip.has(entry.name)) { - // oxlint-disable-next-line no-await-in-loop -- builds the fixture file list in a stable order await walk(join(dir, entry.name)); } } else if (entry.isFile()) { @@ -542,11 +541,9 @@ async function runAll( if (!args.json) { logger.log(`${fx.label} (${fx.fileCount} files @ ${fx.rootDir})`); } - // oxlint-disable-next-line no-await-in-loop -- benchmarks run one fixture at a time so runs do not skew each other's timings await withBenchDb(async () => { for (const op of ops) { const setup = op.setup; - // oxlint-disable-next-line no-await-in-loop -- benchmarks run one operation at a time so runs do not skew each other's timings const samples = await measure( async () => { await op.run(fx.rootDir); diff --git a/packages/cli/script/build.ts b/packages/cli/script/build.ts index b68cf2a374..e487891947 100644 --- a/packages/cli/script/build.ts +++ b/packages/cli/script/build.ts @@ -422,7 +422,6 @@ async function compileAllTargets( let failures = 0; for (const target of targets) { try { - // oxlint-disable-next-line no-await-in-loop -- each target compresses a full binary; one at a time keeps memory bounded await postProcessTarget(target); successes += 1; } catch (error) { diff --git a/packages/cli/script/check-doc-examples.ts b/packages/cli/script/check-doc-examples.ts index d407c0d9e8..bf5149283c 100644 --- a/packages/cli/script/check-doc-examples.ts +++ b/packages/cli/script/check-doc-examples.ts @@ -54,8 +54,6 @@ import { } from "./sdk-run-calls.js"; import { shellCommands } from "./shell-words.js"; import { logger } from "../src/lib/logger.js"; -import { mapBounded } from "../src/lib/fan-out.js"; -import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; await writeRouteTreeStubs(); @@ -401,11 +399,8 @@ for (const { source, invocation } of commandExamples( findings.push({ file: source, example: invocation, problem }); } } -for (const { file, content } of await mapBounded( - [...files, ...SDK_EXAMPLE_FILES], - async (file) => ({ file, content: await readFile(file, "utf-8") }), - CONCURRENCY_LIMIT, -)) { +for (const file of [...files, ...SDK_EXAMPLE_FILES]) { + const content = await readFile(file, "utf-8"); const invocations = file.endsWith(".ts") ? [] : extractInvocations(content); for (const invocation of invocations) { checked += 1; @@ -423,11 +418,8 @@ for (const { file, content } of await mapBounded( } const sourceFiles = listSource(SOURCE_DIR); -for (const { file, content } of await mapBounded( - sourceFiles, - async (file) => ({ file, content: await readFile(file, "utf-8") }), - CONCURRENCY_LIMIT, -)) { +for (const file of sourceFiles) { + const content = await readFile(file, "utf-8"); if (!content.includes("sentry`")) { continue; } diff --git a/packages/cli/script/check-env-coverage.ts b/packages/cli/script/check-env-coverage.ts index 2e13d382ae..890b9e2eb3 100644 --- a/packages/cli/script/check-env-coverage.ts +++ b/packages/cli/script/check-env-coverage.ts @@ -33,8 +33,6 @@ import { readFile } from "node:fs/promises"; import { join } from "node:path"; import { ENV_VAR_REGISTRY } from "../src/lib/env-registry.js"; import { logger } from "../src/lib/logger.js"; -import { mapBounded } from "../src/lib/fan-out.js"; -import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; /** * Well-known env vars that don't start with `SENTRY_` but are still part of the @@ -136,11 +134,8 @@ const files = globSync("src/**/*.ts", { // bracket reads indexed by a constant can be mapped back to a literal name. const constMap = new Map(); const fileContents = new Map(); -for (const { file, content } of await mapBounded( - files, - async (file) => ({ file, content: await readFile(file, "utf-8") }), - CONCURRENCY_LIMIT, -)) { +for (const file of files) { + const content = await readFile(file, "utf-8"); fileContents.set(file, content); for (const match of content.matchAll(ENV_CONST_RE)) { const [, name] = match; @@ -197,11 +192,8 @@ const INSTALLERS: readonly { file: string; read: RegExp; assign?: RegExp }[] = [ /** name -> first "file:line" where an installer reads it. */ const installerReads = new Map(); -const installerContents = await Promise.all( - INSTALLERS.map(({ file }) => readFile(file, "utf-8")), -); -for (const [index, { file, read, assign }] of INSTALLERS.entries()) { - const content = installerContents[index] ?? ""; +for (const { file, read, assign } of INSTALLERS) { + const content = await readFile(file, "utf-8"); const assigned = new Set( assign ? [...content.matchAll(assign)].map((m) => m[1]) : [], ); @@ -260,14 +252,12 @@ for (const name of INTERNAL_ENV_VARS.keys()) { // Every file type under src/, generated files included, not just the env // reads above: a retired name in a string or a comment fails too. -const srcFiles = globSync("src/**/*", { withFileTypes: true }) - .filter((entry) => entry.isFile()) - .map((entry) => join(entry.parentPath, entry.name)); -for (const { file, content } of await mapBounded( - srcFiles, - async (file) => ({ file, content: await readFile(file, "utf-8") }), - CONCURRENCY_LIMIT, -)) { +for (const entry of globSync("src/**/*", { withFileTypes: true })) { + if (!entry.isFile()) { + continue; + } + const file = join(entry.parentPath, entry.name); + const content = await readFile(file, "utf-8"); for (const [prefix, reason] of RETIRED_ENV_PREFIXES) { const index = content.indexOf(prefix); if (index !== -1) { diff --git a/packages/cli/script/check-error-patterns.ts b/packages/cli/script/check-error-patterns.ts index f939bc854a..9360893887 100644 --- a/packages/cli/script/check-error-patterns.ts +++ b/packages/cli/script/check-error-patterns.ts @@ -26,8 +26,6 @@ import { globSync } from "node:fs"; import { readFile } from "node:fs/promises"; import { logger } from "../src/lib/logger.js"; -import { mapBounded } from "../src/lib/fan-out.js"; -import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; export type Violation = { file: string; line: number; message: string }; @@ -273,13 +271,8 @@ export function findAdHocTryPatterns( /** Scan the given files and collect violations. */ export async function scanFiles(files: string[]): Promise { const violations: Violation[] = []; - const contents = await mapBounded( - files, - (filePath) => readFile(filePath, "utf-8"), - CONCURRENCY_LIMIT, - ); - for (const [index, filePath] of files.entries()) { - const content = contents[index] ?? ""; + for (const filePath of files) { + const content = await readFile(filePath, "utf-8"); violations.push(...findContextErrorNewlines(content, filePath)); violations.push(...findAdHocTryPatterns(content, filePath)); } diff --git a/packages/cli/script/check-fragments.ts b/packages/cli/script/check-fragments.ts index b34283122b..e21c244702 100644 --- a/packages/cli/script/check-fragments.ts +++ b/packages/cli/script/check-fragments.ts @@ -27,8 +27,6 @@ import { writeRouteTreeStubs } from "./lib/route-tree-stubs.js"; import { markdownHeadings } from "./markdown.js"; import { DOCS_FRAGMENTS } from "./paths.js"; import { logger } from "../src/lib/logger.js"; -import { mapBounded } from "../src/lib/fan-out.js"; -import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; await writeRouteTreeStubs(); @@ -92,14 +90,9 @@ for (const name of actualFragments) { const EXAMPLES_HEADING_RE = /^examples?\b/i; // Check 3: Fragment content validation -for (const { file, content } of await mapBounded( - fragmentFiles, - async (file) => ({ - file, - content: await readFile(`${FRAGMENTS_DIR}/${file}`, "utf-8"), - }), - CONCURRENCY_LIMIT, -)) { +for (const file of fragmentFiles) { + const content = await readFile(`${FRAGMENTS_DIR}/${file}`, "utf-8"); + if (content.includes("---\ntitle:") || content.startsWith("---\n")) { errors.push( `Fragment contains frontmatter: ${FRAGMENTS_DIR}/${file} (fragments should only contain custom content, not YAML frontmatter)`, @@ -136,17 +129,13 @@ const TOP_LEVEL_FRAGMENTS_DIR = DOCS_FRAGMENTS; /** Top-level fragment files that must exist (for generated doc pages) */ const REQUIRED_TOP_LEVEL_FRAGMENTS = ["configuration"]; -const requiredFragmentsExist = await Promise.all( - REQUIRED_TOP_LEVEL_FRAGMENTS.map((name) => - access(`${TOP_LEVEL_FRAGMENTS_DIR}/${name}.md`).then( - () => true, - () => false, - ), - ), -); -for (const [index, name] of REQUIRED_TOP_LEVEL_FRAGMENTS.entries()) { +for (const name of REQUIRED_TOP_LEVEL_FRAGMENTS) { const path = `${TOP_LEVEL_FRAGMENTS_DIR}/${name}.md`; - if (!requiredFragmentsExist[index]) { + const exists = await access(path).then( + () => true, + () => false, + ); + if (!exists) { errors.push( `Missing top-level fragment: ${path} (required for generated ${name}.md page)`, ); @@ -264,27 +253,13 @@ function getDefaultCommandName(routeName: string): string | undefined { const multiCommandRoutes = getMultiCommandRoutes(); -const multiCommandFragments = await mapBounded( - multiCommandRoutes, - async ([routeName, route]) => ({ - routeName, - route, - fragmentPath: `${FRAGMENTS_DIR}/${routeName}.md`, - // A missing fragment is already caught by Check 1. - content: await readFile(`${FRAGMENTS_DIR}/${routeName}.md`, "utf-8").catch( - () => undefined, - ), - }), - CONCURRENCY_LIMIT, -); - -for (const { - routeName, - route, - fragmentPath, - content, -} of multiCommandFragments) { - if (content === undefined) { +for (const [routeName, route] of multiCommandRoutes) { + const fragmentPath = `${FRAGMENTS_DIR}/${routeName}.md`; + let content: string; + try { + content = await readFile(fragmentPath, "utf-8"); + } catch { + // Fragment doesn't exist — already caught by Check 1 continue; } diff --git a/packages/cli/script/check-patches.ts b/packages/cli/script/check-patches.ts index a931298d49..36d678d70c 100644 --- a/packages/cli/script/check-patches.ts +++ b/packages/cli/script/check-patches.ts @@ -207,7 +207,6 @@ for (const [key, patchPath] of Object.entries(patches)) { throw new Error("unresolved"); } const installed: { version: string } = JSON.parse( - // oxlint-disable-next-line no-await-in-loop -- reports each patch's result in patch order await readFile(pkgJsonPath, "utf-8"), ); if (installed.version !== patchVersion) { @@ -344,7 +343,6 @@ for (const assertion of CONTENT_ASSERTIONS) { if (!assertionPath) { throw new Error("unresolved"); } - // oxlint-disable-next-line no-await-in-loop -- reports each assertion's result in assertion order const contents = await readFile(assertionPath, "utf-8"); if (assertion.staleMarker && contents.includes(assertion.staleMarker)) { errors.push( diff --git a/packages/cli/script/check-stale-references.ts b/packages/cli/script/check-stale-references.ts index f9e05cf111..ae83400232 100644 --- a/packages/cli/script/check-stale-references.ts +++ b/packages/cli/script/check-stale-references.ts @@ -24,8 +24,6 @@ import { readFile } from "node:fs/promises"; import { blankCodeBlocks } from "./markdown.js"; import { DOCS_CONTENT } from "./paths.js"; import { logger } from "../src/lib/logger.js"; -import { mapBounded } from "../src/lib/fan-out.js"; -import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; const pkg = JSON.parse(await readFile("package.json", "utf-8")); const currentPM: string = (pkg.packageManager ?? "").split("@")[0]; @@ -114,18 +112,12 @@ type Finding = { const findings: Finding[] = []; -const scanned = await mapBounded( - FILES_TO_SCAN, - async (filePath) => ({ - filePath, - // A file that doesn't exist is skipped silently (e.g., optional doc files). - content: await readFile(filePath, "utf-8").catch(() => undefined), - }), - CONCURRENCY_LIMIT, -); - -for (const { filePath, content } of scanned) { - if (content === undefined) { +for (const filePath of FILES_TO_SCAN) { + let content: string; + try { + content = await readFile(filePath, "utf-8"); + } catch { + // File doesn't exist — skip silently (e.g., optional doc files) continue; } diff --git a/packages/cli/script/eval-skill.ts b/packages/cli/script/eval-skill.ts index a44a47ba26..0e9b8ef786 100644 --- a/packages/cli/script/eval-skill.ts +++ b/packages/cli/script/eval-skill.ts @@ -67,14 +67,12 @@ async function evalModel( for (const testCase of testCases) { logger.start(`${testCase.id}...`); - // oxlint-disable-next-line no-await-in-loop -- eval cases run one at a time to stay inside the model provider's rate limits const plan = await generatePlan( client, model, skillContent, testCase.prompt, ); - // oxlint-disable-next-line no-await-in-loop -- the judge needs the plan from the step before const result = await judgePlan(client, testCase, plan); results.push(result); @@ -132,7 +130,6 @@ async function main(): Promise { const models: ModelResult[] = []; for (const model of client.agentModels) { - // oxlint-disable-next-line no-await-in-loop -- models run one at a time to stay inside the model provider's rate limits const result = await evalModel(client, model, skillContent, testCases); models.push(result); } diff --git a/packages/cli/script/generate-command-api.ts b/packages/cli/script/generate-command-api.ts index e6d96f0cc8..05fe23fea0 100644 --- a/packages/cli/script/generate-command-api.ts +++ b/packages/cli/script/generate-command-api.ts @@ -28,13 +28,8 @@ export async function emit(): Promise { { commands: Set; reason: string } >(); - const modules = await Promise.all( - analysis.commands.map( - ({ file }) => import(pathToFileURL(resolve(file)).href), - ), - ); - for (const [index, { file, name }] of analysis.commands.entries()) { - const module = modules[index]; + for (const { file, name } of analysis.commands) { + const module = await import(pathToFileURL(resolve(file)).href); const target = module[name] as RouteTarget | undefined; const path = target && paths.get(target); if (!target || !path || !isCommand(target)) continue; diff --git a/packages/cli/script/generate-command-docs.ts b/packages/cli/script/generate-command-docs.ts index 0d9df7df4a..a9c92d9bb8 100644 --- a/packages/cli/script/generate-command-docs.ts +++ b/packages/cli/script/generate-command-docs.ts @@ -389,20 +389,17 @@ export async function emit(): Promise { } // Generate command doc pages - const pagePaths = await Promise.all( - routeInfos.map(async (route) => { - const filePath = `${DOCS_DIR}/${route.name}.md`; - const pageContent = generatePage(route); - const customContent = await readCustomContent(route.name); - const fullContent = customContent - ? pageContent + customContent - : `${pageContent}\n`; - - await writeFile(filePath, fullContent); - return filePath; - }), - ); - generatedFiles.push(...pagePaths); + for (const route of routeInfos) { + const filePath = `${DOCS_DIR}/${route.name}.md`; + const pageContent = generatePage(route); + const customContent = await readCustomContent(route.name); + const fullContent = customContent + ? pageContent + customContent + : `${pageContent}\n`; + + await writeFile(filePath, fullContent); + generatedFiles.push(filePath); + } // Update commands/index.md const indexCustomContent = await readCustomContent("index"); diff --git a/packages/cli/script/generate-docs-sections.ts b/packages/cli/script/generate-docs-sections.ts index 1e4b488ac9..15d9446379 100644 --- a/packages/cli/script/generate-docs-sections.ts +++ b/packages/cli/script/generate-docs-sections.ts @@ -1144,7 +1144,6 @@ export async function emit({ check }: { check: boolean }): Promise { let staleCount = 0; for (const section of sections) { - // oxlint-disable-next-line no-await-in-loop -- several sections live in one file, so each read-modify-write must finish before the next const original = await readFile(section.filePath, "utf-8"); const generated = section.generate(); const updated = replaceMarkerSection( @@ -1159,7 +1158,6 @@ export async function emit({ check }: { check: boolean }): Promise { logger.error(`STALE: ${section.filePath} [${section.sectionName}]`); staleCount += 1; } else { - // oxlint-disable-next-line no-await-in-loop -- several sections live in one file, so each read-modify-write must finish before the next await writeFile(section.filePath, updated); logger.info(`Updated: ${section.filePath} [${section.sectionName}]`); } diff --git a/packages/cli/script/generate-output-schemas.ts b/packages/cli/script/generate-output-schemas.ts index 8b5f2b5e30..a5d9ed1d5a 100644 --- a/packages/cli/script/generate-output-schemas.ts +++ b/packages/cli/script/generate-output-schemas.ts @@ -84,26 +84,22 @@ export async function emit(): Promise { await rm(OUTPUT_DIR, { recursive: true, force: true }); await mkdir(OUTPUT_DIR, { recursive: true }); - const counts = await Promise.all( - files.map(async (file) => { - const name = basename(file, ".ts"); - const exports: Record = await import( - pathToFileURL(resolve(SOURCE_DIR, file)).href - ); - const schemas = Object.entries(exports).filter( - (entry): entry is [string, GenericSchema] => - entry[0].endsWith("Schema") && isSchema(entry[1]), - ); - if (schemas.length > 0) { - await writeFile( - `${OUTPUT_DIR}/${name}.ts`, - renderModule(name, schemas), - ); - } - return schemas.length; - }), - ); - const count = counts.reduce((sum, n) => sum + n, 0); + let count = 0; + for (const file of files) { + const name = basename(file, ".ts"); + const exports: Record = await import( + pathToFileURL(resolve(SOURCE_DIR, file)).href + ); + const schemas = Object.entries(exports).filter( + (entry): entry is [string, GenericSchema] => + entry[0].endsWith("Schema") && isSchema(entry[1]), + ); + if (schemas.length === 0) { + continue; + } + count += schemas.length; + await writeFile(`${OUTPUT_DIR}/${name}.ts`, renderModule(name, schemas)); + } logger.success(`Generated ${OUTPUT_DIR}/ (${count} output schemas)`); } diff --git a/packages/cli/script/generate-skill.ts b/packages/cli/script/generate-skill.ts index d47d352e4b..f0e50445df 100644 --- a/packages/cli/script/generate-skill.ts +++ b/packages/cli/script/generate-skill.ts @@ -687,14 +687,12 @@ export async function emit(): Promise { // The public references are a symlink to these generated plugin references. rmSync(`${SKILL_DIR}/references`, { recursive: true, force: true }); - await Promise.all( - [...files].map(([relativePath, content]) => { - const fullPath = `${SKILL_DIR}/${relativePath}`; - const dir = fullPath.substring(0, fullPath.lastIndexOf("/")); - mkdirSync(dir, { recursive: true }); - return writeFile(fullPath, content); - }), - ); + for (const [relativePath, content] of files) { + const fullPath = `${SKILL_DIR}/${relativePath}`; + const dir = fullPath.substring(0, fullPath.lastIndexOf("/")); + mkdirSync(dir, { recursive: true }); + await writeFile(fullPath, content); + } const publicSkill = files.get("SKILL.md"); if (publicSkill === undefined) { diff --git a/packages/cli/script/generate.ts b/packages/cli/script/generate.ts index ffad84fe02..74723249f8 100644 --- a/packages/cli/script/generate.ts +++ b/packages/cli/script/generate.ts @@ -258,7 +258,6 @@ if (treeSteps.length > 0) { await writeRouteTreeStubs(); await import("../src/app.js"); for (const step of treeSteps) { - // oxlint-disable-next-line no-await-in-loop -- steps emit in order because later steps read files that earlier ones write await (await step.load()).emit(options); if (process.exitCode) { break; diff --git a/packages/cli/script/lib/chunk-build.ts b/packages/cli/script/lib/chunk-build.ts index d8e1243353..a3274f9c19 100644 --- a/packages/cli/script/lib/chunk-build.ts +++ b/packages/cli/script/lib/chunk-build.ts @@ -105,13 +105,12 @@ export async function chunkBuild( entries: MainChunkBuild["entries"], ): Promise { const sorted = [...files].sort(); - const contents = await Promise.all(sorted.map((file) => readFile(file))); const hash = createHash("sha256"); - for (const [index, file] of sorted.entries()) { + for (const file of sorted) { hash .update(basename(file)) .update("\0") - .update(contents[index] ?? ""); + .update(await readFile(file)); } return { id: hash.digest("hex").slice(0, 16), diff --git a/packages/cli/script/lib/split-bundle.ts b/packages/cli/script/lib/split-bundle.ts index f27284ecaa..5e40db6c43 100644 --- a/packages/cli/script/lib/split-bundle.ts +++ b/packages/cli/script/lib/split-bundle.ts @@ -187,7 +187,6 @@ async function buildEsmChunks(options: SplitBundleOptions): Promise<{ `${LAZY_ENTRY_PREFIX}${path}`, ]), ); - // oxlint-disable-next-line no-await-in-loop -- each build pass adds the lazy entries the previous pass discovered const result = await build({ ...options.options, entryPoints: { ...options.entryPoints, ...lazyPoints }, @@ -269,21 +268,20 @@ async function writeEsmChunks( ]), ); await mkdir(scratch, { recursive: true }); - const targets = await Promise.all( - result.outputFiles.map(async (file) => { - const target = join(scratch, relative(outdir, file.path)); - if (file.path.endsWith(".map")) { - await writeFile(target, file.contents); - return undefined; - } - await writeFile( - target, - lowerChunkImports(file.path, file.text, outputs.get(file.path)), - ); - return target; - }), - ); - return targets.filter((target) => target !== undefined); + const files: string[] = []; + for (const file of result.outputFiles) { + const target = join(scratch, relative(outdir, file.path)); + if (file.path.endsWith(".map")) { + await writeFile(target, file.contents); + continue; + } + await writeFile( + target, + lowerChunkImports(file.path, file.text, outputs.get(file.path)), + ); + files.push(target); + } + return files; } /** Pass 2 of a CommonJS build: convert the ESM chunks in `files` to CommonJS. */ @@ -330,12 +328,11 @@ function jsOutputs(metafile: Metafile): string[] { * their content, so a build does not overwrite the chunks of the last one. */ export async function removeBundleOutputs(dir: string): Promise { - const entries = await readdir(dir).catch(() => []); - await Promise.all( - entries - .filter((entry) => BUNDLE_OUTPUT_RE.test(entry)) - .map((entry) => rm(join(dir, entry), { force: true })), - ); + for (const entry of await readdir(dir).catch(() => [])) { + if (BUNDLE_OUTPUT_RE.test(entry)) { + await rm(join(dir, entry), { force: true }); + } + } } /** Build `options.entryPoints` into split chunks, see the module comment. */ diff --git a/packages/cli/script/preview-selectors.ts b/packages/cli/script/preview-selectors.ts index 8d91b1c1f1..0d88a77950 100644 --- a/packages/cli/script/preview-selectors.ts +++ b/packages/cli/script/preview-selectors.ts @@ -32,7 +32,6 @@ async function preview(): Promise { } const chosen: string[] = []; for (const prompt of [organization, project]) { - // oxlint-disable-next-line no-await-in-loop -- interactive prompts run one after another const value = await selectWithFilter(prompt); if (value === null) { return; diff --git a/packages/cli/src/commands/alert/issues/rule-resolve.ts b/packages/cli/src/commands/alert/issues/rule-resolve.ts index 0af9abf829..7192121ca7 100644 --- a/packages/cli/src/commands/alert/issues/rule-resolve.ts +++ b/packages/cli/src/commands/alert/issues/rule-resolve.ts @@ -2,10 +2,7 @@ * Shared issue alert rule reference parsing and resolution (view / delete / edit). */ -import { - MAX_PAGINATION_PAGES, - ORG_FANOUT_CONCURRENCY, -} from "../../../lib/api/infrastructure.js"; +import { MAX_PAGINATION_PAGES } from "../../../lib/api/infrastructure.js"; import { API_MAX_PER_PAGE, getIssueAlertRule, @@ -16,7 +13,6 @@ import { import { type LazyCommand, sentry } from "../../../lib/app-identity.js"; import { ORG_PROJECT_TARGET } from "../../../lib/completion-target.js"; import { ResolutionError, ValidationError } from "../../../lib/errors.js"; -import { mapBounded } from "../../../lib/fan-out.js"; import { fuzzyMatch } from "../../../lib/fuzzy.js"; import { logger } from "../../../lib/logger.js"; import type { ResolvedTarget } from "../../../lib/resolve-target.js"; @@ -95,7 +91,6 @@ export async function listAllIssueRulesForTarget( const all: IssueAlertRule[] = []; let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { - // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await listIssueAlertsPaginated( target.org, target.project, @@ -120,24 +115,18 @@ export async function resolveIssueAlertRule( usageHint: string, ): Promise { if (isAllDigits(ref)) { - const lookups = await mapBounded( - targets, - async (target): Promise => { - try { - return { - target, - rule: await getIssueAlertRule(target.org, target.project, ref), - }; - } catch (e) { - if (isNotFoundApiError(e)) { - return null; - } - throw e; + const hits: IssueRuleResolution[] = []; + for (const target of targets) { + try { + const rule = await getIssueAlertRule(target.org, target.project, ref); + hits.push({ target, rule }); + } catch (e) { + if (isNotFoundApiError(e)) { + continue; } - }, - ORG_FANOUT_CONCURRENCY, - ); - const hits = lookups.filter((hit) => hit !== null); + throw e; + } + } if (hits.length === 1) { return hits[0] as IssueRuleResolution; @@ -158,15 +147,8 @@ export async function resolveIssueAlertRule( const hits: IssueRuleResolution[] = []; const allRuleNames: string[] = []; - const targetRules = await mapBounded( - targets, - async (target) => ({ - target, - rules: await listAllIssueRulesForTarget(target), - }), - ORG_FANOUT_CONCURRENCY, - ); - for (const { target, rules } of targetRules) { + for (const target of targets) { + const rules = await listAllIssueRulesForTarget(target); for (const r of rules) { if (r.name) { allRuleNames.push(r.name); diff --git a/packages/cli/src/commands/alert/metrics/rule-resolve.ts b/packages/cli/src/commands/alert/metrics/rule-resolve.ts index 9cd5ffbc9c..dd0fb473b5 100644 --- a/packages/cli/src/commands/alert/metrics/rule-resolve.ts +++ b/packages/cli/src/commands/alert/metrics/rule-resolve.ts @@ -2,10 +2,7 @@ * Shared metric alert rule reference parsing and resolution (view / delete / edit). */ -import { - MAX_PAGINATION_PAGES, - ORG_FANOUT_CONCURRENCY, -} from "../../../lib/api/infrastructure.js"; +import { MAX_PAGINATION_PAGES } from "../../../lib/api/infrastructure.js"; import { API_MAX_PER_PAGE, getMetricAlertRule, @@ -16,7 +13,6 @@ import { import { type LazyCommand, sentry } from "../../../lib/app-identity.js"; import { ORG_TARGET } from "../../../lib/completion-target.js"; import { ResolutionError, ValidationError } from "../../../lib/errors.js"; -import { mapBounded } from "../../../lib/fan-out.js"; import { fuzzyMatch } from "../../../lib/fuzzy.js"; import { logger } from "../../../lib/logger.js"; import { countChar, isAllDigits } from "../../../lib/utils.js"; @@ -92,7 +88,6 @@ export async function listAllMetricRulesForOrg( const all: MetricAlertRule[] = []; let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { - // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await listMetricAlertsPaginated(orgSlug, { perPage: API_MAX_PER_PAGE, cursor, @@ -116,21 +111,18 @@ export async function resolveMetricAlertRule( usageHint: string, ): Promise { if (isAllDigits(ref)) { - const lookups = await mapBounded( - orgSlugs, - async (orgSlug): Promise => { - try { - return { orgSlug, rule: await getMetricAlertRule(orgSlug, ref) }; - } catch (e) { - if (isNotFoundApiError(e)) { - return null; - } - throw e; + const hits: MetricRuleResolution[] = []; + for (const orgSlug of orgSlugs) { + try { + const rule = await getMetricAlertRule(orgSlug, ref); + hits.push({ orgSlug, rule }); + } catch (e) { + if (isNotFoundApiError(e)) { + continue; } - }, - ORG_FANOUT_CONCURRENCY, - ); - const hits = lookups.filter((hit) => hit !== null); + throw e; + } + } if (hits.length === 1) { return hits[0] as MetricRuleResolution; @@ -151,15 +143,8 @@ export async function resolveMetricAlertRule( const hits: MetricRuleResolution[] = []; const allNames: string[] = []; - const orgRules = await mapBounded( - orgSlugs, - async (orgSlug) => ({ - orgSlug, - rules: await listAllMetricRulesForOrg(orgSlug), - }), - ORG_FANOUT_CONCURRENCY, - ); - for (const { orgSlug, rules } of orgRules) { + for (const orgSlug of orgSlugs) { + const rules = await listAllMetricRulesForOrg(orgSlug); for (const r of rules) { if (r.name) { allNames.push(r.name); diff --git a/packages/cli/src/commands/alert/metrics/view.ts b/packages/cli/src/commands/alert/metrics/view.ts index ccbe99224b..fe7bec4248 100644 --- a/packages/cli/src/commands/alert/metrics/view.ts +++ b/packages/cli/src/commands/alert/metrics/view.ts @@ -6,8 +6,6 @@ import { import { openInBrowser } from "../../../lib/browser.js"; import { buildCommand } from "../../../lib/command.js"; import { ApiError } from "../../../lib/errors.js"; -import { mapBounded } from "../../../lib/fan-out.js"; -import { ORG_FANOUT_CONCURRENCY } from "../../../lib/api/infrastructure.js"; import { formatMetricAlertView, type MetricAlertViewResult, @@ -121,32 +119,22 @@ export const viewCommand = buildCommand({ workflows: [], workflowErrors: [], }; - const lookups = await mapBounded( - new Set(rule.workflowIds ?? []), - async (id) => { - try { - return { - workflow: await getIssueAlertWorkflowDocument(result.orgSlug, id), - }; - } catch (error) { - // A missing or inaccessible link must not hide the readable detector - // or be mistaken for an alert with no notification configuration. - if ( - error instanceof ApiError && - (error.status === 403 || error.status === 404) - ) { - return { error: { id, status: error.status } }; - } + for (const id of new Set(rule.workflowIds ?? [])) { + try { + data.workflows.push( + await getIssueAlertWorkflowDocument(result.orgSlug, id), + ); + } catch (error) { + // A missing or inaccessible link must not hide the readable detector + // or be mistaken for an alert with no notification configuration. + if ( + error instanceof ApiError && + (error.status === 403 || error.status === 404) + ) { + data.workflowErrors.push({ id, status: error.status }); + } else { throw error; } - }, - ORG_FANOUT_CONCURRENCY, - ); - for (const lookup of lookups) { - if ("workflow" in lookup) { - data.workflows.push(lookup.workflow); - } else { - data.workflowErrors.push(lookup.error); } } yield new CommandOutput(data); diff --git a/packages/cli/src/commands/auth/default.ts b/packages/cli/src/commands/auth/default.ts index ca105c8085..2fb9c0f6d8 100644 --- a/packages/cli/src/commands/auth/default.ts +++ b/packages/cli/src/commands/auth/default.ts @@ -190,7 +190,6 @@ export const authDefaultCommand = buildCommand({ if (step.value instanceof CommandOutput) { yield step.value; } - // oxlint-disable-next-line no-await-in-loop -- drives the generator one step at a time step = await generator.next(); } return step.value as { hint?: string } | undefined; diff --git a/packages/cli/src/commands/auth/logout.ts b/packages/cli/src/commands/auth/logout.ts index f39d8ed37a..04f81099f1 100644 --- a/packages/cli/src/commands/auth/logout.ts +++ b/packages/cli/src/commands/auth/logout.ts @@ -204,7 +204,6 @@ async function removeAccounts(accounts: AccountSummary[]): Promise { (a, b) => Number(a.active) - Number(b.active), ); for (const account of ordered) { - // oxlint-disable-next-line no-await-in-loop -- each removal promotes the next account, so accounts are removed in order await removeAccount(account.id, { promoteNext: true }); } } diff --git a/packages/cli/src/commands/build/upload.ts b/packages/cli/src/commands/build/upload.ts index ba069fc83a..14a19c8cca 100644 --- a/packages/cli/src/commands/build/upload.ts +++ b/packages/cli/src/commands/build/upload.ts @@ -372,7 +372,6 @@ export const uploadCommand = buildCommand({ const builds: BuildUploadEntry[] = []; for (const path of paths) { try { - // oxlint-disable-next-line no-await-in-loop -- each build upload already sends its chunks in parallel; one build at a time keeps that cap const artifactUrl = await uploadOne( this, path, diff --git a/packages/cli/src/commands/cli/setup.ts b/packages/cli/src/commands/cli/setup.ts index cbc4ccafd9..40a6556335 100644 --- a/packages/cli/src/commands/cli/setup.ts +++ b/packages/cli/src/commands/cli/setup.ts @@ -144,7 +144,6 @@ async function migrateLegacyConfig( for (const name of configFiles) { const from = join(legacyDir, name); if (existsSync(from)) { - // oxlint-disable-next-line no-await-in-loop -- moves the config files one at a time; a failure stops before the next move await rename(from, join(targetConfigDir, name)); } } diff --git a/packages/cli/src/commands/cli/uninstall.ts b/packages/cli/src/commands/cli/uninstall.ts index 72f7f037b6..778db99f60 100644 --- a/packages/cli/src/commands/cli/uninstall.ts +++ b/packages/cli/src/commands/cli/uninstall.ts @@ -361,7 +361,6 @@ async function executeRemovals( for (const artifact of existing) { try { - // oxlint-disable-next-line no-await-in-loop -- removes artifacts in the listed order and records each outcome await artifact.remove(); result.removed.push(`${artifact.label} (${artifact.path})`); } catch (error) { diff --git a/packages/cli/src/commands/cli/upgrade.ts b/packages/cli/src/commands/cli/upgrade.ts index 6fa2c369c0..c17fa2a45f 100644 --- a/packages/cli/src/commands/cli/upgrade.ts +++ b/packages/cli/src/commands/cli/upgrade.ts @@ -670,7 +670,6 @@ async function spawnWithRetry( env, windowsVerbatimArguments: target.windowsVerbatimArguments, }); - // oxlint-disable-next-line no-await-in-loop -- retries the spawn one attempt at a time, with a backoff between attempts return await new Promise((resolve, reject) => { proc.on("close", (code, signal) => { // SIGKILL on macOS typically means AMFI killed the binary due to @@ -714,7 +713,6 @@ async function spawnWithRetry( log.warn( `Binary is locked (antivirus scan?), retrying in ${delay}ms... (attempt ${attempt}/${SPAWN_MAX_ATTEMPTS})`, ); - // oxlint-disable-next-line no-await-in-loop -- retries the spawn one attempt at a time, with a backoff between attempts await setTimeout(delay); } } diff --git a/packages/cli/src/commands/dashboard/list.ts b/packages/cli/src/commands/dashboard/list.ts index 7343b963c3..7db12ec732 100644 --- a/packages/cli/src/commands/dashboard/list.ts +++ b/packages/cli/src/commands/dashboard/list.ts @@ -300,7 +300,6 @@ async function fetchDashboards( // always uses one page size and resumes mid-page via afterId bookmarks. // oxlint-disable-next-line sentry-cli/no-manual-pagination for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { - // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await listDashboardsPaginated(orgSlug, { perPage: opts.perPage, cursor: serverCursor, diff --git a/packages/cli/src/commands/dashboard/resolve.ts b/packages/cli/src/commands/dashboard/resolve.ts index 11de786e49..6c46a20876 100644 --- a/packages/cli/src/commands/dashboard/resolve.ts +++ b/packages/cli/src/commands/dashboard/resolve.ts @@ -129,7 +129,6 @@ export async function resolveDashboardId( let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { - // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await withDashboardErrors( { orgSlug, operation: "list" }, () => diff --git a/packages/cli/src/commands/dashboard/view.ts b/packages/cli/src/commands/dashboard/view.ts index 507ecf286a..259768bcac 100644 --- a/packages/cli/src/commands/dashboard/view.ts +++ b/packages/cli/src/commands/dashboard/view.ts @@ -309,7 +309,6 @@ export const viewCommand = buildCommand({ try { while (!controller.signal.aborted) { - // oxlint-disable-next-line no-await-in-loop -- refreshes the dashboard on an interval until aborted const [widgetData, droppedData] = await Promise.all([ queryAllWidgets(regionUrl, orgSlug, dashboard, { ...widgetTimeOpts, @@ -334,7 +333,6 @@ export const viewCommand = buildCommand({ yield new CommandOutput(viewData); - // oxlint-disable-next-line no-await-in-loop -- refreshes the dashboard on an interval until aborted await abortableSleep(interval * 1000, controller.signal); } } finally { diff --git a/packages/cli/src/commands/event/send.ts b/packages/cli/src/commands/event/send.ts index f0692f81e1..969e248bc7 100644 --- a/packages/cli/src/commands/event/send.ts +++ b/packages/cli/src/commands/event/send.ts @@ -361,13 +361,11 @@ built entirely from the file contents. if (eventFiles.length > 0) { for (const file of eventFiles) { - // oxlint-disable-next-line no-await-in-loop -- sends each file and yields its result before the next one const { body, eventId } = await buildFilePayload( file, flags.raw ?? false, dsnComponents, ); - // oxlint-disable-next-line no-await-in-loop -- sends each file and yields its result before the next one await sendEnvelopeRequest(dsn, body); yield new CommandOutput({ eventId, file }); } diff --git a/packages/cli/src/commands/issue/view.ts b/packages/cli/src/commands/issue/view.ts index 7538af2496..44cfb0d743 100644 --- a/packages/cli/src/commands/issue/view.ts +++ b/packages/cli/src/commands/issue/view.ts @@ -310,7 +310,6 @@ async function openIssuesInBrowser( ); for (const issue of issues) { - // oxlint-disable-next-line no-await-in-loop -- opens browser tabs one at a time, in order await openInBrowser(issue.permalink, "issue"); } } diff --git a/packages/cli/src/commands/local/daemon.ts b/packages/cli/src/commands/local/daemon.ts index 9dcf709a32..7a7ce358a1 100644 --- a/packages/cli/src/commands/local/daemon.ts +++ b/packages/cli/src/commands/local/daemon.ts @@ -224,7 +224,6 @@ async function withDaemonOwnershipGuard( action: () => Promise, ): Promise { const path = join(directory, "local-control-plane.owner.guard"); - // oxlint-disable no-await-in-loop -- retries the guard file until it is free; each attempt waits for the one before for (let attempt = 0; attempt < 40; attempt += 1) { let guard: Awaited>; try { @@ -253,7 +252,6 @@ async function withDaemonOwnershipGuard( await rm(path, { force: true }); } } - // oxlint-enable no-await-in-loop throw new Error( "Timed out waiting for Local daemon ownership arbitration; active ownership has been preserved.", ); @@ -285,7 +283,6 @@ export async function claimDaemonOwnership( }); }; for (let attempt = 0; attempt < 40; attempt += 1) { - // oxlint-disable-next-line no-await-in-loop -- retries the ownership claim until it is free; each attempt waits for the one before const release = await withDaemonOwnershipGuard(directory, async () => { const claimed = await tryClaim(); if (claimed) return claimed; @@ -328,7 +325,6 @@ export async function claimDaemonOwnership( return undefined; }); if (release) return release; - // oxlint-disable-next-line no-await-in-loop -- waits between checks of the daemon state until the deadline await sleep(125); } throw new Error("Timed out waiting for Sentry Local daemon ownership."); @@ -355,7 +351,6 @@ function isProcessRunning(pid: number): boolean { async function readOwnerPid(path: string): Promise { for (let attempt = 0; ; attempt += 1) { try { - // oxlint-disable-next-line no-await-in-loop -- retries the read only while Windows briefly denies it return Number(await readFile(path, "utf8")); } catch (error) { if (error instanceof Error && "code" in error) { @@ -363,7 +358,6 @@ async function readOwnerPid(path: string): Promise { // Windows may briefly deny reads while the previous owner removes its // file. Retry without interpreting an unreadable owner as absent. if (error.code === "EPERM" && attempt < 4) { - // oxlint-disable-next-line no-await-in-loop -- waits between checks of the daemon state until the deadline await sleep(125); continue; } @@ -497,9 +491,7 @@ export async function waitForLocalDaemonShutdown( const directory = getConfigDir(); const deadline = Date.now() + 5_000; while (Date.now() < deadline) { - // oxlint-disable-next-line no-await-in-loop -- polls the daemon state until the deadline const current = await readLocalDaemonState(directory); - // oxlint-disable-next-line no-await-in-loop -- polls the daemon state until the deadline const owner = await readOwnerPid( join(directory, "local-control-plane.owner"), ); @@ -507,7 +499,6 @@ export async function waitForLocalDaemonShutdown( current?.pid === state.pid && current.token === state.token; if ((!ownsState && owner !== state.pid) || !isProcessRunning(state.pid)) return; - // oxlint-disable-next-line no-await-in-loop -- waits between checks of the daemon state until the deadline await sleep(125); } throw new Error( @@ -521,14 +512,11 @@ async function waitForLocalDaemon( startupError?: () => Error | undefined, ): Promise { while (Date.now() < deadline) { - // oxlint-disable-next-line no-await-in-loop -- waits between checks of the daemon state until the deadline await sleep(125); - // oxlint-disable-next-line no-await-in-loop -- polls the daemon state until the deadline const state = await discoverLocalDaemon(true); if (state) return state; const error = startupError?.(); if (error) { - // oxlint-disable-next-line no-await-in-loop -- polls the daemon state until the deadline const owner = await readOwnerPid( join(getConfigDir(), "local-control-plane.owner"), ); diff --git a/packages/cli/src/commands/local/receiver-ingest.ts b/packages/cli/src/commands/local/receiver-ingest.ts index 6f7ee61ab2..8d7f8a0aa9 100644 --- a/packages/cli/src/commands/local/receiver-ingest.ts +++ b/packages/cli/src/commands/local/receiver-ingest.ts @@ -95,12 +95,10 @@ export async function readReceiverBody( let size = 0; try { for (;;) { - // oxlint-disable-next-line no-await-in-loop -- reads the request body in order, one chunk at a time const { done, value } = await reader.read(); if (done) return Buffer.concat(chunks, size); size += value.byteLength; if (size > maxBytes) { - // oxlint-disable-next-line no-await-in-loop -- reads the request body in order, one chunk at a time await reader .cancel() .catch(() => logger.debug("Local request body was already closed.")); diff --git a/packages/cli/src/commands/local/run.ts b/packages/cli/src/commands/local/run.ts index 4ec7541409..c8f11dc9c8 100644 --- a/packages/cli/src/commands/local/run.ts +++ b/packages/cli/src/commands/local/run.ts @@ -1163,7 +1163,6 @@ async function waitForAppExit(pid: number, ms: number): Promise { if (Date.now() >= deadline) { return false; } - // oxlint-disable-next-line no-await-in-loop -- waits for the app process to exit await new Promise((r) => setTimeout(r, GROUP_POLL_MS)); } return true; diff --git a/packages/cli/src/commands/local/server.ts b/packages/cli/src/commands/local/server.ts index 314ff263fa..b7e7a30a68 100644 --- a/packages/cli/src/commands/local/server.ts +++ b/packages/cli/src/commands/local/server.ts @@ -986,7 +986,6 @@ async function consumeSSEWithWarning( const replays = createReplayTracker(); while (!signal.aborted) { - // oxlint-disable-next-line no-await-in-loop -- reconnects one attempt at a time until aborted const result = await attemptSSEConnection({ url, streamUrl, @@ -1046,7 +1045,6 @@ async function consumeSSEWithWarning( logger.info( `SSE connection lost, reconnecting in ${retryDelay / 1000}s...`, ); - // oxlint-disable-next-line no-await-in-loop -- reconnects one attempt at a time until aborted await sleepUnlessAborted(retryDelay, signal); retryDelay = Math.min(retryDelay * 2, SSE_MAX_RETRY_MS); } diff --git a/packages/cli/src/commands/log/tail.ts b/packages/cli/src/commands/log/tail.ts index 9633135114..4a9bec685b 100644 --- a/packages/cli/src/commands/log/tail.ts +++ b/packages/cli/src/commands/log/tail.ts @@ -197,13 +197,11 @@ async function* generateFollowLogs( // Poll loop — exits when SIGINT fires for (;;) { - // oxlint-disable-next-line no-await-in-loop -- polls for new logs; each request starts after the last timestamp await abortableSleep(pollIntervalMs, controller.signal); if (controller.signal.aborted) { break; } - // oxlint-disable-next-line no-await-in-loop -- polls for new logs; each request starts after the last timestamp const newLogs = await fetchPoll(config, lastTimestamp); if (newLogs && newLogs.length > 0) { yield [...newLogs].reverse(); diff --git a/packages/cli/src/commands/log/view.ts b/packages/cli/src/commands/log/view.ts index 7291739717..0a1f86f115 100644 --- a/packages/cli/src/commands/log/view.ts +++ b/packages/cli/src/commands/log/view.ts @@ -319,7 +319,6 @@ async function handleWebOpen(orgSlug: string, logIds: string[]): Promise { } } for (const id of logIds) { - // oxlint-disable-next-line no-await-in-loop -- opens browser tabs one at a time, in order await openInBrowser(buildLogsUrl(orgSlug, id), "log"); } } diff --git a/packages/cli/src/commands/proguard/upload.ts b/packages/cli/src/commands/proguard/upload.ts index b14527b245..63d85f5f1a 100644 --- a/packages/cli/src/commands/proguard/upload.ts +++ b/packages/cli/src/commands/proguard/upload.ts @@ -15,13 +15,11 @@ import { uploadProguardMappings } from "../../lib/api/proguard.js"; import { buildCommand } from "../../lib/command.js"; import { parseFilePath, parseText } from "../../lib/completion-target.js"; import { ContextError, ValidationError } from "../../lib/errors.js"; -import { mapBounded } from "../../lib/fan-out.js"; import { mdKvTable, renderMarkdown } from "../../lib/formatters/markdown.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { logger } from "../../lib/logger.js"; import { computeProguardUuid } from "../../lib/proguard.js"; import { resolveOrgAndProject } from "../../lib/resolve-target.js"; -import { CONCURRENCY_LIMIT } from "../../lib/scan/constants.js"; import { sentry } from "../../lib/app-identity.js"; const log = logger.withTag("proguard.upload"); @@ -253,15 +251,12 @@ export const uploadCommand = buildCommand({ } // 4. Read each file and compute UUID - const mappings = await mapBounded( - paths, - async (path): Promise => { - const content = await readMappingFile(path); - const uuid = flags.uuid ?? computeProguardUuid(content); - return { path, uuid, content }; - }, - CONCURRENCY_LIMIT, - ); + const mappings: ProguardMapping[] = []; + for (const path of paths) { + const content = await readMappingFile(path); + const uuid = flags.uuid ?? computeProguardUuid(content); + mappings.push({ path, uuid, content }); + } // 5. Deduplicate mappings with identical content (same UUID = same content) const uniqueMappings = deduplicateMappings(mappings); diff --git a/packages/cli/src/commands/project/create.ts b/packages/cli/src/commands/project/create.ts index 1c0e5a3b68..c17d0f7311 100644 --- a/packages/cli/src/commands/project/create.ts +++ b/packages/cli/src/commands/project/create.ts @@ -764,7 +764,6 @@ export const createCommand = buildCommand({ try { for (const { name, platform } of parsed) { results.push( - // oxlint-disable-next-line no-await-in-loop -- creates projects one at a time to respect rate limits await createOneProject({ orgSlug, name, diff --git a/packages/cli/src/commands/project/list.ts b/packages/cli/src/commands/project/list.ts index e2d8ccda13..7ba8a9a6d5 100644 --- a/packages/cli/src/commands/project/list.ts +++ b/packages/cli/src/commands/project/list.ts @@ -37,8 +37,6 @@ import { resolveCursor, } from "../../lib/db/pagination.js"; import { ResolutionError, withAuthGuard } from "../../lib/errors.js"; -import { mapBounded } from "../../lib/fan-out.js"; -import { ORG_FANOUT_CONCURRENCY } from "../../lib/api/infrastructure.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { type Column, formatTable } from "../../lib/formatters/table.js"; import { @@ -157,12 +155,18 @@ export async function fetchOrgProjectsByName( */ export async function fetchAllOrgProjects(): Promise { const orgs = await listOrganizations(); - const orgResults = await mapBounded( - orgs, - (org) => withAuthGuard(() => fetchOrgProjects(org.slug)), - ORG_FANOUT_CONCURRENCY, - ); - return orgResults.flatMap((result) => (result.ok ? result.value : [])); + const results: ProjectWithOrg[] = []; + + for (const org of orgs) { + const projectsResult = await withAuthGuard(() => + fetchOrgProjects(org.slug), + ); + if (projectsResult.ok) { + results.push(...projectsResult.value); + } + } + + return results; } /** diff --git a/packages/cli/src/commands/react-native/gradle.ts b/packages/cli/src/commands/react-native/gradle.ts index 1baf243b9a..23f022edd6 100644 --- a/packages/cli/src/commands/react-native/gradle.ts +++ b/packages/cli/src/commands/react-native/gradle.ts @@ -217,7 +217,6 @@ export const gradleCommand = buildCommand({ log.info( `Uploading sourcemaps for release ${flags.release} distribution ${dist}`, ); - // oxlint-disable-next-line no-await-in-loop -- each upload already sends its chunks in parallel; one dist at a time keeps that cap await uploadSourcemaps({ org, project, diff --git a/packages/cli/src/commands/react-native/xcode.ts b/packages/cli/src/commands/react-native/xcode.ts index c94d18c806..8ab1707bdf 100644 --- a/packages/cli/src/commands/react-native/xcode.ts +++ b/packages/cli/src/commands/react-native/xcode.ts @@ -151,7 +151,6 @@ async function waitUntilAvailable( const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { try { - // oxlint-disable-next-line no-await-in-loop -- polls the URL until it answers or the deadline passes const res = await fetch(url, { method: "GET" }); if (res.status < 500) { return true; @@ -159,7 +158,6 @@ async function waitUntilAvailable( } catch (err) { log.debug("Packager not up yet", err); } - // oxlint-disable-next-line no-await-in-loop -- polls the URL until it answers or the deadline passes await sleep(500); } return false; @@ -361,7 +359,6 @@ async function uploadPair( let uploads = 0; if (dists.length > 0) { for (const d of dists) { - // oxlint-disable-next-line no-await-in-loop -- each upload already sends its chunks in parallel; one dist at a time keeps that cap await uploadSourcemaps({ org, project, diff --git a/packages/cli/src/commands/sourcemap/upload.ts b/packages/cli/src/commands/sourcemap/upload.ts index 4f1045a848..f93e3f377e 100644 --- a/packages/cli/src/commands/sourcemap/upload.ts +++ b/packages/cli/src/commands/sourcemap/upload.ts @@ -28,11 +28,9 @@ import { parseText, } from "../../lib/completion-target.js"; import { ContextError, ValidationError } from "../../lib/errors.js"; -import { mapBounded } from "../../lib/fan-out.js"; import { mdKvTable, renderMarkdown } from "../../lib/formatters/markdown.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { resolveOrgAndProject } from "../../lib/resolve-target.js"; -import { CONCURRENCY_LIMIT } from "../../lib/scan/constants.js"; import { assertDirectoryReadable, buildEmptyDiscoveryError, @@ -266,19 +264,18 @@ async function stripUploadedSources( files: ArtifactFile[], strip: SourcesStrip, ): Promise { - await mapBounded( - files.filter((file) => file.type === "source_map"), - async (file) => { - const json = file.content - ? file.content.toString("utf-8") - : await readFile(file.path, "utf-8"); - const stripped = stripSourcemapSources(json, strip); - if (stripped !== undefined) { - file.content = Buffer.from(stripped); - } - }, - CONCURRENCY_LIMIT, - ); + for (const file of files) { + if (file.type !== "source_map") { + continue; + } + const json = file.content + ? file.content.toString("utf-8") + : await readFile(file.path, "utf-8"); + const stripped = stripSourcemapSources(json, strip); + if (stripped !== undefined) { + file.content = Buffer.from(stripped); + } + } } export const uploadCommand = buildCommand({ diff --git a/packages/cli/src/lib/agent-skills.ts b/packages/cli/src/lib/agent-skills.ts index b663450aa4..09feaf3dd1 100644 --- a/packages/cli/src/lib/agent-skills.ts +++ b/packages/cli/src/lib/agent-skills.ts @@ -116,7 +116,6 @@ async function writeSkillFiles( if (!existsSync(dir)) { mkdirSync(dir, { recursive: true, mode: 0o755 }); } - // oxlint-disable-next-line no-await-in-loop -- writes the skill files one at a time; a failure stops before the next write await atomicWriteFile(fullPath, content); if (relativePath.startsWith("references/")) { referenceCount += 1; @@ -181,7 +180,6 @@ export async function installAgentSkills( continue; } - // oxlint-disable-next-line no-await-in-loop -- writes the skill files one at a time; a failure stops before the next write const location = await writeSkillFiles( getSkillInstallPath(homeDir, target.rootDir), ); diff --git a/packages/cli/src/lib/api/attribute-pagination.ts b/packages/cli/src/lib/api/attribute-pagination.ts index 70e6f908e5..4f70eb8e9c 100644 --- a/packages/cli/src/lib/api/attribute-pagination.ts +++ b/packages/cli/src/lib/api/attribute-pagination.ts @@ -96,7 +96,6 @@ export async function fetchAttributeTypePage( // coordinate system, so paginate()'s row-count bookmarks do not apply. // oxlint-disable-next-line sentry-cli/no-manual-pagination -- requires key bookmarks and cross-page deduplication for (let pageIndex = 0; pageIndex < MAX_PAGINATION_PAGES; pageIndex++) { - // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const page = await listTraceItemAttributes(org, { ...options, attributeTypes: [type], diff --git a/packages/cli/src/lib/api/chunk-upload.ts b/packages/cli/src/lib/api/chunk-upload.ts index 4a93b422b4..9cc5d3877b 100644 --- a/packages/cli/src/lib/api/chunk-upload.ts +++ b/packages/cli/src/lib/api/chunk-upload.ts @@ -374,7 +374,6 @@ export async function hashChunks( for (let offset = 0; offset < fileSize; offset += chunkSize) { const size = Math.min(chunkSize, fileSize - offset); const buf = Buffer.alloc(size); - // oxlint-disable-next-line no-await-in-loop -- reads the file into one reused buffer, one chunk at a time await fh.read(buf, 0, size, offset); const sha1 = createHash("sha1").update(buf).digest("hex"); overallHasher.update(buf); @@ -583,14 +582,8 @@ async function uploadChunkBatch(params: { const fieldName = encoding === "gzip" ? "file_gzip" : "file"; const form = new FormData(); - // The batch is capped by the server's chunksPerRequest, so encode it at once. - const encoded = await Promise.all( - batch.map(async (chunk) => ({ - chunk, - payload: await encodeChunk(chunk.data, encoding), - })), - ); - for (const { chunk, payload } of encoded) { + for (const chunk of batch) { + const payload = await encodeChunk(chunk.data, encoding); form.append( fieldName, new Blob([payload], { type: "application/octet-stream" }), @@ -786,10 +779,8 @@ export async function pollAssembly(params: { const deadline = Date.now() + deadlineMs; while (Date.now() < deadline) { - // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); - // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done const pollResult = await assemble(); if (pollResult.state === "ok") { diff --git a/packages/cli/src/lib/api/code-mappings.ts b/packages/cli/src/lib/api/code-mappings.ts index caf918176e..4df974f603 100644 --- a/packages/cli/src/lib/api/code-mappings.ts +++ b/packages/cli/src/lib/api/code-mappings.ts @@ -119,7 +119,6 @@ export async function uploadCodeMappings( ); } - // oxlint-disable-next-line no-await-in-loop -- batches upsert into one project and repository, one request at a time const result = await bulkUpsertOrganizationCodeMappings({ ...config, path: { organization_id_or_slug: org }, diff --git a/packages/cli/src/lib/api/conversations.ts b/packages/cli/src/lib/api/conversations.ts index f1fd2f5427..c785747fc4 100644 --- a/packages/cli/src/lib/api/conversations.ts +++ b/packages/cli/src/lib/api/conversations.ts @@ -135,7 +135,6 @@ export async function getConversationSpans( let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { - // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const result = await retrieveOrganizationAiConversation({ ...config, path: { diff --git a/packages/cli/src/lib/api/dart-symbols.ts b/packages/cli/src/lib/api/dart-symbols.ts index d17c02c875..a982b81bee 100644 --- a/packages/cli/src/lib/api/dart-symbols.ts +++ b/packages/cli/src/lib/api/dart-symbols.ts @@ -166,10 +166,8 @@ export async function uploadDartSymbolMap( // Step 6: Poll assemble endpoint until done const deadline = Date.now() + ASSEMBLE_MAX_WAIT_MS; while (Date.now() < deadline) { - // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); - // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done const pollResult = await assembleDebugFiles(org, project, assembleBody); const { allDone: done } = checkAssembleResponse( diff --git a/packages/cli/src/lib/api/dashboards.ts b/packages/cli/src/lib/api/dashboards.ts index 3e64899632..498ece60d9 100644 --- a/packages/cli/src/lib/api/dashboards.ts +++ b/packages/cli/src/lib/api/dashboards.ts @@ -52,7 +52,6 @@ import { import type { EventsDataset } from "../datasets.js"; import { reportCliError } from "../error-reporting.js"; import { ApiError, stringifyUnknown } from "../errors.js"; -import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; import { getSdkClientConfig } from "../sentry-sdk-client.js"; @@ -582,7 +581,6 @@ async function queryWidgetTimeseries( const aggregates = query.aggregates ?? []; const columns = query.columns ?? []; - // oxlint-disable-next-line no-await-in-loop -- widgets already fan out at ORG_FANOUT_CONCURRENCY; a widget's queries run in turn so the total stays at that cap const result = await listOrganizationEventsTimeseries({ ...getSdkClientConfig(regionUrl), path: { organization_id_or_slug: orgSlug }, @@ -801,6 +799,28 @@ function widgetErrorMessage(error: unknown): string { * @param options - Query options (period override, environment filter) * @returns Map of widget index → query result */ +/** Collect settled results from a batch into the results map. */ +function collectBatchResults( + batchResults: PromiseSettledResult[], + startIndex: number, + results: Map, +): void { + for (let j = 0; j < batchResults.length; j++) { + const result = batchResults[j]; + const idx = startIndex + j; + if (result?.status === "fulfilled") { + results.set(idx, result.value); + } else { + results.set(idx, { + type: "error", + message: result?.reason + ? stringifyUnknown(result.reason) + : "Unknown error", + }); + } + } +} + export async function queryAllWidgets( regionUrl: string, orgSlug: string, @@ -822,11 +842,18 @@ export async function queryAllWidgets( project: options.project ?? dashboard.projects ?? undefined, }; - const widgetResults = await mapBounded( - widgets, - async (widget): Promise => { - try { - return await queryWidgetData({ + const results = new Map(); + if (widgets.length === 0) { + return results; + } + + // Process in batches to respect concurrency limit + const batchSize = ORG_FANOUT_CONCURRENCY; + for (let i = 0; i < widgets.length; i += batchSize) { + const batch = widgets.slice(i, i + batchSize); + const batchResults = await Promise.allSettled( + batch.map((widget) => + queryWidgetData({ regionUrl, orgSlug, widget, @@ -835,17 +862,13 @@ export async function queryAllWidgets( end: options.end, periodSeconds: options.periodSeconds, options: mergedOptions, - }); - } catch (error) { - return { - type: "error", - message: error ? stringifyUnknown(error) : "Unknown error", - }; - } - }, - ORG_FANOUT_CONCURRENCY, - ); - return new Map(widgetResults.entries()); + }), + ), + ); + collectBatchResults(batchResults, i, results); + } + + return results; } /** Material unintentional drops for one dataset of a dashboard's widgets. */ diff --git a/packages/cli/src/lib/api/debug-files.ts b/packages/cli/src/lib/api/debug-files.ts index bcd996e08c..923349d322 100644 --- a/packages/cli/src/lib/api/debug-files.ts +++ b/packages/cli/src/lib/api/debug-files.ts @@ -19,7 +19,6 @@ */ import { ApiError, ValidationError } from "../errors.js"; -import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; import { resolveOrgRegion } from "../region.js"; import { @@ -38,7 +37,6 @@ import { type UploadEncoding, uploadChunkPayloads, } from "./chunk-upload.js"; -import { ORG_FANOUT_CONCURRENCY } from "./infrastructure.js"; const log = logger.withTag("api.debug-files"); @@ -361,14 +359,9 @@ async function postAssemble( project: string, bodies: readonly Record[], ): Promise { - const responses = await mapBounded( - bodies, - (body) => assembleDebugFiles(org, project, body), - ORG_FANOUT_CONCURRENCY, - ); const merged: DifAssembleResponse = {}; - for (const response of responses) { - Object.assign(merged, response); + for (const body of bodies) { + Object.assign(merged, await assembleDebugFiles(org, project, body)); } return merged; } @@ -591,14 +584,11 @@ export async function uploadDebugFiles( break; } - // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); - // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done response = await postAssemble(org, project, bodies); evaluation = evaluateAssembly(response, chunked, wait); reportProcessing(); // Re-sends report progress too, so a long retry does not look hung. - // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await uploadMissing({ chunked, missingChecksums: evaluation.missingChecksums, diff --git a/packages/cli/src/lib/api/explore.ts b/packages/cli/src/lib/api/explore.ts index 8cdf87b220..b72a38dce1 100644 --- a/packages/cli/src/lib/api/explore.ts +++ b/packages/cli/src/lib/api/explore.ts @@ -225,7 +225,6 @@ export async function queryMetricsMeta( let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page += 1) { - // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const result = await fetchEventsPage( regionUrl, orgSlug, diff --git a/packages/cli/src/lib/api/infrastructure.ts b/packages/cli/src/lib/api/infrastructure.ts index 2878d4f1e5..0fd9924744 100644 --- a/packages/cli/src/lib/api/infrastructure.ts +++ b/packages/cli/src/lib/api/infrastructure.ts @@ -856,7 +856,6 @@ export async function autoPaginate( let cursor: string | undefined = initialCursor; for (let page = 0; page < MAX_PAGINATION_PAGES; page += 1) { - // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const result = await fetchPage(cursor); allRows.push(...result.data); diff --git a/packages/cli/src/lib/api/issue-app-links.ts b/packages/cli/src/lib/api/issue-app-links.ts index b8b206334c..8986b147ef 100644 --- a/packages/cli/src/lib/api/issue-app-links.ts +++ b/packages/cli/src/lib/api/issue-app-links.ts @@ -514,7 +514,6 @@ async function resolveFields( ); } pending.splice(index, 1); - // oxlint-disable-next-line no-await-in-loop -- a field resolves only after the fields it depends on values[field.name] = await resolveFieldValue({ field, targetField, diff --git a/packages/cli/src/lib/api/preprod-artifacts.ts b/packages/cli/src/lib/api/preprod-artifacts.ts index 7c1d8f9cf9..21e49876ac 100644 --- a/packages/cli/src/lib/api/preprod-artifacts.ts +++ b/packages/cli/src/lib/api/preprod-artifacts.ts @@ -305,7 +305,6 @@ export async function uploadBuild( const deadline = Date.now() + ASSEMBLE_MAX_WAIT_MS; while (Date.now() < deadline) { - // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done const result = await assembleProjectPreprodArtifact({ ...config, path: { organization_id_or_slug: org, project_id_or_slug: project }, @@ -343,7 +342,6 @@ export async function uploadBuild( const missing = new Set(data.missingChunks ?? []); if (missing.size > 0) { - // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await uploadMissingChunks({ chunks, missingChecksums: missing, @@ -356,7 +354,6 @@ export async function uploadBuild( // Always pace between assemble POSTs (matches the legacy poll loop and // avoids a busy loop should the server keep reporting the same chunks). - // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); } @@ -604,7 +601,6 @@ export async function waitForSnapshotArchive( onBuildStarted?.(); const deadline = Date.now() + SNAPSHOT_ARCHIVE_TIMEOUT_MS; - // oxlint-disable-next-line no-await-in-loop -- polls until the snapshot archive is ready while (!(await getSnapshotArchiveReady(org, snapshotId))) { if (Date.now() >= deadline) { throw new TimeoutError( @@ -613,7 +609,6 @@ export async function waitForSnapshotArchive( }s. The build may still be running; try again shortly.`, ); } - // oxlint-disable-next-line no-await-in-loop -- polls until the snapshot archive is ready await new Promise((r) => setTimeout(r, SNAPSHOT_ARCHIVE_POLL_MS)); } } diff --git a/packages/cli/src/lib/api/proguard.ts b/packages/cli/src/lib/api/proguard.ts index ded82e9e3b..1beee0dac9 100644 --- a/packages/cli/src/lib/api/proguard.ts +++ b/packages/cli/src/lib/api/proguard.ts @@ -170,9 +170,8 @@ export async function uploadProguardMappings( return; } - // Step 5: Upload missing chunks, one mapping at a time + // Step 5: Upload missing chunks in parallel across all mappings for (const cm of chunkedMappings) { - // oxlint-disable-next-line no-await-in-loop -- each call already uploads its chunks at serverOptions.concurrency; one mapping at a time keeps that cap await uploadMissingBufferChunks({ chunks: cm.chunks, missingChecksums, @@ -206,10 +205,8 @@ async function pollDifAssembly(params: { const deadline = Date.now() + ASSEMBLE_MAX_WAIT_MS; while (Date.now() < deadline) { - // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); - // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done const pollResult = await assemble(); const { allDone } = checkAssembleResponse(pollResult, checksums, endpoint); diff --git a/packages/cli/src/lib/api/releases.ts b/packages/cli/src/lib/api/releases.ts index bc5bd61b95..4b712f9998 100644 --- a/packages/cli/src/lib/api/releases.ts +++ b/packages/cli/src/lib/api/releases.ts @@ -636,7 +636,6 @@ async function findSentryRepository( for (const query of queries) { let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { - // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const result = await listRepositoriesPaginated(orgSlug, { cursor, perPage: API_MAX_PER_PAGE, diff --git a/packages/cli/src/lib/api/replays.ts b/packages/cli/src/lib/api/replays.ts index 4a6b9d0f46..cfd0ae7f5c 100644 --- a/packages/cli/src/lib/api/replays.ts +++ b/packages/cli/src/lib/api/replays.ts @@ -344,7 +344,6 @@ export async function getReplayRecordingSegments( let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page += 1) { - // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await fetchReplayRecordingSegmentsPage({ orgSlug, projectSlugOrId, diff --git a/packages/cli/src/lib/bash-hook/traceback.ts b/packages/cli/src/lib/bash-hook/traceback.ts index 8b43b4ad0b..9ff018d4aa 100644 --- a/packages/cli/src/lib/bash-hook/traceback.ts +++ b/packages/cli/src/lib/bash-hook/traceback.ts @@ -12,10 +12,8 @@ import { readFile } from "node:fs/promises"; import type { Breadcrumb, Event, StackFrame } from "@sentry/core"; import { uuid4 } from "@sentry/core"; import { ValidationError } from "../errors.js"; -import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; import { omitUndefined } from "../omit-undefined.js"; -import { CONCURRENCY_LIMIT } from "../scan/constants.js"; const log = logger.withTag("bash-hook.traceback"); @@ -122,38 +120,30 @@ export function parseTracebackContent(content: string): TracebackData { * Enrich stack frames with source context from the original files. * * Reads each frame's source file and attaches ±5 lines of context around - * the error line. Each distinct file is read once. + * the error line. File contents are cached to avoid redundant reads. */ async function enrichFramesWithSourceContext( frames: StackFrame[], ): Promise { - const filenames = new Set( - frames.flatMap((frame) => - frame.filename && frame.lineno ? [frame.filename] : [], - ), - ); - const sources = new Map( - await mapBounded( - filenames, - async (filename) => { - try { - const content = await readFile(filename, "utf-8"); - return [filename, content.split("\n")] as const; - } catch (err) { - log.debug(`Could not read source file ${filename}`, err); - return [filename, null] as const; - } - }, - CONCURRENCY_LIMIT, - ), - ); + const sourceCache = new Map(); for (const frame of frames) { if (!(frame.filename && frame.lineno)) { continue; } - const lines = sources.get(frame.filename); + let lines = sourceCache.get(frame.filename); + if (lines === undefined) { + try { + const content = await readFile(frame.filename, "utf-8"); + lines = content.split("\n"); + } catch (err) { + log.debug(`Could not read source file ${frame.filename}`, err); + lines = null; + } + sourceCache.set(frame.filename, lines); + } + if (!lines) { continue; } diff --git a/packages/cli/src/lib/build/asset-catalog-extract.ts b/packages/cli/src/lib/build/asset-catalog-extract.ts index ee45ea3e18..b725227428 100644 --- a/packages/cli/src/lib/build/asset-catalog-extract.ts +++ b/packages/cli/src/lib/build/asset-catalog-extract.ts @@ -32,9 +32,7 @@ import { strictObject, string, } from "valibot"; -import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; -import { CONCURRENCY_LIMIT } from "../scan/constants.js"; import { getSeaRawAsset } from "../sea-assets.js"; const log = logger.withTag("build.asset-catalog"); @@ -168,33 +166,35 @@ async function canonicalizeOutput( const manifest: unknown = JSON.parse(await readFile(manifestPath, "utf8")); const assets = parse(array(AssetCatalogEntrySchema), manifest); const seenIds = new Set(); - for (const { imageId } of assets) { + const renditions = []; + for (const { imageId, ...asset } of assets) { if (imageId && seenIds.has(imageId)) { throw new Error("Asset-catalog manifest contains duplicate image IDs"); } seenIds.add(imageId); + // NSString.pathExtension treats a trailing dot as an empty extension. + const extension = `.${ + posix + .extname(asset.filename ?? "") + .slice(1) + .toLowerCase() || "png" + }`; + const sourcePath = join(outputDirectory, `${imageId}${extension}`); + const hasImage = + imageId !== "" && + IMAGE_EXTENSIONS.has(extension) && + (await regularFile(sourcePath)); + const hash = hasImage ? await imageHash(sourcePath) : ""; + const identity = `${catalogRelativePath}\0${JSON.stringify(asset)}\0${hash}`; + renditions.push({ + imageId, + asset, + extension, + sourcePath, + hasImage, + identity, + }); } - const renditions = await mapBounded( - assets, - async ({ imageId, ...asset }) => { - // NSString.pathExtension treats a trailing dot as an empty extension. - const extension = `.${ - posix - .extname(asset.filename ?? "") - .slice(1) - .toLowerCase() || "png" - }`; - const sourcePath = join(outputDirectory, `${imageId}${extension}`); - const hasImage = - imageId !== "" && - IMAGE_EXTENSIONS.has(extension) && - (await regularFile(sourcePath)); - const hash = hasImage ? await imageHash(sourcePath) : ""; - const identity = `${catalogRelativePath}\0${JSON.stringify(asset)}\0${hash}`; - return { imageId, asset, extension, sourcePath, hasImage, identity }; - }, - CONCURRENCY_LIMIT, - ); renditions.sort((a, b) => a.identity < b.identity ? -1 : a.identity > b.identity ? 1 : 0, ); @@ -203,7 +203,6 @@ async function canonicalizeOutput( const occurrences = new Map(); const canonicalAssets: AssetCatalogEntry[] = []; const files: AssetCatalogExtraction["files"] = []; - const copies: { from: string; to: string }[] = []; for (const rendition of renditions) { const occurrence = occurrences.get(rendition.identity) ?? 0; occurrences.set(rendition.identity, occurrence + 1); @@ -214,15 +213,10 @@ async function canonicalizeOutput( if (rendition.hasImage) { const name = `${imageId}${rendition.extension}`; const sourcePath = join(canonicalDirectory, name); - copies.push({ from: rendition.sourcePath, to: sourcePath }); + await copyFile(rendition.sourcePath, sourcePath, COPY_FILE_FLAGS); files.push({ name, sourcePath }); } } - await mapBounded( - copies, - ({ from, to }) => copyFile(from, to, COPY_FILE_FLAGS), - CONCURRENCY_LIMIT, - ); const sourcePath = join(canonicalDirectory, "Assets.json"); await writeFile(sourcePath, `${JSON.stringify(canonicalAssets)}\n`); files.push({ name: "Assets.json", sourcePath }); diff --git a/packages/cli/src/lib/build/dsyms.ts b/packages/cli/src/lib/build/dsyms.ts index 6fe2ff1454..68aa605aae 100644 --- a/packages/cli/src/lib/build/dsyms.ts +++ b/packages/cli/src/lib/build/dsyms.ts @@ -49,7 +49,6 @@ async function collectBundle( ); } if (dirent.isDirectory()) { - // oxlint-disable-next-line no-await-in-loop -- walks the bundle depth-first so entries keep their order entries.push(...(await collectBundle(sourcePath, relPath))); } else if (dirent.isFile()) { entries.push({ relPath, sourcePath }); @@ -175,7 +174,6 @@ export async function collectDsymEntries( ): Promise { const entries: DsymEntry[] = []; const seenBundles = new Set(); - // oxlint-disable no-await-in-loop -- inputs are staged in argument order, and bundle names must be unique across them for (const input of paths) { // resolve strips trailing separators before lstat and extension detection. // lstat("link.dSYM/") would otherwise follow a directory symlink on POSIX. @@ -221,6 +219,5 @@ export async function collectDsymEntries( entries.push(...files); } } - // oxlint-enable no-await-in-loop return entries; } diff --git a/packages/cli/src/lib/build/index.ts b/packages/cli/src/lib/build/index.ts index d5117ce9b6..2c8bab5082 100644 --- a/packages/cli/src/lib/build/index.ts +++ b/packages/cli/src/lib/build/index.ts @@ -173,7 +173,6 @@ export async function detectBuildFormatFromFile( const size = (await src.stat()).size; let position = 0; while (position < size) { - // oxlint-disable-next-line no-await-in-loop -- reads the file into one reused buffer, one chunk at a time const read = await src.read(buf, 0, buf.length, position); if (read.bytesRead === 0) { break; @@ -368,10 +367,8 @@ async function collectArchiveEntries(root: string): Promise { // not descended into (matching Rust's WalkDir with follow_links = false). let payload: { sourcePath: string } | { linkTarget: Uint8Array }; if (dirent.isSymbolicLink()) { - // oxlint-disable-next-line no-await-in-loop -- walks the tree depth-first so archive entries keep a stable order payload = { linkTarget: strToU8(await readlink(full)) }; } else if (dirent.isDirectory()) { - // oxlint-disable-next-line no-await-in-loop -- walks the tree depth-first so archive entries keep a stable order await walk(full, relPath); continue; } else if (dirent.isFile()) { @@ -383,7 +380,6 @@ async function collectArchiveEntries(root: string): Promise { // Encode the full Unix mode (type + permission bits) into the upper 16 // bits of the ZIP external attributes so symlinks and exec bits survive. - // oxlint-disable-next-line no-await-in-loop -- walks the tree depth-first so archive entries keep a stable order const { mode } = await lstat(full); const attrs = ((mode & 0xff_ff) << 16) >>> 0; entries.push({ relPath, attrs, ...payload }); @@ -433,10 +429,8 @@ export async function normalizeBuildDirectory( const name = `${dirName}/${entry.relPath}`; const options = { os: ZIP_OS_UNIX, attrs: entry.attrs }; if ("sourcePath" in entry) { - // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addFile(name, entry.sourcePath, options); } else { - // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addData(name, entry.linkTarget, options); } } @@ -469,7 +463,6 @@ async function addParsedAssetCatalogs( const files = new Map(); try { for (const catalog of catalogs) { - // oxlint-disable-next-line no-await-in-loop -- each extraction runs the asset-catalog helper; the finally block cleans up only the extractions that finished const extraction = await extractAssetCatalogImages( catalog.relPath, catalog.sourcePath, @@ -505,11 +498,12 @@ async function addParsedAssetCatalogs( for (const [name, sourcePath] of [...files].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0, )) { - // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addFile(name, sourcePath); } } finally { - await Promise.all(extractions.map((extraction) => extraction.cleanup())); + for (const extraction of extractions) { + await extraction.cleanup(); + } } } @@ -719,9 +713,7 @@ async function stageIpaPayload( const staged: StagedIpaEntry[] = []; for (const { name, entry } of await readIpaPayloadEntries(ipaPath, zip)) { const stagePath = join(stageDir, `e${staged.length}`); - // oxlint-disable-next-line no-await-in-loop -- copies IPA entries in archive order from one open zip await pipeline( - // oxlint-disable-next-line no-await-in-loop -- copies IPA entries in archive order from one open zip await zip.openReadStreamPromise(entry), createWriteStream(stagePath), ); @@ -826,10 +818,8 @@ export async function normalizeIpa( try { for (const item of items) { if (item.stagePath !== undefined) { - // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addFile(item.name, item.stagePath, item.options); } else if (item.data !== undefined) { - // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addData(item.name, item.data); } } diff --git a/packages/cli/src/lib/build/zip-writer.ts b/packages/cli/src/lib/build/zip-writer.ts index 3bfa649f96..b9c34687a5 100644 --- a/packages/cli/src/lib/build/zip-writer.ts +++ b/packages/cli/src/lib/build/zip-writer.ts @@ -203,7 +203,6 @@ export class DeterministicZipWriter { let size = 0; const buf = Buffer.allocUnsafe(STREAM_CHUNK_SIZE); for (;;) { - // oxlint-disable-next-line no-await-in-loop -- reads the source into one reused buffer, one chunk at a time const { bytesRead } = await src.read(buf, 0, buf.length, null); if (bytesRead === 0) { break; @@ -218,12 +217,10 @@ export class DeterministicZipWriter { // Pass 2: copy the stored bytes. let position = 0; while (position < size) { - // oxlint-disable-next-line no-await-in-loop -- reads the source into one reused buffer, one chunk at a time const { bytesRead } = await src.read(buf, 0, buf.length, position); if (bytesRead === 0) { break; } - // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await this.fh.write(buf, 0, bytesRead); position += bytesRead; } @@ -261,9 +258,7 @@ export class DeterministicZipWriter { rec.writeUInt32LE(entry.attrs, 38); // external attributes rec.writeUInt32LE(entry.localHeaderOffset, 42); - // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await this.fh.write(rec, 0, rec.length); - // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await this.fh.write(entry.nameBytes, 0, entry.nameBytes.length); this.offset += CENTRAL_HEADER_FIXED_SIZE + entry.nameBytes.length; } diff --git a/packages/cli/src/lib/command.ts b/packages/cli/src/lib/command.ts index af2f98ce4e..63060f0098 100644 --- a/packages/cli/src/lib/command.ts +++ b/packages/cli/src/lib/command.ts @@ -928,7 +928,6 @@ export function buildCommand< let result = await generator.next(); while (!result.done) { handleYieldedValue(stdout, result.value, cleanFlags, renderer); - // oxlint-disable-next-line no-await-in-loop -- drives the generator one step at a time result = await generator.next(); } return result.value as CommandReturn | undefined; diff --git a/packages/cli/src/lib/complete.ts b/packages/cli/src/lib/complete.ts index a7639d6d26..0b0e16fc84 100644 --- a/packages/cli/src/lib/complete.ts +++ b/packages/cli/src/lib/complete.ts @@ -844,7 +844,6 @@ async function positionalOrg( positionals: readonly string[], ): Promise { for (const word of positionals) { - // oxlint-disable-next-line no-await-in-loop -- checks positionals in order and stops at the first that names an org const scope = await parseTargetScope(word); if (scope?.org) { return scope.org; diff --git a/packages/cli/src/lib/db/dsn-cache.ts b/packages/cli/src/lib/db/dsn-cache.ts index da5722fd0c..538169fdda 100644 --- a/packages/cli/src/lib/db/dsn-cache.ts +++ b/packages/cli/src/lib/db/dsn-cache.ts @@ -14,8 +14,6 @@ import type { ResolvedProjectInfo, } from "../dsn/types.js"; import { invocationState } from "../env.js"; -import { mapBounded } from "../fan-out.js"; -import { CONCURRENCY_LIMIT } from "../scan/constants.js"; import { getDatabase, maybeCleanupCaches, recordCacheHit } from "./index.js"; import { safeParseJson } from "./json.js"; import { runUpsert, touchCacheEntry } from "./utils.js"; @@ -291,13 +289,13 @@ async function validateSourceMtimes( projectRoot: string, sourceMtimes: Record, ): Promise { - const matches = await mapBounded( - Object.entries(sourceMtimes), - ([relativePath, cachedMtime]) => - validateFileMtime(join(projectRoot, relativePath), cachedMtime), - CONCURRENCY_LIMIT, - ); - return matches.every(Boolean); + for (const [relativePath, cachedMtime] of Object.entries(sourceMtimes)) { + const fullPath = join(projectRoot, relativePath); + if (!(await validateFileMtime(fullPath, cachedMtime))) { + return false; + } + } + return true; } /** @@ -312,13 +310,13 @@ async function validateDirMtimes( projectRoot: string, dirMtimes: Record, ): Promise { - const matches = await mapBounded( - Object.entries(dirMtimes), - ([relativePath, cachedMtime]) => - validateDirMtime(join(projectRoot, relativePath), cachedMtime), - CONCURRENCY_LIMIT, - ); - return matches.every(Boolean); + for (const [relativePath, cachedMtime] of Object.entries(dirMtimes)) { + const fullPath = join(projectRoot, relativePath); + if (!(await validateDirMtime(fullPath, cachedMtime))) { + return false; + } + } + return true; } /** Type guard: value is a plain object with all-numeric values (mtimes record). */ diff --git a/packages/cli/src/lib/detect-agent.ts b/packages/cli/src/lib/detect-agent.ts index 81d3207d2b..1fa3519a90 100644 --- a/packages/cli/src/lib/detect-agent.ts +++ b/packages/cli/src/lib/detect-agent.ts @@ -326,7 +326,6 @@ export async function detectAgentFromProcessTree(): Promise< let pid = process.ppid; for (let depth = 0; depth < MAX_ANCESTOR_DEPTH && pid > 1; depth++) { - // oxlint-disable-next-line no-await-in-loop -- walks up the process tree; each parent comes from the step before const info = await _getProcessInfo(pid); if (!info) { break; diff --git a/packages/cli/src/lib/dev-script.ts b/packages/cli/src/lib/dev-script.ts index ae362c2bc3..edf86e5b1c 100644 --- a/packages/cli/src/lib/dev-script.ts +++ b/packages/cli/src/lib/dev-script.ts @@ -788,7 +788,6 @@ async function tryDockerCompose(cwd: string): Promise { for (const filename of ["docker-compose.yml", "compose.yml"]) { // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. try { - // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match await access(join(cwd, filename)); return { args: ["docker", "compose", "up"], source: filename }; } catch { diff --git a/packages/cli/src/lib/dif/find.ts b/packages/cli/src/lib/dif/find.ts index 133b58ac60..7ca4c18786 100644 --- a/packages/cli/src/lib/dif/find.ts +++ b/packages/cli/src/lib/dif/find.ts @@ -318,7 +318,6 @@ export async function findDebugFiles(opts: FindOptions): Promise { continue; } seen.add(abs); - // oxlint-disable-next-line no-await-in-loop -- walks the paths in order and stops once every requested ID is found for await (const entry of walkPath(path)) { if (state.remaining.size === 0) { break; diff --git a/packages/cli/src/lib/dif/scan.ts b/packages/cli/src/lib/dif/scan.ts index 467ff0771f..afc91af95e 100644 --- a/packages/cli/src/lib/dif/scan.ts +++ b/packages/cli/src/lib/dif/scan.ts @@ -309,12 +309,10 @@ export async function scanPaths(paths: string[]): Promise { }; for (const path of paths) { - // oxlint-disable-next-line no-await-in-loop -- walks the paths in argument order so the deduplicated file list keeps it const info = await statExplicitPath(path); if (info.isFile()) { add(path); } else if (info.isDirectory()) { - // oxlint-disable-next-line no-await-in-loop -- walks the paths in argument order so the deduplicated file list keeps it for await (const entry of walkDebugFileDir(path)) { add(entry.absolutePath); } @@ -508,7 +506,6 @@ export async function prepareDifs( // means the path was a `.zip` and is fully handled. `null` means "not a // zip" — fall through to normal file handling. if (scanZips) { - // oxlint-disable-next-line no-await-in-loop -- zip inputs are inflated in memory; one path at a time keeps one archive in memory const zipPrepared = await prepareZipDifs( path, filters, @@ -528,7 +525,6 @@ export async function prepareDifs( } } - // oxlint-disable-next-line no-await-in-loop -- zip inputs are inflated in memory; one path at a time keeps one archive in memory const { difs, oversized } = await prepareFileDif( path, filters, diff --git a/packages/cli/src/lib/docs-context.ts b/packages/cli/src/lib/docs-context.ts index 197ea1c7d8..5ce885daf2 100644 --- a/packages/cli/src/lib/docs-context.ts +++ b/packages/cli/src/lib/docs-context.ts @@ -104,40 +104,29 @@ export async function detectDocsContextFromReader( const languages = new Set(); let sentryConfigured = false; - const [manifests, configs] = await Promise.all([ - Promise.all( - DOCS_CONTEXT_MANIFESTS.map(async (manifest) => { - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - try { - return { manifest, contents: await reader.readManifest(manifest) }; - } catch { - // Missing/unreadable metadata is optional and must not block lookup. - return { manifest, contents: undefined }; - } - }), - ), - Promise.all( - DOCS_CONTEXT_CONFIGS.map(async (config) => { - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - try { - return await reader.hasConfig(config); - } catch { - // Config presence is an optional signal only. - return false; - } - }), - ), - ]); + for (const manifest of DOCS_CONTEXT_MANIFESTS) { + // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. + try { + const contents = await reader.readManifest(manifest); + if (contents === undefined) { + continue; + } + addLanguageSignal(manifest, languages); + addFrameworkSignals(contents, frameworks); + sentryConfigured ||= containsSentrySdk(contents); + } catch { + // Missing/unreadable metadata is optional and must not block lookup. + } + } - for (const { manifest, contents } of manifests) { - if (contents === undefined) { - continue; + for (const config of DOCS_CONTEXT_CONFIGS) { + // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. + try { + sentryConfigured ||= await reader.hasConfig(config); + } catch { + // Config presence is an optional signal only. } - addLanguageSignal(manifest, languages); - addFrameworkSignals(contents, frameworks); - sentryConfigured ||= containsSentrySdk(contents); } - sentryConfigured ||= configs.includes(true); return { frameworks: [...frameworks].sort(), diff --git a/packages/cli/src/lib/dsn/env-file.ts b/packages/cli/src/lib/dsn/env-file.ts index 2f80eb9d32..e4409a560e 100644 --- a/packages/cli/src/lib/dsn/env-file.ts +++ b/packages/cli/src/lib/dsn/env-file.ts @@ -199,61 +199,43 @@ export async function detectFromAllEnvFiles( export async function detectFromMonorepoEnvFiles( cwd: string, ): Promise { - const roots = await Promise.all( - MONOREPO_ROOTS.map((monorepoRoot) => - detectFromMonorepoRoot(cwd, monorepoRoot), - ), - ); const dsns: DetectedDsn[] = []; const sourceMtimes: Record = {}; let packagesScanned = 0; - for (const root of roots) { - dsns.push(...root.dsns); - Object.assign(sourceMtimes, root.sourceMtimes); - packagesScanned += root.packagesScanned; - } - return { dsns, sourceMtimes, packagesScanned }; -} -/** Detect DSNs from .env files in the packages of one monorepo root. */ -async function detectFromMonorepoRoot( - cwd: string, - monorepoRoot: string, -): Promise> { - const dsns: DetectedDsn[] = []; - const sourceMtimes: Record = {}; - let packagesScanned = 0; - const rootDir = join(cwd, monorepoRoot); + for (const monorepoRoot of MONOREPO_ROOTS) { + const rootDir = join(cwd, monorepoRoot); - // Bun's opendir() may not throw on a missing directory — the error - // surfaces when iterating. Wrap the full open+iterate in one try/catch. - // No explicit handle.close() needed: for-await-of auto-closes the Dir - // handle when the loop exits (including early return or break). - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - try { - for await (const entry of await opendir(rootDir)) { - // Skip hidden dirs (.git, .cache) and non-directories. Accept - // symlinks too — pnpm/Yarn workspaces can symlink packages, and - // detectDsnInPackage gracefully handles non-directory targets. - if ( - entry.name.startsWith(".") || - !(entry.isDirectory() || entry.isSymbolicLink()) - ) { - continue; - } + // Bun's opendir() may not throw on a missing directory — the error + // surfaces when iterating. Wrap the full open+iterate in one try/catch. + // No explicit handle.close() needed: for-await-of auto-closes the Dir + // handle when the loop exits (including early return or break). + // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. + try { + for await (const entry of await opendir(rootDir)) { + // Skip hidden dirs (.git, .cache) and non-directories. Accept + // symlinks too — pnpm/Yarn workspaces can symlink packages, and + // detectDsnInPackage gracefully handles non-directory targets. + if ( + entry.name.startsWith(".") || + !(entry.isDirectory() || entry.isSymbolicLink()) + ) { + continue; + } - packagesScanned += 1; - const pkgDir = join(rootDir, entry.name); - const packagePath = `${monorepoRoot}/${entry.name}`; + packagesScanned += 1; + const pkgDir = join(rootDir, entry.name); + const packagePath = `${monorepoRoot}/${entry.name}`; - const result = await detectDsnInPackage(pkgDir, packagePath); - if (result.dsn) { - dsns.push(result.dsn); - Object.assign(sourceMtimes, result.sourceMtimes); + const result = await detectDsnInPackage(pkgDir, packagePath); + if (result.dsn) { + dsns.push(result.dsn); + Object.assign(sourceMtimes, result.sourceMtimes); + } } + } catch { + // Directory doesn't exist or scan failed, skip this monorepo root } - } catch { - // Directory doesn't exist or scan failed, skip this monorepo root } return { dsns, sourceMtimes, packagesScanned }; diff --git a/packages/cli/src/lib/dsn/project-root.ts b/packages/cli/src/lib/dsn/project-root.ts index 0373c065ba..fa7542c70e 100644 --- a/packages/cli/src/lib/dsn/project-root.ts +++ b/packages/cli/src/lib/dsn/project-root.ts @@ -373,11 +373,9 @@ function checkEnvForDsn(dir: string): Promise { // Guard: skip non-regular files (FIFOs, sockets, etc.) that would block. // 1Password streams secrets via symlinked named pipes; Bun.file().text() // blocks indefinitely on these. - // oxlint-disable-next-line no-await-in-loop -- checks env files in priority order and stops at the first DSN if (!(await isRegularFile(filePath, "checkEnvForDsn.stat"))) { continue; } - // oxlint-disable-next-line no-await-in-loop -- checks env files in priority order and stops at the first DSN const content = await readFile(filePath, "utf-8"); const dsn = extractDsnFromEnvContent(content); if (dsn) { diff --git a/packages/cli/src/lib/dsn/resolver.ts b/packages/cli/src/lib/dsn/resolver.ts index 1a8b87f393..27a9cc0ca1 100644 --- a/packages/cli/src/lib/dsn/resolver.ts +++ b/packages/cli/src/lib/dsn/resolver.ts @@ -9,12 +9,10 @@ import { findProjectByDsn, listOrganizations, listProjects, - ORG_FANOUT_CONCURRENCY, resolveOrgDisplayName, } from "../api-client.js"; import { sentry } from "../app-identity.js"; import { getCachedDsn, updateCachedResolution } from "../db/dsn-cache.js"; -import { mapBounded } from "../fan-out.js"; import { getDsnSourceDescription } from "./detector.js"; import type { DetectedDsn, @@ -159,32 +157,32 @@ type AccessibleProject = { * @returns Array of org/project pairs */ export async function getAccessibleProjects(): Promise { + const results: AccessibleProject[] = []; + // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. try { const orgs = await listOrganizations(); - const orgProjects = await mapBounded( - orgs, - async (org): Promise => { - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - try { - const projects = await listProjects(org.slug); - return projects.map((project) => ({ + for (const org of orgs) { + // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. + try { + const projects = await listProjects(org.slug); + + for (const project of projects) { + results.push({ org: org.slug, project: project.slug, orgName: org.name, projectName: project.name, - })); - } catch { - // Skip orgs we can't access - return []; + }); } - }, - ORG_FANOUT_CONCURRENCY, - ); - return orgProjects.flat(); + } catch { + // Skip orgs we can't access + } + } } catch { // Not authenticated or API error - return []; } + + return results; } diff --git a/packages/cli/src/lib/dsn/scanner.ts b/packages/cli/src/lib/dsn/scanner.ts index adc7c726b5..a296a59dd4 100644 --- a/packages/cli/src/lib/dsn/scanner.ts +++ b/packages/cli/src/lib/dsn/scanner.ts @@ -67,7 +67,6 @@ export async function scanSpecificFiles( const dsns: DetectedDsn[] = []; const sourceMtimes: Record = {}; - // oxlint-disable no-await-in-loop -- files are checked in priority order, and stopOnFirst returns at the first DSN for (const filename of filenames) { const filepath = join(cwd, filename); @@ -113,7 +112,6 @@ export async function scanSpecificFiles( }); } } - // oxlint-enable no-await-in-loop return { dsns, sourceMtimes }; } diff --git a/packages/cli/src/lib/fs-utils.ts b/packages/cli/src/lib/fs-utils.ts index a7a5e49e8e..f58dba46c7 100644 --- a/packages/cli/src/lib/fs-utils.ts +++ b/packages/cli/src/lib/fs-utils.ts @@ -130,7 +130,6 @@ export async function findFile( ): Promise { for (const extension of extensions) { const candidate = `${basePath}${extension}`; - // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match if (await isRegularFile(candidate, "findFile")) { return candidate; } diff --git a/packages/cli/src/lib/ghcr.ts b/packages/cli/src/lib/ghcr.ts index 9f12e207e1..356bfb8a40 100644 --- a/packages/cli/src/lib/ghcr.ts +++ b/packages/cli/src/lib/ghcr.ts @@ -116,7 +116,6 @@ async function fetchWithRetry( for (let attempt = 0; attempt <= GHCR_MAX_RETRIES; attempt++) { try { - // oxlint-disable-next-line no-await-in-loop -- retries one attempt at a time, with a backoff between attempts const response = await customFetch(url, { ...init, signal: buildSignal(timeout, externalSignal), @@ -607,7 +606,6 @@ export async function listTags( let lastTag: string | undefined; for (;;) { - // oxlint-disable-next-line no-await-in-loop -- each tag page starts after the last tag of the page before const tags = await fetchTagPage(token, lastTag, signal, source); if (tags.length === 0) { break; diff --git a/packages/cli/src/lib/jvm-bundle.ts b/packages/cli/src/lib/jvm-bundle.ts index 0f1653ade9..aa2c2a3e92 100644 --- a/packages/cli/src/lib/jvm-bundle.ts +++ b/packages/cli/src/lib/jvm-bundle.ts @@ -11,9 +11,7 @@ import { readdir, readFile, realpath, stat } from "node:fs/promises"; import { extname, join, relative } from "node:path"; -import { mapBounded } from "./fan-out.js"; import { logger } from "./logger.js"; -import { CONCURRENCY_LIMIT } from "./scan/constants.js"; import { ZipWriter } from "./sourcemap/zip.js"; const log = logger.withTag("jvm-bundle"); @@ -331,7 +329,6 @@ async function collectJvmSources( entries.sort((a, b) => a.name.localeCompare(b.name)); for (const entry of entries) { - // oxlint-disable-next-line no-await-in-loop -- walks the tree in sorted order so the bundle is deterministic await processEntry(entry, dir); } } @@ -355,29 +352,26 @@ type ValidatedEntry = { async function readAndValidateFiles( urlToAbsPath: Map, ): Promise { - const entries = await mapBounded( - urlToAbsPath, - async ([url, absPath]): Promise => { - const bundlePath = `files/_/${url.replace(URL_PREFIX_RE, "")}`; + const validated: ValidatedEntry[] = []; + + for (const [url, absPath] of urlToAbsPath) { + const bundlePath = `files/_/${url.replace(URL_PREFIX_RE, "")}`; + try { + const content = await readFile(absPath); + // Skip non-UTF-8 files (binary files that happen to have JVM extensions) try { - const content = await readFile(absPath); - // Skip non-UTF-8 files (binary files that happen to have JVM extensions) - try { - new TextDecoder("utf-8", { fatal: true }).decode(content); - } catch { - log.debug(`Skipping non-UTF-8 file: ${absPath}`); - return null; - } - return { url, bundlePath, content }; - } catch (err) { - log.debug(`Failed to read source file: ${absPath}`, err); - return null; + new TextDecoder("utf-8", { fatal: true }).decode(content); + } catch { + log.debug(`Skipping non-UTF-8 file: ${absPath}`); + continue; } - }, - CONCURRENCY_LIMIT, - ); + validated.push({ url, bundlePath, content }); + } catch (err) { + log.debug(`Failed to read source file: ${absPath}`, err); + } + } - return entries.filter((entry) => entry !== null); + return validated; } /** @@ -398,7 +392,6 @@ async function writeBundle( ); for (const { bundlePath, content } of validatedFiles) { - // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addEntry(bundlePath, content); } diff --git a/packages/cli/src/lib/oauth.ts b/packages/cli/src/lib/oauth.ts index e30d33b968..423287810e 100644 --- a/packages/cli/src/lib/oauth.ts +++ b/packages/cli/src/lib/oauth.ts @@ -464,10 +464,8 @@ export async function performDeviceFlow( // Step 2: Poll for token while (Date.now() < timeoutAt) { - // oxlint-disable-next-line no-await-in-loop -- polls the device-code endpoint at the interval the server sets await sleep(pollInterval * 1000); - // oxlint-disable-next-line no-await-in-loop -- polls the device-code endpoint at the interval the server sets const result = await attemptPoll(device_code, pollInterval); switch (result.status) { diff --git a/packages/cli/src/lib/polling.ts b/packages/cli/src/lib/polling.ts index 42c0778881..6d66c41ee7 100644 --- a/packages/cli/src/lib/polling.ts +++ b/packages/cli/src/lib/polling.ts @@ -92,7 +92,6 @@ export async function poll(options: PollOptions): Promise { try { while (Date.now() - startTime < timeoutMs) { - // oxlint-disable-next-line no-await-in-loop -- polls until the state is done or the timeout passes const state = await fetchState(); if (state) { @@ -106,7 +105,6 @@ export async function poll(options: PollOptions): Promise { } } - // oxlint-disable-next-line no-await-in-loop -- polls until the state is done or the timeout passes await sleepMs(pollIntervalMs); } diff --git a/packages/cli/src/lib/scan/concurrent.ts b/packages/cli/src/lib/scan/concurrent.ts index a1bf533f59..e563032679 100644 --- a/packages/cli/src/lib/scan/concurrent.ts +++ b/packages/cli/src/lib/scan/concurrent.ts @@ -186,7 +186,6 @@ export async function* mapFilesConcurrentStream( if (producerDone) { break; } - // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await awake; resetAwake(); } diff --git a/packages/cli/src/lib/scan/grep.ts b/packages/cli/src/lib/scan/grep.ts index 7fcb37c9d2..b26a6e23b9 100644 --- a/packages/cli/src/lib/scan/grep.ts +++ b/packages/cli/src/lib/scan/grep.ts @@ -508,7 +508,6 @@ async function* grepViaWorkers( notifyPending = false; continue; } - // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await new Promise((resolve) => { if (notifyPending) { notifyPending = false; diff --git a/packages/cli/src/lib/scan/walker.ts b/packages/cli/src/lib/scan/walker.ts index 1472e58fca..fa48dace5c 100644 --- a/packages/cli/src/lib/scan/walker.ts +++ b/packages/cli/src/lib/scan/walker.ts @@ -201,7 +201,6 @@ async function processDir( if (isCancelled()) { return; } - // oxlint-disable-next-line no-await-in-loop -- entries are cheap to process and cancellation is checked between them; directories are the unit of concurrency const result = await processEntry(entry, frame, ctx); if (result !== null) { push(result); @@ -298,7 +297,6 @@ async function* walkFilesImpl(opts: WalkOptions): AsyncGenerator { */ async function* walkSerial(ctx: WalkContext): AsyncGenerator { const { cfg, matcher, stack } = ctx; - // oxlint-disable no-await-in-loop -- the serial walker visits one directory and one entry at a time; walkParallel is the concurrent path while (stack.length > 0) { checkAborted(cfg.signal); const frame = stack.pop() as DirFrame; @@ -327,7 +325,6 @@ async function* walkSerial(ctx: WalkContext): AsyncGenerator { } } } - // oxlint-enable no-await-in-loop } /** @@ -462,13 +459,11 @@ async function* walkParallel(ctx: WalkContext): AsyncGenerator { if (activeWorkers === 0) { return; } - // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await workerAwake; continue; } activeWorkers += 1; try { - // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await processDir(frame, ctx, push, () => cancelled); } finally { activeWorkers -= 1; @@ -527,7 +522,6 @@ async function* walkParallel(ctx: WalkContext): AsyncGenerator { if (stack.length === 0 && activeWorkers === 0) { break; } - // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await consumerAwake; resetConsumerAwake(); } diff --git a/packages/cli/src/lib/sentryclirc-import.ts b/packages/cli/src/lib/sentryclirc-import.ts index e95dea56b3..793d5d6bc7 100644 --- a/packages/cli/src/lib/sentryclirc-import.ts +++ b/packages/cli/src/lib/sentryclirc-import.ts @@ -269,13 +269,15 @@ export async function discoverRcFiles( } // Check global fallback paths (config-dir first, then homedir) - const globalFiles = await Promise.all( - // The walk above skips these paths, so none of them is in `seen`. - [...globalPathSet].map((globalPath) => - readRcFile(globalPath, classifyRcFileLocation(globalPath)), - ), - ); - for (const file of globalFiles) { + for (const globalPath of globalPathSet) { + if (seen.has(globalPath)) { + continue; + } + seen.add(globalPath); + const file = await readRcFile( + globalPath, + classifyRcFileLocation(globalPath), + ); if (file) { files.push(file); } @@ -777,12 +779,12 @@ function clearImportRecord(): void { /** Verify all source files in a record still match their stored hashes */ async function verifyRecordHashes(record: ImportRecord): Promise { - const matches = await Promise.all( - record.sources.map((source) => - verifyFileHash(source.path, source.contentHash), - ), - ); - return matches.every(Boolean); + for (const source of record.sources) { + if (!(await verifyFileHash(source.path, source.contentHash))) { + return false; + } + } + return true; } /** diff --git a/packages/cli/src/lib/sentryclirc.ts b/packages/cli/src/lib/sentryclirc.ts index fc16aa5740..8e26ae9a93 100644 --- a/packages/cli/src/lib/sentryclirc.ts +++ b/packages/cli/src/lib/sentryclirc.ts @@ -247,7 +247,6 @@ export async function applyGlobalFallbacks( if (isComplete(result)) { break; } - // oxlint-disable-next-line no-await-in-loop -- later global files fill only the keys the earlier ones left unset, and the loop stops once the config is complete await tryApplyFile(result, globalPath, true); } } diff --git a/packages/cli/src/lib/snapshots/archive.ts b/packages/cli/src/lib/snapshots/archive.ts index 2356ca14e3..d1908fcebb 100644 --- a/packages/cli/src/lib/snapshots/archive.ts +++ b/packages/cli/src/lib/snapshots/archive.ts @@ -118,7 +118,6 @@ export async function extractZipStream( let current = await iterator.next(); while (!current.done) { const chunk = current.value; - // oxlint-disable-next-line no-await-in-loop -- drives the iterator one step at a time current = await iterator.next(); unzip.push(chunk, current.done === true); pushedAny = true; diff --git a/packages/cli/src/lib/sourcemap/inject.ts b/packages/cli/src/lib/sourcemap/inject.ts index 5a12e7a4d0..1491edfd4b 100644 --- a/packages/cli/src/lib/sourcemap/inject.ts +++ b/packages/cli/src/lib/sourcemap/inject.ts @@ -11,10 +11,8 @@ import ignore from "ignore"; import picomatch from "picomatch"; import { NODE_MODULES_DIRNAME } from "../constants.js"; import { ValidationError } from "../errors.js"; -import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; import { isLikelyBinary } from "../scan/binary.js"; -import { CONCURRENCY_LIMIT } from "../scan/constants.js"; import { walkFiles } from "../scan/index.js"; import { hasDebugIdRegistration, @@ -175,39 +173,32 @@ export async function injectDirectory( options.include, ); - if (options.dryRun) { - return await mapBounded( - filePairs, - async ({ jsPath, map }): Promise => { - // Match the real run's ID precedence and runtime registration check. - const jsBytes = await readFile(jsPath); - const js = jsBytes.toString("utf-8"); - const binary = isLikelyBinary(jsBytes); - const existing = await readPairDebugId(js, map); - // An ID the bundle only registers at runtime is reused; the file still - // changes, since the comment and the map ID are written. - const registered = - existing || binary ? undefined : readRegisteredDebugId(js); - return { - jsPath, - map, - mapPath: map.kind === "external" ? map.mapPath : undefined, - injected: !( - existing && - (binary || hasDebugIdRegistration(js, existing)) - ), - debugId: existing ?? registered ?? "(pending)", - }; - }, - CONCURRENCY_LIMIT, - ); - } - const results: InjectResult[] = []; for (const { jsPath, map } of filePairs) { const mapPath = map.kind === "external" ? map.mapPath : undefined; + if (options.dryRun) { + // Match the real run's ID precedence and runtime registration check. + const jsBytes = await readFile(jsPath); + const js = jsBytes.toString("utf-8"); + const binary = isLikelyBinary(jsBytes); + const existing = await readPairDebugId(js, map); + // An ID the bundle only registers at runtime is reused; the file still + // changes, since the comment and the map ID are written. + const registered = + existing || binary ? undefined : readRegisteredDebugId(js); + results.push({ + jsPath, + map, + mapPath, + injected: !( + existing && + (binary || hasDebugIdRegistration(js, existing)) + ), + debugId: existing ?? registered ?? "(pending)", + }); + continue; + } if (map.kind === "external") { - // oxlint-disable-next-line no-await-in-loop -- two bundles can reference one map file, so writes run one pair at a time const r = await injectDebugId(jsPath, map.mapPath); results.push({ jsPath, @@ -217,7 +208,6 @@ export async function injectDirectory( debugId: r.debugId, }); } else { - // oxlint-disable-next-line no-await-in-loop -- two bundles can reference one map file, so writes run one pair at a time const r = await injectInlineDebugId(jsPath, map.decoded); results.push({ jsPath, @@ -246,26 +236,24 @@ export async function injectDirectory( export async function readExistingDebugIds( pairs: FilePair[], ): Promise { - return await mapBounded( - pairs, - async ({ jsPath, map }): Promise => { - const jsBytes = await readFile(jsPath); - const js = jsBytes.toString("utf-8"); - const existing = await readPairDebugId(js, map); - const registered = - existing || isLikelyBinary(jsBytes) - ? undefined - : readRegisteredDebugId(js); - return { - jsPath, - map, - mapPath: map.kind === "external" ? map.mapPath : undefined, - injected: false, - debugId: existing ?? registered ?? "", - }; - }, - CONCURRENCY_LIMIT, - ); + const results: InjectResult[] = []; + for (const { jsPath, map } of pairs) { + const jsBytes = await readFile(jsPath); + const js = jsBytes.toString("utf-8"); + const existing = await readPairDebugId(js, map); + const registered = + existing || isLikelyBinary(jsBytes) + ? undefined + : readRegisteredDebugId(js); + results.push({ + jsPath, + map, + mapPath: map.kind === "external" ? map.mapPath : undefined, + injected: false, + debugId: existing ?? registered ?? "", + }); + } + return results; } /** @@ -398,7 +386,6 @@ async function readDirectiveTail(filePath: string): Promise { const readSize = Math.min(DIRECTIVE_CHUNK_BYTES, end); const offset = end - readSize; const buf = Buffer.alloc(readSize); - // oxlint-disable-next-line no-await-in-loop -- reads the file backwards into one reused buffer await fh.read(buf, 0, readSize, offset); chunks.unshift(buf); collected += readSize; diff --git a/packages/cli/src/lib/sourcemap/zip.ts b/packages/cli/src/lib/sourcemap/zip.ts index 5291559184..69ca49f2f7 100644 --- a/packages/cli/src/lib/sourcemap/zip.ts +++ b/packages/cli/src/lib/sourcemap/zip.ts @@ -283,12 +283,10 @@ export class ZipWriter { fill(); for (let result = inFlight.shift(); result; result = inFlight.shift()) { - // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order while later reads run ahead const settled = await result; if (!settled.ok) { throw settled.error; } - // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order while later reads run ahead await this.writeEntry(settled.entry); bytesInFlight -= settled.entry.uncompressedSize; fill(); diff --git a/packages/cli/src/lib/target-scope.ts b/packages/cli/src/lib/target-scope.ts index cba011bbbb..99d977d342 100644 --- a/packages/cli/src/lib/target-scope.ts +++ b/packages/cli/src/lib/target-scope.ts @@ -242,7 +242,6 @@ async function filterToProject( ...requested, ...url.searchParams.getAll("projectSlug"), ]) { - // oxlint-disable-next-line no-await-in-loop -- stops at the first project outside the scope, before more lookups are sent if (!(await anyScopeProject(context, [project]))) { throw outsideScope(subject, scope); } @@ -300,14 +299,12 @@ async function lookUpFirst( return; } for (const attempt of widerQuery ? [query, widerQuery] : [query]) { - // oxlint-disable-next-line no-await-in-loop -- sends the wider query only when the first one does not list the item const response = await context.send( `${context.api}${path}${attempt ? `?${attempt}` : ""}`, ); if (!response.ok) { return response; } - // oxlint-disable-next-line no-await-in-loop -- sends the wider query only when the first one does not list the item if (listed !== undefined && lists(await readJson(response), listed)) { foundInScope.add(key); } @@ -376,7 +373,6 @@ async function applyRule( throw outsideScope(subject, scope); } for (const target of targets) { - // oxlint-disable-next-line no-await-in-loop -- returns the first failed lookup, before more lookups are sent const failed = await lookUpFirst(context, target); if (failed) { return { input, response: failed, verify: NOTHING_TO_VERIFY }; diff --git a/packages/cli/src/lib/upgrade.ts b/packages/cli/src/lib/upgrade.ts index ecdc178845..9ad637e58f 100644 --- a/packages/cli/src/lib/upgrade.ts +++ b/packages/cli/src/lib/upgrade.ts @@ -416,7 +416,6 @@ async function detectLegacyInstallationMethod(): Promise { const packageManagers: PackageManager[] = ["npm", "pnpm", "bun", "yarn"]; for (const pm of packageManagers) { - // oxlint-disable-next-line no-await-in-loop -- checks package managers in popularity order and stops at the first match if (await isInstalledWith(pm)) { return pm; } @@ -498,7 +497,6 @@ export async function fetchLatestFromGitHubWithSource( const visitedPages = new Set([firstPage]); const versions: string[] = []; for (;;) { - // oxlint-disable-next-line no-await-in-loop -- each release page comes from the Link header of the page before const data = await parseUpgradeJson( response, signal, @@ -523,7 +521,6 @@ export async function fetchLatestFromGitHubWithSource( ); } visitedPages.add(nextPage); - // oxlint-disable-next-line no-await-in-loop -- each release page comes from the Link header of the page before response = await fetchWithUpgradeError( nextPage, { headers: getGitHubHeaders(), ...(signal && { signal }) }, @@ -1176,7 +1173,6 @@ async function waitForBinaryVisible(path: string): Promise { log.debug( `Downloaded binary not yet visible at ${path}, retrying in ${delay}ms (attempt ${attempt}/${VERIFY_MAX_ATTEMPTS})`, ); - // oxlint-disable-next-line no-await-in-loop -- retries one attempt at a time, with a backoff between attempts await setTimeout(delay); } throw new UpgradeError( diff --git a/packages/cli/src/lib/walk-up.ts b/packages/cli/src/lib/walk-up.ts index 6df3a9cc5a..2516ff2d38 100644 --- a/packages/cli/src/lib/walk-up.ts +++ b/packages/cli/src/lib/walk-up.ts @@ -29,7 +29,6 @@ export async function* walkUpFrom(startDir: string): AsyncGenerator { for (;;) { let real: string; try { - // oxlint-disable-next-line no-await-in-loop -- walks up one parent directory at a time real = await realpath(current); } catch { // Can't resolve (broken symlink, permission denied) — stop walking diff --git a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts index 9e4cb70dc3..ece063f07a 100644 --- a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts +++ b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts @@ -520,7 +520,6 @@ async function createOrMergeNextJsFiles( const configVariants = ["server", "edge"] as const; for (const configVariant of configVariants) { - // oxlint-disable-next-line no-await-in-loop -- each config step can prompt the user, so the steps run in turn await traceStep(`create-sentry-${configVariant}-config`, async () => { const jsConfig = `sentry.${configVariant}.config.js`; const tsConfig = `sentry.${configVariant}.config.ts`; diff --git a/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts b/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts index c6605284fb..c0d43e6133 100644 --- a/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts @@ -214,7 +214,6 @@ export async function createConfigFiles( const configVariants = ["server", "client"] as const; for (const configVariant of configVariants) { - // oxlint-disable-next-line no-await-in-loop -- each config step can prompt the user, so the steps run in turn await traceStep(`create-sentry-${configVariant}-config`, async () => { const jsConfig = `sentry.${configVariant}.config.js`; const tsConfig = `sentry.${configVariant}.config.ts`; diff --git a/packages/cli/src/lib/wizard/react-native/javascript.ts b/packages/cli/src/lib/wizard/react-native/javascript.ts index 6812905a84..a4ab339717 100644 --- a/packages/cli/src/lib/wizard/react-native/javascript.ts +++ b/packages/cli/src/lib/wizard/react-native/javascript.ts @@ -261,7 +261,6 @@ export function getMainAppFilePath(): Promise { return traceStep("find-app-js-file", async () => { for (const dir of APP_FILE_DIRS) { for (const name of APP_FILE_NAMES) { - // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match const match = await findFile(path.join(dir, name), APP_FILE_EXTENSIONS); if (match) { return match; diff --git a/packages/cli/src/lib/wizard/remix/codemods/express-server.ts b/packages/cli/src/lib/wizard/remix/codemods/express-server.ts index aa10298287..97b8227d4e 100644 --- a/packages/cli/src/lib/wizard/remix/codemods/express-server.ts +++ b/packages/cli/src/lib/wizard/remix/codemods/express-server.ts @@ -18,7 +18,6 @@ export async function findCustomExpressServerImplementation() { ]; for (const filePath of possiblePaths) { - // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match const filename = await findFile(filePath); if (!filename) { @@ -31,7 +30,6 @@ export async function findCustomExpressServerImplementation() { continue; } - // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match const fileMod = await loadFile(filename); const createRequestHandlerImport = fileMod.imports.$items.find( (imp) => diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts index a80c7a6aac..bbff682d1d 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -77,7 +77,6 @@ export async function configureSentryCLI( let validPath = false; let relativeArtifactPath: string | undefined; do { - // oxlint-disable-next-line no-await-in-loop -- prompts the user until they give a usable path const rawArtifactPath = await abortIfCancelled( clack.text({ message: "Where are your build artifacts located?", @@ -112,7 +111,6 @@ export async function configureSentryCLI( } const runBuildOrEnterPathOrProceed = - // oxlint-disable-next-line no-await-in-loop -- prompts the user until they give a usable path await askToRunBuildOrEnterPathOrProceed({ relativeArtifactPath, }); diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts index c371991504..44ba1f27d1 100644 --- a/packages/cli/src/lib/wizard/utils/clack/index.ts +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -1628,7 +1628,6 @@ export async function featureSelectionPrompt>( const selectedFeatures: Record = {}; for (const feature of features) { - // oxlint-disable-next-line no-await-in-loop -- asks the feature questions one at a time selectedFeatures[feature.id] = await askFlagQuestion( feature.flag, feature, diff --git a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts index de7ed67a28..b63d30fd31 100644 --- a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts +++ b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts @@ -554,7 +554,6 @@ export async function offerProjectScopedMcpConfig( Sentry.setTag("mcp-editors-count", editors.length); // Configure each selected editor - // oxlint-disable no-await-in-loop -- configures one editor at a time; each step can prompt or print instructions for (const editor of editors) { // Track which editor is being configured Sentry.setTag("mcp-editor", editor); @@ -656,5 +655,4 @@ export async function offerProjectScopedMcpConfig( } } } - // oxlint-enable no-await-in-loop } diff --git a/packages/cli/src/lib/wrangler.ts b/packages/cli/src/lib/wrangler.ts index ccf7ae72be..89ef25737e 100644 --- a/packages/cli/src/lib/wrangler.ts +++ b/packages/cli/src/lib/wrangler.ts @@ -391,7 +391,6 @@ async function hasWranglerConfig( for (const filename of WRANGLER_CONFIG_FILES) { // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. try { - // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match await access(join(cwd, filename)); return true; } catch { diff --git a/packages/cli/test/lib/dsn/errors.test.ts b/packages/cli/test/lib/dsn/errors.test.ts index 1ac318f829..cf1bae8277 100644 --- a/packages/cli/test/lib/dsn/errors.test.ts +++ b/packages/cli/test/lib/dsn/errors.test.ts @@ -26,7 +26,6 @@ vi.mock("../../../src/lib/api-client.js", () => ({ listOrganizations: mockListOrganizations, listProjects: mockListProjects, findProjectByDsn: vi.fn(() => Promise.resolve(null)), - ORG_FANOUT_CONCURRENCY: 5, })); describe("formatConflictError", () => { diff --git a/packages/cli/test/lib/dsn/resolver.test.ts b/packages/cli/test/lib/dsn/resolver.test.ts index 594061a024..00f49653f3 100644 --- a/packages/cli/test/lib/dsn/resolver.test.ts +++ b/packages/cli/test/lib/dsn/resolver.test.ts @@ -35,7 +35,6 @@ vi.mock("../../../src/lib/api-client.js", () => ({ listProjects: mockListProjects, findProjectByDsn: mockFindProjectByDsn, resolveOrgDisplayName: mockResolveOrgDisplayName, - ORG_FANOUT_CONCURRENCY: 5, })); // Now import the resolver after mocking diff --git a/packages/http/src/policy.ts b/packages/http/src/policy.ts index 93db35970c..48c5f6bce8 100644 --- a/packages/http/src/policy.ts +++ b/packages/http/src/policy.ts @@ -157,11 +157,9 @@ async function policyRequestHeaders( // Lowercase names, as `http-cache-semantics` stores them and `Vary` // matching compares them. for (const [rawName, value] of Object.entries(headers)) { - result[rawName.toLowerCase()] = value; - } - const authorization = result["authorization"]; - if (authorization) { - result["authorization"] = await sha256Hex(authorization); + const name = rawName.toLowerCase(); + result[name] = + name === "authorization" && value ? await sha256Hex(value) : value; } return result; } diff --git a/packages/http/src/retry.ts b/packages/http/src/retry.ts index 5dc7d3bc5c..4d5685d62d 100644 --- a/packages/http/src/retry.ts +++ b/packages/http/src/retry.ts @@ -278,7 +278,6 @@ export async function fetchWithRetry( for (let attempt = 0; ; attempt++) { let response: Response; try { - // oxlint-disable-next-line no-await-in-loop -- retries are sequential by definition response = await send(attempt); } catch (error) { const delayMs = @@ -289,7 +288,6 @@ export async function fetchWithRetry( throw error; } options.onRetry?.({ attempt, delayMs, status: undefined, error }); - // oxlint-disable-next-line no-await-in-loop -- waits out the backoff before the next attempt await sleep(delayMs, signal); waitedMs += delayMs; continue; @@ -303,7 +301,6 @@ export async function fetchWithRetry( } response.body?.cancel().catch(() => undefined); options.onRetry?.({ attempt, delayMs, status: response.status }); - // oxlint-disable-next-line no-await-in-loop -- waits out the backoff before the next attempt await sleep(delayMs, signal); waitedMs += delayMs; } diff --git a/packages/mcp-core/scripts/generate-otel-namespaces.ts b/packages/mcp-core/scripts/generate-otel-namespaces.ts index b976c016f2..541ebcffbd 100644 --- a/packages/mcp-core/scripts/generate-otel-namespaces.ts +++ b/packages/mcp-core/scripts/generate-otel-namespaces.ts @@ -343,7 +343,6 @@ async function generateNamespaceFiles() { } } - // oxlint-disable-next-line no-await-in-loop -- fetches one namespace at a time to stay under GitHub's raw-content rate limits const yamlContent = await fetchYamlContent(namespace); if (!yamlContent) { console.log(`⏭️ Skipping ${namespace} (no registry.yaml found)`); diff --git a/packages/mcp-core/scripts/generate-platform-setup.ts b/packages/mcp-core/scripts/generate-platform-setup.ts index 5f964d17c1..8cca97d436 100644 --- a/packages/mcp-core/scripts/generate-platform-setup.ts +++ b/packages/mcp-core/scripts/generate-platform-setup.ts @@ -208,7 +208,6 @@ async function main() { for (const platform of platforms) { const linkPath = DOCS_PATH_OVERRIDES[platform.id] ?? new URL(platform.link).pathname; - // oxlint-disable-next-line no-await-in-loop -- resolves one platform at a time to keep the load on docs.sentry.io low const path = normalizePath(await resolveRedirects(linkPath)); // The platform list page is not a setup guide (for example `other`). if (path === "platforms" || !index.has(path)) { diff --git a/packages/mcp-core/scripts/measure-ui-views.ts b/packages/mcp-core/scripts/measure-ui-views.ts index 6b81af293d..d074464fb9 100644 --- a/packages/mcp-core/scripts/measure-ui-views.ts +++ b/packages/mcp-core/scripts/measure-ui-views.ts @@ -89,7 +89,6 @@ async function readViews(): Promise { if (budget === undefined) { throw new Error(`${uri} is not in UI_RESOURCES, so it has no budget`); } - // oxlint-disable-next-line no-await-in-loop -- reads go over one stdio MCP connection and report budgets in resource order const { contents } = await client.readResource({ uri }); for (const content of contents) { const body = diff --git a/packages/mcp-core/scripts/validate-skills-mapping.ts b/packages/mcp-core/scripts/validate-skills-mapping.ts index 8cebd6cc17..93bb583bb8 100644 --- a/packages/mcp-core/scripts/validate-skills-mapping.ts +++ b/packages/mcp-core/scripts/validate-skills-mapping.ts @@ -57,13 +57,18 @@ function getToolsForSkill(skill: Skill): string[] { * Validate skills-to-tools-to-scopes mapping */ async function validateMapping(): Promise { - const results: ValidationResult[] = await Promise.all( - (Object.keys(SKILLS) as Skill[]).map(async (skillId) => ({ + const results: ValidationResult[] = []; + + for (const skillId of Object.keys(SKILLS) as Skill[]) { + const enabledTools = getToolsForSkill(skillId); + const requiredScopes = await getScopesForSkills(new Set([skillId])); + + results.push({ skill: skillId, - enabledTools: getToolsForSkill(skillId), - requiredScopes: await getScopesForSkills(new Set([skillId])), - })), - ); + enabledTools, + requiredScopes, + }); + } return results; } diff --git a/packages/mcp-core/src/api-client/client.ts b/packages/mcp-core/src/api-client/client.ts index accafd5d33..cd0d03ba10 100644 --- a/packages/mcp-core/src/api-client/client.ts +++ b/packages/mcp-core/src/api-client/client.ts @@ -5117,14 +5117,12 @@ export class SentryApiService { queryParams.set("cursor", cursor); } - // oxlint-disable-next-line no-await-in-loop -- cursor pagination: each page needs the previous page's cursor const response = await this.request( apiPath`/organizations/${organizationSlug}/agents/conversations/${conversationId}/` + `?${queryParams.toString()}`, undefined, opts, ); - // oxlint-disable-next-line no-await-in-loop -- cursor pagination: each page needs the previous page's cursor const body = await readJsonResponse(response); const details = AIConversationDetailsResponseSchema.parse(body); // Pages repeat the same conversation-scoped title. diff --git a/packages/mcp-core/src/internal/fetch-utils.ts b/packages/mcp-core/src/internal/fetch-utils.ts index a9e8f5dee3..1d04390295 100644 --- a/packages/mcp-core/src/internal/fetch-utils.ts +++ b/packages/mcp-core/src/internal/fetch-utils.ts @@ -91,7 +91,6 @@ export async function retryWithBackoff( for (let attempt = 0; attempt <= maxRetries; attempt++) { try { - // oxlint-disable-next-line no-await-in-loop -- retries are sequential by definition return await fn(); } catch (error) { lastError = error; @@ -104,7 +103,6 @@ export async function retryWithBackoff( } // Wait before retrying with exponential backoff - // oxlint-disable-next-line no-await-in-loop -- waits out the backoff before the next attempt await sleep(delay, signal); delay = Math.min(delay * 2, 30000); // Cap at 30 seconds } diff --git a/packages/mcp-core/src/tools/catalog/analyze-issue-with-seer.ts b/packages/mcp-core/src/tools/catalog/analyze-issue-with-seer.ts index 250be51769..3526080805 100644 --- a/packages/mcp-core/src/tools/catalog/analyze-issue-with-seer.ts +++ b/packages/mcp-core/src/tools/catalog/analyze-issue-with-seer.ts @@ -230,12 +230,10 @@ export default defineTool({ } // Wait before next poll - // oxlint-disable-next-line no-await-in-loop -- polls Seer until the run finishes await sleep(SEER_POLLING_INTERVAL, context.signal); // Refresh state with error handling try { - // oxlint-disable-next-line no-await-in-loop -- polls Seer until the run finishes autofixState = await retryWithBackoff( () => apiService.getAutofixState({ diff --git a/packages/mcp-core/src/tools/catalog/get-doc.ts b/packages/mcp-core/src/tools/catalog/get-doc.ts index aa859e5726..fa9e3d7eaa 100644 --- a/packages/mcp-core/src/tools/catalog/get-doc.ts +++ b/packages/mcp-core/src/tools/catalog/get-doc.ts @@ -87,7 +87,6 @@ export default defineTool({ // off the allowed hosts is reported as a missing page. let response: Response; for (let redirects = 0; ; redirects++) { - // oxlint-disable-next-line no-await-in-loop -- follows redirects one hop at a time so each hop is checked against the allowlist response = await fetchWithTimeout( docUrl, { diff --git a/packages/mcp-core/src/tools/support/alert-rule-connections.ts b/packages/mcp-core/src/tools/support/alert-rule-connections.ts index 66b2d99c52..5b9cc9b54a 100644 --- a/packages/mcp-core/src/tools/support/alert-rule-connections.ts +++ b/packages/mcp-core/src/tools/support/alert-rule-connections.ts @@ -76,7 +76,6 @@ export async function resolveAlertRuleConnections( [params.removeProjectSlugs, params.removeDetectorIds, removals], ] as const) { for (const projectSlug of new Set(projectSlugs ?? [])) { - // oxlint-disable-next-line no-await-in-loop -- the project scope check must stop before more lookups go out const project = await api.getProject({ organizationSlug: params.organizationSlug, projectSlugOrId: projectSlug, @@ -88,7 +87,6 @@ export async function resolveAlertRuleConnections( hasEvidence: projectId === params.scopedProject?.id, }); - // oxlint-disable-next-line no-await-in-loop -- the project scope check must stop before more lookups go out const detectors = await fetchEveryPage(async (cursor) => { const page = await api.listDetectorsPage({ organizationSlug: params.organizationSlug, @@ -130,7 +128,6 @@ export async function resolveAlertRuleConnections( removals.add(detectorId); continue; } - // oxlint-disable-next-line no-await-in-loop -- the project scope check must stop before more lookups go out const detector = await api.getDetector({ organizationSlug: params.organizationSlug, detectorId, diff --git a/packages/mcp-core/src/tools/support/alert-rule-details.ts b/packages/mcp-core/src/tools/support/alert-rule-details.ts index ba89bd31c6..7622728454 100644 --- a/packages/mcp-core/src/tools/support/alert-rule-details.ts +++ b/packages/mcp-core/src/tools/support/alert-rule-details.ts @@ -217,53 +217,51 @@ export async function getAlertRuleDetails( projectSlugOrId: scopedProjectSlug, }) : undefined; - const sources: AlertRuleDetails["sources"] = await Promise.all( - (rule.detectorIds ?? []).map( - async (id): Promise => { - try { - const detector = await api.getDetector({ - organizationSlug, - detectorId: id, - }); - if ( - project && - detector.projectId !== null && - String(detector.projectId) !== String(project.id) - ) { - return { id: String(id), status: "outside_project_constraint" }; - } - return { - id: String(detector.id), - status: "available", - name: detector.name, - type: detector.type, - projectId: - detector.projectId === null ? null : String(detector.projectId), - enabled: detector.enabled, - config: toDetectorConfig(detector.type, detector.config), - conditionGroup: detector.conditionGroup - ? conditionGroupSchema.parse(detector.conditionGroup) - : null, - dataSources: (detector.dataSources ?? []).map(sourceDetails), - }; - } catch (error) { - if ( - !( - error instanceof ApiNotFoundError || - error instanceof ApiPermissionError - ) - ) { - throw error; - } - return { - id: String(id), - status: "unavailable", - reason: "Not found or not accessible.", - }; - } - }, - ), - ); + const sources: AlertRuleDetails["sources"] = []; + for (const id of rule.detectorIds ?? []) { + try { + const detector = await api.getDetector({ + organizationSlug, + detectorId: id, + }); + if ( + project && + detector.projectId !== null && + String(detector.projectId) !== String(project.id) + ) { + sources.push({ id: String(id), status: "outside_project_constraint" }); + continue; + } + sources.push({ + id: String(detector.id), + status: "available", + name: detector.name, + type: detector.type, + projectId: + detector.projectId === null ? null : String(detector.projectId), + enabled: detector.enabled, + config: toDetectorConfig(detector.type, detector.config), + conditionGroup: detector.conditionGroup + ? conditionGroupSchema.parse(detector.conditionGroup) + : null, + dataSources: (detector.dataSources ?? []).map(sourceDetails), + }); + } catch (error) { + if ( + !( + error instanceof ApiNotFoundError || + error instanceof ApiPermissionError + ) + ) { + throw error; + } + sources.push({ + id: String(id), + status: "unavailable", + reason: "Not found or not accessible.", + }); + } + } const projectIds = project ? scope.projectIds.filter((id) => id === String(project.id)) : scope.projectIds; diff --git a/packages/mcp-core/src/tools/support/issue-linking/app.ts b/packages/mcp-core/src/tools/support/issue-linking/app.ts index 53ec41098f..bac222abc2 100644 --- a/packages/mcp-core/src/tools/support/issue-linking/app.ts +++ b/packages/mcp-core/src/tools/support/issue-linking/app.ts @@ -214,7 +214,6 @@ async function resolveFields( if (field.type === "select") { let choices = field.choices ?? field.options ?? []; if (field.uri) { - // oxlint-disable-next-line no-await-in-loop -- a field's options depend on the values chosen for earlier fields const options = await api.getSentryAppExternalRequestOptions({ installationUuid, uri: validateUri(field.uri), diff --git a/packages/mcp-core/src/tools/support/search-events/seer.ts b/packages/mcp-core/src/tools/support/search-events/seer.ts index 1d203cfe6a..105559ac35 100644 --- a/packages/mcp-core/src/tools/support/search-events/seer.ts +++ b/packages/mcp-core/src/tools/support/search-events/seer.ts @@ -304,7 +304,6 @@ async function runSearchAgent({ const deadline = Date.now() + SEER_SEARCH_AGENT_TIMEOUT; while (Date.now() < deadline) { - // oxlint-disable-next-line no-await-in-loop -- polls the search agent until it finishes or times out const { session } = await apiService.getSearchAgentState({ organizationSlug, runId: run.sentry_run_id, @@ -326,7 +325,6 @@ async function runSearchAgent({ return null; } - // oxlint-disable-next-line no-await-in-loop -- polls the search agent until it finishes or times out await sleep(SEER_SEARCH_AGENT_POLLING_INTERVAL, apiService.signal); } diff --git a/packages/mcp-test-client/src/index.ts b/packages/mcp-test-client/src/index.ts index 55cf839e9c..87ce5d1430 100644 --- a/packages/mcp-test-client/src/index.ts +++ b/packages/mcp-test-client/src/index.ts @@ -201,7 +201,6 @@ program for (;;) { try { - // oxlint-disable-next-line no-await-in-loop -- interactive prompt: reads one line at a time const userInput = await rl.question(chalk.gray("> ")); if ( @@ -213,7 +212,6 @@ program } if (userInput.trim()) { - // oxlint-disable-next-line no-await-in-loop -- interactive prompt: answers one line at a time await runAgent(connection, userInput, agentConfig); // Add newline after response before next prompt console.log(); diff --git a/packages/toolkit-core/src/mcp-limits.ts b/packages/toolkit-core/src/mcp-limits.ts index fc9101a7cd..59ceaf4a66 100644 --- a/packages/toolkit-core/src/mcp-limits.ts +++ b/packages/toolkit-core/src/mcp-limits.ts @@ -44,14 +44,12 @@ export async function readBoundedBody( const chunks: Uint8Array[] = []; let received = 0; for (;;) { - // oxlint-disable-next-line no-await-in-loop -- reads the request body stream chunk by chunk const { done, value } = await reader.read(); if (done) { break; } received += value.byteLength; if (received > MAX_MCP_REQUEST_BODY_BYTES) { - // oxlint-disable-next-line no-await-in-loop -- stops reading once the body is over the limit await reader.cancel(); return undefined; } diff --git a/scripts/cli-nightly-verify.mjs b/scripts/cli-nightly-verify.mjs index 824f3c1a96..20dd249f48 100644 --- a/scripts/cli-nightly-verify.mjs +++ b/scripts/cli-nightly-verify.mjs @@ -58,7 +58,6 @@ async function main() { ); let failed = false; for (const tag of ["nightly", `nightly-${version}`]) { - // oxlint-disable-next-line no-await-in-loop -- checks the two tags in order so the log lists them in order const manifest = await getJson( `https://ghcr.io/v2/${REPOSITORY}/manifests/${tag}`, { diff --git a/scripts/cloudflare-deployment.mjs b/scripts/cloudflare-deployment.mjs index 6189614b19..353683882f 100644 --- a/scripts/cloudflare-deployment.mjs +++ b/scripts/cloudflare-deployment.mjs @@ -258,9 +258,7 @@ export async function listSettled( attempt < SETTLE_ATTEMPTS && !settled(deployments); attempt++ ) { - // oxlint-disable-next-line no-await-in-loop -- polls until the deployments settle await sleep(SETTLE_DELAY_MS); - // oxlint-disable-next-line no-await-in-loop -- polls until the deployments settle deployments = await list(env); } return deployments; @@ -311,13 +309,11 @@ async function waitUntilReadable( const deadline = now() + READABLE_TIMEOUT_MS; let streak = 0; while (now() < deadline) { - // oxlint-disable-next-line no-await-in-loop -- polls until every version is readable const readable = await Promise.all( versionIds.map((versionId) => readVersion(env, versionId, worker)), ); streak = readable.every(Boolean) ? streak + 1 : 0; if (streak === READABLE_STREAK) return; - // oxlint-disable-next-line no-await-in-loop -- polls until every version is readable await sleep(SETTLE_DELAY_MS); } throw new DeploymentError( diff --git a/scripts/generate-parsers.mjs b/scripts/generate-parsers.mjs index fcadd31c20..066e5b3b39 100644 --- a/scripts/generate-parsers.mjs +++ b/scripts/generate-parsers.mjs @@ -86,29 +86,26 @@ const grammars = (await readdir(grammarDir)).filter((file) => ); await mkdir(outputDir, { recursive: true }); -// Each grammar writes its own output files, so they generate concurrently. -await Promise.all( - grammars.map(async (file) => { - const name = file.slice(0, -".pegjs".length); - const grammarPath = join(grammarDir, file); - const declarationsPath = join(grammarDir, `${name}.d.ts`); - if (!existsSync(declarationsPath)) { - throw new Error(`${declarationsPath} is missing`); - } +for (const file of grammars) { + const name = file.slice(0, -".pegjs".length); + const grammarPath = join(grammarDir, file); + const declarationsPath = join(grammarDir, `${name}.d.ts`); + if (!existsSync(declarationsPath)) { + throw new Error(`${declarationsPath} is missing`); + } - const parserSource = peggy.generate(await readFile(grammarPath, "utf-8"), { - output: "source", - format: "es", - grammarSource: relative(packageDir, grammarPath).split(sep).join("/"), - }); - const declarations = rebaseDeclarations( - await readFile(declarationsPath, "utf-8"), - declarationsPath, - ); + const parserSource = peggy.generate(await readFile(grammarPath, "utf-8"), { + output: "source", + format: "es", + grammarSource: relative(packageDir, grammarPath).split(sep).join("/"), + }); + const declarations = rebaseDeclarations( + await readFile(declarationsPath, "utf-8"), + declarationsPath, + ); - const outputBase = join(outputDir, `${name}-grammar`); - await writeFile(`${outputBase}.js`, `${HEADER}\n${parserSource}\n`); - await writeFile(`${outputBase}.d.ts`, `${HEADER}\n${declarations}`); - console.log(`Generated ${relative(process.cwd(), outputBase)}.{js,d.ts}`); - }), -); + const outputBase = join(outputDir, `${name}-grammar`); + await writeFile(`${outputBase}.js`, `${HEADER}\n${parserSource}\n`); + await writeFile(`${outputBase}.d.ts`, `${HEADER}\n${declarations}`); + console.log(`Generated ${relative(process.cwd(), outputBase)}.{js,d.ts}`); +} From a7d705cd88c25601abc135bed0d5ce3e29c9dc3f Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:42:40 +0000 Subject: [PATCH 4/9] ref(cli): Fan out independent awaits in loops in src Run independent per-item work with `mapBounded` or `Promise.all` instead of one item at a time, keeping result order and error behaviour: alert rule and workflow lookups, project listing across orgs, DSN project access, dashboard widget queries, assemble batches, chunk encoding, DSN cache and `.sentryclirc` checks, and local file reads and hashes. API fan-out is capped at `ORG_FANOUT_CONCURRENCY`, local file work at `CONCURRENCY_LIMIT`. Loops that must stay sequential get a disable comment with the reason. --- .../src/commands/alert/issues/rule-resolve.ts | 46 ++++++--- .../commands/alert/metrics/rule-resolve.ts | 43 ++++++--- .../cli/src/commands/alert/metrics/view.ts | 40 +++++--- packages/cli/src/commands/auth/default.ts | 1 + packages/cli/src/commands/auth/logout.ts | 1 + packages/cli/src/commands/build/upload.ts | 1 + packages/cli/src/commands/cli/setup.ts | 1 + packages/cli/src/commands/cli/uninstall.ts | 1 + packages/cli/src/commands/cli/upgrade.ts | 2 + packages/cli/src/commands/dashboard/list.ts | 1 + .../cli/src/commands/dashboard/resolve.ts | 1 + packages/cli/src/commands/dashboard/view.ts | 2 + packages/cli/src/commands/event/send.ts | 2 + packages/cli/src/commands/issue/view.ts | 1 + packages/cli/src/commands/local/daemon.ts | 12 +++ .../cli/src/commands/local/receiver-ingest.ts | 2 + packages/cli/src/commands/local/run.ts | 1 + packages/cli/src/commands/local/server.ts | 2 + packages/cli/src/commands/log/tail.ts | 2 + packages/cli/src/commands/log/view.ts | 1 + packages/cli/src/commands/proguard/upload.ts | 17 ++-- packages/cli/src/commands/project/create.ts | 1 + packages/cli/src/commands/project/list.ts | 20 ++-- .../cli/src/commands/react-native/gradle.ts | 1 + .../cli/src/commands/react-native/xcode.ts | 3 + packages/cli/src/commands/sourcemap/upload.ts | 27 +++--- packages/cli/src/lib/agent-skills.ts | 2 + .../cli/src/lib/api/attribute-pagination.ts | 1 + packages/cli/src/lib/api/chunk-upload.ts | 13 ++- packages/cli/src/lib/api/code-mappings.ts | 1 + packages/cli/src/lib/api/conversations.ts | 1 + packages/cli/src/lib/api/dart-symbols.ts | 2 + packages/cli/src/lib/api/dashboards.ts | 59 ++++-------- packages/cli/src/lib/api/debug-files.ts | 14 ++- packages/cli/src/lib/api/explore.ts | 1 + packages/cli/src/lib/api/infrastructure.ts | 1 + packages/cli/src/lib/api/issue-app-links.ts | 1 + packages/cli/src/lib/api/preprod-artifacts.ts | 5 + packages/cli/src/lib/api/proguard.ts | 5 +- packages/cli/src/lib/api/releases.ts | 1 + packages/cli/src/lib/api/replays.ts | 1 + packages/cli/src/lib/bash-hook/traceback.ts | 38 +++++--- .../src/lib/build/asset-catalog-extract.ts | 56 ++++++----- packages/cli/src/lib/build/dsyms.ts | 3 + packages/cli/src/lib/build/index.ts | 16 +++- packages/cli/src/lib/build/zip-writer.ts | 5 + packages/cli/src/lib/command.ts | 1 + packages/cli/src/lib/complete.ts | 1 + packages/cli/src/lib/db/dsn-cache.ts | 30 +++--- packages/cli/src/lib/detect-agent.ts | 1 + packages/cli/src/lib/dev-script.ts | 1 + packages/cli/src/lib/dif/find.ts | 1 + packages/cli/src/lib/dif/scan.ts | 4 + packages/cli/src/lib/docs-context.ts | 51 ++++++---- packages/cli/src/lib/dsn/env-file.ts | 74 +++++++++------ packages/cli/src/lib/dsn/project-root.ts | 2 + packages/cli/src/lib/dsn/resolver.ts | 34 +++---- packages/cli/src/lib/dsn/scanner.ts | 2 + packages/cli/src/lib/fs-utils.ts | 1 + packages/cli/src/lib/ghcr.ts | 2 + packages/cli/src/lib/jvm-bundle.ts | 41 ++++---- packages/cli/src/lib/oauth.ts | 2 + packages/cli/src/lib/polling.ts | 2 + packages/cli/src/lib/scan/concurrent.ts | 1 + packages/cli/src/lib/scan/grep.ts | 1 + packages/cli/src/lib/scan/walker.ts | 6 ++ packages/cli/src/lib/sentryclirc-import.ts | 28 +++--- packages/cli/src/lib/sentryclirc.ts | 1 + packages/cli/src/lib/snapshots/archive.ts | 1 + packages/cli/src/lib/sourcemap/inject.ts | 93 +++++++++++-------- packages/cli/src/lib/sourcemap/zip.ts | 2 + packages/cli/src/lib/target-scope.ts | 4 + packages/cli/src/lib/upgrade.ts | 4 + packages/cli/src/lib/walk-up.ts | 1 + .../src/lib/wizard/nextjs/nextjs-wizard.ts | 1 + packages/cli/src/lib/wizard/nuxt/sdk-setup.ts | 1 + .../src/lib/wizard/react-native/javascript.ts | 1 + .../wizard/remix/codemods/express-server.ts | 2 + .../lib/wizard/sourcemaps/tools/sentry-cli.ts | 2 + .../cli/src/lib/wizard/utils/clack/index.ts | 1 + .../src/lib/wizard/utils/clack/mcp-config.ts | 2 + packages/cli/src/lib/wrangler.ts | 1 + 82 files changed, 551 insertions(+), 310 deletions(-) diff --git a/packages/cli/src/commands/alert/issues/rule-resolve.ts b/packages/cli/src/commands/alert/issues/rule-resolve.ts index 7192121ca7..0af9abf829 100644 --- a/packages/cli/src/commands/alert/issues/rule-resolve.ts +++ b/packages/cli/src/commands/alert/issues/rule-resolve.ts @@ -2,7 +2,10 @@ * Shared issue alert rule reference parsing and resolution (view / delete / edit). */ -import { MAX_PAGINATION_PAGES } from "../../../lib/api/infrastructure.js"; +import { + MAX_PAGINATION_PAGES, + ORG_FANOUT_CONCURRENCY, +} from "../../../lib/api/infrastructure.js"; import { API_MAX_PER_PAGE, getIssueAlertRule, @@ -13,6 +16,7 @@ import { import { type LazyCommand, sentry } from "../../../lib/app-identity.js"; import { ORG_PROJECT_TARGET } from "../../../lib/completion-target.js"; import { ResolutionError, ValidationError } from "../../../lib/errors.js"; +import { mapBounded } from "../../../lib/fan-out.js"; import { fuzzyMatch } from "../../../lib/fuzzy.js"; import { logger } from "../../../lib/logger.js"; import type { ResolvedTarget } from "../../../lib/resolve-target.js"; @@ -91,6 +95,7 @@ export async function listAllIssueRulesForTarget( const all: IssueAlertRule[] = []; let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await listIssueAlertsPaginated( target.org, target.project, @@ -115,18 +120,24 @@ export async function resolveIssueAlertRule( usageHint: string, ): Promise { if (isAllDigits(ref)) { - const hits: IssueRuleResolution[] = []; - for (const target of targets) { - try { - const rule = await getIssueAlertRule(target.org, target.project, ref); - hits.push({ target, rule }); - } catch (e) { - if (isNotFoundApiError(e)) { - continue; + const lookups = await mapBounded( + targets, + async (target): Promise => { + try { + return { + target, + rule: await getIssueAlertRule(target.org, target.project, ref), + }; + } catch (e) { + if (isNotFoundApiError(e)) { + return null; + } + throw e; } - throw e; - } - } + }, + ORG_FANOUT_CONCURRENCY, + ); + const hits = lookups.filter((hit) => hit !== null); if (hits.length === 1) { return hits[0] as IssueRuleResolution; @@ -147,8 +158,15 @@ export async function resolveIssueAlertRule( const hits: IssueRuleResolution[] = []; const allRuleNames: string[] = []; - for (const target of targets) { - const rules = await listAllIssueRulesForTarget(target); + const targetRules = await mapBounded( + targets, + async (target) => ({ + target, + rules: await listAllIssueRulesForTarget(target), + }), + ORG_FANOUT_CONCURRENCY, + ); + for (const { target, rules } of targetRules) { for (const r of rules) { if (r.name) { allRuleNames.push(r.name); diff --git a/packages/cli/src/commands/alert/metrics/rule-resolve.ts b/packages/cli/src/commands/alert/metrics/rule-resolve.ts index dd0fb473b5..9cd5ffbc9c 100644 --- a/packages/cli/src/commands/alert/metrics/rule-resolve.ts +++ b/packages/cli/src/commands/alert/metrics/rule-resolve.ts @@ -2,7 +2,10 @@ * Shared metric alert rule reference parsing and resolution (view / delete / edit). */ -import { MAX_PAGINATION_PAGES } from "../../../lib/api/infrastructure.js"; +import { + MAX_PAGINATION_PAGES, + ORG_FANOUT_CONCURRENCY, +} from "../../../lib/api/infrastructure.js"; import { API_MAX_PER_PAGE, getMetricAlertRule, @@ -13,6 +16,7 @@ import { import { type LazyCommand, sentry } from "../../../lib/app-identity.js"; import { ORG_TARGET } from "../../../lib/completion-target.js"; import { ResolutionError, ValidationError } from "../../../lib/errors.js"; +import { mapBounded } from "../../../lib/fan-out.js"; import { fuzzyMatch } from "../../../lib/fuzzy.js"; import { logger } from "../../../lib/logger.js"; import { countChar, isAllDigits } from "../../../lib/utils.js"; @@ -88,6 +92,7 @@ export async function listAllMetricRulesForOrg( const all: MetricAlertRule[] = []; let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await listMetricAlertsPaginated(orgSlug, { perPage: API_MAX_PER_PAGE, cursor, @@ -111,18 +116,21 @@ export async function resolveMetricAlertRule( usageHint: string, ): Promise { if (isAllDigits(ref)) { - const hits: MetricRuleResolution[] = []; - for (const orgSlug of orgSlugs) { - try { - const rule = await getMetricAlertRule(orgSlug, ref); - hits.push({ orgSlug, rule }); - } catch (e) { - if (isNotFoundApiError(e)) { - continue; + const lookups = await mapBounded( + orgSlugs, + async (orgSlug): Promise => { + try { + return { orgSlug, rule: await getMetricAlertRule(orgSlug, ref) }; + } catch (e) { + if (isNotFoundApiError(e)) { + return null; + } + throw e; } - throw e; - } - } + }, + ORG_FANOUT_CONCURRENCY, + ); + const hits = lookups.filter((hit) => hit !== null); if (hits.length === 1) { return hits[0] as MetricRuleResolution; @@ -143,8 +151,15 @@ export async function resolveMetricAlertRule( const hits: MetricRuleResolution[] = []; const allNames: string[] = []; - for (const orgSlug of orgSlugs) { - const rules = await listAllMetricRulesForOrg(orgSlug); + const orgRules = await mapBounded( + orgSlugs, + async (orgSlug) => ({ + orgSlug, + rules: await listAllMetricRulesForOrg(orgSlug), + }), + ORG_FANOUT_CONCURRENCY, + ); + for (const { orgSlug, rules } of orgRules) { for (const r of rules) { if (r.name) { allNames.push(r.name); diff --git a/packages/cli/src/commands/alert/metrics/view.ts b/packages/cli/src/commands/alert/metrics/view.ts index fe7bec4248..ccbe99224b 100644 --- a/packages/cli/src/commands/alert/metrics/view.ts +++ b/packages/cli/src/commands/alert/metrics/view.ts @@ -6,6 +6,8 @@ import { import { openInBrowser } from "../../../lib/browser.js"; import { buildCommand } from "../../../lib/command.js"; import { ApiError } from "../../../lib/errors.js"; +import { mapBounded } from "../../../lib/fan-out.js"; +import { ORG_FANOUT_CONCURRENCY } from "../../../lib/api/infrastructure.js"; import { formatMetricAlertView, type MetricAlertViewResult, @@ -119,22 +121,32 @@ export const viewCommand = buildCommand({ workflows: [], workflowErrors: [], }; - for (const id of new Set(rule.workflowIds ?? [])) { - try { - data.workflows.push( - await getIssueAlertWorkflowDocument(result.orgSlug, id), - ); - } catch (error) { - // A missing or inaccessible link must not hide the readable detector - // or be mistaken for an alert with no notification configuration. - if ( - error instanceof ApiError && - (error.status === 403 || error.status === 404) - ) { - data.workflowErrors.push({ id, status: error.status }); - } else { + const lookups = await mapBounded( + new Set(rule.workflowIds ?? []), + async (id) => { + try { + return { + workflow: await getIssueAlertWorkflowDocument(result.orgSlug, id), + }; + } catch (error) { + // A missing or inaccessible link must not hide the readable detector + // or be mistaken for an alert with no notification configuration. + if ( + error instanceof ApiError && + (error.status === 403 || error.status === 404) + ) { + return { error: { id, status: error.status } }; + } throw error; } + }, + ORG_FANOUT_CONCURRENCY, + ); + for (const lookup of lookups) { + if ("workflow" in lookup) { + data.workflows.push(lookup.workflow); + } else { + data.workflowErrors.push(lookup.error); } } yield new CommandOutput(data); diff --git a/packages/cli/src/commands/auth/default.ts b/packages/cli/src/commands/auth/default.ts index 2fb9c0f6d8..ca105c8085 100644 --- a/packages/cli/src/commands/auth/default.ts +++ b/packages/cli/src/commands/auth/default.ts @@ -190,6 +190,7 @@ export const authDefaultCommand = buildCommand({ if (step.value instanceof CommandOutput) { yield step.value; } + // oxlint-disable-next-line no-await-in-loop -- drives the generator one step at a time step = await generator.next(); } return step.value as { hint?: string } | undefined; diff --git a/packages/cli/src/commands/auth/logout.ts b/packages/cli/src/commands/auth/logout.ts index 04f81099f1..f39d8ed37a 100644 --- a/packages/cli/src/commands/auth/logout.ts +++ b/packages/cli/src/commands/auth/logout.ts @@ -204,6 +204,7 @@ async function removeAccounts(accounts: AccountSummary[]): Promise { (a, b) => Number(a.active) - Number(b.active), ); for (const account of ordered) { + // oxlint-disable-next-line no-await-in-loop -- each removal promotes the next account, so accounts are removed in order await removeAccount(account.id, { promoteNext: true }); } } diff --git a/packages/cli/src/commands/build/upload.ts b/packages/cli/src/commands/build/upload.ts index 14a19c8cca..ba069fc83a 100644 --- a/packages/cli/src/commands/build/upload.ts +++ b/packages/cli/src/commands/build/upload.ts @@ -372,6 +372,7 @@ export const uploadCommand = buildCommand({ const builds: BuildUploadEntry[] = []; for (const path of paths) { try { + // oxlint-disable-next-line no-await-in-loop -- each build upload already sends its chunks in parallel; one build at a time keeps that cap const artifactUrl = await uploadOne( this, path, diff --git a/packages/cli/src/commands/cli/setup.ts b/packages/cli/src/commands/cli/setup.ts index 40a6556335..cbc4ccafd9 100644 --- a/packages/cli/src/commands/cli/setup.ts +++ b/packages/cli/src/commands/cli/setup.ts @@ -144,6 +144,7 @@ async function migrateLegacyConfig( for (const name of configFiles) { const from = join(legacyDir, name); if (existsSync(from)) { + // oxlint-disable-next-line no-await-in-loop -- moves the config files one at a time; a failure stops before the next move await rename(from, join(targetConfigDir, name)); } } diff --git a/packages/cli/src/commands/cli/uninstall.ts b/packages/cli/src/commands/cli/uninstall.ts index 778db99f60..72f7f037b6 100644 --- a/packages/cli/src/commands/cli/uninstall.ts +++ b/packages/cli/src/commands/cli/uninstall.ts @@ -361,6 +361,7 @@ async function executeRemovals( for (const artifact of existing) { try { + // oxlint-disable-next-line no-await-in-loop -- removes artifacts in the listed order and records each outcome await artifact.remove(); result.removed.push(`${artifact.label} (${artifact.path})`); } catch (error) { diff --git a/packages/cli/src/commands/cli/upgrade.ts b/packages/cli/src/commands/cli/upgrade.ts index c17fa2a45f..6fa2c369c0 100644 --- a/packages/cli/src/commands/cli/upgrade.ts +++ b/packages/cli/src/commands/cli/upgrade.ts @@ -670,6 +670,7 @@ async function spawnWithRetry( env, windowsVerbatimArguments: target.windowsVerbatimArguments, }); + // oxlint-disable-next-line no-await-in-loop -- retries the spawn one attempt at a time, with a backoff between attempts return await new Promise((resolve, reject) => { proc.on("close", (code, signal) => { // SIGKILL on macOS typically means AMFI killed the binary due to @@ -713,6 +714,7 @@ async function spawnWithRetry( log.warn( `Binary is locked (antivirus scan?), retrying in ${delay}ms... (attempt ${attempt}/${SPAWN_MAX_ATTEMPTS})`, ); + // oxlint-disable-next-line no-await-in-loop -- retries the spawn one attempt at a time, with a backoff between attempts await setTimeout(delay); } } diff --git a/packages/cli/src/commands/dashboard/list.ts b/packages/cli/src/commands/dashboard/list.ts index 7db12ec732..7343b963c3 100644 --- a/packages/cli/src/commands/dashboard/list.ts +++ b/packages/cli/src/commands/dashboard/list.ts @@ -300,6 +300,7 @@ async function fetchDashboards( // always uses one page size and resumes mid-page via afterId bookmarks. // oxlint-disable-next-line sentry-cli/no-manual-pagination for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await listDashboardsPaginated(orgSlug, { perPage: opts.perPage, cursor: serverCursor, diff --git a/packages/cli/src/commands/dashboard/resolve.ts b/packages/cli/src/commands/dashboard/resolve.ts index 6c46a20876..11de786e49 100644 --- a/packages/cli/src/commands/dashboard/resolve.ts +++ b/packages/cli/src/commands/dashboard/resolve.ts @@ -129,6 +129,7 @@ export async function resolveDashboardId( let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await withDashboardErrors( { orgSlug, operation: "list" }, () => diff --git a/packages/cli/src/commands/dashboard/view.ts b/packages/cli/src/commands/dashboard/view.ts index 259768bcac..507ecf286a 100644 --- a/packages/cli/src/commands/dashboard/view.ts +++ b/packages/cli/src/commands/dashboard/view.ts @@ -309,6 +309,7 @@ export const viewCommand = buildCommand({ try { while (!controller.signal.aborted) { + // oxlint-disable-next-line no-await-in-loop -- refreshes the dashboard on an interval until aborted const [widgetData, droppedData] = await Promise.all([ queryAllWidgets(regionUrl, orgSlug, dashboard, { ...widgetTimeOpts, @@ -333,6 +334,7 @@ export const viewCommand = buildCommand({ yield new CommandOutput(viewData); + // oxlint-disable-next-line no-await-in-loop -- refreshes the dashboard on an interval until aborted await abortableSleep(interval * 1000, controller.signal); } } finally { diff --git a/packages/cli/src/commands/event/send.ts b/packages/cli/src/commands/event/send.ts index 969e248bc7..f0692f81e1 100644 --- a/packages/cli/src/commands/event/send.ts +++ b/packages/cli/src/commands/event/send.ts @@ -361,11 +361,13 @@ built entirely from the file contents. if (eventFiles.length > 0) { for (const file of eventFiles) { + // oxlint-disable-next-line no-await-in-loop -- sends each file and yields its result before the next one const { body, eventId } = await buildFilePayload( file, flags.raw ?? false, dsnComponents, ); + // oxlint-disable-next-line no-await-in-loop -- sends each file and yields its result before the next one await sendEnvelopeRequest(dsn, body); yield new CommandOutput({ eventId, file }); } diff --git a/packages/cli/src/commands/issue/view.ts b/packages/cli/src/commands/issue/view.ts index 44cfb0d743..7538af2496 100644 --- a/packages/cli/src/commands/issue/view.ts +++ b/packages/cli/src/commands/issue/view.ts @@ -310,6 +310,7 @@ async function openIssuesInBrowser( ); for (const issue of issues) { + // oxlint-disable-next-line no-await-in-loop -- opens browser tabs one at a time, in order await openInBrowser(issue.permalink, "issue"); } } diff --git a/packages/cli/src/commands/local/daemon.ts b/packages/cli/src/commands/local/daemon.ts index 7a7ce358a1..9dcf709a32 100644 --- a/packages/cli/src/commands/local/daemon.ts +++ b/packages/cli/src/commands/local/daemon.ts @@ -224,6 +224,7 @@ async function withDaemonOwnershipGuard( action: () => Promise, ): Promise { const path = join(directory, "local-control-plane.owner.guard"); + // oxlint-disable no-await-in-loop -- retries the guard file until it is free; each attempt waits for the one before for (let attempt = 0; attempt < 40; attempt += 1) { let guard: Awaited>; try { @@ -252,6 +253,7 @@ async function withDaemonOwnershipGuard( await rm(path, { force: true }); } } + // oxlint-enable no-await-in-loop throw new Error( "Timed out waiting for Local daemon ownership arbitration; active ownership has been preserved.", ); @@ -283,6 +285,7 @@ export async function claimDaemonOwnership( }); }; for (let attempt = 0; attempt < 40; attempt += 1) { + // oxlint-disable-next-line no-await-in-loop -- retries the ownership claim until it is free; each attempt waits for the one before const release = await withDaemonOwnershipGuard(directory, async () => { const claimed = await tryClaim(); if (claimed) return claimed; @@ -325,6 +328,7 @@ export async function claimDaemonOwnership( return undefined; }); if (release) return release; + // oxlint-disable-next-line no-await-in-loop -- waits between checks of the daemon state until the deadline await sleep(125); } throw new Error("Timed out waiting for Sentry Local daemon ownership."); @@ -351,6 +355,7 @@ function isProcessRunning(pid: number): boolean { async function readOwnerPid(path: string): Promise { for (let attempt = 0; ; attempt += 1) { try { + // oxlint-disable-next-line no-await-in-loop -- retries the read only while Windows briefly denies it return Number(await readFile(path, "utf8")); } catch (error) { if (error instanceof Error && "code" in error) { @@ -358,6 +363,7 @@ async function readOwnerPid(path: string): Promise { // Windows may briefly deny reads while the previous owner removes its // file. Retry without interpreting an unreadable owner as absent. if (error.code === "EPERM" && attempt < 4) { + // oxlint-disable-next-line no-await-in-loop -- waits between checks of the daemon state until the deadline await sleep(125); continue; } @@ -491,7 +497,9 @@ export async function waitForLocalDaemonShutdown( const directory = getConfigDir(); const deadline = Date.now() + 5_000; while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls the daemon state until the deadline const current = await readLocalDaemonState(directory); + // oxlint-disable-next-line no-await-in-loop -- polls the daemon state until the deadline const owner = await readOwnerPid( join(directory, "local-control-plane.owner"), ); @@ -499,6 +507,7 @@ export async function waitForLocalDaemonShutdown( current?.pid === state.pid && current.token === state.token; if ((!ownsState && owner !== state.pid) || !isProcessRunning(state.pid)) return; + // oxlint-disable-next-line no-await-in-loop -- waits between checks of the daemon state until the deadline await sleep(125); } throw new Error( @@ -512,11 +521,14 @@ async function waitForLocalDaemon( startupError?: () => Error | undefined, ): Promise { while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- waits between checks of the daemon state until the deadline await sleep(125); + // oxlint-disable-next-line no-await-in-loop -- polls the daemon state until the deadline const state = await discoverLocalDaemon(true); if (state) return state; const error = startupError?.(); if (error) { + // oxlint-disable-next-line no-await-in-loop -- polls the daemon state until the deadline const owner = await readOwnerPid( join(getConfigDir(), "local-control-plane.owner"), ); diff --git a/packages/cli/src/commands/local/receiver-ingest.ts b/packages/cli/src/commands/local/receiver-ingest.ts index 8d7f8a0aa9..6f7ee61ab2 100644 --- a/packages/cli/src/commands/local/receiver-ingest.ts +++ b/packages/cli/src/commands/local/receiver-ingest.ts @@ -95,10 +95,12 @@ export async function readReceiverBody( let size = 0; try { for (;;) { + // oxlint-disable-next-line no-await-in-loop -- reads the request body in order, one chunk at a time const { done, value } = await reader.read(); if (done) return Buffer.concat(chunks, size); size += value.byteLength; if (size > maxBytes) { + // oxlint-disable-next-line no-await-in-loop -- reads the request body in order, one chunk at a time await reader .cancel() .catch(() => logger.debug("Local request body was already closed.")); diff --git a/packages/cli/src/commands/local/run.ts b/packages/cli/src/commands/local/run.ts index c8f11dc9c8..4ec7541409 100644 --- a/packages/cli/src/commands/local/run.ts +++ b/packages/cli/src/commands/local/run.ts @@ -1163,6 +1163,7 @@ async function waitForAppExit(pid: number, ms: number): Promise { if (Date.now() >= deadline) { return false; } + // oxlint-disable-next-line no-await-in-loop -- waits for the app process to exit await new Promise((r) => setTimeout(r, GROUP_POLL_MS)); } return true; diff --git a/packages/cli/src/commands/local/server.ts b/packages/cli/src/commands/local/server.ts index b7e7a30a68..314ff263fa 100644 --- a/packages/cli/src/commands/local/server.ts +++ b/packages/cli/src/commands/local/server.ts @@ -986,6 +986,7 @@ async function consumeSSEWithWarning( const replays = createReplayTracker(); while (!signal.aborted) { + // oxlint-disable-next-line no-await-in-loop -- reconnects one attempt at a time until aborted const result = await attemptSSEConnection({ url, streamUrl, @@ -1045,6 +1046,7 @@ async function consumeSSEWithWarning( logger.info( `SSE connection lost, reconnecting in ${retryDelay / 1000}s...`, ); + // oxlint-disable-next-line no-await-in-loop -- reconnects one attempt at a time until aborted await sleepUnlessAborted(retryDelay, signal); retryDelay = Math.min(retryDelay * 2, SSE_MAX_RETRY_MS); } diff --git a/packages/cli/src/commands/log/tail.ts b/packages/cli/src/commands/log/tail.ts index 4a9bec685b..9633135114 100644 --- a/packages/cli/src/commands/log/tail.ts +++ b/packages/cli/src/commands/log/tail.ts @@ -197,11 +197,13 @@ async function* generateFollowLogs( // Poll loop — exits when SIGINT fires for (;;) { + // oxlint-disable-next-line no-await-in-loop -- polls for new logs; each request starts after the last timestamp await abortableSleep(pollIntervalMs, controller.signal); if (controller.signal.aborted) { break; } + // oxlint-disable-next-line no-await-in-loop -- polls for new logs; each request starts after the last timestamp const newLogs = await fetchPoll(config, lastTimestamp); if (newLogs && newLogs.length > 0) { yield [...newLogs].reverse(); diff --git a/packages/cli/src/commands/log/view.ts b/packages/cli/src/commands/log/view.ts index 0a1f86f115..7291739717 100644 --- a/packages/cli/src/commands/log/view.ts +++ b/packages/cli/src/commands/log/view.ts @@ -319,6 +319,7 @@ async function handleWebOpen(orgSlug: string, logIds: string[]): Promise { } } for (const id of logIds) { + // oxlint-disable-next-line no-await-in-loop -- opens browser tabs one at a time, in order await openInBrowser(buildLogsUrl(orgSlug, id), "log"); } } diff --git a/packages/cli/src/commands/proguard/upload.ts b/packages/cli/src/commands/proguard/upload.ts index 63d85f5f1a..b14527b245 100644 --- a/packages/cli/src/commands/proguard/upload.ts +++ b/packages/cli/src/commands/proguard/upload.ts @@ -15,11 +15,13 @@ import { uploadProguardMappings } from "../../lib/api/proguard.js"; import { buildCommand } from "../../lib/command.js"; import { parseFilePath, parseText } from "../../lib/completion-target.js"; import { ContextError, ValidationError } from "../../lib/errors.js"; +import { mapBounded } from "../../lib/fan-out.js"; import { mdKvTable, renderMarkdown } from "../../lib/formatters/markdown.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { logger } from "../../lib/logger.js"; import { computeProguardUuid } from "../../lib/proguard.js"; import { resolveOrgAndProject } from "../../lib/resolve-target.js"; +import { CONCURRENCY_LIMIT } from "../../lib/scan/constants.js"; import { sentry } from "../../lib/app-identity.js"; const log = logger.withTag("proguard.upload"); @@ -251,12 +253,15 @@ export const uploadCommand = buildCommand({ } // 4. Read each file and compute UUID - const mappings: ProguardMapping[] = []; - for (const path of paths) { - const content = await readMappingFile(path); - const uuid = flags.uuid ?? computeProguardUuid(content); - mappings.push({ path, uuid, content }); - } + const mappings = await mapBounded( + paths, + async (path): Promise => { + const content = await readMappingFile(path); + const uuid = flags.uuid ?? computeProguardUuid(content); + return { path, uuid, content }; + }, + CONCURRENCY_LIMIT, + ); // 5. Deduplicate mappings with identical content (same UUID = same content) const uniqueMappings = deduplicateMappings(mappings); diff --git a/packages/cli/src/commands/project/create.ts b/packages/cli/src/commands/project/create.ts index c17d0f7311..1c0e5a3b68 100644 --- a/packages/cli/src/commands/project/create.ts +++ b/packages/cli/src/commands/project/create.ts @@ -764,6 +764,7 @@ export const createCommand = buildCommand({ try { for (const { name, platform } of parsed) { results.push( + // oxlint-disable-next-line no-await-in-loop -- creates projects one at a time to respect rate limits await createOneProject({ orgSlug, name, diff --git a/packages/cli/src/commands/project/list.ts b/packages/cli/src/commands/project/list.ts index 7ba8a9a6d5..e2d8ccda13 100644 --- a/packages/cli/src/commands/project/list.ts +++ b/packages/cli/src/commands/project/list.ts @@ -37,6 +37,8 @@ import { resolveCursor, } from "../../lib/db/pagination.js"; import { ResolutionError, withAuthGuard } from "../../lib/errors.js"; +import { mapBounded } from "../../lib/fan-out.js"; +import { ORG_FANOUT_CONCURRENCY } from "../../lib/api/infrastructure.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { type Column, formatTable } from "../../lib/formatters/table.js"; import { @@ -155,18 +157,12 @@ export async function fetchOrgProjectsByName( */ export async function fetchAllOrgProjects(): Promise { const orgs = await listOrganizations(); - const results: ProjectWithOrg[] = []; - - for (const org of orgs) { - const projectsResult = await withAuthGuard(() => - fetchOrgProjects(org.slug), - ); - if (projectsResult.ok) { - results.push(...projectsResult.value); - } - } - - return results; + const orgResults = await mapBounded( + orgs, + (org) => withAuthGuard(() => fetchOrgProjects(org.slug)), + ORG_FANOUT_CONCURRENCY, + ); + return orgResults.flatMap((result) => (result.ok ? result.value : [])); } /** diff --git a/packages/cli/src/commands/react-native/gradle.ts b/packages/cli/src/commands/react-native/gradle.ts index 23f022edd6..1baf243b9a 100644 --- a/packages/cli/src/commands/react-native/gradle.ts +++ b/packages/cli/src/commands/react-native/gradle.ts @@ -217,6 +217,7 @@ export const gradleCommand = buildCommand({ log.info( `Uploading sourcemaps for release ${flags.release} distribution ${dist}`, ); + // oxlint-disable-next-line no-await-in-loop -- each upload already sends its chunks in parallel; one dist at a time keeps that cap await uploadSourcemaps({ org, project, diff --git a/packages/cli/src/commands/react-native/xcode.ts b/packages/cli/src/commands/react-native/xcode.ts index 8ab1707bdf..c94d18c806 100644 --- a/packages/cli/src/commands/react-native/xcode.ts +++ b/packages/cli/src/commands/react-native/xcode.ts @@ -151,6 +151,7 @@ async function waitUntilAvailable( const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { try { + // oxlint-disable-next-line no-await-in-loop -- polls the URL until it answers or the deadline passes const res = await fetch(url, { method: "GET" }); if (res.status < 500) { return true; @@ -158,6 +159,7 @@ async function waitUntilAvailable( } catch (err) { log.debug("Packager not up yet", err); } + // oxlint-disable-next-line no-await-in-loop -- polls the URL until it answers or the deadline passes await sleep(500); } return false; @@ -359,6 +361,7 @@ async function uploadPair( let uploads = 0; if (dists.length > 0) { for (const d of dists) { + // oxlint-disable-next-line no-await-in-loop -- each upload already sends its chunks in parallel; one dist at a time keeps that cap await uploadSourcemaps({ org, project, diff --git a/packages/cli/src/commands/sourcemap/upload.ts b/packages/cli/src/commands/sourcemap/upload.ts index f93e3f377e..4f1045a848 100644 --- a/packages/cli/src/commands/sourcemap/upload.ts +++ b/packages/cli/src/commands/sourcemap/upload.ts @@ -28,9 +28,11 @@ import { parseText, } from "../../lib/completion-target.js"; import { ContextError, ValidationError } from "../../lib/errors.js"; +import { mapBounded } from "../../lib/fan-out.js"; import { mdKvTable, renderMarkdown } from "../../lib/formatters/markdown.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { resolveOrgAndProject } from "../../lib/resolve-target.js"; +import { CONCURRENCY_LIMIT } from "../../lib/scan/constants.js"; import { assertDirectoryReadable, buildEmptyDiscoveryError, @@ -264,18 +266,19 @@ async function stripUploadedSources( files: ArtifactFile[], strip: SourcesStrip, ): Promise { - for (const file of files) { - if (file.type !== "source_map") { - continue; - } - const json = file.content - ? file.content.toString("utf-8") - : await readFile(file.path, "utf-8"); - const stripped = stripSourcemapSources(json, strip); - if (stripped !== undefined) { - file.content = Buffer.from(stripped); - } - } + await mapBounded( + files.filter((file) => file.type === "source_map"), + async (file) => { + const json = file.content + ? file.content.toString("utf-8") + : await readFile(file.path, "utf-8"); + const stripped = stripSourcemapSources(json, strip); + if (stripped !== undefined) { + file.content = Buffer.from(stripped); + } + }, + CONCURRENCY_LIMIT, + ); } export const uploadCommand = buildCommand({ diff --git a/packages/cli/src/lib/agent-skills.ts b/packages/cli/src/lib/agent-skills.ts index 09feaf3dd1..b663450aa4 100644 --- a/packages/cli/src/lib/agent-skills.ts +++ b/packages/cli/src/lib/agent-skills.ts @@ -116,6 +116,7 @@ async function writeSkillFiles( if (!existsSync(dir)) { mkdirSync(dir, { recursive: true, mode: 0o755 }); } + // oxlint-disable-next-line no-await-in-loop -- writes the skill files one at a time; a failure stops before the next write await atomicWriteFile(fullPath, content); if (relativePath.startsWith("references/")) { referenceCount += 1; @@ -180,6 +181,7 @@ export async function installAgentSkills( continue; } + // oxlint-disable-next-line no-await-in-loop -- writes the skill files one at a time; a failure stops before the next write const location = await writeSkillFiles( getSkillInstallPath(homeDir, target.rootDir), ); diff --git a/packages/cli/src/lib/api/attribute-pagination.ts b/packages/cli/src/lib/api/attribute-pagination.ts index 4f70eb8e9c..70e6f908e5 100644 --- a/packages/cli/src/lib/api/attribute-pagination.ts +++ b/packages/cli/src/lib/api/attribute-pagination.ts @@ -96,6 +96,7 @@ export async function fetchAttributeTypePage( // coordinate system, so paginate()'s row-count bookmarks do not apply. // oxlint-disable-next-line sentry-cli/no-manual-pagination -- requires key bookmarks and cross-page deduplication for (let pageIndex = 0; pageIndex < MAX_PAGINATION_PAGES; pageIndex++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const page = await listTraceItemAttributes(org, { ...options, attributeTypes: [type], diff --git a/packages/cli/src/lib/api/chunk-upload.ts b/packages/cli/src/lib/api/chunk-upload.ts index 9cc5d3877b..4a93b422b4 100644 --- a/packages/cli/src/lib/api/chunk-upload.ts +++ b/packages/cli/src/lib/api/chunk-upload.ts @@ -374,6 +374,7 @@ export async function hashChunks( for (let offset = 0; offset < fileSize; offset += chunkSize) { const size = Math.min(chunkSize, fileSize - offset); const buf = Buffer.alloc(size); + // oxlint-disable-next-line no-await-in-loop -- reads the file into one reused buffer, one chunk at a time await fh.read(buf, 0, size, offset); const sha1 = createHash("sha1").update(buf).digest("hex"); overallHasher.update(buf); @@ -582,8 +583,14 @@ async function uploadChunkBatch(params: { const fieldName = encoding === "gzip" ? "file_gzip" : "file"; const form = new FormData(); - for (const chunk of batch) { - const payload = await encodeChunk(chunk.data, encoding); + // The batch is capped by the server's chunksPerRequest, so encode it at once. + const encoded = await Promise.all( + batch.map(async (chunk) => ({ + chunk, + payload: await encodeChunk(chunk.data, encoding), + })), + ); + for (const { chunk, payload } of encoded) { form.append( fieldName, new Blob([payload], { type: "application/octet-stream" }), @@ -779,8 +786,10 @@ export async function pollAssembly(params: { const deadline = Date.now() + deadlineMs; while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done const pollResult = await assemble(); if (pollResult.state === "ok") { diff --git a/packages/cli/src/lib/api/code-mappings.ts b/packages/cli/src/lib/api/code-mappings.ts index 4df974f603..caf918176e 100644 --- a/packages/cli/src/lib/api/code-mappings.ts +++ b/packages/cli/src/lib/api/code-mappings.ts @@ -119,6 +119,7 @@ export async function uploadCodeMappings( ); } + // oxlint-disable-next-line no-await-in-loop -- batches upsert into one project and repository, one request at a time const result = await bulkUpsertOrganizationCodeMappings({ ...config, path: { organization_id_or_slug: org }, diff --git a/packages/cli/src/lib/api/conversations.ts b/packages/cli/src/lib/api/conversations.ts index c785747fc4..f1fd2f5427 100644 --- a/packages/cli/src/lib/api/conversations.ts +++ b/packages/cli/src/lib/api/conversations.ts @@ -135,6 +135,7 @@ export async function getConversationSpans( let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const result = await retrieveOrganizationAiConversation({ ...config, path: { diff --git a/packages/cli/src/lib/api/dart-symbols.ts b/packages/cli/src/lib/api/dart-symbols.ts index a982b81bee..d17c02c875 100644 --- a/packages/cli/src/lib/api/dart-symbols.ts +++ b/packages/cli/src/lib/api/dart-symbols.ts @@ -166,8 +166,10 @@ export async function uploadDartSymbolMap( // Step 6: Poll assemble endpoint until done const deadline = Date.now() + ASSEMBLE_MAX_WAIT_MS; while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done const pollResult = await assembleDebugFiles(org, project, assembleBody); const { allDone: done } = checkAssembleResponse( diff --git a/packages/cli/src/lib/api/dashboards.ts b/packages/cli/src/lib/api/dashboards.ts index 498ece60d9..3e64899632 100644 --- a/packages/cli/src/lib/api/dashboards.ts +++ b/packages/cli/src/lib/api/dashboards.ts @@ -52,6 +52,7 @@ import { import type { EventsDataset } from "../datasets.js"; import { reportCliError } from "../error-reporting.js"; import { ApiError, stringifyUnknown } from "../errors.js"; +import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; import { getSdkClientConfig } from "../sentry-sdk-client.js"; @@ -581,6 +582,7 @@ async function queryWidgetTimeseries( const aggregates = query.aggregates ?? []; const columns = query.columns ?? []; + // oxlint-disable-next-line no-await-in-loop -- widgets already fan out at ORG_FANOUT_CONCURRENCY; a widget's queries run in turn so the total stays at that cap const result = await listOrganizationEventsTimeseries({ ...getSdkClientConfig(regionUrl), path: { organization_id_or_slug: orgSlug }, @@ -799,28 +801,6 @@ function widgetErrorMessage(error: unknown): string { * @param options - Query options (period override, environment filter) * @returns Map of widget index → query result */ -/** Collect settled results from a batch into the results map. */ -function collectBatchResults( - batchResults: PromiseSettledResult[], - startIndex: number, - results: Map, -): void { - for (let j = 0; j < batchResults.length; j++) { - const result = batchResults[j]; - const idx = startIndex + j; - if (result?.status === "fulfilled") { - results.set(idx, result.value); - } else { - results.set(idx, { - type: "error", - message: result?.reason - ? stringifyUnknown(result.reason) - : "Unknown error", - }); - } - } -} - export async function queryAllWidgets( regionUrl: string, orgSlug: string, @@ -842,18 +822,11 @@ export async function queryAllWidgets( project: options.project ?? dashboard.projects ?? undefined, }; - const results = new Map(); - if (widgets.length === 0) { - return results; - } - - // Process in batches to respect concurrency limit - const batchSize = ORG_FANOUT_CONCURRENCY; - for (let i = 0; i < widgets.length; i += batchSize) { - const batch = widgets.slice(i, i + batchSize); - const batchResults = await Promise.allSettled( - batch.map((widget) => - queryWidgetData({ + const widgetResults = await mapBounded( + widgets, + async (widget): Promise => { + try { + return await queryWidgetData({ regionUrl, orgSlug, widget, @@ -862,13 +835,17 @@ export async function queryAllWidgets( end: options.end, periodSeconds: options.periodSeconds, options: mergedOptions, - }), - ), - ); - collectBatchResults(batchResults, i, results); - } - - return results; + }); + } catch (error) { + return { + type: "error", + message: error ? stringifyUnknown(error) : "Unknown error", + }; + } + }, + ORG_FANOUT_CONCURRENCY, + ); + return new Map(widgetResults.entries()); } /** Material unintentional drops for one dataset of a dashboard's widgets. */ diff --git a/packages/cli/src/lib/api/debug-files.ts b/packages/cli/src/lib/api/debug-files.ts index 923349d322..bcd996e08c 100644 --- a/packages/cli/src/lib/api/debug-files.ts +++ b/packages/cli/src/lib/api/debug-files.ts @@ -19,6 +19,7 @@ */ import { ApiError, ValidationError } from "../errors.js"; +import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; import { resolveOrgRegion } from "../region.js"; import { @@ -37,6 +38,7 @@ import { type UploadEncoding, uploadChunkPayloads, } from "./chunk-upload.js"; +import { ORG_FANOUT_CONCURRENCY } from "./infrastructure.js"; const log = logger.withTag("api.debug-files"); @@ -359,9 +361,14 @@ async function postAssemble( project: string, bodies: readonly Record[], ): Promise { + const responses = await mapBounded( + bodies, + (body) => assembleDebugFiles(org, project, body), + ORG_FANOUT_CONCURRENCY, + ); const merged: DifAssembleResponse = {}; - for (const body of bodies) { - Object.assign(merged, await assembleDebugFiles(org, project, body)); + for (const response of responses) { + Object.assign(merged, response); } return merged; } @@ -584,11 +591,14 @@ export async function uploadDebugFiles( break; } + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done response = await postAssemble(org, project, bodies); evaluation = evaluateAssembly(response, chunked, wait); reportProcessing(); // Re-sends report progress too, so a long retry does not look hung. + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await uploadMissing({ chunked, missingChecksums: evaluation.missingChecksums, diff --git a/packages/cli/src/lib/api/explore.ts b/packages/cli/src/lib/api/explore.ts index b72a38dce1..8cdf87b220 100644 --- a/packages/cli/src/lib/api/explore.ts +++ b/packages/cli/src/lib/api/explore.ts @@ -225,6 +225,7 @@ export async function queryMetricsMeta( let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page += 1) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const result = await fetchEventsPage( regionUrl, orgSlug, diff --git a/packages/cli/src/lib/api/infrastructure.ts b/packages/cli/src/lib/api/infrastructure.ts index 0fd9924744..2878d4f1e5 100644 --- a/packages/cli/src/lib/api/infrastructure.ts +++ b/packages/cli/src/lib/api/infrastructure.ts @@ -856,6 +856,7 @@ export async function autoPaginate( let cursor: string | undefined = initialCursor; for (let page = 0; page < MAX_PAGINATION_PAGES; page += 1) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const result = await fetchPage(cursor); allRows.push(...result.data); diff --git a/packages/cli/src/lib/api/issue-app-links.ts b/packages/cli/src/lib/api/issue-app-links.ts index 8986b147ef..b8b206334c 100644 --- a/packages/cli/src/lib/api/issue-app-links.ts +++ b/packages/cli/src/lib/api/issue-app-links.ts @@ -514,6 +514,7 @@ async function resolveFields( ); } pending.splice(index, 1); + // oxlint-disable-next-line no-await-in-loop -- a field resolves only after the fields it depends on values[field.name] = await resolveFieldValue({ field, targetField, diff --git a/packages/cli/src/lib/api/preprod-artifacts.ts b/packages/cli/src/lib/api/preprod-artifacts.ts index 21e49876ac..7c1d8f9cf9 100644 --- a/packages/cli/src/lib/api/preprod-artifacts.ts +++ b/packages/cli/src/lib/api/preprod-artifacts.ts @@ -305,6 +305,7 @@ export async function uploadBuild( const deadline = Date.now() + ASSEMBLE_MAX_WAIT_MS; while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done const result = await assembleProjectPreprodArtifact({ ...config, path: { organization_id_or_slug: org, project_id_or_slug: project }, @@ -342,6 +343,7 @@ export async function uploadBuild( const missing = new Set(data.missingChunks ?? []); if (missing.size > 0) { + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await uploadMissingChunks({ chunks, missingChecksums: missing, @@ -354,6 +356,7 @@ export async function uploadBuild( // Always pace between assemble POSTs (matches the legacy poll loop and // avoids a busy loop should the server keep reporting the same chunks). + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); } @@ -601,6 +604,7 @@ export async function waitForSnapshotArchive( onBuildStarted?.(); const deadline = Date.now() + SNAPSHOT_ARCHIVE_TIMEOUT_MS; + // oxlint-disable-next-line no-await-in-loop -- polls until the snapshot archive is ready while (!(await getSnapshotArchiveReady(org, snapshotId))) { if (Date.now() >= deadline) { throw new TimeoutError( @@ -609,6 +613,7 @@ export async function waitForSnapshotArchive( }s. The build may still be running; try again shortly.`, ); } + // oxlint-disable-next-line no-await-in-loop -- polls until the snapshot archive is ready await new Promise((r) => setTimeout(r, SNAPSHOT_ARCHIVE_POLL_MS)); } } diff --git a/packages/cli/src/lib/api/proguard.ts b/packages/cli/src/lib/api/proguard.ts index 1beee0dac9..ded82e9e3b 100644 --- a/packages/cli/src/lib/api/proguard.ts +++ b/packages/cli/src/lib/api/proguard.ts @@ -170,8 +170,9 @@ export async function uploadProguardMappings( return; } - // Step 5: Upload missing chunks in parallel across all mappings + // Step 5: Upload missing chunks, one mapping at a time for (const cm of chunkedMappings) { + // oxlint-disable-next-line no-await-in-loop -- each call already uploads its chunks at serverOptions.concurrency; one mapping at a time keeps that cap await uploadMissingBufferChunks({ chunks: cm.chunks, missingChecksums, @@ -205,8 +206,10 @@ async function pollDifAssembly(params: { const deadline = Date.now() + ASSEMBLE_MAX_WAIT_MS; while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done await new Promise((r) => setTimeout(r, ASSEMBLE_POLL_INTERVAL_MS)); + // oxlint-disable-next-line no-await-in-loop -- polls the assemble endpoint until the server reports done const pollResult = await assemble(); const { allDone } = checkAssembleResponse(pollResult, checksums, endpoint); diff --git a/packages/cli/src/lib/api/releases.ts b/packages/cli/src/lib/api/releases.ts index 4b712f9998..bc5bd61b95 100644 --- a/packages/cli/src/lib/api/releases.ts +++ b/packages/cli/src/lib/api/releases.ts @@ -636,6 +636,7 @@ async function findSentryRepository( for (const query of queries) { let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const result = await listRepositoriesPaginated(orgSlug, { cursor, perPage: API_MAX_PER_PAGE, diff --git a/packages/cli/src/lib/api/replays.ts b/packages/cli/src/lib/api/replays.ts index cfd0ae7f5c..4a6b9d0f46 100644 --- a/packages/cli/src/lib/api/replays.ts +++ b/packages/cli/src/lib/api/replays.ts @@ -344,6 +344,7 @@ export async function getReplayRecordingSegments( let cursor: string | undefined; for (let page = 0; page < MAX_PAGINATION_PAGES; page += 1) { + // oxlint-disable-next-line no-await-in-loop -- each page needs the cursor from the page before const { data, nextCursor } = await fetchReplayRecordingSegmentsPage({ orgSlug, projectSlugOrId, diff --git a/packages/cli/src/lib/bash-hook/traceback.ts b/packages/cli/src/lib/bash-hook/traceback.ts index 9ff018d4aa..8b43b4ad0b 100644 --- a/packages/cli/src/lib/bash-hook/traceback.ts +++ b/packages/cli/src/lib/bash-hook/traceback.ts @@ -12,8 +12,10 @@ import { readFile } from "node:fs/promises"; import type { Breadcrumb, Event, StackFrame } from "@sentry/core"; import { uuid4 } from "@sentry/core"; import { ValidationError } from "../errors.js"; +import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; import { omitUndefined } from "../omit-undefined.js"; +import { CONCURRENCY_LIMIT } from "../scan/constants.js"; const log = logger.withTag("bash-hook.traceback"); @@ -120,30 +122,38 @@ export function parseTracebackContent(content: string): TracebackData { * Enrich stack frames with source context from the original files. * * Reads each frame's source file and attaches ±5 lines of context around - * the error line. File contents are cached to avoid redundant reads. + * the error line. Each distinct file is read once. */ async function enrichFramesWithSourceContext( frames: StackFrame[], ): Promise { - const sourceCache = new Map(); + const filenames = new Set( + frames.flatMap((frame) => + frame.filename && frame.lineno ? [frame.filename] : [], + ), + ); + const sources = new Map( + await mapBounded( + filenames, + async (filename) => { + try { + const content = await readFile(filename, "utf-8"); + return [filename, content.split("\n")] as const; + } catch (err) { + log.debug(`Could not read source file ${filename}`, err); + return [filename, null] as const; + } + }, + CONCURRENCY_LIMIT, + ), + ); for (const frame of frames) { if (!(frame.filename && frame.lineno)) { continue; } - let lines = sourceCache.get(frame.filename); - if (lines === undefined) { - try { - const content = await readFile(frame.filename, "utf-8"); - lines = content.split("\n"); - } catch (err) { - log.debug(`Could not read source file ${frame.filename}`, err); - lines = null; - } - sourceCache.set(frame.filename, lines); - } - + const lines = sources.get(frame.filename); if (!lines) { continue; } diff --git a/packages/cli/src/lib/build/asset-catalog-extract.ts b/packages/cli/src/lib/build/asset-catalog-extract.ts index b725227428..ee45ea3e18 100644 --- a/packages/cli/src/lib/build/asset-catalog-extract.ts +++ b/packages/cli/src/lib/build/asset-catalog-extract.ts @@ -32,7 +32,9 @@ import { strictObject, string, } from "valibot"; +import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; +import { CONCURRENCY_LIMIT } from "../scan/constants.js"; import { getSeaRawAsset } from "../sea-assets.js"; const log = logger.withTag("build.asset-catalog"); @@ -166,35 +168,33 @@ async function canonicalizeOutput( const manifest: unknown = JSON.parse(await readFile(manifestPath, "utf8")); const assets = parse(array(AssetCatalogEntrySchema), manifest); const seenIds = new Set(); - const renditions = []; - for (const { imageId, ...asset } of assets) { + for (const { imageId } of assets) { if (imageId && seenIds.has(imageId)) { throw new Error("Asset-catalog manifest contains duplicate image IDs"); } seenIds.add(imageId); - // NSString.pathExtension treats a trailing dot as an empty extension. - const extension = `.${ - posix - .extname(asset.filename ?? "") - .slice(1) - .toLowerCase() || "png" - }`; - const sourcePath = join(outputDirectory, `${imageId}${extension}`); - const hasImage = - imageId !== "" && - IMAGE_EXTENSIONS.has(extension) && - (await regularFile(sourcePath)); - const hash = hasImage ? await imageHash(sourcePath) : ""; - const identity = `${catalogRelativePath}\0${JSON.stringify(asset)}\0${hash}`; - renditions.push({ - imageId, - asset, - extension, - sourcePath, - hasImage, - identity, - }); } + const renditions = await mapBounded( + assets, + async ({ imageId, ...asset }) => { + // NSString.pathExtension treats a trailing dot as an empty extension. + const extension = `.${ + posix + .extname(asset.filename ?? "") + .slice(1) + .toLowerCase() || "png" + }`; + const sourcePath = join(outputDirectory, `${imageId}${extension}`); + const hasImage = + imageId !== "" && + IMAGE_EXTENSIONS.has(extension) && + (await regularFile(sourcePath)); + const hash = hasImage ? await imageHash(sourcePath) : ""; + const identity = `${catalogRelativePath}\0${JSON.stringify(asset)}\0${hash}`; + return { imageId, asset, extension, sourcePath, hasImage, identity }; + }, + CONCURRENCY_LIMIT, + ); renditions.sort((a, b) => a.identity < b.identity ? -1 : a.identity > b.identity ? 1 : 0, ); @@ -203,6 +203,7 @@ async function canonicalizeOutput( const occurrences = new Map(); const canonicalAssets: AssetCatalogEntry[] = []; const files: AssetCatalogExtraction["files"] = []; + const copies: { from: string; to: string }[] = []; for (const rendition of renditions) { const occurrence = occurrences.get(rendition.identity) ?? 0; occurrences.set(rendition.identity, occurrence + 1); @@ -213,10 +214,15 @@ async function canonicalizeOutput( if (rendition.hasImage) { const name = `${imageId}${rendition.extension}`; const sourcePath = join(canonicalDirectory, name); - await copyFile(rendition.sourcePath, sourcePath, COPY_FILE_FLAGS); + copies.push({ from: rendition.sourcePath, to: sourcePath }); files.push({ name, sourcePath }); } } + await mapBounded( + copies, + ({ from, to }) => copyFile(from, to, COPY_FILE_FLAGS), + CONCURRENCY_LIMIT, + ); const sourcePath = join(canonicalDirectory, "Assets.json"); await writeFile(sourcePath, `${JSON.stringify(canonicalAssets)}\n`); files.push({ name: "Assets.json", sourcePath }); diff --git a/packages/cli/src/lib/build/dsyms.ts b/packages/cli/src/lib/build/dsyms.ts index 68aa605aae..6fe2ff1454 100644 --- a/packages/cli/src/lib/build/dsyms.ts +++ b/packages/cli/src/lib/build/dsyms.ts @@ -49,6 +49,7 @@ async function collectBundle( ); } if (dirent.isDirectory()) { + // oxlint-disable-next-line no-await-in-loop -- walks the bundle depth-first so entries keep their order entries.push(...(await collectBundle(sourcePath, relPath))); } else if (dirent.isFile()) { entries.push({ relPath, sourcePath }); @@ -174,6 +175,7 @@ export async function collectDsymEntries( ): Promise { const entries: DsymEntry[] = []; const seenBundles = new Set(); + // oxlint-disable no-await-in-loop -- inputs are staged in argument order, and bundle names must be unique across them for (const input of paths) { // resolve strips trailing separators before lstat and extension detection. // lstat("link.dSYM/") would otherwise follow a directory symlink on POSIX. @@ -219,5 +221,6 @@ export async function collectDsymEntries( entries.push(...files); } } + // oxlint-enable no-await-in-loop return entries; } diff --git a/packages/cli/src/lib/build/index.ts b/packages/cli/src/lib/build/index.ts index 2c8bab5082..d5117ce9b6 100644 --- a/packages/cli/src/lib/build/index.ts +++ b/packages/cli/src/lib/build/index.ts @@ -173,6 +173,7 @@ export async function detectBuildFormatFromFile( const size = (await src.stat()).size; let position = 0; while (position < size) { + // oxlint-disable-next-line no-await-in-loop -- reads the file into one reused buffer, one chunk at a time const read = await src.read(buf, 0, buf.length, position); if (read.bytesRead === 0) { break; @@ -367,8 +368,10 @@ async function collectArchiveEntries(root: string): Promise { // not descended into (matching Rust's WalkDir with follow_links = false). let payload: { sourcePath: string } | { linkTarget: Uint8Array }; if (dirent.isSymbolicLink()) { + // oxlint-disable-next-line no-await-in-loop -- walks the tree depth-first so archive entries keep a stable order payload = { linkTarget: strToU8(await readlink(full)) }; } else if (dirent.isDirectory()) { + // oxlint-disable-next-line no-await-in-loop -- walks the tree depth-first so archive entries keep a stable order await walk(full, relPath); continue; } else if (dirent.isFile()) { @@ -380,6 +383,7 @@ async function collectArchiveEntries(root: string): Promise { // Encode the full Unix mode (type + permission bits) into the upper 16 // bits of the ZIP external attributes so symlinks and exec bits survive. + // oxlint-disable-next-line no-await-in-loop -- walks the tree depth-first so archive entries keep a stable order const { mode } = await lstat(full); const attrs = ((mode & 0xff_ff) << 16) >>> 0; entries.push({ relPath, attrs, ...payload }); @@ -429,8 +433,10 @@ export async function normalizeBuildDirectory( const name = `${dirName}/${entry.relPath}`; const options = { os: ZIP_OS_UNIX, attrs: entry.attrs }; if ("sourcePath" in entry) { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addFile(name, entry.sourcePath, options); } else { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addData(name, entry.linkTarget, options); } } @@ -463,6 +469,7 @@ async function addParsedAssetCatalogs( const files = new Map(); try { for (const catalog of catalogs) { + // oxlint-disable-next-line no-await-in-loop -- each extraction runs the asset-catalog helper; the finally block cleans up only the extractions that finished const extraction = await extractAssetCatalogImages( catalog.relPath, catalog.sourcePath, @@ -498,12 +505,11 @@ async function addParsedAssetCatalogs( for (const [name, sourcePath] of [...files].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0, )) { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addFile(name, sourcePath); } } finally { - for (const extraction of extractions) { - await extraction.cleanup(); - } + await Promise.all(extractions.map((extraction) => extraction.cleanup())); } } @@ -713,7 +719,9 @@ async function stageIpaPayload( const staged: StagedIpaEntry[] = []; for (const { name, entry } of await readIpaPayloadEntries(ipaPath, zip)) { const stagePath = join(stageDir, `e${staged.length}`); + // oxlint-disable-next-line no-await-in-loop -- copies IPA entries in archive order from one open zip await pipeline( + // oxlint-disable-next-line no-await-in-loop -- copies IPA entries in archive order from one open zip await zip.openReadStreamPromise(entry), createWriteStream(stagePath), ); @@ -818,8 +826,10 @@ export async function normalizeIpa( try { for (const item of items) { if (item.stagePath !== undefined) { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addFile(item.name, item.stagePath, item.options); } else if (item.data !== undefined) { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addData(item.name, item.data); } } diff --git a/packages/cli/src/lib/build/zip-writer.ts b/packages/cli/src/lib/build/zip-writer.ts index b9c34687a5..3bfa649f96 100644 --- a/packages/cli/src/lib/build/zip-writer.ts +++ b/packages/cli/src/lib/build/zip-writer.ts @@ -203,6 +203,7 @@ export class DeterministicZipWriter { let size = 0; const buf = Buffer.allocUnsafe(STREAM_CHUNK_SIZE); for (;;) { + // oxlint-disable-next-line no-await-in-loop -- reads the source into one reused buffer, one chunk at a time const { bytesRead } = await src.read(buf, 0, buf.length, null); if (bytesRead === 0) { break; @@ -217,10 +218,12 @@ export class DeterministicZipWriter { // Pass 2: copy the stored bytes. let position = 0; while (position < size) { + // oxlint-disable-next-line no-await-in-loop -- reads the source into one reused buffer, one chunk at a time const { bytesRead } = await src.read(buf, 0, buf.length, position); if (bytesRead === 0) { break; } + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await this.fh.write(buf, 0, bytesRead); position += bytesRead; } @@ -258,7 +261,9 @@ export class DeterministicZipWriter { rec.writeUInt32LE(entry.attrs, 38); // external attributes rec.writeUInt32LE(entry.localHeaderOffset, 42); + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await this.fh.write(rec, 0, rec.length); + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await this.fh.write(entry.nameBytes, 0, entry.nameBytes.length); this.offset += CENTRAL_HEADER_FIXED_SIZE + entry.nameBytes.length; } diff --git a/packages/cli/src/lib/command.ts b/packages/cli/src/lib/command.ts index 63060f0098..af2f98ce4e 100644 --- a/packages/cli/src/lib/command.ts +++ b/packages/cli/src/lib/command.ts @@ -928,6 +928,7 @@ export function buildCommand< let result = await generator.next(); while (!result.done) { handleYieldedValue(stdout, result.value, cleanFlags, renderer); + // oxlint-disable-next-line no-await-in-loop -- drives the generator one step at a time result = await generator.next(); } return result.value as CommandReturn | undefined; diff --git a/packages/cli/src/lib/complete.ts b/packages/cli/src/lib/complete.ts index 0b0e16fc84..a7639d6d26 100644 --- a/packages/cli/src/lib/complete.ts +++ b/packages/cli/src/lib/complete.ts @@ -844,6 +844,7 @@ async function positionalOrg( positionals: readonly string[], ): Promise { for (const word of positionals) { + // oxlint-disable-next-line no-await-in-loop -- checks positionals in order and stops at the first that names an org const scope = await parseTargetScope(word); if (scope?.org) { return scope.org; diff --git a/packages/cli/src/lib/db/dsn-cache.ts b/packages/cli/src/lib/db/dsn-cache.ts index 538169fdda..da5722fd0c 100644 --- a/packages/cli/src/lib/db/dsn-cache.ts +++ b/packages/cli/src/lib/db/dsn-cache.ts @@ -14,6 +14,8 @@ import type { ResolvedProjectInfo, } from "../dsn/types.js"; import { invocationState } from "../env.js"; +import { mapBounded } from "../fan-out.js"; +import { CONCURRENCY_LIMIT } from "../scan/constants.js"; import { getDatabase, maybeCleanupCaches, recordCacheHit } from "./index.js"; import { safeParseJson } from "./json.js"; import { runUpsert, touchCacheEntry } from "./utils.js"; @@ -289,13 +291,13 @@ async function validateSourceMtimes( projectRoot: string, sourceMtimes: Record, ): Promise { - for (const [relativePath, cachedMtime] of Object.entries(sourceMtimes)) { - const fullPath = join(projectRoot, relativePath); - if (!(await validateFileMtime(fullPath, cachedMtime))) { - return false; - } - } - return true; + const matches = await mapBounded( + Object.entries(sourceMtimes), + ([relativePath, cachedMtime]) => + validateFileMtime(join(projectRoot, relativePath), cachedMtime), + CONCURRENCY_LIMIT, + ); + return matches.every(Boolean); } /** @@ -310,13 +312,13 @@ async function validateDirMtimes( projectRoot: string, dirMtimes: Record, ): Promise { - for (const [relativePath, cachedMtime] of Object.entries(dirMtimes)) { - const fullPath = join(projectRoot, relativePath); - if (!(await validateDirMtime(fullPath, cachedMtime))) { - return false; - } - } - return true; + const matches = await mapBounded( + Object.entries(dirMtimes), + ([relativePath, cachedMtime]) => + validateDirMtime(join(projectRoot, relativePath), cachedMtime), + CONCURRENCY_LIMIT, + ); + return matches.every(Boolean); } /** Type guard: value is a plain object with all-numeric values (mtimes record). */ diff --git a/packages/cli/src/lib/detect-agent.ts b/packages/cli/src/lib/detect-agent.ts index 1fa3519a90..81d3207d2b 100644 --- a/packages/cli/src/lib/detect-agent.ts +++ b/packages/cli/src/lib/detect-agent.ts @@ -326,6 +326,7 @@ export async function detectAgentFromProcessTree(): Promise< let pid = process.ppid; for (let depth = 0; depth < MAX_ANCESTOR_DEPTH && pid > 1; depth++) { + // oxlint-disable-next-line no-await-in-loop -- walks up the process tree; each parent comes from the step before const info = await _getProcessInfo(pid); if (!info) { break; diff --git a/packages/cli/src/lib/dev-script.ts b/packages/cli/src/lib/dev-script.ts index edf86e5b1c..ae362c2bc3 100644 --- a/packages/cli/src/lib/dev-script.ts +++ b/packages/cli/src/lib/dev-script.ts @@ -788,6 +788,7 @@ async function tryDockerCompose(cwd: string): Promise { for (const filename of ["docker-compose.yml", "compose.yml"]) { // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. try { + // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match await access(join(cwd, filename)); return { args: ["docker", "compose", "up"], source: filename }; } catch { diff --git a/packages/cli/src/lib/dif/find.ts b/packages/cli/src/lib/dif/find.ts index 7ca4c18786..133b58ac60 100644 --- a/packages/cli/src/lib/dif/find.ts +++ b/packages/cli/src/lib/dif/find.ts @@ -318,6 +318,7 @@ export async function findDebugFiles(opts: FindOptions): Promise { continue; } seen.add(abs); + // oxlint-disable-next-line no-await-in-loop -- walks the paths in order and stops once every requested ID is found for await (const entry of walkPath(path)) { if (state.remaining.size === 0) { break; diff --git a/packages/cli/src/lib/dif/scan.ts b/packages/cli/src/lib/dif/scan.ts index afc91af95e..467ff0771f 100644 --- a/packages/cli/src/lib/dif/scan.ts +++ b/packages/cli/src/lib/dif/scan.ts @@ -309,10 +309,12 @@ export async function scanPaths(paths: string[]): Promise { }; for (const path of paths) { + // oxlint-disable-next-line no-await-in-loop -- walks the paths in argument order so the deduplicated file list keeps it const info = await statExplicitPath(path); if (info.isFile()) { add(path); } else if (info.isDirectory()) { + // oxlint-disable-next-line no-await-in-loop -- walks the paths in argument order so the deduplicated file list keeps it for await (const entry of walkDebugFileDir(path)) { add(entry.absolutePath); } @@ -506,6 +508,7 @@ export async function prepareDifs( // means the path was a `.zip` and is fully handled. `null` means "not a // zip" — fall through to normal file handling. if (scanZips) { + // oxlint-disable-next-line no-await-in-loop -- zip inputs are inflated in memory; one path at a time keeps one archive in memory const zipPrepared = await prepareZipDifs( path, filters, @@ -525,6 +528,7 @@ export async function prepareDifs( } } + // oxlint-disable-next-line no-await-in-loop -- zip inputs are inflated in memory; one path at a time keeps one archive in memory const { difs, oversized } = await prepareFileDif( path, filters, diff --git a/packages/cli/src/lib/docs-context.ts b/packages/cli/src/lib/docs-context.ts index 5ce885daf2..197ea1c7d8 100644 --- a/packages/cli/src/lib/docs-context.ts +++ b/packages/cli/src/lib/docs-context.ts @@ -104,29 +104,40 @@ export async function detectDocsContextFromReader( const languages = new Set(); let sentryConfigured = false; - for (const manifest of DOCS_CONTEXT_MANIFESTS) { - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - try { - const contents = await reader.readManifest(manifest); - if (contents === undefined) { - continue; - } - addLanguageSignal(manifest, languages); - addFrameworkSignals(contents, frameworks); - sentryConfigured ||= containsSentrySdk(contents); - } catch { - // Missing/unreadable metadata is optional and must not block lookup. - } - } + const [manifests, configs] = await Promise.all([ + Promise.all( + DOCS_CONTEXT_MANIFESTS.map(async (manifest) => { + // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. + try { + return { manifest, contents: await reader.readManifest(manifest) }; + } catch { + // Missing/unreadable metadata is optional and must not block lookup. + return { manifest, contents: undefined }; + } + }), + ), + Promise.all( + DOCS_CONTEXT_CONFIGS.map(async (config) => { + // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. + try { + return await reader.hasConfig(config); + } catch { + // Config presence is an optional signal only. + return false; + } + }), + ), + ]); - for (const config of DOCS_CONTEXT_CONFIGS) { - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - try { - sentryConfigured ||= await reader.hasConfig(config); - } catch { - // Config presence is an optional signal only. + for (const { manifest, contents } of manifests) { + if (contents === undefined) { + continue; } + addLanguageSignal(manifest, languages); + addFrameworkSignals(contents, frameworks); + sentryConfigured ||= containsSentrySdk(contents); } + sentryConfigured ||= configs.includes(true); return { frameworks: [...frameworks].sort(), diff --git a/packages/cli/src/lib/dsn/env-file.ts b/packages/cli/src/lib/dsn/env-file.ts index e4409a560e..2f80eb9d32 100644 --- a/packages/cli/src/lib/dsn/env-file.ts +++ b/packages/cli/src/lib/dsn/env-file.ts @@ -199,43 +199,61 @@ export async function detectFromAllEnvFiles( export async function detectFromMonorepoEnvFiles( cwd: string, ): Promise { + const roots = await Promise.all( + MONOREPO_ROOTS.map((monorepoRoot) => + detectFromMonorepoRoot(cwd, monorepoRoot), + ), + ); const dsns: DetectedDsn[] = []; const sourceMtimes: Record = {}; let packagesScanned = 0; + for (const root of roots) { + dsns.push(...root.dsns); + Object.assign(sourceMtimes, root.sourceMtimes); + packagesScanned += root.packagesScanned; + } + return { dsns, sourceMtimes, packagesScanned }; +} - for (const monorepoRoot of MONOREPO_ROOTS) { - const rootDir = join(cwd, monorepoRoot); +/** Detect DSNs from .env files in the packages of one monorepo root. */ +async function detectFromMonorepoRoot( + cwd: string, + monorepoRoot: string, +): Promise> { + const dsns: DetectedDsn[] = []; + const sourceMtimes: Record = {}; + let packagesScanned = 0; + const rootDir = join(cwd, monorepoRoot); - // Bun's opendir() may not throw on a missing directory — the error - // surfaces when iterating. Wrap the full open+iterate in one try/catch. - // No explicit handle.close() needed: for-await-of auto-closes the Dir - // handle when the loop exits (including early return or break). - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - try { - for await (const entry of await opendir(rootDir)) { - // Skip hidden dirs (.git, .cache) and non-directories. Accept - // symlinks too — pnpm/Yarn workspaces can symlink packages, and - // detectDsnInPackage gracefully handles non-directory targets. - if ( - entry.name.startsWith(".") || - !(entry.isDirectory() || entry.isSymbolicLink()) - ) { - continue; - } + // Bun's opendir() may not throw on a missing directory — the error + // surfaces when iterating. Wrap the full open+iterate in one try/catch. + // No explicit handle.close() needed: for-await-of auto-closes the Dir + // handle when the loop exits (including early return or break). + // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. + try { + for await (const entry of await opendir(rootDir)) { + // Skip hidden dirs (.git, .cache) and non-directories. Accept + // symlinks too — pnpm/Yarn workspaces can symlink packages, and + // detectDsnInPackage gracefully handles non-directory targets. + if ( + entry.name.startsWith(".") || + !(entry.isDirectory() || entry.isSymbolicLink()) + ) { + continue; + } - packagesScanned += 1; - const pkgDir = join(rootDir, entry.name); - const packagePath = `${monorepoRoot}/${entry.name}`; + packagesScanned += 1; + const pkgDir = join(rootDir, entry.name); + const packagePath = `${monorepoRoot}/${entry.name}`; - const result = await detectDsnInPackage(pkgDir, packagePath); - if (result.dsn) { - dsns.push(result.dsn); - Object.assign(sourceMtimes, result.sourceMtimes); - } + const result = await detectDsnInPackage(pkgDir, packagePath); + if (result.dsn) { + dsns.push(result.dsn); + Object.assign(sourceMtimes, result.sourceMtimes); } - } catch { - // Directory doesn't exist or scan failed, skip this monorepo root } + } catch { + // Directory doesn't exist or scan failed, skip this monorepo root } return { dsns, sourceMtimes, packagesScanned }; diff --git a/packages/cli/src/lib/dsn/project-root.ts b/packages/cli/src/lib/dsn/project-root.ts index fa7542c70e..0373c065ba 100644 --- a/packages/cli/src/lib/dsn/project-root.ts +++ b/packages/cli/src/lib/dsn/project-root.ts @@ -373,9 +373,11 @@ function checkEnvForDsn(dir: string): Promise { // Guard: skip non-regular files (FIFOs, sockets, etc.) that would block. // 1Password streams secrets via symlinked named pipes; Bun.file().text() // blocks indefinitely on these. + // oxlint-disable-next-line no-await-in-loop -- checks env files in priority order and stops at the first DSN if (!(await isRegularFile(filePath, "checkEnvForDsn.stat"))) { continue; } + // oxlint-disable-next-line no-await-in-loop -- checks env files in priority order and stops at the first DSN const content = await readFile(filePath, "utf-8"); const dsn = extractDsnFromEnvContent(content); if (dsn) { diff --git a/packages/cli/src/lib/dsn/resolver.ts b/packages/cli/src/lib/dsn/resolver.ts index 27a9cc0ca1..1a8b87f393 100644 --- a/packages/cli/src/lib/dsn/resolver.ts +++ b/packages/cli/src/lib/dsn/resolver.ts @@ -9,10 +9,12 @@ import { findProjectByDsn, listOrganizations, listProjects, + ORG_FANOUT_CONCURRENCY, resolveOrgDisplayName, } from "../api-client.js"; import { sentry } from "../app-identity.js"; import { getCachedDsn, updateCachedResolution } from "../db/dsn-cache.js"; +import { mapBounded } from "../fan-out.js"; import { getDsnSourceDescription } from "./detector.js"; import type { DetectedDsn, @@ -157,32 +159,32 @@ type AccessibleProject = { * @returns Array of org/project pairs */ export async function getAccessibleProjects(): Promise { - const results: AccessibleProject[] = []; - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. try { const orgs = await listOrganizations(); - for (const org of orgs) { - // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. - try { - const projects = await listProjects(org.slug); - - for (const project of projects) { - results.push({ + const orgProjects = await mapBounded( + orgs, + async (org): Promise => { + // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. + try { + const projects = await listProjects(org.slug); + return projects.map((project) => ({ org: org.slug, project: project.slug, orgName: org.name, projectName: project.name, - }); + })); + } catch { + // Skip orgs we can't access + return []; } - } catch { - // Skip orgs we can't access - } - } + }, + ORG_FANOUT_CONCURRENCY, + ); + return orgProjects.flat(); } catch { // Not authenticated or API error + return []; } - - return results; } diff --git a/packages/cli/src/lib/dsn/scanner.ts b/packages/cli/src/lib/dsn/scanner.ts index a296a59dd4..adc7c726b5 100644 --- a/packages/cli/src/lib/dsn/scanner.ts +++ b/packages/cli/src/lib/dsn/scanner.ts @@ -67,6 +67,7 @@ export async function scanSpecificFiles( const dsns: DetectedDsn[] = []; const sourceMtimes: Record = {}; + // oxlint-disable no-await-in-loop -- files are checked in priority order, and stopOnFirst returns at the first DSN for (const filename of filenames) { const filepath = join(cwd, filename); @@ -112,6 +113,7 @@ export async function scanSpecificFiles( }); } } + // oxlint-enable no-await-in-loop return { dsns, sourceMtimes }; } diff --git a/packages/cli/src/lib/fs-utils.ts b/packages/cli/src/lib/fs-utils.ts index f58dba46c7..a7a5e49e8e 100644 --- a/packages/cli/src/lib/fs-utils.ts +++ b/packages/cli/src/lib/fs-utils.ts @@ -130,6 +130,7 @@ export async function findFile( ): Promise { for (const extension of extensions) { const candidate = `${basePath}${extension}`; + // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match if (await isRegularFile(candidate, "findFile")) { return candidate; } diff --git a/packages/cli/src/lib/ghcr.ts b/packages/cli/src/lib/ghcr.ts index 356bfb8a40..9f12e207e1 100644 --- a/packages/cli/src/lib/ghcr.ts +++ b/packages/cli/src/lib/ghcr.ts @@ -116,6 +116,7 @@ async function fetchWithRetry( for (let attempt = 0; attempt <= GHCR_MAX_RETRIES; attempt++) { try { + // oxlint-disable-next-line no-await-in-loop -- retries one attempt at a time, with a backoff between attempts const response = await customFetch(url, { ...init, signal: buildSignal(timeout, externalSignal), @@ -606,6 +607,7 @@ export async function listTags( let lastTag: string | undefined; for (;;) { + // oxlint-disable-next-line no-await-in-loop -- each tag page starts after the last tag of the page before const tags = await fetchTagPage(token, lastTag, signal, source); if (tags.length === 0) { break; diff --git a/packages/cli/src/lib/jvm-bundle.ts b/packages/cli/src/lib/jvm-bundle.ts index aa2c2a3e92..0f1653ade9 100644 --- a/packages/cli/src/lib/jvm-bundle.ts +++ b/packages/cli/src/lib/jvm-bundle.ts @@ -11,7 +11,9 @@ import { readdir, readFile, realpath, stat } from "node:fs/promises"; import { extname, join, relative } from "node:path"; +import { mapBounded } from "./fan-out.js"; import { logger } from "./logger.js"; +import { CONCURRENCY_LIMIT } from "./scan/constants.js"; import { ZipWriter } from "./sourcemap/zip.js"; const log = logger.withTag("jvm-bundle"); @@ -329,6 +331,7 @@ async function collectJvmSources( entries.sort((a, b) => a.name.localeCompare(b.name)); for (const entry of entries) { + // oxlint-disable-next-line no-await-in-loop -- walks the tree in sorted order so the bundle is deterministic await processEntry(entry, dir); } } @@ -352,26 +355,29 @@ type ValidatedEntry = { async function readAndValidateFiles( urlToAbsPath: Map, ): Promise { - const validated: ValidatedEntry[] = []; - - for (const [url, absPath] of urlToAbsPath) { - const bundlePath = `files/_/${url.replace(URL_PREFIX_RE, "")}`; - try { - const content = await readFile(absPath); - // Skip non-UTF-8 files (binary files that happen to have JVM extensions) + const entries = await mapBounded( + urlToAbsPath, + async ([url, absPath]): Promise => { + const bundlePath = `files/_/${url.replace(URL_PREFIX_RE, "")}`; try { - new TextDecoder("utf-8", { fatal: true }).decode(content); - } catch { - log.debug(`Skipping non-UTF-8 file: ${absPath}`); - continue; + const content = await readFile(absPath); + // Skip non-UTF-8 files (binary files that happen to have JVM extensions) + try { + new TextDecoder("utf-8", { fatal: true }).decode(content); + } catch { + log.debug(`Skipping non-UTF-8 file: ${absPath}`); + return null; + } + return { url, bundlePath, content }; + } catch (err) { + log.debug(`Failed to read source file: ${absPath}`, err); + return null; } - validated.push({ url, bundlePath, content }); - } catch (err) { - log.debug(`Failed to read source file: ${absPath}`, err); - } - } + }, + CONCURRENCY_LIMIT, + ); - return validated; + return entries.filter((entry) => entry !== null); } /** @@ -392,6 +398,7 @@ async function writeBundle( ); for (const { bundlePath, content } of validatedFiles) { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order await zip.addEntry(bundlePath, content); } diff --git a/packages/cli/src/lib/oauth.ts b/packages/cli/src/lib/oauth.ts index 423287810e..e30d33b968 100644 --- a/packages/cli/src/lib/oauth.ts +++ b/packages/cli/src/lib/oauth.ts @@ -464,8 +464,10 @@ export async function performDeviceFlow( // Step 2: Poll for token while (Date.now() < timeoutAt) { + // oxlint-disable-next-line no-await-in-loop -- polls the device-code endpoint at the interval the server sets await sleep(pollInterval * 1000); + // oxlint-disable-next-line no-await-in-loop -- polls the device-code endpoint at the interval the server sets const result = await attemptPoll(device_code, pollInterval); switch (result.status) { diff --git a/packages/cli/src/lib/polling.ts b/packages/cli/src/lib/polling.ts index 6d66c41ee7..42c0778881 100644 --- a/packages/cli/src/lib/polling.ts +++ b/packages/cli/src/lib/polling.ts @@ -92,6 +92,7 @@ export async function poll(options: PollOptions): Promise { try { while (Date.now() - startTime < timeoutMs) { + // oxlint-disable-next-line no-await-in-loop -- polls until the state is done or the timeout passes const state = await fetchState(); if (state) { @@ -105,6 +106,7 @@ export async function poll(options: PollOptions): Promise { } } + // oxlint-disable-next-line no-await-in-loop -- polls until the state is done or the timeout passes await sleepMs(pollIntervalMs); } diff --git a/packages/cli/src/lib/scan/concurrent.ts b/packages/cli/src/lib/scan/concurrent.ts index e563032679..a1bf533f59 100644 --- a/packages/cli/src/lib/scan/concurrent.ts +++ b/packages/cli/src/lib/scan/concurrent.ts @@ -186,6 +186,7 @@ export async function* mapFilesConcurrentStream( if (producerDone) { break; } + // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await awake; resetAwake(); } diff --git a/packages/cli/src/lib/scan/grep.ts b/packages/cli/src/lib/scan/grep.ts index b26a6e23b9..7fcb37c9d2 100644 --- a/packages/cli/src/lib/scan/grep.ts +++ b/packages/cli/src/lib/scan/grep.ts @@ -508,6 +508,7 @@ async function* grepViaWorkers( notifyPending = false; continue; } + // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await new Promise((resolve) => { if (notifyPending) { notifyPending = false; diff --git a/packages/cli/src/lib/scan/walker.ts b/packages/cli/src/lib/scan/walker.ts index fa48dace5c..1472e58fca 100644 --- a/packages/cli/src/lib/scan/walker.ts +++ b/packages/cli/src/lib/scan/walker.ts @@ -201,6 +201,7 @@ async function processDir( if (isCancelled()) { return; } + // oxlint-disable-next-line no-await-in-loop -- entries are cheap to process and cancellation is checked between them; directories are the unit of concurrency const result = await processEntry(entry, frame, ctx); if (result !== null) { push(result); @@ -297,6 +298,7 @@ async function* walkFilesImpl(opts: WalkOptions): AsyncGenerator { */ async function* walkSerial(ctx: WalkContext): AsyncGenerator { const { cfg, matcher, stack } = ctx; + // oxlint-disable no-await-in-loop -- the serial walker visits one directory and one entry at a time; walkParallel is the concurrent path while (stack.length > 0) { checkAborted(cfg.signal); const frame = stack.pop() as DirFrame; @@ -325,6 +327,7 @@ async function* walkSerial(ctx: WalkContext): AsyncGenerator { } } } + // oxlint-enable no-await-in-loop } /** @@ -459,11 +462,13 @@ async function* walkParallel(ctx: WalkContext): AsyncGenerator { if (activeWorkers === 0) { return; } + // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await workerAwake; continue; } activeWorkers += 1; try { + // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await processDir(frame, ctx, push, () => cancelled); } finally { activeWorkers -= 1; @@ -522,6 +527,7 @@ async function* walkParallel(ctx: WalkContext): AsyncGenerator { if (stack.length === 0 && activeWorkers === 0) { break; } + // oxlint-disable-next-line no-await-in-loop -- the coordinator waits for the next wake-up before it drains the queue again await consumerAwake; resetConsumerAwake(); } diff --git a/packages/cli/src/lib/sentryclirc-import.ts b/packages/cli/src/lib/sentryclirc-import.ts index 793d5d6bc7..e95dea56b3 100644 --- a/packages/cli/src/lib/sentryclirc-import.ts +++ b/packages/cli/src/lib/sentryclirc-import.ts @@ -269,15 +269,13 @@ export async function discoverRcFiles( } // Check global fallback paths (config-dir first, then homedir) - for (const globalPath of globalPathSet) { - if (seen.has(globalPath)) { - continue; - } - seen.add(globalPath); - const file = await readRcFile( - globalPath, - classifyRcFileLocation(globalPath), - ); + const globalFiles = await Promise.all( + // The walk above skips these paths, so none of them is in `seen`. + [...globalPathSet].map((globalPath) => + readRcFile(globalPath, classifyRcFileLocation(globalPath)), + ), + ); + for (const file of globalFiles) { if (file) { files.push(file); } @@ -779,12 +777,12 @@ function clearImportRecord(): void { /** Verify all source files in a record still match their stored hashes */ async function verifyRecordHashes(record: ImportRecord): Promise { - for (const source of record.sources) { - if (!(await verifyFileHash(source.path, source.contentHash))) { - return false; - } - } - return true; + const matches = await Promise.all( + record.sources.map((source) => + verifyFileHash(source.path, source.contentHash), + ), + ); + return matches.every(Boolean); } /** diff --git a/packages/cli/src/lib/sentryclirc.ts b/packages/cli/src/lib/sentryclirc.ts index 8e26ae9a93..fc16aa5740 100644 --- a/packages/cli/src/lib/sentryclirc.ts +++ b/packages/cli/src/lib/sentryclirc.ts @@ -247,6 +247,7 @@ export async function applyGlobalFallbacks( if (isComplete(result)) { break; } + // oxlint-disable-next-line no-await-in-loop -- later global files fill only the keys the earlier ones left unset, and the loop stops once the config is complete await tryApplyFile(result, globalPath, true); } } diff --git a/packages/cli/src/lib/snapshots/archive.ts b/packages/cli/src/lib/snapshots/archive.ts index d1908fcebb..2356ca14e3 100644 --- a/packages/cli/src/lib/snapshots/archive.ts +++ b/packages/cli/src/lib/snapshots/archive.ts @@ -118,6 +118,7 @@ export async function extractZipStream( let current = await iterator.next(); while (!current.done) { const chunk = current.value; + // oxlint-disable-next-line no-await-in-loop -- drives the iterator one step at a time current = await iterator.next(); unzip.push(chunk, current.done === true); pushedAny = true; diff --git a/packages/cli/src/lib/sourcemap/inject.ts b/packages/cli/src/lib/sourcemap/inject.ts index 1491edfd4b..5a12e7a4d0 100644 --- a/packages/cli/src/lib/sourcemap/inject.ts +++ b/packages/cli/src/lib/sourcemap/inject.ts @@ -11,8 +11,10 @@ import ignore from "ignore"; import picomatch from "picomatch"; import { NODE_MODULES_DIRNAME } from "../constants.js"; import { ValidationError } from "../errors.js"; +import { mapBounded } from "../fan-out.js"; import { logger } from "../logger.js"; import { isLikelyBinary } from "../scan/binary.js"; +import { CONCURRENCY_LIMIT } from "../scan/constants.js"; import { walkFiles } from "../scan/index.js"; import { hasDebugIdRegistration, @@ -173,32 +175,39 @@ export async function injectDirectory( options.include, ); + if (options.dryRun) { + return await mapBounded( + filePairs, + async ({ jsPath, map }): Promise => { + // Match the real run's ID precedence and runtime registration check. + const jsBytes = await readFile(jsPath); + const js = jsBytes.toString("utf-8"); + const binary = isLikelyBinary(jsBytes); + const existing = await readPairDebugId(js, map); + // An ID the bundle only registers at runtime is reused; the file still + // changes, since the comment and the map ID are written. + const registered = + existing || binary ? undefined : readRegisteredDebugId(js); + return { + jsPath, + map, + mapPath: map.kind === "external" ? map.mapPath : undefined, + injected: !( + existing && + (binary || hasDebugIdRegistration(js, existing)) + ), + debugId: existing ?? registered ?? "(pending)", + }; + }, + CONCURRENCY_LIMIT, + ); + } + const results: InjectResult[] = []; for (const { jsPath, map } of filePairs) { const mapPath = map.kind === "external" ? map.mapPath : undefined; - if (options.dryRun) { - // Match the real run's ID precedence and runtime registration check. - const jsBytes = await readFile(jsPath); - const js = jsBytes.toString("utf-8"); - const binary = isLikelyBinary(jsBytes); - const existing = await readPairDebugId(js, map); - // An ID the bundle only registers at runtime is reused; the file still - // changes, since the comment and the map ID are written. - const registered = - existing || binary ? undefined : readRegisteredDebugId(js); - results.push({ - jsPath, - map, - mapPath, - injected: !( - existing && - (binary || hasDebugIdRegistration(js, existing)) - ), - debugId: existing ?? registered ?? "(pending)", - }); - continue; - } if (map.kind === "external") { + // oxlint-disable-next-line no-await-in-loop -- two bundles can reference one map file, so writes run one pair at a time const r = await injectDebugId(jsPath, map.mapPath); results.push({ jsPath, @@ -208,6 +217,7 @@ export async function injectDirectory( debugId: r.debugId, }); } else { + // oxlint-disable-next-line no-await-in-loop -- two bundles can reference one map file, so writes run one pair at a time const r = await injectInlineDebugId(jsPath, map.decoded); results.push({ jsPath, @@ -236,24 +246,26 @@ export async function injectDirectory( export async function readExistingDebugIds( pairs: FilePair[], ): Promise { - const results: InjectResult[] = []; - for (const { jsPath, map } of pairs) { - const jsBytes = await readFile(jsPath); - const js = jsBytes.toString("utf-8"); - const existing = await readPairDebugId(js, map); - const registered = - existing || isLikelyBinary(jsBytes) - ? undefined - : readRegisteredDebugId(js); - results.push({ - jsPath, - map, - mapPath: map.kind === "external" ? map.mapPath : undefined, - injected: false, - debugId: existing ?? registered ?? "", - }); - } - return results; + return await mapBounded( + pairs, + async ({ jsPath, map }): Promise => { + const jsBytes = await readFile(jsPath); + const js = jsBytes.toString("utf-8"); + const existing = await readPairDebugId(js, map); + const registered = + existing || isLikelyBinary(jsBytes) + ? undefined + : readRegisteredDebugId(js); + return { + jsPath, + map, + mapPath: map.kind === "external" ? map.mapPath : undefined, + injected: false, + debugId: existing ?? registered ?? "", + }; + }, + CONCURRENCY_LIMIT, + ); } /** @@ -386,6 +398,7 @@ async function readDirectiveTail(filePath: string): Promise { const readSize = Math.min(DIRECTIVE_CHUNK_BYTES, end); const offset = end - readSize; const buf = Buffer.alloc(readSize); + // oxlint-disable-next-line no-await-in-loop -- reads the file backwards into one reused buffer await fh.read(buf, 0, readSize, offset); chunks.unshift(buf); collected += readSize; diff --git a/packages/cli/src/lib/sourcemap/zip.ts b/packages/cli/src/lib/sourcemap/zip.ts index 69ca49f2f7..5291559184 100644 --- a/packages/cli/src/lib/sourcemap/zip.ts +++ b/packages/cli/src/lib/sourcemap/zip.ts @@ -283,10 +283,12 @@ export class ZipWriter { fill(); for (let result = inFlight.shift(); result; result = inFlight.shift()) { + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order while later reads run ahead const settled = await result; if (!settled.ok) { throw settled.error; } + // oxlint-disable-next-line no-await-in-loop -- entries are written to one archive in order while later reads run ahead await this.writeEntry(settled.entry); bytesInFlight -= settled.entry.uncompressedSize; fill(); diff --git a/packages/cli/src/lib/target-scope.ts b/packages/cli/src/lib/target-scope.ts index 99d977d342..cba011bbbb 100644 --- a/packages/cli/src/lib/target-scope.ts +++ b/packages/cli/src/lib/target-scope.ts @@ -242,6 +242,7 @@ async function filterToProject( ...requested, ...url.searchParams.getAll("projectSlug"), ]) { + // oxlint-disable-next-line no-await-in-loop -- stops at the first project outside the scope, before more lookups are sent if (!(await anyScopeProject(context, [project]))) { throw outsideScope(subject, scope); } @@ -299,12 +300,14 @@ async function lookUpFirst( return; } for (const attempt of widerQuery ? [query, widerQuery] : [query]) { + // oxlint-disable-next-line no-await-in-loop -- sends the wider query only when the first one does not list the item const response = await context.send( `${context.api}${path}${attempt ? `?${attempt}` : ""}`, ); if (!response.ok) { return response; } + // oxlint-disable-next-line no-await-in-loop -- sends the wider query only when the first one does not list the item if (listed !== undefined && lists(await readJson(response), listed)) { foundInScope.add(key); } @@ -373,6 +376,7 @@ async function applyRule( throw outsideScope(subject, scope); } for (const target of targets) { + // oxlint-disable-next-line no-await-in-loop -- returns the first failed lookup, before more lookups are sent const failed = await lookUpFirst(context, target); if (failed) { return { input, response: failed, verify: NOTHING_TO_VERIFY }; diff --git a/packages/cli/src/lib/upgrade.ts b/packages/cli/src/lib/upgrade.ts index 9ad637e58f..ecdc178845 100644 --- a/packages/cli/src/lib/upgrade.ts +++ b/packages/cli/src/lib/upgrade.ts @@ -416,6 +416,7 @@ async function detectLegacyInstallationMethod(): Promise { const packageManagers: PackageManager[] = ["npm", "pnpm", "bun", "yarn"]; for (const pm of packageManagers) { + // oxlint-disable-next-line no-await-in-loop -- checks package managers in popularity order and stops at the first match if (await isInstalledWith(pm)) { return pm; } @@ -497,6 +498,7 @@ export async function fetchLatestFromGitHubWithSource( const visitedPages = new Set([firstPage]); const versions: string[] = []; for (;;) { + // oxlint-disable-next-line no-await-in-loop -- each release page comes from the Link header of the page before const data = await parseUpgradeJson( response, signal, @@ -521,6 +523,7 @@ export async function fetchLatestFromGitHubWithSource( ); } visitedPages.add(nextPage); + // oxlint-disable-next-line no-await-in-loop -- each release page comes from the Link header of the page before response = await fetchWithUpgradeError( nextPage, { headers: getGitHubHeaders(), ...(signal && { signal }) }, @@ -1173,6 +1176,7 @@ async function waitForBinaryVisible(path: string): Promise { log.debug( `Downloaded binary not yet visible at ${path}, retrying in ${delay}ms (attempt ${attempt}/${VERIFY_MAX_ATTEMPTS})`, ); + // oxlint-disable-next-line no-await-in-loop -- retries one attempt at a time, with a backoff between attempts await setTimeout(delay); } throw new UpgradeError( diff --git a/packages/cli/src/lib/walk-up.ts b/packages/cli/src/lib/walk-up.ts index 2516ff2d38..6df3a9cc5a 100644 --- a/packages/cli/src/lib/walk-up.ts +++ b/packages/cli/src/lib/walk-up.ts @@ -29,6 +29,7 @@ export async function* walkUpFrom(startDir: string): AsyncGenerator { for (;;) { let real: string; try { + // oxlint-disable-next-line no-await-in-loop -- walks up one parent directory at a time real = await realpath(current); } catch { // Can't resolve (broken symlink, permission denied) — stop walking diff --git a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts index ece063f07a..9e4cb70dc3 100644 --- a/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts +++ b/packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts @@ -520,6 +520,7 @@ async function createOrMergeNextJsFiles( const configVariants = ["server", "edge"] as const; for (const configVariant of configVariants) { + // oxlint-disable-next-line no-await-in-loop -- each config step can prompt the user, so the steps run in turn await traceStep(`create-sentry-${configVariant}-config`, async () => { const jsConfig = `sentry.${configVariant}.config.js`; const tsConfig = `sentry.${configVariant}.config.ts`; diff --git a/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts b/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts index c0d43e6133..c6605284fb 100644 --- a/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts +++ b/packages/cli/src/lib/wizard/nuxt/sdk-setup.ts @@ -214,6 +214,7 @@ export async function createConfigFiles( const configVariants = ["server", "client"] as const; for (const configVariant of configVariants) { + // oxlint-disable-next-line no-await-in-loop -- each config step can prompt the user, so the steps run in turn await traceStep(`create-sentry-${configVariant}-config`, async () => { const jsConfig = `sentry.${configVariant}.config.js`; const tsConfig = `sentry.${configVariant}.config.ts`; diff --git a/packages/cli/src/lib/wizard/react-native/javascript.ts b/packages/cli/src/lib/wizard/react-native/javascript.ts index a4ab339717..6812905a84 100644 --- a/packages/cli/src/lib/wizard/react-native/javascript.ts +++ b/packages/cli/src/lib/wizard/react-native/javascript.ts @@ -261,6 +261,7 @@ export function getMainAppFilePath(): Promise { return traceStep("find-app-js-file", async () => { for (const dir of APP_FILE_DIRS) { for (const name of APP_FILE_NAMES) { + // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match const match = await findFile(path.join(dir, name), APP_FILE_EXTENSIONS); if (match) { return match; diff --git a/packages/cli/src/lib/wizard/remix/codemods/express-server.ts b/packages/cli/src/lib/wizard/remix/codemods/express-server.ts index 97b8227d4e..aa10298287 100644 --- a/packages/cli/src/lib/wizard/remix/codemods/express-server.ts +++ b/packages/cli/src/lib/wizard/remix/codemods/express-server.ts @@ -18,6 +18,7 @@ export async function findCustomExpressServerImplementation() { ]; for (const filePath of possiblePaths) { + // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match const filename = await findFile(filePath); if (!filename) { @@ -30,6 +31,7 @@ export async function findCustomExpressServerImplementation() { continue; } + // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match const fileMod = await loadFile(filename); const createRequestHandlerImport = fileMod.imports.$items.find( (imp) => diff --git a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts index bbff682d1d..a80c7a6aac 100644 --- a/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts +++ b/packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts @@ -77,6 +77,7 @@ export async function configureSentryCLI( let validPath = false; let relativeArtifactPath: string | undefined; do { + // oxlint-disable-next-line no-await-in-loop -- prompts the user until they give a usable path const rawArtifactPath = await abortIfCancelled( clack.text({ message: "Where are your build artifacts located?", @@ -111,6 +112,7 @@ export async function configureSentryCLI( } const runBuildOrEnterPathOrProceed = + // oxlint-disable-next-line no-await-in-loop -- prompts the user until they give a usable path await askToRunBuildOrEnterPathOrProceed({ relativeArtifactPath, }); diff --git a/packages/cli/src/lib/wizard/utils/clack/index.ts b/packages/cli/src/lib/wizard/utils/clack/index.ts index 44ba1f27d1..c371991504 100644 --- a/packages/cli/src/lib/wizard/utils/clack/index.ts +++ b/packages/cli/src/lib/wizard/utils/clack/index.ts @@ -1628,6 +1628,7 @@ export async function featureSelectionPrompt>( const selectedFeatures: Record = {}; for (const feature of features) { + // oxlint-disable-next-line no-await-in-loop -- asks the feature questions one at a time selectedFeatures[feature.id] = await askFlagQuestion( feature.flag, feature, diff --git a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts index b63d30fd31..de7ed67a28 100644 --- a/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts +++ b/packages/cli/src/lib/wizard/utils/clack/mcp-config.ts @@ -554,6 +554,7 @@ export async function offerProjectScopedMcpConfig( Sentry.setTag("mcp-editors-count", editors.length); // Configure each selected editor + // oxlint-disable no-await-in-loop -- configures one editor at a time; each step can prompt or print instructions for (const editor of editors) { // Track which editor is being configured Sentry.setTag("mcp-editor", editor); @@ -655,4 +656,5 @@ export async function offerProjectScopedMcpConfig( } } } + // oxlint-enable no-await-in-loop } diff --git a/packages/cli/src/lib/wrangler.ts b/packages/cli/src/lib/wrangler.ts index 89ef25737e..ccf7ae72be 100644 --- a/packages/cli/src/lib/wrangler.ts +++ b/packages/cli/src/lib/wrangler.ts @@ -391,6 +391,7 @@ async function hasWranglerConfig( for (const filename of WRANGLER_CONFIG_FILES) { // oxlint-disable-next-line sentry-cli/no-silent-catch -- grandfathered silent catch — see #1531; drain by adding log.debug()/log.warn() or re-throwing. try { + // oxlint-disable-next-line no-await-in-loop -- checks candidates in priority order and stops at the first match await access(join(cwd, filename)); return true; } catch { From aa23dd0831a4d004e474910cf4d953eef8ae244e Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:42:42 +0000 Subject: [PATCH 5/9] test(cli): Export ORG_FANOUT_CONCURRENCY from the DSN api-client mocks `getAccessibleProjects` now caps its fan-out with `ORG_FANOUT_CONCURRENCY`, which these mocks replace with `undefined`. --- packages/cli/test/lib/dsn/errors.test.ts | 1 + packages/cli/test/lib/dsn/resolver.test.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/packages/cli/test/lib/dsn/errors.test.ts b/packages/cli/test/lib/dsn/errors.test.ts index cf1bae8277..1ac318f829 100644 --- a/packages/cli/test/lib/dsn/errors.test.ts +++ b/packages/cli/test/lib/dsn/errors.test.ts @@ -26,6 +26,7 @@ vi.mock("../../../src/lib/api-client.js", () => ({ listOrganizations: mockListOrganizations, listProjects: mockListProjects, findProjectByDsn: vi.fn(() => Promise.resolve(null)), + ORG_FANOUT_CONCURRENCY: 5, })); describe("formatConflictError", () => { diff --git a/packages/cli/test/lib/dsn/resolver.test.ts b/packages/cli/test/lib/dsn/resolver.test.ts index 00f49653f3..594061a024 100644 --- a/packages/cli/test/lib/dsn/resolver.test.ts +++ b/packages/cli/test/lib/dsn/resolver.test.ts @@ -35,6 +35,7 @@ vi.mock("../../../src/lib/api-client.js", () => ({ listProjects: mockListProjects, findProjectByDsn: mockFindProjectByDsn, resolveOrgDisplayName: mockResolveOrgDisplayName, + ORG_FANOUT_CONCURRENCY: 5, })); // Now import the resolver after mocking From cda9616c6d9e05cb24a243acf3b233192f6268fe Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:42:43 +0000 Subject: [PATCH 6/9] ref(cli): Fan out independent awaits in loops in build scripts File reads in the doc, env, error-pattern, fragment, patch and stale-reference checks, chunk hashing, bundle and doc page writes, generated schema modules and command module imports run concurrently, keeping output order. Benchmarks, evals, ordered generation steps and shared-file rewrites stay sequential with a reason. --- packages/cli/script/bench-sweep.ts | 2 + packages/cli/script/bench.ts | 3 + packages/cli/script/build.ts | 1 + packages/cli/script/check-doc-examples.ts | 16 ++++-- packages/cli/script/check-env-coverage.ts | 30 ++++++---- packages/cli/script/check-error-patterns.ts | 11 +++- packages/cli/script/check-fragments.ts | 57 +++++++++++++------ packages/cli/script/check-patches.ts | 36 ++++++++---- packages/cli/script/check-stale-references.ts | 20 +++++-- packages/cli/script/eval-skill.ts | 3 + packages/cli/script/generate-command-api.ts | 9 ++- packages/cli/script/generate-command-docs.ts | 25 ++++---- packages/cli/script/generate-docs-sections.ts | 2 + .../cli/script/generate-output-schemas.ts | 36 ++++++------ packages/cli/script/generate-skill.ts | 14 +++-- packages/cli/script/generate.ts | 1 + packages/cli/script/lib/chunk-build.ts | 5 +- packages/cli/script/lib/split-bundle.ts | 41 ++++++------- packages/cli/script/preview-selectors.ts | 1 + 19 files changed, 209 insertions(+), 104 deletions(-) diff --git a/packages/cli/script/bench-sweep.ts b/packages/cli/script/bench-sweep.ts index 06190f1ced..5372cff827 100644 --- a/packages/cli/script/bench-sweep.ts +++ b/packages/cli/script/bench-sweep.ts @@ -245,6 +245,7 @@ async function runSweep(args: SweepArgs): Promise { if (!args.json) { logger.log(`\n${fx.label} (${fx.rootDir})`); } + // oxlint-disable-next-line no-await-in-loop -- benchmarks run one fixture at a time so runs do not skew each other's timings await withBenchDb(async () => { await sweepFixture(fx, ops, args, results); }); @@ -263,6 +264,7 @@ async function sweepFixture( for (const op of ops) { for (const concurrency of args.values) { const setup = op.setup; + // oxlint-disable-next-line no-await-in-loop -- benchmarks run one sample at a time so runs do not skew each other's timings const samples = await measure(() => op.run(fx.rootDir, concurrency), { runs: args.runs, warmup: args.warmup, diff --git a/packages/cli/script/bench.ts b/packages/cli/script/bench.ts index 2492bed6ac..63058667c9 100644 --- a/packages/cli/script/bench.ts +++ b/packages/cli/script/bench.ts @@ -303,6 +303,7 @@ async function roughFileCount(root: string): Promise { for (const entry of entries) { if (entry.isDirectory()) { if (!skip.has(entry.name)) { + // oxlint-disable-next-line no-await-in-loop -- walks a large fixture tree one directory at a time to keep open handles bounded await walk(join(dir, entry.name)); } } else if (entry.isFile()) { @@ -541,9 +542,11 @@ async function runAll( if (!args.json) { logger.log(`${fx.label} (${fx.fileCount} files @ ${fx.rootDir})`); } + // oxlint-disable-next-line no-await-in-loop -- benchmarks run one fixture at a time so runs do not skew each other's timings await withBenchDb(async () => { for (const op of ops) { const setup = op.setup; + // oxlint-disable-next-line no-await-in-loop -- benchmarks run one operation at a time so runs do not skew each other's timings const samples = await measure( async () => { await op.run(fx.rootDir); diff --git a/packages/cli/script/build.ts b/packages/cli/script/build.ts index e487891947..b68cf2a374 100644 --- a/packages/cli/script/build.ts +++ b/packages/cli/script/build.ts @@ -422,6 +422,7 @@ async function compileAllTargets( let failures = 0; for (const target of targets) { try { + // oxlint-disable-next-line no-await-in-loop -- each target compresses a full binary; one at a time keeps memory bounded await postProcessTarget(target); successes += 1; } catch (error) { diff --git a/packages/cli/script/check-doc-examples.ts b/packages/cli/script/check-doc-examples.ts index bf5149283c..d407c0d9e8 100644 --- a/packages/cli/script/check-doc-examples.ts +++ b/packages/cli/script/check-doc-examples.ts @@ -54,6 +54,8 @@ import { } from "./sdk-run-calls.js"; import { shellCommands } from "./shell-words.js"; import { logger } from "../src/lib/logger.js"; +import { mapBounded } from "../src/lib/fan-out.js"; +import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; await writeRouteTreeStubs(); @@ -399,8 +401,11 @@ for (const { source, invocation } of commandExamples( findings.push({ file: source, example: invocation, problem }); } } -for (const file of [...files, ...SDK_EXAMPLE_FILES]) { - const content = await readFile(file, "utf-8"); +for (const { file, content } of await mapBounded( + [...files, ...SDK_EXAMPLE_FILES], + async (file) => ({ file, content: await readFile(file, "utf-8") }), + CONCURRENCY_LIMIT, +)) { const invocations = file.endsWith(".ts") ? [] : extractInvocations(content); for (const invocation of invocations) { checked += 1; @@ -418,8 +423,11 @@ for (const file of [...files, ...SDK_EXAMPLE_FILES]) { } const sourceFiles = listSource(SOURCE_DIR); -for (const file of sourceFiles) { - const content = await readFile(file, "utf-8"); +for (const { file, content } of await mapBounded( + sourceFiles, + async (file) => ({ file, content: await readFile(file, "utf-8") }), + CONCURRENCY_LIMIT, +)) { if (!content.includes("sentry`")) { continue; } diff --git a/packages/cli/script/check-env-coverage.ts b/packages/cli/script/check-env-coverage.ts index 890b9e2eb3..2e13d382ae 100644 --- a/packages/cli/script/check-env-coverage.ts +++ b/packages/cli/script/check-env-coverage.ts @@ -33,6 +33,8 @@ import { readFile } from "node:fs/promises"; import { join } from "node:path"; import { ENV_VAR_REGISTRY } from "../src/lib/env-registry.js"; import { logger } from "../src/lib/logger.js"; +import { mapBounded } from "../src/lib/fan-out.js"; +import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; /** * Well-known env vars that don't start with `SENTRY_` but are still part of the @@ -134,8 +136,11 @@ const files = globSync("src/**/*.ts", { // bracket reads indexed by a constant can be mapped back to a literal name. const constMap = new Map(); const fileContents = new Map(); -for (const file of files) { - const content = await readFile(file, "utf-8"); +for (const { file, content } of await mapBounded( + files, + async (file) => ({ file, content: await readFile(file, "utf-8") }), + CONCURRENCY_LIMIT, +)) { fileContents.set(file, content); for (const match of content.matchAll(ENV_CONST_RE)) { const [, name] = match; @@ -192,8 +197,11 @@ const INSTALLERS: readonly { file: string; read: RegExp; assign?: RegExp }[] = [ /** name -> first "file:line" where an installer reads it. */ const installerReads = new Map(); -for (const { file, read, assign } of INSTALLERS) { - const content = await readFile(file, "utf-8"); +const installerContents = await Promise.all( + INSTALLERS.map(({ file }) => readFile(file, "utf-8")), +); +for (const [index, { file, read, assign }] of INSTALLERS.entries()) { + const content = installerContents[index] ?? ""; const assigned = new Set( assign ? [...content.matchAll(assign)].map((m) => m[1]) : [], ); @@ -252,12 +260,14 @@ for (const name of INTERNAL_ENV_VARS.keys()) { // Every file type under src/, generated files included, not just the env // reads above: a retired name in a string or a comment fails too. -for (const entry of globSync("src/**/*", { withFileTypes: true })) { - if (!entry.isFile()) { - continue; - } - const file = join(entry.parentPath, entry.name); - const content = await readFile(file, "utf-8"); +const srcFiles = globSync("src/**/*", { withFileTypes: true }) + .filter((entry) => entry.isFile()) + .map((entry) => join(entry.parentPath, entry.name)); +for (const { file, content } of await mapBounded( + srcFiles, + async (file) => ({ file, content: await readFile(file, "utf-8") }), + CONCURRENCY_LIMIT, +)) { for (const [prefix, reason] of RETIRED_ENV_PREFIXES) { const index = content.indexOf(prefix); if (index !== -1) { diff --git a/packages/cli/script/check-error-patterns.ts b/packages/cli/script/check-error-patterns.ts index 9360893887..f939bc854a 100644 --- a/packages/cli/script/check-error-patterns.ts +++ b/packages/cli/script/check-error-patterns.ts @@ -26,6 +26,8 @@ import { globSync } from "node:fs"; import { readFile } from "node:fs/promises"; import { logger } from "../src/lib/logger.js"; +import { mapBounded } from "../src/lib/fan-out.js"; +import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; export type Violation = { file: string; line: number; message: string }; @@ -271,8 +273,13 @@ export function findAdHocTryPatterns( /** Scan the given files and collect violations. */ export async function scanFiles(files: string[]): Promise { const violations: Violation[] = []; - for (const filePath of files) { - const content = await readFile(filePath, "utf-8"); + const contents = await mapBounded( + files, + (filePath) => readFile(filePath, "utf-8"), + CONCURRENCY_LIMIT, + ); + for (const [index, filePath] of files.entries()) { + const content = contents[index] ?? ""; violations.push(...findContextErrorNewlines(content, filePath)); violations.push(...findAdHocTryPatterns(content, filePath)); } diff --git a/packages/cli/script/check-fragments.ts b/packages/cli/script/check-fragments.ts index e21c244702..b34283122b 100644 --- a/packages/cli/script/check-fragments.ts +++ b/packages/cli/script/check-fragments.ts @@ -27,6 +27,8 @@ import { writeRouteTreeStubs } from "./lib/route-tree-stubs.js"; import { markdownHeadings } from "./markdown.js"; import { DOCS_FRAGMENTS } from "./paths.js"; import { logger } from "../src/lib/logger.js"; +import { mapBounded } from "../src/lib/fan-out.js"; +import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; await writeRouteTreeStubs(); @@ -90,9 +92,14 @@ for (const name of actualFragments) { const EXAMPLES_HEADING_RE = /^examples?\b/i; // Check 3: Fragment content validation -for (const file of fragmentFiles) { - const content = await readFile(`${FRAGMENTS_DIR}/${file}`, "utf-8"); - +for (const { file, content } of await mapBounded( + fragmentFiles, + async (file) => ({ + file, + content: await readFile(`${FRAGMENTS_DIR}/${file}`, "utf-8"), + }), + CONCURRENCY_LIMIT, +)) { if (content.includes("---\ntitle:") || content.startsWith("---\n")) { errors.push( `Fragment contains frontmatter: ${FRAGMENTS_DIR}/${file} (fragments should only contain custom content, not YAML frontmatter)`, @@ -129,13 +136,17 @@ const TOP_LEVEL_FRAGMENTS_DIR = DOCS_FRAGMENTS; /** Top-level fragment files that must exist (for generated doc pages) */ const REQUIRED_TOP_LEVEL_FRAGMENTS = ["configuration"]; -for (const name of REQUIRED_TOP_LEVEL_FRAGMENTS) { +const requiredFragmentsExist = await Promise.all( + REQUIRED_TOP_LEVEL_FRAGMENTS.map((name) => + access(`${TOP_LEVEL_FRAGMENTS_DIR}/${name}.md`).then( + () => true, + () => false, + ), + ), +); +for (const [index, name] of REQUIRED_TOP_LEVEL_FRAGMENTS.entries()) { const path = `${TOP_LEVEL_FRAGMENTS_DIR}/${name}.md`; - const exists = await access(path).then( - () => true, - () => false, - ); - if (!exists) { + if (!requiredFragmentsExist[index]) { errors.push( `Missing top-level fragment: ${path} (required for generated ${name}.md page)`, ); @@ -253,13 +264,27 @@ function getDefaultCommandName(routeName: string): string | undefined { const multiCommandRoutes = getMultiCommandRoutes(); -for (const [routeName, route] of multiCommandRoutes) { - const fragmentPath = `${FRAGMENTS_DIR}/${routeName}.md`; - let content: string; - try { - content = await readFile(fragmentPath, "utf-8"); - } catch { - // Fragment doesn't exist — already caught by Check 1 +const multiCommandFragments = await mapBounded( + multiCommandRoutes, + async ([routeName, route]) => ({ + routeName, + route, + fragmentPath: `${FRAGMENTS_DIR}/${routeName}.md`, + // A missing fragment is already caught by Check 1. + content: await readFile(`${FRAGMENTS_DIR}/${routeName}.md`, "utf-8").catch( + () => undefined, + ), + }), + CONCURRENCY_LIMIT, +); + +for (const { + routeName, + route, + fragmentPath, + content, +} of multiCommandFragments) { + if (content === undefined) { continue; } diff --git a/packages/cli/script/check-patches.ts b/packages/cli/script/check-patches.ts index 36d678d70c..52d15a3a86 100644 --- a/packages/cli/script/check-patches.ts +++ b/packages/cli/script/check-patches.ts @@ -187,7 +187,22 @@ function parsePatchKey(key: string): { name: string; version?: string } { return { name: key }; } -for (const [key, patchPath] of Object.entries(patches)) { +/** Read an installed package file, or `undefined` when it can't be resolved or read. */ +function readInstalledFile(file: string): Promise { + const path = resolvePackageFile(file); + return path + ? readFile(path, "utf-8").catch(() => undefined) + : Promise.resolve(undefined); +} + +const patchEntries = Object.entries(patches); +const installedPackageJsons = await Promise.all( + patchEntries.map(([key]) => + readInstalledFile(`${parsePatchKey(key).name}/package.json`), + ), +); + +for (const [index, [key, patchPath]] of patchEntries.entries()) { const { name } = parsePatchKey(key); // Extract version from patch path: "patches/@stricli%2Fcore@1.2.5.patch" → "1.2.5" // Handles pre-release versions like "1.2.3-beta.1" by matching everything after @M.N.P until .patch @@ -201,14 +216,12 @@ for (const [key, patchPath] of Object.entries(patches)) { const patchVersion = versionMatch[1]; // Resolve installed version - const pkgJsonPath = resolvePackageFile(`${name}/package.json`); + const pkgJson = installedPackageJsons[index]; try { - if (!pkgJsonPath) { + if (pkgJson === undefined) { throw new Error("unresolved"); } - const installed: { version: string } = JSON.parse( - await readFile(pkgJsonPath, "utf-8"), - ); + const installed: { version: string } = JSON.parse(pkgJson); if (installed.version !== patchVersion) { warnings.push( ` ${name}: patch targets ${patchVersion}, installed ${installed.version} — regenerate with: pnpm patch ${name}`, @@ -337,13 +350,16 @@ const CONTENT_ASSERTIONS: ReadonlyArray<{ }, ]; -for (const assertion of CONTENT_ASSERTIONS) { - const assertionPath = resolvePackageFile(assertion.file); +const assertionContents = await Promise.all( + CONTENT_ASSERTIONS.map((assertion) => readInstalledFile(assertion.file)), +); + +for (const [index, assertion] of CONTENT_ASSERTIONS.entries()) { + const contents = assertionContents[index]; try { - if (!assertionPath) { + if (contents === undefined) { throw new Error("unresolved"); } - const contents = await readFile(assertionPath, "utf-8"); if (assertion.staleMarker && contents.includes(assertion.staleMarker)) { errors.push( ` ${assertion.description} — patch not applied to ${assertion.file} (regenerate the patch for the current dependency version)`, diff --git a/packages/cli/script/check-stale-references.ts b/packages/cli/script/check-stale-references.ts index ae83400232..f9e05cf111 100644 --- a/packages/cli/script/check-stale-references.ts +++ b/packages/cli/script/check-stale-references.ts @@ -24,6 +24,8 @@ import { readFile } from "node:fs/promises"; import { blankCodeBlocks } from "./markdown.js"; import { DOCS_CONTENT } from "./paths.js"; import { logger } from "../src/lib/logger.js"; +import { mapBounded } from "../src/lib/fan-out.js"; +import { CONCURRENCY_LIMIT } from "../src/lib/scan/constants.js"; const pkg = JSON.parse(await readFile("package.json", "utf-8")); const currentPM: string = (pkg.packageManager ?? "").split("@")[0]; @@ -112,12 +114,18 @@ type Finding = { const findings: Finding[] = []; -for (const filePath of FILES_TO_SCAN) { - let content: string; - try { - content = await readFile(filePath, "utf-8"); - } catch { - // File doesn't exist — skip silently (e.g., optional doc files) +const scanned = await mapBounded( + FILES_TO_SCAN, + async (filePath) => ({ + filePath, + // A file that doesn't exist is skipped silently (e.g., optional doc files). + content: await readFile(filePath, "utf-8").catch(() => undefined), + }), + CONCURRENCY_LIMIT, +); + +for (const { filePath, content } of scanned) { + if (content === undefined) { continue; } diff --git a/packages/cli/script/eval-skill.ts b/packages/cli/script/eval-skill.ts index 0e9b8ef786..a44a47ba26 100644 --- a/packages/cli/script/eval-skill.ts +++ b/packages/cli/script/eval-skill.ts @@ -67,12 +67,14 @@ async function evalModel( for (const testCase of testCases) { logger.start(`${testCase.id}...`); + // oxlint-disable-next-line no-await-in-loop -- eval cases run one at a time to stay inside the model provider's rate limits const plan = await generatePlan( client, model, skillContent, testCase.prompt, ); + // oxlint-disable-next-line no-await-in-loop -- the judge needs the plan from the step before const result = await judgePlan(client, testCase, plan); results.push(result); @@ -130,6 +132,7 @@ async function main(): Promise { const models: ModelResult[] = []; for (const model of client.agentModels) { + // oxlint-disable-next-line no-await-in-loop -- models run one at a time to stay inside the model provider's rate limits const result = await evalModel(client, model, skillContent, testCases); models.push(result); } diff --git a/packages/cli/script/generate-command-api.ts b/packages/cli/script/generate-command-api.ts index 05fe23fea0..e6d96f0cc8 100644 --- a/packages/cli/script/generate-command-api.ts +++ b/packages/cli/script/generate-command-api.ts @@ -28,8 +28,13 @@ export async function emit(): Promise { { commands: Set; reason: string } >(); - for (const { file, name } of analysis.commands) { - const module = await import(pathToFileURL(resolve(file)).href); + const modules = await Promise.all( + analysis.commands.map( + ({ file }) => import(pathToFileURL(resolve(file)).href), + ), + ); + for (const [index, { file, name }] of analysis.commands.entries()) { + const module = modules[index]; const target = module[name] as RouteTarget | undefined; const path = target && paths.get(target); if (!target || !path || !isCommand(target)) continue; diff --git a/packages/cli/script/generate-command-docs.ts b/packages/cli/script/generate-command-docs.ts index a9c92d9bb8..0d9df7df4a 100644 --- a/packages/cli/script/generate-command-docs.ts +++ b/packages/cli/script/generate-command-docs.ts @@ -389,17 +389,20 @@ export async function emit(): Promise { } // Generate command doc pages - for (const route of routeInfos) { - const filePath = `${DOCS_DIR}/${route.name}.md`; - const pageContent = generatePage(route); - const customContent = await readCustomContent(route.name); - const fullContent = customContent - ? pageContent + customContent - : `${pageContent}\n`; - - await writeFile(filePath, fullContent); - generatedFiles.push(filePath); - } + const pagePaths = await Promise.all( + routeInfos.map(async (route) => { + const filePath = `${DOCS_DIR}/${route.name}.md`; + const pageContent = generatePage(route); + const customContent = await readCustomContent(route.name); + const fullContent = customContent + ? pageContent + customContent + : `${pageContent}\n`; + + await writeFile(filePath, fullContent); + return filePath; + }), + ); + generatedFiles.push(...pagePaths); // Update commands/index.md const indexCustomContent = await readCustomContent("index"); diff --git a/packages/cli/script/generate-docs-sections.ts b/packages/cli/script/generate-docs-sections.ts index 15d9446379..1e4b488ac9 100644 --- a/packages/cli/script/generate-docs-sections.ts +++ b/packages/cli/script/generate-docs-sections.ts @@ -1144,6 +1144,7 @@ export async function emit({ check }: { check: boolean }): Promise { let staleCount = 0; for (const section of sections) { + // oxlint-disable-next-line no-await-in-loop -- several sections live in one file, so each read-modify-write must finish before the next const original = await readFile(section.filePath, "utf-8"); const generated = section.generate(); const updated = replaceMarkerSection( @@ -1158,6 +1159,7 @@ export async function emit({ check }: { check: boolean }): Promise { logger.error(`STALE: ${section.filePath} [${section.sectionName}]`); staleCount += 1; } else { + // oxlint-disable-next-line no-await-in-loop -- several sections live in one file, so each read-modify-write must finish before the next await writeFile(section.filePath, updated); logger.info(`Updated: ${section.filePath} [${section.sectionName}]`); } diff --git a/packages/cli/script/generate-output-schemas.ts b/packages/cli/script/generate-output-schemas.ts index a5d9ed1d5a..8b5f2b5e30 100644 --- a/packages/cli/script/generate-output-schemas.ts +++ b/packages/cli/script/generate-output-schemas.ts @@ -84,22 +84,26 @@ export async function emit(): Promise { await rm(OUTPUT_DIR, { recursive: true, force: true }); await mkdir(OUTPUT_DIR, { recursive: true }); - let count = 0; - for (const file of files) { - const name = basename(file, ".ts"); - const exports: Record = await import( - pathToFileURL(resolve(SOURCE_DIR, file)).href - ); - const schemas = Object.entries(exports).filter( - (entry): entry is [string, GenericSchema] => - entry[0].endsWith("Schema") && isSchema(entry[1]), - ); - if (schemas.length === 0) { - continue; - } - count += schemas.length; - await writeFile(`${OUTPUT_DIR}/${name}.ts`, renderModule(name, schemas)); - } + const counts = await Promise.all( + files.map(async (file) => { + const name = basename(file, ".ts"); + const exports: Record = await import( + pathToFileURL(resolve(SOURCE_DIR, file)).href + ); + const schemas = Object.entries(exports).filter( + (entry): entry is [string, GenericSchema] => + entry[0].endsWith("Schema") && isSchema(entry[1]), + ); + if (schemas.length > 0) { + await writeFile( + `${OUTPUT_DIR}/${name}.ts`, + renderModule(name, schemas), + ); + } + return schemas.length; + }), + ); + const count = counts.reduce((sum, n) => sum + n, 0); logger.success(`Generated ${OUTPUT_DIR}/ (${count} output schemas)`); } diff --git a/packages/cli/script/generate-skill.ts b/packages/cli/script/generate-skill.ts index f0e50445df..d47d352e4b 100644 --- a/packages/cli/script/generate-skill.ts +++ b/packages/cli/script/generate-skill.ts @@ -687,12 +687,14 @@ export async function emit(): Promise { // The public references are a symlink to these generated plugin references. rmSync(`${SKILL_DIR}/references`, { recursive: true, force: true }); - for (const [relativePath, content] of files) { - const fullPath = `${SKILL_DIR}/${relativePath}`; - const dir = fullPath.substring(0, fullPath.lastIndexOf("/")); - mkdirSync(dir, { recursive: true }); - await writeFile(fullPath, content); - } + await Promise.all( + [...files].map(([relativePath, content]) => { + const fullPath = `${SKILL_DIR}/${relativePath}`; + const dir = fullPath.substring(0, fullPath.lastIndexOf("/")); + mkdirSync(dir, { recursive: true }); + return writeFile(fullPath, content); + }), + ); const publicSkill = files.get("SKILL.md"); if (publicSkill === undefined) { diff --git a/packages/cli/script/generate.ts b/packages/cli/script/generate.ts index 74723249f8..ffad84fe02 100644 --- a/packages/cli/script/generate.ts +++ b/packages/cli/script/generate.ts @@ -258,6 +258,7 @@ if (treeSteps.length > 0) { await writeRouteTreeStubs(); await import("../src/app.js"); for (const step of treeSteps) { + // oxlint-disable-next-line no-await-in-loop -- steps emit in order because later steps read files that earlier ones write await (await step.load()).emit(options); if (process.exitCode) { break; diff --git a/packages/cli/script/lib/chunk-build.ts b/packages/cli/script/lib/chunk-build.ts index a3274f9c19..d8e1243353 100644 --- a/packages/cli/script/lib/chunk-build.ts +++ b/packages/cli/script/lib/chunk-build.ts @@ -105,12 +105,13 @@ export async function chunkBuild( entries: MainChunkBuild["entries"], ): Promise { const sorted = [...files].sort(); + const contents = await Promise.all(sorted.map((file) => readFile(file))); const hash = createHash("sha256"); - for (const file of sorted) { + for (const [index, file] of sorted.entries()) { hash .update(basename(file)) .update("\0") - .update(await readFile(file)); + .update(contents[index] ?? ""); } return { id: hash.digest("hex").slice(0, 16), diff --git a/packages/cli/script/lib/split-bundle.ts b/packages/cli/script/lib/split-bundle.ts index 5e40db6c43..f27284ecaa 100644 --- a/packages/cli/script/lib/split-bundle.ts +++ b/packages/cli/script/lib/split-bundle.ts @@ -187,6 +187,7 @@ async function buildEsmChunks(options: SplitBundleOptions): Promise<{ `${LAZY_ENTRY_PREFIX}${path}`, ]), ); + // oxlint-disable-next-line no-await-in-loop -- each build pass adds the lazy entries the previous pass discovered const result = await build({ ...options.options, entryPoints: { ...options.entryPoints, ...lazyPoints }, @@ -268,20 +269,21 @@ async function writeEsmChunks( ]), ); await mkdir(scratch, { recursive: true }); - const files: string[] = []; - for (const file of result.outputFiles) { - const target = join(scratch, relative(outdir, file.path)); - if (file.path.endsWith(".map")) { - await writeFile(target, file.contents); - continue; - } - await writeFile( - target, - lowerChunkImports(file.path, file.text, outputs.get(file.path)), - ); - files.push(target); - } - return files; + const targets = await Promise.all( + result.outputFiles.map(async (file) => { + const target = join(scratch, relative(outdir, file.path)); + if (file.path.endsWith(".map")) { + await writeFile(target, file.contents); + return undefined; + } + await writeFile( + target, + lowerChunkImports(file.path, file.text, outputs.get(file.path)), + ); + return target; + }), + ); + return targets.filter((target) => target !== undefined); } /** Pass 2 of a CommonJS build: convert the ESM chunks in `files` to CommonJS. */ @@ -328,11 +330,12 @@ function jsOutputs(metafile: Metafile): string[] { * their content, so a build does not overwrite the chunks of the last one. */ export async function removeBundleOutputs(dir: string): Promise { - for (const entry of await readdir(dir).catch(() => [])) { - if (BUNDLE_OUTPUT_RE.test(entry)) { - await rm(join(dir, entry), { force: true }); - } - } + const entries = await readdir(dir).catch(() => []); + await Promise.all( + entries + .filter((entry) => BUNDLE_OUTPUT_RE.test(entry)) + .map((entry) => rm(join(dir, entry), { force: true })), + ); } /** Build `options.entryPoints` into split chunks, see the module comment. */ diff --git a/packages/cli/script/preview-selectors.ts b/packages/cli/script/preview-selectors.ts index 0d88a77950..8d91b1c1f1 100644 --- a/packages/cli/script/preview-selectors.ts +++ b/packages/cli/script/preview-selectors.ts @@ -32,6 +32,7 @@ async function preview(): Promise { } const chosen: string[] = []; for (const prompt of [organization, project]) { + // oxlint-disable-next-line no-await-in-loop -- interactive prompts run one after another const value = await selectWithFilter(prompt); if (value === null) { return; From bed6897e81cc4dae5f87a03de9ac9ed9fd96fc85 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:42:44 +0000 Subject: [PATCH 7/9] ref(mcp): Mark sequential awaits in loops in mcp-core Skill scope validation and UI resource reads in scripts run concurrently. Pagination, polling, retries, redirect hops, dependent link fields and project scope checks stay sequential with a reason. Detector lookups for an alert rule stay one at a time, since mcp-core has no fan-out cap. --- .../scripts/generate-otel-namespaces.ts | 1 + .../scripts/generate-platform-setup.ts | 1 + packages/mcp-core/scripts/measure-ui-views.ts | 20 +++++++++++++------ .../scripts/validate-skills-mapping.ts | 17 ++++++---------- packages/mcp-core/src/api-client/client.ts | 2 ++ packages/mcp-core/src/internal/fetch-utils.ts | 2 ++ .../tools/catalog/analyze-issue-with-seer.ts | 2 ++ .../mcp-core/src/tools/catalog/get-doc.ts | 1 + .../tools/support/alert-rule-connections.ts | 3 +++ .../src/tools/support/alert-rule-details.ts | 1 + .../src/tools/support/issue-linking/app.ts | 1 + .../src/tools/support/search-events/seer.ts | 2 ++ 12 files changed, 36 insertions(+), 17 deletions(-) diff --git a/packages/mcp-core/scripts/generate-otel-namespaces.ts b/packages/mcp-core/scripts/generate-otel-namespaces.ts index 541ebcffbd..b976c016f2 100644 --- a/packages/mcp-core/scripts/generate-otel-namespaces.ts +++ b/packages/mcp-core/scripts/generate-otel-namespaces.ts @@ -343,6 +343,7 @@ async function generateNamespaceFiles() { } } + // oxlint-disable-next-line no-await-in-loop -- fetches one namespace at a time to stay under GitHub's raw-content rate limits const yamlContent = await fetchYamlContent(namespace); if (!yamlContent) { console.log(`⏭️ Skipping ${namespace} (no registry.yaml found)`); diff --git a/packages/mcp-core/scripts/generate-platform-setup.ts b/packages/mcp-core/scripts/generate-platform-setup.ts index 8cca97d436..5f964d17c1 100644 --- a/packages/mcp-core/scripts/generate-platform-setup.ts +++ b/packages/mcp-core/scripts/generate-platform-setup.ts @@ -208,6 +208,7 @@ async function main() { for (const platform of platforms) { const linkPath = DOCS_PATH_OVERRIDES[platform.id] ?? new URL(platform.link).pathname; + // oxlint-disable-next-line no-await-in-loop -- resolves one platform at a time to keep the load on docs.sentry.io low const path = normalizePath(await resolveRedirects(linkPath)); // The platform list page is not a setup guide (for example `other`). if (path === "platforms" || !index.has(path)) { diff --git a/packages/mcp-core/scripts/measure-ui-views.ts b/packages/mcp-core/scripts/measure-ui-views.ts index d074464fb9..550c61d1c1 100644 --- a/packages/mcp-core/scripts/measure-ui-views.ts +++ b/packages/mcp-core/scripts/measure-ui-views.ts @@ -84,12 +84,20 @@ async function readViews(): Promise { try { const { resources } = await client.listResources(); const views: ViewStats[] = []; - for (const { uri } of resources.filter((r) => r.uri.startsWith("ui://"))) { - const budget = UI_RESOURCES.find((r) => r.uri === uri)?.budgetBytes; - if (budget === undefined) { - throw new Error(`${uri} is not in UI_RESOURCES, so it has no budget`); - } - const { contents } = await client.readResource({ uri }); + const budgeted = resources + .filter((r) => r.uri.startsWith("ui://")) + .map(({ uri }) => { + const budget = UI_RESOURCES.find((r) => r.uri === uri)?.budgetBytes; + if (budget === undefined) { + throw new Error(`${uri} is not in UI_RESOURCES, so it has no budget`); + } + return { uri, budget }; + }); + const reads = await Promise.all( + budgeted.map(({ uri }) => client.readResource({ uri })), + ); + for (const [index, { budget }] of budgeted.entries()) { + const { contents } = reads[index] ?? { contents: [] }; for (const content of contents) { const body = "text" in content diff --git a/packages/mcp-core/scripts/validate-skills-mapping.ts b/packages/mcp-core/scripts/validate-skills-mapping.ts index 93bb583bb8..8cebd6cc17 100644 --- a/packages/mcp-core/scripts/validate-skills-mapping.ts +++ b/packages/mcp-core/scripts/validate-skills-mapping.ts @@ -57,18 +57,13 @@ function getToolsForSkill(skill: Skill): string[] { * Validate skills-to-tools-to-scopes mapping */ async function validateMapping(): Promise { - const results: ValidationResult[] = []; - - for (const skillId of Object.keys(SKILLS) as Skill[]) { - const enabledTools = getToolsForSkill(skillId); - const requiredScopes = await getScopesForSkills(new Set([skillId])); - - results.push({ + const results: ValidationResult[] = await Promise.all( + (Object.keys(SKILLS) as Skill[]).map(async (skillId) => ({ skill: skillId, - enabledTools, - requiredScopes, - }); - } + enabledTools: getToolsForSkill(skillId), + requiredScopes: await getScopesForSkills(new Set([skillId])), + })), + ); return results; } diff --git a/packages/mcp-core/src/api-client/client.ts b/packages/mcp-core/src/api-client/client.ts index cd0d03ba10..accafd5d33 100644 --- a/packages/mcp-core/src/api-client/client.ts +++ b/packages/mcp-core/src/api-client/client.ts @@ -5117,12 +5117,14 @@ export class SentryApiService { queryParams.set("cursor", cursor); } + // oxlint-disable-next-line no-await-in-loop -- cursor pagination: each page needs the previous page's cursor const response = await this.request( apiPath`/organizations/${organizationSlug}/agents/conversations/${conversationId}/` + `?${queryParams.toString()}`, undefined, opts, ); + // oxlint-disable-next-line no-await-in-loop -- cursor pagination: each page needs the previous page's cursor const body = await readJsonResponse(response); const details = AIConversationDetailsResponseSchema.parse(body); // Pages repeat the same conversation-scoped title. diff --git a/packages/mcp-core/src/internal/fetch-utils.ts b/packages/mcp-core/src/internal/fetch-utils.ts index 1d04390295..a9e8f5dee3 100644 --- a/packages/mcp-core/src/internal/fetch-utils.ts +++ b/packages/mcp-core/src/internal/fetch-utils.ts @@ -91,6 +91,7 @@ export async function retryWithBackoff( for (let attempt = 0; attempt <= maxRetries; attempt++) { try { + // oxlint-disable-next-line no-await-in-loop -- retries are sequential by definition return await fn(); } catch (error) { lastError = error; @@ -103,6 +104,7 @@ export async function retryWithBackoff( } // Wait before retrying with exponential backoff + // oxlint-disable-next-line no-await-in-loop -- waits out the backoff before the next attempt await sleep(delay, signal); delay = Math.min(delay * 2, 30000); // Cap at 30 seconds } diff --git a/packages/mcp-core/src/tools/catalog/analyze-issue-with-seer.ts b/packages/mcp-core/src/tools/catalog/analyze-issue-with-seer.ts index 3526080805..250be51769 100644 --- a/packages/mcp-core/src/tools/catalog/analyze-issue-with-seer.ts +++ b/packages/mcp-core/src/tools/catalog/analyze-issue-with-seer.ts @@ -230,10 +230,12 @@ export default defineTool({ } // Wait before next poll + // oxlint-disable-next-line no-await-in-loop -- polls Seer until the run finishes await sleep(SEER_POLLING_INTERVAL, context.signal); // Refresh state with error handling try { + // oxlint-disable-next-line no-await-in-loop -- polls Seer until the run finishes autofixState = await retryWithBackoff( () => apiService.getAutofixState({ diff --git a/packages/mcp-core/src/tools/catalog/get-doc.ts b/packages/mcp-core/src/tools/catalog/get-doc.ts index fa9e3d7eaa..aa859e5726 100644 --- a/packages/mcp-core/src/tools/catalog/get-doc.ts +++ b/packages/mcp-core/src/tools/catalog/get-doc.ts @@ -87,6 +87,7 @@ export default defineTool({ // off the allowed hosts is reported as a missing page. let response: Response; for (let redirects = 0; ; redirects++) { + // oxlint-disable-next-line no-await-in-loop -- follows redirects one hop at a time so each hop is checked against the allowlist response = await fetchWithTimeout( docUrl, { diff --git a/packages/mcp-core/src/tools/support/alert-rule-connections.ts b/packages/mcp-core/src/tools/support/alert-rule-connections.ts index 5b9cc9b54a..66b2d99c52 100644 --- a/packages/mcp-core/src/tools/support/alert-rule-connections.ts +++ b/packages/mcp-core/src/tools/support/alert-rule-connections.ts @@ -76,6 +76,7 @@ export async function resolveAlertRuleConnections( [params.removeProjectSlugs, params.removeDetectorIds, removals], ] as const) { for (const projectSlug of new Set(projectSlugs ?? [])) { + // oxlint-disable-next-line no-await-in-loop -- the project scope check must stop before more lookups go out const project = await api.getProject({ organizationSlug: params.organizationSlug, projectSlugOrId: projectSlug, @@ -87,6 +88,7 @@ export async function resolveAlertRuleConnections( hasEvidence: projectId === params.scopedProject?.id, }); + // oxlint-disable-next-line no-await-in-loop -- the project scope check must stop before more lookups go out const detectors = await fetchEveryPage(async (cursor) => { const page = await api.listDetectorsPage({ organizationSlug: params.organizationSlug, @@ -128,6 +130,7 @@ export async function resolveAlertRuleConnections( removals.add(detectorId); continue; } + // oxlint-disable-next-line no-await-in-loop -- the project scope check must stop before more lookups go out const detector = await api.getDetector({ organizationSlug: params.organizationSlug, detectorId, diff --git a/packages/mcp-core/src/tools/support/alert-rule-details.ts b/packages/mcp-core/src/tools/support/alert-rule-details.ts index 7622728454..2ced616e97 100644 --- a/packages/mcp-core/src/tools/support/alert-rule-details.ts +++ b/packages/mcp-core/src/tools/support/alert-rule-details.ts @@ -220,6 +220,7 @@ export async function getAlertRuleDetails( const sources: AlertRuleDetails["sources"] = []; for (const id of rule.detectorIds ?? []) { try { + // oxlint-disable-next-line no-await-in-loop -- mcp-core has no fan-out cap; one lookup at a time keeps a rule with many sources from bursting the API const detector = await api.getDetector({ organizationSlug, detectorId: id, diff --git a/packages/mcp-core/src/tools/support/issue-linking/app.ts b/packages/mcp-core/src/tools/support/issue-linking/app.ts index bac222abc2..53ec41098f 100644 --- a/packages/mcp-core/src/tools/support/issue-linking/app.ts +++ b/packages/mcp-core/src/tools/support/issue-linking/app.ts @@ -214,6 +214,7 @@ async function resolveFields( if (field.type === "select") { let choices = field.choices ?? field.options ?? []; if (field.uri) { + // oxlint-disable-next-line no-await-in-loop -- a field's options depend on the values chosen for earlier fields const options = await api.getSentryAppExternalRequestOptions({ installationUuid, uri: validateUri(field.uri), diff --git a/packages/mcp-core/src/tools/support/search-events/seer.ts b/packages/mcp-core/src/tools/support/search-events/seer.ts index 105559ac35..1d203cfe6a 100644 --- a/packages/mcp-core/src/tools/support/search-events/seer.ts +++ b/packages/mcp-core/src/tools/support/search-events/seer.ts @@ -304,6 +304,7 @@ async function runSearchAgent({ const deadline = Date.now() + SEER_SEARCH_AGENT_TIMEOUT; while (Date.now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls the search agent until it finishes or times out const { session } = await apiService.getSearchAgentState({ organizationSlug, runId: run.sentry_run_id, @@ -325,6 +326,7 @@ async function runSearchAgent({ return null; } + // oxlint-disable-next-line no-await-in-loop -- polls the search agent until it finishes or times out await sleep(SEER_SEARCH_AGENT_POLLING_INTERVAL, apiService.signal); } From b7d2c8245f1d885f07b15c30e3444eca7e1358c6 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:42:47 +0000 Subject: [PATCH 8/9] ref: Mark sequential awaits in loops in the remaining packages http computes the `authorization` digest once, after the header copy. Grammar generation, nightly manifest checks and envelope directory walks run concurrently. Retries, stream reads, prompts, polling and replays stay sequential with a reason. --- .../verify-toolkit/scripts/mcp-call.mjs | 1 + apps/docs-mcp/src/agent/features-agent.ts | 1 + apps/docs-mcp/src/agent/model-fallback.ts | 2 + apps/local/scripts/replay.ts | 29 +++++++----- packages/http/src/policy.ts | 8 ++-- packages/http/src/retry.ts | 3 ++ packages/mcp-test-client/src/index.ts | 2 + packages/toolkit-core/src/mcp-limits.ts | 2 + scripts/cli-nightly-verify.mjs | 15 ++++--- scripts/cloudflare-deployment.mjs | 4 ++ scripts/generate-parsers.mjs | 45 ++++++++++--------- 11 files changed, 71 insertions(+), 41 deletions(-) diff --git a/.agents/skills/verify-toolkit/scripts/mcp-call.mjs b/.agents/skills/verify-toolkit/scripts/mcp-call.mjs index ff23ed21dc..56f8e6bdf8 100755 --- a/.agents/skills/verify-toolkit/scripts/mcp-call.mjs +++ b/.agents/skills/verify-toolkit/scripts/mcp-call.mjs @@ -113,6 +113,7 @@ try { ); for (const [n, [name, toolArgs]] of opts.calls.entries()) { const file = `call-${n + 1}-${name}.json`; + // oxlint-disable-next-line no-await-in-loop -- calls run in the order given, since a later call can depend on an earlier one's side effects const result = await client.callTool({ name, arguments: toolArgs }); write(file, { request: { name, arguments: toolArgs }, result }); const shape = result.structuredContent diff --git a/apps/docs-mcp/src/agent/features-agent.ts b/apps/docs-mcp/src/agent/features-agent.ts index 45ce82cd29..24a7e904cf 100644 --- a/apps/docs-mcp/src/agent/features-agent.ts +++ b/apps/docs-mcp/src/agent/features-agent.ts @@ -237,6 +237,7 @@ export async function parseFeaturesOutput( `Structured output was truncated because the model finished with reason "${finishReason}".`, ); } + // oxlint-disable-next-line no-await-in-loop -- steps parse in order: a cut-off step throws before later steps are read, and the last valid output wins const { value } = await parsePartialJson(preprocessJsonText(text)); const parsed = featuresOutputSchema.safeParse(value); if (!parsed.success) { diff --git a/apps/docs-mcp/src/agent/model-fallback.ts b/apps/docs-mcp/src/agent/model-fallback.ts index 299e65f210..516205264e 100644 --- a/apps/docs-mcp/src/agent/model-fallback.ts +++ b/apps/docs-mcp/src/agent/model-fallback.ts @@ -187,6 +187,7 @@ function createFallbackModel( for (const [index, model] of models.entries()) { for (;;) { try { + // oxlint-disable-next-line no-await-in-loop -- tries one model at a time and falls back only after it fails return { model, result: await call(model) }; } catch (error) { lastError = error; @@ -202,6 +203,7 @@ function createFallbackModel( break; } retryCount++; + // oxlint-disable-next-line no-await-in-loop -- backs off before retrying the same model await wait(delay, signal); } } diff --git a/apps/local/scripts/replay.ts b/apps/local/scripts/replay.ts index 88d8e68959..61ddf05c7b 100644 --- a/apps/local/scripts/replay.ts +++ b/apps/local/scripts/replay.ts @@ -21,17 +21,20 @@ async function envelopeFiles(path: string): Promise { const info = await stat(path); if (info.isFile()) return [path]; const entries = await readdir(path, { withFileTypes: true }); - const files: string[] = []; - for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) { - const child = join(path, entry.name); - if (entry.isDirectory()) files.push(...(await envelopeFiles(child))); - else if ( - entry.isFile() && - [".txt", ".bin", ".envelope"].includes(extname(entry.name)) - ) - files.push(child); - } - return files; + // Sorted, and flattened in that order, so envelopes replay in a stable order. + const nested = await Promise.all( + entries + .sort((a, b) => a.name.localeCompare(b.name)) + .map(async (entry) => { + const child = join(path, entry.name); + if (entry.isDirectory()) return await envelopeFiles(child); + return entry.isFile() && + [".txt", ".bin", ".envelope"].includes(extname(entry.name)) + ? [child] + : []; + }), + ); + return nested.flat(); } /** Replay raw bytes through the public receiver endpoint; never bypass ingestion. */ export async function replayEnvelopes({ @@ -69,7 +72,9 @@ export async function replayEnvelopes({ let sent = 0; for (let cycle = 0; cycle < repeat; cycle++) for (const file of files) { + // oxlint-disable-next-line no-await-in-loop -- replays envelopes one at a time, spaced by --interval if (sent && interval) await delay(interval); + // oxlint-disable-next-line no-await-in-loop -- replays envelopes one at a time, spaced by --interval const raw = await readFile(file); const body = compression === "gzip" @@ -77,6 +82,7 @@ export async function replayEnvelopes({ : compression === "br" ? brotliCompressSync(raw) : raw; + // oxlint-disable-next-line no-await-in-loop -- replays envelopes one at a time, spaced by --interval const response = await fetch(target, { method: "POST", headers: { @@ -89,6 +95,7 @@ export async function replayEnvelopes({ redirect: "error", signal: AbortSignal.timeout(10_000), }); + // oxlint-disable-next-line no-await-in-loop -- replays envelopes one at a time, spaced by --interval await response.body?.cancel(); if (!response.ok) throw new Error(`Receiver rejected ${file}: HTTP ${response.status}`); diff --git a/packages/http/src/policy.ts b/packages/http/src/policy.ts index 48c5f6bce8..93db35970c 100644 --- a/packages/http/src/policy.ts +++ b/packages/http/src/policy.ts @@ -157,9 +157,11 @@ async function policyRequestHeaders( // Lowercase names, as `http-cache-semantics` stores them and `Vary` // matching compares them. for (const [rawName, value] of Object.entries(headers)) { - const name = rawName.toLowerCase(); - result[name] = - name === "authorization" && value ? await sha256Hex(value) : value; + result[rawName.toLowerCase()] = value; + } + const authorization = result["authorization"]; + if (authorization) { + result["authorization"] = await sha256Hex(authorization); } return result; } diff --git a/packages/http/src/retry.ts b/packages/http/src/retry.ts index 4d5685d62d..5dc7d3bc5c 100644 --- a/packages/http/src/retry.ts +++ b/packages/http/src/retry.ts @@ -278,6 +278,7 @@ export async function fetchWithRetry( for (let attempt = 0; ; attempt++) { let response: Response; try { + // oxlint-disable-next-line no-await-in-loop -- retries are sequential by definition response = await send(attempt); } catch (error) { const delayMs = @@ -288,6 +289,7 @@ export async function fetchWithRetry( throw error; } options.onRetry?.({ attempt, delayMs, status: undefined, error }); + // oxlint-disable-next-line no-await-in-loop -- waits out the backoff before the next attempt await sleep(delayMs, signal); waitedMs += delayMs; continue; @@ -301,6 +303,7 @@ export async function fetchWithRetry( } response.body?.cancel().catch(() => undefined); options.onRetry?.({ attempt, delayMs, status: response.status }); + // oxlint-disable-next-line no-await-in-loop -- waits out the backoff before the next attempt await sleep(delayMs, signal); waitedMs += delayMs; } diff --git a/packages/mcp-test-client/src/index.ts b/packages/mcp-test-client/src/index.ts index 87ce5d1430..55cf839e9c 100644 --- a/packages/mcp-test-client/src/index.ts +++ b/packages/mcp-test-client/src/index.ts @@ -201,6 +201,7 @@ program for (;;) { try { + // oxlint-disable-next-line no-await-in-loop -- interactive prompt: reads one line at a time const userInput = await rl.question(chalk.gray("> ")); if ( @@ -212,6 +213,7 @@ program } if (userInput.trim()) { + // oxlint-disable-next-line no-await-in-loop -- interactive prompt: answers one line at a time await runAgent(connection, userInput, agentConfig); // Add newline after response before next prompt console.log(); diff --git a/packages/toolkit-core/src/mcp-limits.ts b/packages/toolkit-core/src/mcp-limits.ts index 59ceaf4a66..fc9101a7cd 100644 --- a/packages/toolkit-core/src/mcp-limits.ts +++ b/packages/toolkit-core/src/mcp-limits.ts @@ -44,12 +44,14 @@ export async function readBoundedBody( const chunks: Uint8Array[] = []; let received = 0; for (;;) { + // oxlint-disable-next-line no-await-in-loop -- reads the request body stream chunk by chunk const { done, value } = await reader.read(); if (done) { break; } received += value.byteLength; if (received > MAX_MCP_REQUEST_BODY_BYTES) { + // oxlint-disable-next-line no-await-in-loop -- stops reading once the body is over the limit await reader.cancel(); return undefined; } diff --git a/scripts/cli-nightly-verify.mjs b/scripts/cli-nightly-verify.mjs index 20dd249f48..11bd17fa1d 100644 --- a/scripts/cli-nightly-verify.mjs +++ b/scripts/cli-nightly-verify.mjs @@ -57,14 +57,17 @@ async function main() { `https://ghcr.io/token?scope=repository:${REPOSITORY}:pull`, ); let failed = false; - for (const tag of ["nightly", `nightly-${version}`]) { - const manifest = await getJson( - `https://ghcr.io/v2/${REPOSITORY}/manifests/${tag}`, - { + const tags = ["nightly", `nightly-${version}`]; + const manifests = await Promise.all( + tags.map((tag) => + getJson(`https://ghcr.io/v2/${REPOSITORY}/manifests/${tag}`, { Authorization: `Bearer ${token}`, Accept: "application/vnd.oci.image.manifest.v1+json", - }, - ); + }), + ), + ); + for (const [index, tag] of tags.entries()) { + const manifest = manifests[index]; for (const problem of checkNightlyManifest(manifest, { version, files })) { console.error(`::error::${tag}: ${problem}`); failed = true; diff --git a/scripts/cloudflare-deployment.mjs b/scripts/cloudflare-deployment.mjs index 353683882f..6189614b19 100644 --- a/scripts/cloudflare-deployment.mjs +++ b/scripts/cloudflare-deployment.mjs @@ -258,7 +258,9 @@ export async function listSettled( attempt < SETTLE_ATTEMPTS && !settled(deployments); attempt++ ) { + // oxlint-disable-next-line no-await-in-loop -- polls until the deployments settle await sleep(SETTLE_DELAY_MS); + // oxlint-disable-next-line no-await-in-loop -- polls until the deployments settle deployments = await list(env); } return deployments; @@ -309,11 +311,13 @@ async function waitUntilReadable( const deadline = now() + READABLE_TIMEOUT_MS; let streak = 0; while (now() < deadline) { + // oxlint-disable-next-line no-await-in-loop -- polls until every version is readable const readable = await Promise.all( versionIds.map((versionId) => readVersion(env, versionId, worker)), ); streak = readable.every(Boolean) ? streak + 1 : 0; if (streak === READABLE_STREAK) return; + // oxlint-disable-next-line no-await-in-loop -- polls until every version is readable await sleep(SETTLE_DELAY_MS); } throw new DeploymentError( diff --git a/scripts/generate-parsers.mjs b/scripts/generate-parsers.mjs index 066e5b3b39..fcadd31c20 100644 --- a/scripts/generate-parsers.mjs +++ b/scripts/generate-parsers.mjs @@ -86,26 +86,29 @@ const grammars = (await readdir(grammarDir)).filter((file) => ); await mkdir(outputDir, { recursive: true }); -for (const file of grammars) { - const name = file.slice(0, -".pegjs".length); - const grammarPath = join(grammarDir, file); - const declarationsPath = join(grammarDir, `${name}.d.ts`); - if (!existsSync(declarationsPath)) { - throw new Error(`${declarationsPath} is missing`); - } +// Each grammar writes its own output files, so they generate concurrently. +await Promise.all( + grammars.map(async (file) => { + const name = file.slice(0, -".pegjs".length); + const grammarPath = join(grammarDir, file); + const declarationsPath = join(grammarDir, `${name}.d.ts`); + if (!existsSync(declarationsPath)) { + throw new Error(`${declarationsPath} is missing`); + } - const parserSource = peggy.generate(await readFile(grammarPath, "utf-8"), { - output: "source", - format: "es", - grammarSource: relative(packageDir, grammarPath).split(sep).join("/"), - }); - const declarations = rebaseDeclarations( - await readFile(declarationsPath, "utf-8"), - declarationsPath, - ); + const parserSource = peggy.generate(await readFile(grammarPath, "utf-8"), { + output: "source", + format: "es", + grammarSource: relative(packageDir, grammarPath).split(sep).join("/"), + }); + const declarations = rebaseDeclarations( + await readFile(declarationsPath, "utf-8"), + declarationsPath, + ); - const outputBase = join(outputDir, `${name}-grammar`); - await writeFile(`${outputBase}.js`, `${HEADER}\n${parserSource}\n`); - await writeFile(`${outputBase}.d.ts`, `${HEADER}\n${declarations}`); - console.log(`Generated ${relative(process.cwd(), outputBase)}.{js,d.ts}`); -} + const outputBase = join(outputDir, `${name}-grammar`); + await writeFile(`${outputBase}.js`, `${HEADER}\n${parserSource}\n`); + await writeFile(`${outputBase}.d.ts`, `${HEADER}\n${declarations}`); + console.log(`Generated ${relative(process.cwd(), outputBase)}.{js,d.ts}`); + }), +); From a47c8fbf71005037ffbffd88659023762fd21bd6 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:43:02 +0000 Subject: [PATCH 9/9] ref: Turn on no-await-in-loop for the whole repo Move `no-await-in-loop` from the `packages/cli/src` override to the root rules and drop the per-file off list. Test files keep the rule off by glob: their loops are table-driven assertions against shared state. --- .oxlintrc.json | 91 ++++-------------------------------------- packages/cli/AGENTS.md | 2 +- 2 files changed, 8 insertions(+), 85 deletions(-) diff --git a/.oxlintrc.json b/.oxlintrc.json index 7a416d0fc7..a78ef22902 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -50,6 +50,7 @@ ], "typescript/no-unnecessary-type-constraint": "error", "prefer-const": "error", + "no-await-in-loop": "error", "no-else-return": ["error", { "allowElseIf": false }], "no-new-wrappers": "error", "no-new": "error", @@ -252,8 +253,7 @@ "files": ["packages/cli/src/**/*.ts"], "rules": { "typescript/no-explicit-any": "error", - "typescript/no-non-null-assertion": "error", - "no-await-in-loop": "error" + "typescript/no-non-null-assertion": "error" } }, { @@ -512,88 +512,11 @@ }, { "files": [ - "packages/cli/src/commands/alert/issues/rule-resolve.ts", - "packages/cli/src/commands/alert/metrics/rule-resolve.ts", - "packages/cli/src/commands/alert/metrics/view.ts", - "packages/cli/src/commands/auth/default.ts", - "packages/cli/src/commands/auth/logout.ts", - "packages/cli/src/commands/build/upload.ts", - "packages/cli/src/commands/cli/setup.ts", - "packages/cli/src/commands/cli/uninstall.ts", - "packages/cli/src/commands/cli/upgrade.ts", - "packages/cli/src/commands/dashboard/list.ts", - "packages/cli/src/commands/dashboard/resolve.ts", - "packages/cli/src/commands/dashboard/view.ts", - "packages/cli/src/commands/event/send.ts", - "packages/cli/src/commands/issue/view.ts", - "packages/cli/src/commands/local/daemon.ts", - "packages/cli/src/commands/local/receiver-ingest.ts", - "packages/cli/src/commands/local/run.ts", - "packages/cli/src/commands/local/server.ts", - "packages/cli/src/commands/log/tail.ts", - "packages/cli/src/commands/log/view.ts", - "packages/cli/src/commands/proguard/upload.ts", - "packages/cli/src/commands/project/create.ts", - "packages/cli/src/commands/project/list.ts", - "packages/cli/src/commands/react-native/gradle.ts", - "packages/cli/src/commands/react-native/xcode.ts", - "packages/cli/src/commands/sourcemap/upload.ts", - "packages/cli/src/lib/agent-skills.ts", - "packages/cli/src/lib/api/attribute-pagination.ts", - "packages/cli/src/lib/api/chunk-upload.ts", - "packages/cli/src/lib/api/code-mappings.ts", - "packages/cli/src/lib/api/conversations.ts", - "packages/cli/src/lib/api/dart-symbols.ts", - "packages/cli/src/lib/api/dashboards.ts", - "packages/cli/src/lib/api/debug-files.ts", - "packages/cli/src/lib/api/explore.ts", - "packages/cli/src/lib/api/infrastructure.ts", - "packages/cli/src/lib/api/issue-app-links.ts", - "packages/cli/src/lib/api/preprod-artifacts.ts", - "packages/cli/src/lib/api/proguard.ts", - "packages/cli/src/lib/api/releases.ts", - "packages/cli/src/lib/api/replays.ts", - "packages/cli/src/lib/bash-hook/traceback.ts", - "packages/cli/src/lib/build/asset-catalog-extract.ts", - "packages/cli/src/lib/build/dsyms.ts", - "packages/cli/src/lib/build/index.ts", - "packages/cli/src/lib/build/zip-writer.ts", - "packages/cli/src/lib/command.ts", - "packages/cli/src/lib/complete.ts", - "packages/cli/src/lib/db/dsn-cache.ts", - "packages/cli/src/lib/detect-agent.ts", - "packages/cli/src/lib/dev-script.ts", - "packages/cli/src/lib/dif/find.ts", - "packages/cli/src/lib/dif/scan.ts", - "packages/cli/src/lib/docs-context.ts", - "packages/cli/src/lib/dsn/env-file.ts", - "packages/cli/src/lib/dsn/project-root.ts", - "packages/cli/src/lib/dsn/resolver.ts", - "packages/cli/src/lib/dsn/scanner.ts", - "packages/cli/src/lib/fs-utils.ts", - "packages/cli/src/lib/ghcr.ts", - "packages/cli/src/lib/jvm-bundle.ts", - "packages/cli/src/lib/oauth.ts", - "packages/cli/src/lib/polling.ts", - "packages/cli/src/lib/scan/concurrent.ts", - "packages/cli/src/lib/scan/grep.ts", - "packages/cli/src/lib/scan/walker.ts", - "packages/cli/src/lib/sentryclirc-import.ts", - "packages/cli/src/lib/sentryclirc.ts", - "packages/cli/src/lib/snapshots/archive.ts", - "packages/cli/src/lib/sourcemap/inject.ts", - "packages/cli/src/lib/sourcemap/zip.ts", - "packages/cli/src/lib/target-scope.ts", - "packages/cli/src/lib/upgrade.ts", - "packages/cli/src/lib/walk-up.ts", - "packages/cli/src/lib/wizard/nextjs/nextjs-wizard.ts", - "packages/cli/src/lib/wizard/nuxt/sdk-setup.ts", - "packages/cli/src/lib/wizard/react-native/javascript.ts", - "packages/cli/src/lib/wizard/remix/codemods/express-server.ts", - "packages/cli/src/lib/wizard/sourcemaps/tools/sentry-cli.ts", - "packages/cli/src/lib/wizard/utils/clack/index.ts", - "packages/cli/src/lib/wizard/utils/clack/mcp-config.ts", - "packages/cli/src/lib/wrangler.ts" + "**/*.test.ts", + "**/*.test.tsx", + "**/*.test.mjs", + "**/test-utils/**", + "packages/cli/test/**" ], "rules": { "no-await-in-loop": "off" diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.md index 132c957772..f07a5f31f6 100644 --- a/packages/cli/AGENTS.md +++ b/packages/cli/AGENTS.md @@ -1078,7 +1078,7 @@ Don't copy a pattern from a neighboring file without this check. The wizards wer | Absolute date/time display | `src/lib/formatters/time-utils.ts` (`formatLocalDateTime` and `formatLocalTime` for epoch ms or ISO strings, `formatUtcTimestamp`, `formatAxisTimestamp` for chart axes). `sentry-cli/no-inline-date-format` rejects `new Date(x).toLocale*String()` elsewhere in `src/`. | | Table/markdown output | `src/lib/formatters/` directory | | Pagination | `src/lib/db/pagination.ts`, `src/lib/list-command.ts` | -| Independent async work over a list (instead of `await` in a loop) | `src/lib/fan-out.ts` (`mapBounded(items, fn, concurrency)`): pass `ORG_FANOUT_CONCURRENCY` for API calls, `CONCURRENCY_LIMIT` (`src/lib/scan/constants.ts`) for local files. Oxlint's `no-await-in-loop` is on in `src/`, except for the files listed in its `"off"` override in `/.oxlintrc.json`; a file comes off that list once its loops are fixed. | +| Independent async work over a list (instead of `await` in a loop) | `src/lib/fan-out.ts` (`mapBounded(items, fn, concurrency)`): pass `ORG_FANOUT_CONCURRENCY` for API calls, `CONCURRENCY_LIMIT` (`src/lib/scan/constants.ts`) for local files. Oxlint's `no-await-in-loop` is on for the whole repo except test files. A loop that must stay sequential (cursor pages, polling, retries, ordered writes, first match wins) gets `// oxlint-disable-next-line no-await-in-loop -- `. | | Error classes | `src/lib/errors.ts` (never create ad-hoc error types) | | Search query building | `src/lib/search-query.ts` (wraps `@sentry/toolkit-core/search-query`), `src/lib/arg-parsing.ts` |