From 42180694c016fcd883af3b0cb36c3fa5ebe11c92 Mon Sep 17 00:00:00 2001 From: "Artem Viter (ardmn)" Date: Tue, 24 Nov 2026 14:38:57 +0400 Subject: [PATCH 1/8] build(eslint): node:test calls are known-safe, numbers allowed in templates 51 of the 94 bulk-suppressed violations were two rule settings, not code problems: - no-floating-promises flagged every top-level node:test test() call. The promise it returns only reports completion and is fulfilled whether the test passes or fails; the runner tracks the test. allowForKnownSafeCalls names node:test's test/it/describe/suite. - restrict-template-expressions (strictTypeChecked) rejects numbers. A number has one string form; booleans, null, arrays and objects stay errors, as before. Bulk suppressions count per file and rule, so a fixed violation can hide a new one in the same file. Fewer suppressed rules means fewer places where that can happen. Refs ardmn/work#16 --- eslint-suppressions.json | 49 ++-------------------------------------- eslint.config.mjs | 29 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 47 deletions(-) diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 4d04e49..0e4613c 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -15,17 +15,11 @@ "example-shared/src/screens/JsonScreen.tsx": { "@typescript-eslint/no-misused-promises": { "count": 1 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 2 } }, "example-shared/src/screens/NetworkScreen.tsx": { "@typescript-eslint/no-non-null-assertion": { "count": 1 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 1 } }, "example-shared/src/screens/PerformanceScreen.tsx": { @@ -34,39 +28,6 @@ }, "@typescript-eslint/no-misused-promises": { "count": 1 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 3 - } - }, - "scripts/__tests__/generate-native-contract.test.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 6 - } - }, - "scripts/__tests__/host-cpu.test.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 3 - } - }, - "scripts/__tests__/lib.test.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 5 - } - }, - "scripts/__tests__/package-exports.test.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 2 - } - }, - "scripts/__tests__/perf-parse.test.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 6 - } - }, - "scripts/__tests__/stats.test.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 3 } }, "scripts/generate-native-contract.ts": { @@ -74,7 +35,7 @@ "count": 2 }, "@typescript-eslint/restrict-template-expressions": { - "count": 4 + "count": 3 } }, "scripts/lib.ts": { @@ -85,7 +46,7 @@ "count": 1 }, "@typescript-eslint/restrict-template-expressions": { - "count": 3 + "count": 2 } }, "scripts/measure-perf.ts": { @@ -94,9 +55,6 @@ }, "@typescript-eslint/restrict-plus-operands": { "count": 1 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 16 } }, "scripts/stats.ts": { @@ -136,9 +94,6 @@ }, "@typescript-eslint/no-unnecessary-condition": { "count": 2 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 2 } } } \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs index f8ea0e7..20e6d5b 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -54,6 +54,35 @@ export default defineConfig([ tsconfigRootDir: __dirname, }, }, + rules: { + '@typescript-eslint/no-floating-promises': [ + 'error', + { + // node:test's test() returns a promise that only reports completion: it is fulfilled + // when the test ends, failed or not, and the runner tracks the test itself. + allowForKnownSafeCalls: [ + { + from: 'package', + name: ['test', 'it', 'describe', 'suite'], + package: 'node:test', + }, + ], + }, + ], + '@typescript-eslint/restrict-template-expressions': [ + 'error', + { + // strictTypeChecked's options with numbers allowed, as in recommendedTypeChecked: a + // number has one string form, while booleans, null, arrays and objects stay errors. + allowAny: false, + allowBoolean: false, + allowNever: false, + allowNullish: false, + allowNumber: true, + allowRegExp: false, + }, + ], + }, }, { ignores: [ From 01fd9b97afcf3c2fe00c9cd380d1eef6a9f876ec Mon Sep 17 00:00:00 2001 From: "Artem Viter (ardmn)" Date: Tue, 24 Nov 2026 14:39:08 +0400 Subject: [PATCH 2/8] ci: one checksum-verified fetch-tool action, linters fetched first, every check reported The lint and secrets jobs downloaded five tools with five copies of the same curl/sha256sum snippet, inside the linter steps: - A download happened after yarn lint and the tests, so an early failure skipped it, and the cache save ran at the end of the job (with always(), so also on cancelled runs). - A cached file that failed its checksum was never replaced: `[ -f ]` skipped the download, the check failed, and the save was skipped on a cache hit. Every run failed until the entry expired. - The lint job ran its checks fail-fast, so one failing check hid the others; the Android step ran unit tests and lint in one Gradle call without --continue, so a failing test hid lint. Now: - scripts/verified-download.ts owns "use a download only if its SHA-256 matches" for the scripts (bundletool in lib.ts, which had its own copy) and CI. A file already there is re-checked; one that fails is reported and downloaded again; a download is checked before it is written and renamed into place. Network errors, 5xx and 429 are retried. No dependencies, so the secrets job needs only Node, not a yarn install. - .github/actions/fetch-tool (the approach of remote-compose-storybook's action of the same name) restores the tool's cache entry, runs scripts/fetch-tool.ts (verify or download, extract from a zip or tar, install on PATH), and saves a new download right away. The lint job fetches all four tools before any check. - Each lint check runs with !cancelled() and skips only when what it needs did not install. In native-tests, the lockfile check and the Android step run after an earlier failure too, and Gradle gets --continue. - Quoted three shell expansions actionlint's shellcheck reported (SC2086) in the turbo and NDK steps, so actionlint passes on the whole file. A cache entry cannot be overwritten, so after a corrupted hit the job downloads on every run (with a warning naming the fix, gh cache delete) instead of failing. Refs ardmn/work#15 --- .github/actions/fetch-tool/action.yml | 59 +++++ .github/workflows/ci.yml | 216 ++++++++---------- scripts/__tests__/verified-download.test.ts | 237 ++++++++++++++++++++ scripts/fetch-tool.ts | 95 ++++++++ scripts/lib.ts | 25 +-- scripts/verified-download.ts | 100 +++++++++ 6 files changed, 592 insertions(+), 140 deletions(-) create mode 100644 .github/actions/fetch-tool/action.yml create mode 100644 scripts/__tests__/verified-download.test.ts create mode 100644 scripts/fetch-tool.ts create mode 100644 scripts/verified-download.ts diff --git a/.github/actions/fetch-tool/action.yml b/.github/actions/fetch-tool/action.yml new file mode 100644 index 0000000..f435e98 --- /dev/null +++ b/.github/actions/fetch-tool/action.yml @@ -0,0 +1,59 @@ +name: Fetch a pinned tool +description: >- + Restores the tool's release file from the cache, or downloads it; checks its SHA-256 either way + (a cached copy that fails is downloaded again); installs it on PATH for the job's later steps; and + saves a new download to the cache at once, so a later failing step does not lose it. The caller + names the release URL and its SHA-256, so the pinned version stays visible in the workflow. Needs + the checkout and Node from .nvmrc (scripts/fetch-tool.ts runs with Node's TypeScript support). + +inputs: + name: + description: The file name the tool is installed under (a command name, or a jar's name). + required: true + url: + description: The release asset to download (a zip, a tar archive in any compression tar detects, or the tool itself). + required: true + sha256: + description: The SHA-256 of the downloaded file, from the official release. + required: true + archive-path: + description: The tool's path inside the archive; empty when the download is the tool itself. + required: false + default: '' + +outputs: + path: + description: The installed file, for tools run by path (a jar). + value: ${{ steps.fetch.outputs.path }} + +runs: + using: composite + steps: + # Keyed by the checksum: a version bump is a new key, and an entry only ever holds the file + # that checksum names (it is saved below only after the check passed). + - name: Restore cached ${{ inputs.name }} + id: restore + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/ci-tools-cache/${{ inputs.name }}-${{ inputs.sha256 }} + key: ci-tools-${{ runner.os }}-${{ inputs.name }}-${{ inputs.sha256 }} + + - name: Download, verify and install ${{ inputs.name }} + id: fetch + shell: bash + env: + NAME: ${{ inputs.name }} + URL: ${{ inputs.url }} + SHA256: ${{ inputs.sha256 }} + ARCHIVE_PATH: ${{ inputs.archive-path }} + CACHE_FILE: ${{ runner.temp }}/ci-tools-cache/${{ inputs.name }}-${{ inputs.sha256 }} + run: node scripts/fetch-tool.ts + + # A cache entry cannot be overwritten: after a corrupted hit (downloaded again above, with a + # warning) every run downloads until the entry is deleted (`gh cache delete `) or expires. + - name: Save ${{ inputs.name }} to the cache + if: steps.restore.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/ci-tools-cache/${{ inputs.name }}-${{ inputs.sha256 }} + key: ci-tools-${{ runner.os }}-${{ inputs.name }}-${{ inputs.sha256 }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9c5f69c..76e55ce 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,10 +23,9 @@ jobs: lint: runs-on: ubuntu-latest - # Downloaded linters: one place for each version and the sha256 of its release file. The - # files are cached under these values, and every run checks the checksum, cached or not. + # Downloaded linters: one place for each version and the sha256 of its release file. Each is + # cached under its checksum and checked on every run, cached or not (.github/actions/fetch-tool). env: - TOOLS_DIR: /home/runner/.cache/ci-tools KTLINT_VERSION: 1.8.0 KTLINT_SHA256: a3fd620207d5c40da6ca789b95e7f823c54e854b7fade7f613e91096a3706d75 DETEKT_VERSION: 1.23.8 @@ -36,11 +35,16 @@ jobs: SWIFTLINT_VERSION: 0.65.1 SWIFTLINT_SHA256: caeed6f4a679c35539ffaf124f6c4ab4a8416917f7d8796279dc52b74026059d + # The tools are fetched first, so a download saved to the cache is kept whatever fails later. + # Every check after them runs even when an earlier check failed (`!cancelled()`), so one run + # reports every failing check; a check still skips when what it needs (dependencies or its + # tool) did not install. steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup + id: setup uses: ./.github/actions/setup - name: Install JDK (ktlint, detekt) @@ -49,136 +53,101 @@ jobs: distribution: 'zulu' java-version: '17' - # One cache per tool, keyed by its checksum: bumping one tool re-downloads only that one. Each - # is saved even when a later step fails (a lint finding is the common failure), and only a - # file that passed its checksum is ever written to the cached path. - - name: Restore cached ktlint - id: cache-ktlint - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + - name: Fetch ktlint + id: ktlint + uses: ./.github/actions/fetch-tool with: - path: ${{ env.TOOLS_DIR }}/ktlint-${{ env.KTLINT_VERSION }} - key: ci-tools-${{ runner.os }}-ktlint-${{ env.KTLINT_SHA256 }} - - - name: Restore cached detekt - id: cache-detekt - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + name: ktlint + url: https://github.com/pinterest/ktlint/releases/download/${{ env.KTLINT_VERSION }}/ktlint + sha256: ${{ env.KTLINT_SHA256 }} + + - name: Fetch detekt + # Maven Central's artifact and the sha256 Central publishes for it. + id: detekt + uses: ./.github/actions/fetch-tool with: - path: ${{ env.TOOLS_DIR }}/detekt-cli-${{ env.DETEKT_VERSION }}-all.jar - key: ci-tools-${{ runner.os }}-detekt-${{ env.DETEKT_SHA256 }} + name: detekt-cli.jar + url: https://repo1.maven.org/maven2/io/gitlab/arturbosch/detekt/detekt-cli/${{ env.DETEKT_VERSION }}/detekt-cli-${{ env.DETEKT_VERSION }}-all.jar + sha256: ${{ env.DETEKT_SHA256 }} - - name: Restore cached SwiftFormat - id: cache-swiftformat - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + - name: Fetch SwiftFormat + id: swiftformat + uses: ./.github/actions/fetch-tool with: - path: ${{ env.TOOLS_DIR }}/swiftformat-${{ env.SWIFTFORMAT_VERSION }}-linux.zip - key: ci-tools-${{ runner.os }}-swiftformat-${{ env.SWIFTFORMAT_SHA256 }} - - - name: Restore cached SwiftLint - id: cache-swiftlint - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + name: swiftformat + url: https://github.com/nicklockwood/SwiftFormat/releases/download/${{ env.SWIFTFORMAT_VERSION }}/swiftformat_linux.zip + sha256: ${{ env.SWIFTFORMAT_SHA256 }} + archive-path: swiftformat_linux + + - name: Fetch SwiftLint + # The statically linked Linux build runs on this runner without a Swift toolchain. + id: swiftlint + uses: ./.github/actions/fetch-tool with: - path: ${{ env.TOOLS_DIR }}/swiftlint-${{ env.SWIFTLINT_VERSION }}-linux-amd64.zip - key: ci-tools-${{ runner.os }}-swiftlint-${{ env.SWIFTLINT_SHA256 }} + name: swiftlint + url: https://github.com/realm/SwiftLint/releases/download/${{ env.SWIFTLINT_VERSION }}/swiftlint_linux_amd64.zip + sha256: ${{ env.SWIFTLINT_SHA256 }} + archive-path: swiftlint-static - name: Lint files + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} run: yarn lint - name: Typecheck files + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} run: yarn typecheck - name: Unused files, exports and dependencies (knip) + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} run: yarn knip - name: Native contract is generated from the Codegen spec + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} run: yarn contract --check - name: Expo demo dependencies match its Expo SDK (expo install --check, offline) # Offline: checks against the SDK's own bundledNativeModules.json, so the result changes only # with a change here. Online it would ask Expo's API for the newest patch releases, which can # be younger than .yarnrc.yml's 7-day npmMinimalAgeGate and so not installable yet. + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} env: EXPO_OFFLINE: '1' run: yarn workspace react-native-remote-compose-example-expo expo install --check - name: Unit tests (library contract, diagnostics, Expo plugin) + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} run: yarn test --ci - - name: Script tests (native contract, measurement parsing, version copies) + - name: Script tests (native contract, measurement parsing, version copies, downloads) + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} run: yarn test:scripts - - name: Lint Kotlin (ktlint, checksum-pinned) - run: | - mkdir -p "$TOOLS_DIR" - tool="$TOOLS_DIR/ktlint-$KTLINT_VERSION" - [ -f "$tool" ] || { curl -sSfL -o "$tool.part" "https://github.com/pinterest/ktlint/releases/download/$KTLINT_VERSION/ktlint" && echo "$KTLINT_SHA256 $tool.part" | sha256sum -c - && mv "$tool.part" "$tool"; } - echo "$KTLINT_SHA256 $tool" | sha256sum -c - - chmod +x "$tool" - "$tool" "android/src/**/*.kt" "!android/src/main/java/com/remotecompose/contract/**" "tools/remote-compose-json/**/*.kt" "tools/remote-compose-json/*.kts" - - - name: Static analysis for Kotlin (detekt, checksum-pinned, new findings only) - # Maven Central's artifact and the sha256 Central publishes for it. Pre-existing findings - # are in detekt-baseline.xml. - run: | - mkdir -p "$TOOLS_DIR" - tool="$TOOLS_DIR/detekt-cli-$DETEKT_VERSION-all.jar" - [ -f "$tool" ] || { curl -sSfL -o "$tool.part" "https://repo1.maven.org/maven2/io/gitlab/arturbosch/detekt/detekt-cli/$DETEKT_VERSION/detekt-cli-$DETEKT_VERSION-all.jar" && echo "$DETEKT_SHA256 $tool.part" | sha256sum -c - && mv "$tool.part" "$tool"; } - echo "$DETEKT_SHA256 $tool" | sha256sum -c - - java -jar "$tool" --build-upon-default-config --config detekt.yml --baseline detekt-baseline.xml --input android/src,tools/remote-compose-json/src --excludes '**/contract/**' - - - name: Format Swift (SwiftFormat --lint, checksum-pinned) - # The formatter lefthook runs before each commit, so a commit made without hooks is caught too. - run: | - mkdir -p "$TOOLS_DIR" - archive="$TOOLS_DIR/swiftformat-$SWIFTFORMAT_VERSION-linux.zip" - [ -f "$archive" ] || { curl -sSfL -o "$archive.part" "https://github.com/nicklockwood/SwiftFormat/releases/download/$SWIFTFORMAT_VERSION/swiftformat_linux.zip" && echo "$SWIFTFORMAT_SHA256 $archive.part" | sha256sum -c - && mv "$archive.part" "$archive"; } - echo "$SWIFTFORMAT_SHA256 $archive" | sha256sum -c - - unzip -q -o "$archive" -d "$RUNNER_TEMP/swiftformat" - "$RUNNER_TEMP/swiftformat/swiftformat_linux" --lint ios - - - name: Lint Swift (SwiftLint, checksum-pinned) - # The statically linked Linux build runs on this runner without a Swift toolchain. It skips - # the few rules that need SourceKit (statement_position; SwiftFormat covers that one). - run: | - mkdir -p "$TOOLS_DIR" - archive="$TOOLS_DIR/swiftlint-$SWIFTLINT_VERSION-linux-amd64.zip" - [ -f "$archive" ] || { curl -sSfL -o "$archive.part" "https://github.com/realm/SwiftLint/releases/download/$SWIFTLINT_VERSION/swiftlint_linux_amd64.zip" && echo "$SWIFTLINT_SHA256 $archive.part" | sha256sum -c - && mv "$archive.part" "$archive"; } - echo "$SWIFTLINT_SHA256 $archive" | sha256sum -c - - unzip -q -o "$archive" -d "$RUNNER_TEMP/swiftlint" - "$RUNNER_TEMP/swiftlint/swiftlint-static" lint --strict --no-cache - - - name: Save downloaded ktlint to the cache - if: always() && steps.cache-ktlint.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ env.TOOLS_DIR }}/ktlint-${{ env.KTLINT_VERSION }} - key: ci-tools-${{ runner.os }}-ktlint-${{ env.KTLINT_SHA256 }} + - name: Lint Kotlin (ktlint) + if: ${{ !cancelled() && steps.ktlint.outcome == 'success' }} + run: ktlint "android/src/**/*.kt" "!android/src/main/java/com/remotecompose/contract/**" "tools/remote-compose-json/**/*.kt" "tools/remote-compose-json/*.kts" - - name: Save downloaded detekt to the cache - if: always() && steps.cache-detekt.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ env.TOOLS_DIR }}/detekt-cli-${{ env.DETEKT_VERSION }}-all.jar - key: ci-tools-${{ runner.os }}-detekt-${{ env.DETEKT_SHA256 }} + - name: Static analysis for Kotlin (detekt, new findings only) + # Pre-existing findings are in detekt-baseline.xml. + if: ${{ !cancelled() && steps.detekt.outcome == 'success' }} + env: + DETEKT_JAR: ${{ steps.detekt.outputs.path }} + run: java -jar "$DETEKT_JAR" --build-upon-default-config --config detekt.yml --baseline detekt-baseline.xml --input android/src,tools/remote-compose-json/src --excludes '**/contract/**' - - name: Save downloaded SwiftFormat to the cache - if: always() && steps.cache-swiftformat.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ env.TOOLS_DIR }}/swiftformat-${{ env.SWIFTFORMAT_VERSION }}-linux.zip - key: ci-tools-${{ runner.os }}-swiftformat-${{ env.SWIFTFORMAT_SHA256 }} + - name: Format Swift (SwiftFormat --lint) + # The formatter lefthook runs before each commit, so a commit made without hooks is caught too. + if: ${{ !cancelled() && steps.swiftformat.outcome == 'success' }} + run: swiftformat --lint ios - - name: Save downloaded SwiftLint to the cache - if: always() && steps.cache-swiftlint.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ env.TOOLS_DIR }}/swiftlint-${{ env.SWIFTLINT_VERSION }}-linux-amd64.zip - key: ci-tools-${{ runner.os }}-swiftlint-${{ env.SWIFTLINT_SHA256 }} + - name: Lint Swift (SwiftLint) + # The static build skips the few rules that need SourceKit (statement_position; SwiftFormat + # covers that one). + if: ${{ !cancelled() && steps.swiftlint.outcome == 'success' }} + run: swiftlint lint --strict --no-cache secrets: runs-on: ubuntu-latest env: - TOOLS_DIR: /home/runner/.cache/ci-tools GITLEAKS_VERSION: 8.30.1 GITLEAKS_SHA256: 551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb @@ -188,33 +157,28 @@ jobs: with: fetch-depth: 0 # every commit, not only the tip: a secret removed later is still leaked - - name: Restore cached gitleaks - id: cache-gitleaks - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + - name: Setup Node.js (fetch-tool) + # Node only: the fetch-tool script needs no dependencies, so no yarn install here. + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: - path: ${{ env.TOOLS_DIR }}/gitleaks_${{ env.GITLEAKS_VERSION }}_linux_x64.tar.gz - key: ci-tools-${{ runner.os }}-gitleaks-${{ env.GITLEAKS_SHA256 }} + node-version-file: .nvmrc + package-manager-cache: false - - name: Scan the git history for secrets (gitleaks, checksum-pinned) + - name: Fetch gitleaks # The CLI, pinned like the other tools; gitleaks-action needs a license key on organisation repos. - run: | - mkdir -p "$TOOLS_DIR" - archive="$TOOLS_DIR/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" - [ -f "$archive" ] || { curl -sSfL -o "$archive.part" "https://github.com/gitleaks/gitleaks/releases/download/v$GITLEAKS_VERSION/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" && echo "$GITLEAKS_SHA256 $archive.part" | sha256sum -c - && mv "$archive.part" "$archive"; } - echo "$GITLEAKS_SHA256 $archive" | sha256sum -c - - tar -xzf "$archive" -C "$RUNNER_TEMP" gitleaks - # --log-opts: HEAD limits the scan to the checked-out commit's history (without it gitleaks - # runs `git log --all`, and fetch-depth 0 fetches every branch, so a key on any stale branch - # would fail every run); --diff-merges=separate also scans what a merge commit adds itself - # (a conflict resolution), which plain `git log -p` skips. - "$RUNNER_TEMP/gitleaks" git --no-banner --redact --config .gitleaks.toml --log-opts="--diff-merges=separate HEAD" . - - - name: Save downloaded gitleaks to the cache - if: always() && steps.cache-gitleaks.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + uses: ./.github/actions/fetch-tool with: - path: ${{ env.TOOLS_DIR }}/gitleaks_${{ env.GITLEAKS_VERSION }}_linux_x64.tar.gz - key: ci-tools-${{ runner.os }}-gitleaks-${{ env.GITLEAKS_SHA256 }} + name: gitleaks + url: https://github.com/gitleaks/gitleaks/releases/download/v${{ env.GITLEAKS_VERSION }}/gitleaks_${{ env.GITLEAKS_VERSION }}_linux_x64.tar.gz + sha256: ${{ env.GITLEAKS_SHA256 }} + archive-path: gitleaks + + - name: Scan the git history for secrets (gitleaks) + # --log-opts: HEAD limits the scan to the checked-out commit's history (without it gitleaks + # runs `git log --all`, and fetch-depth 0 fetches every branch, so a key on any stale branch + # would fail every run); --diff-merges=separate also scans what a merge commit adds itself + # (a conflict resolution), which plain `git log -p` skips. + run: gitleaks git --no-banner --redact --config .gitleaks.toml --log-opts="--diff-merges=separate HEAD" . supply-chain: # Google's reusable workflow (the action alone is not meant to be used directly). No SARIF @@ -237,6 +201,11 @@ jobs: native-tests: runs-on: ubuntu-latest + # The lockfile check and the Android step run even when an earlier check failed, so one run + # reports all of them; they still skip when the wrapper validation, setup or JDK did not pass + # (the JDK step runs only after both). The documents step builds and runs the converter the + # first step tests, so it keeps the default and skips after a converter failure. + steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -250,6 +219,7 @@ jobs: uses: ./.github/actions/setup - name: Install JDK + id: jdk uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: distribution: 'zulu' @@ -262,6 +232,7 @@ jobs: # The lockfiles are what OSV-Scanner (supply-chain) scans: a lock that no longer matches the # declared dependencies would hide a downgrade or a removed library and scan versions that do # not ship. Rewrite both and fail on any difference. + if: ${{ !cancelled() && steps.jdk.outcome == 'success' }} run: | tools/remote-compose-json/gradlew -p tools/remote-compose-json dependencies --write-locks --console=plain > /dev/null example/android/gradlew -p example/android :app:dependencies --configuration releaseRuntimeClasspath --write-locks --console=plain > /dev/null @@ -283,7 +254,10 @@ jobs: - name: Android unit tests (host value resolution) and Android Lint (new findings only) # Lint's pre-existing findings are in android/lint-baseline.xml. remoteComposeStrictLint makes # warnings fail here only; apps that lint the library keep lint's default (errors only). - run: example/android/gradlew -p example/android :react-native-remote-compose:testDebugUnitTest :react-native-remote-compose:lintDebug -PremoteComposeStrictLint=true --console=plain + # --continue: lint runs and reports even when a unit test fails (lint does not depend on the + # tests), and the step still fails on either. + if: ${{ !cancelled() && steps.jdk.outcome == 'success' }} + run: example/android/gradlew -p example/android :react-native-remote-compose:testDebugUnitTest :react-native-remote-compose:lintDebug -PremoteComposeStrictLint=true --continue --console=plain build-library: runs-on: ubuntu-latest @@ -325,7 +299,7 @@ jobs: TURBO_CACHE_STATUS=$(node -p "($(yarn turbo run build:android --cache-dir="${{ env.TURBO_CACHE_DIR }}" --dry=json)).tasks.filter(t => t.task === 'build:android' && t.command !== '').every(t => t.cache.status === 'HIT') ? 'HIT' : 'MISS'") if [[ $TURBO_CACHE_STATUS == "HIT" ]]; then - echo "turbo_cache_hit=1" >> $GITHUB_ENV + echo "turbo_cache_hit=1" >> "$GITHUB_ENV" fi - name: Install JDK @@ -341,7 +315,7 @@ jobs: /bin/bash -c "yes | $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --licenses > /dev/null" # The runner image can carry an incomplete NDK directory, which AGP then refuses # ("did not have a source.properties file"); install the version React Native asks for. - $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --install "ndk;27.1.12297006" > /dev/null + "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --install "ndk;27.1.12297006" > /dev/null - name: Cache Gradle @@ -392,7 +366,7 @@ jobs: TURBO_CACHE_STATUS=$(node -p "($(yarn turbo run build:ios --cache-dir="${{ env.TURBO_CACHE_DIR }}" --dry=json)).tasks.filter(t => t.task === 'build:ios' && t.command !== '').every(t => t.cache.status === 'HIT') ? 'HIT' : 'MISS'") if [[ $TURBO_CACHE_STATUS == "HIT" ]]; then - echo "turbo_cache_hit=1" >> $GITHUB_ENV + echo "turbo_cache_hit=1" >> "$GITHUB_ENV" fi - name: Use appropriate Xcode version diff --git a/scripts/__tests__/verified-download.test.ts b/scripts/__tests__/verified-download.test.ts new file mode 100644 index 0000000..8f62cd9 --- /dev/null +++ b/scripts/__tests__/verified-download.test.ts @@ -0,0 +1,237 @@ +import assert from 'node:assert/strict'; +import { execFile, execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { after, before, test } from 'node:test'; +import { promisify } from 'node:util'; +import { ensureVerifiedFile } from '../verified-download.ts'; + +const TOOL = Buffer.from('#!/bin/sh\necho pinned tool\n'); +const sha256 = (bytes: Uint8Array) => + createHash('sha256').update(bytes).digest('hex'); + +/** Paths the test server answers; every request is counted per path. */ +const routes = new Map(); +const requests = new Map(); +let server: Server; +let base: string; + +before(async () => { + server = createServer((req, res) => { + const path = req.url ?? ''; + requests.set(path, (requests.get(path) ?? 0) + 1); + const route = routes.get(path) ?? { status: 404, body: new Uint8Array() }; + res.writeHead(route.status).end(route.body); + }); + await new Promise((listening) => + server.listen(0, '127.0.0.1', listening) + ); + base = `http://127.0.0.1:${String((server.address() as AddressInfo).port)}`; +}); + +after(() => { + server.close(); +}); + +const tempDir = () => mkdtempSync(join(tmpdir(), 'rc-download-')); +const quiet = { retryDelayMs: 1, warn: () => undefined }; + +test('a missing file is downloaded, checked and written', async () => { + routes.set('/tool', { status: 200, body: TOOL }); + const file = join(tempDir(), 'nested/tool'); + const downloaded = await ensureVerifiedFile( + file, + { url: `${base}/tool`, sha256: sha256(TOOL) }, + quiet + ); + assert.equal(downloaded, true); + assert.deepEqual(readFileSync(file), TOOL); + assert.equal(existsSync(`${file}.part`), false); +}); + +test('a cached file that matches is used without a request', async () => { + routes.set('/cached', { status: 200, body: TOOL }); + const file = join(tempDir(), 'tool'); + writeFileSync(file, TOOL); + const downloaded = await ensureVerifiedFile( + file, + { url: `${base}/cached`, sha256: sha256(TOOL) }, + quiet + ); + assert.equal(downloaded, false); + assert.equal(requests.get('/cached'), undefined); +}); + +test('a corrupted cached file is reported and replaced by a verified download', async () => { + routes.set('/corrupted', { status: 200, body: TOOL }); + const file = join(tempDir(), 'tool'); + writeFileSync(file, 'truncated'); + const warnings: string[] = []; + const downloaded = await ensureVerifiedFile( + file, + { url: `${base}/corrupted`, sha256: sha256(TOOL) }, + { retryDelayMs: 1, warn: (message) => warnings.push(message) } + ); + assert.equal(downloaded, true); + assert.deepEqual(readFileSync(file), TOOL); + assert.equal(warnings.length, 1); + assert.match(warnings[0] ?? '', /downloading it again/); +}); + +test('a download that fails its checksum is refused and never written', async () => { + routes.set('/tampered', { status: 200, body: Buffer.from('tampered') }); + const file = join(tempDir(), 'tool'); + await assert.rejects( + ensureVerifiedFile( + file, + { url: `${base}/tampered`, sha256: sha256(TOOL) }, + quiet + ), + /has checksum .*, expected .*refusing to use it/ + ); + assert.equal(existsSync(file), false); + assert.equal(existsSync(`${file}.part`), false); +}); + +test('a server error is retried up to the attempt limit, a 404 is not', async () => { + routes.set('/flaky', { status: 503, body: new Uint8Array() }); + await assert.rejects( + ensureVerifiedFile( + join(tempDir(), 'tool'), + { url: `${base}/flaky`, sha256: sha256(TOOL) }, + quiet + ), + /failed after 3 tries: HTTP 503/ + ); + assert.equal(requests.get('/flaky'), 3); + + await assert.rejects( + ensureVerifiedFile( + join(tempDir(), 'tool'), + { url: `${base}/missing`, sha256: sha256(TOOL) }, + quiet + ), + /failed: HTTP 404/ + ); + assert.equal(requests.get('/missing'), 1); +}); + +test('a malformed pinned checksum is refused before any request', async () => { + await assert.rejects( + ensureVerifiedFile( + join(tempDir(), 'tool'), + { url: `${base}/never`, sha256: sha256(TOOL).toUpperCase() }, + quiet + ), + /64 lowercase hex digits/ + ); + assert.equal(requests.get('/never'), undefined); +}); + +// The CI step (scripts/fetch-tool.ts), run as the fetch-tool action runs it. Asynchronously: the +// test server runs on this process's event loop. +const FETCH_TOOL = resolve(import.meta.dirname, '../fetch-tool.ts'); + +async function fetchTool(env: Record) { + const runnerTemp = tempDir(); + const githubPath = join(runnerTemp, 'github_path'); + const githubOutput = join(runnerTemp, 'github_output'); + writeFileSync(githubPath, ''); + writeFileSync(githubOutput, ''); + await promisify(execFile)(process.execPath, [FETCH_TOOL], { + env: { + ...process.env, + RUNNER_TEMP: runnerTemp, + GITHUB_PATH: githubPath, + GITHUB_OUTPUT: githubOutput, + CACHE_FILE: join(runnerTemp, 'cache/download'), + ARCHIVE_PATH: '', + ...env, + }, + }); + return { + path: readFileSync(githubPath, 'utf8'), + output: readFileSync(githubOutput, 'utf8'), + cacheFile: join(runnerTemp, 'cache/download'), + bin: join(runnerTemp, 'tools'), + }; +} + +test('fetch-tool installs a plain download as an executable on PATH', async () => { + routes.set('/plain', { status: 200, body: TOOL }); + const result = await fetchTool({ + NAME: 'tool', + URL: `${base}/plain`, + SHA256: sha256(TOOL), + }); + const installed = join(result.bin, 'tool/bin/tool'); + assert.equal(result.path, `${join(result.bin, 'tool/bin')}\n`); + assert.equal(result.output, `path=${installed}\ndownloaded=true\n`); + assert.deepEqual(readFileSync(installed), TOOL); + assert.match(statSync(installed).mode.toString(8), /755$/); + assert.deepEqual(readFileSync(result.cacheFile), TOOL); +}); + +test('fetch-tool extracts the named file from a tar archive', async () => { + const source = tempDir(); + mkdirSync(join(source, 'dist')); + writeFileSync(join(source, 'dist/tool'), TOOL); + writeFileSync(join(source, 'README'), 'not installed'); + const archive = join(tempDir(), 'tool.tar.gz'); + execFileSync('tar', ['-czf', archive, '-C', source, 'dist', 'README']); + const bytes = readFileSync(archive); + routes.set('/archive.tar.gz', { status: 200, body: bytes }); + const result = await fetchTool({ + NAME: 'tool', + URL: `${base}/archive.tar.gz`, + SHA256: sha256(bytes), + ARCHIVE_PATH: 'dist/tool', + }); + assert.deepEqual(readFileSync(join(result.bin, 'tool/bin/tool')), TOOL); + assert.match(result.output, /downloaded=true/); +}); + +test('fetch-tool extracts the named file from a zip archive', async () => { + const source = tempDir(); + writeFileSync(join(source, 'tool_linux'), TOOL); + writeFileSync(join(source, 'LICENSE'), 'not installed'); + const archive = join(tempDir(), 'tool.zip'); + execFileSync('zip', ['-q', archive, 'tool_linux', 'LICENSE'], { + cwd: source, + }); + const bytes = readFileSync(archive); + routes.set('/archive.zip', { status: 200, body: bytes }); + const result = await fetchTool({ + NAME: 'tool', + URL: `${base}/archive.zip`, + SHA256: sha256(bytes), + ARCHIVE_PATH: 'tool_linux', + }); + assert.deepEqual(readFileSync(join(result.bin, 'tool/bin/tool')), TOOL); +}); + +test('fetch-tool refuses a download that fails its checksum and installs nothing', async () => { + routes.set('/bad', { status: 200, body: Buffer.from('tampered') }); + const runnerTemp = tempDir(); + await assert.rejects( + fetchTool({ + NAME: 'tool', + URL: `${base}/bad`, + SHA256: sha256(TOOL), + RUNNER_TEMP: runnerTemp, + }), + /refusing to use it/ + ); + assert.equal(existsSync(join(runnerTemp, 'tools')), false); +}); diff --git a/scripts/fetch-tool.ts b/scripts/fetch-tool.ts new file mode 100644 index 0000000..6a108fe --- /dev/null +++ b/scripts/fetch-tool.ts @@ -0,0 +1,95 @@ +/** + * The step of .github/actions/fetch-tool: makes the cached download hold the pinned release file + * (verified-download.ts replaces a missing or corrupted one), then installs the tool into + * $RUNNER_TEMP/tools//bin and puts that directory on the job's PATH. + * + * Inputs, as environment variables: NAME (the installed file name), URL, SHA256, ARCHIVE_PATH (the + * file inside a zip or tar archive; empty when the download is the tool itself) and CACHE_FILE + * (where the download is kept, the path actions/cache saves). Outputs, to $GITHUB_OUTPUT: `path` + * (the installed file) and `downloaded` (`true` when the cached file was missing or replaced). + */ +import { execFileSync } from 'node:child_process'; +import { + appendFileSync, + chmodSync, + copyFileSync, + mkdirSync, + openSync, + readSync, + closeSync, + renameSync, + rmSync, +} from 'node:fs'; +import { join } from 'node:path'; +import { ensureVerifiedFile } from './verified-download.ts'; + +function input(name: string, required = true): string { + // unknown: process.env's values are `any` in this repository's TypeScript program. + const raw: unknown = process.env[name]; + const value = typeof raw === 'string' ? raw : ''; + if (required && value === '') throw new Error(`${name} is not set.`); + return value; +} + +/** A zip starts with "PK"; anything else is left to tar, which detects its compression. */ +function isZip(file: string): boolean { + const fd = openSync(file, 'r'); + try { + const magic = Buffer.alloc(2); + readSync(fd, magic, 0, 2, 0); + return magic.toString('latin1') === 'PK'; + } finally { + closeSync(fd); + } +} + +const name = input('NAME'); +const archivePath = input('ARCHIVE_PATH', false); +const cacheFile = input('CACHE_FILE'); +if (!/^[A-Za-z0-9._-]+$/.test(name) || name.startsWith('.')) { + throw new Error(`NAME must be a plain file name, got '${name}'.`); +} + +const downloaded = await ensureVerifiedFile( + cacheFile, + { url: input('URL'), sha256: input('SHA256') }, + { + warn: (message) => { + console.log( + `::warning::${message} The cache entry cannot be overwritten; delete it (gh cache delete) to stop downloading on every run.` + ); + }, + } +); + +const dir = join(input('RUNNER_TEMP'), 'tools', name); +const bin = join(dir, 'bin'); +const tool = join(bin, name); +rmSync(dir, { recursive: true, force: true }); +mkdirSync(bin, { recursive: true }); +if (archivePath === '') { + copyFileSync(cacheFile, tool); +} else { + const extracted = join(dir, 'extracted'); + mkdirSync(extracted); + if (isZip(cacheFile)) { + execFileSync('unzip', ['-q', cacheFile, archivePath, '-d', extracted], { + stdio: 'inherit', + }); + } else { + execFileSync('tar', ['-xf', cacheFile, '-C', extracted, archivePath], { + stdio: 'inherit', + }); + } + renameSync(join(extracted, archivePath), tool); +} +chmodSync(tool, 0o755); + +appendFileSync(input('GITHUB_PATH'), `${bin}\n`); +appendFileSync( + input('GITHUB_OUTPUT'), + `path=${tool}\ndownloaded=${String(downloaded)}\n` +); +console.log( + `${name}: ${downloaded ? 'downloaded and verified' : 'cached copy verified'}, installed at ${tool}` +); diff --git a/scripts/lib.ts b/scripts/lib.ts index aa7ca0d..2f1e6fe 100644 --- a/scripts/lib.ts +++ b/scripts/lib.ts @@ -5,21 +5,19 @@ * failing command stops the script with a message that names the log and what to do. */ import crossSpawn from 'cross-spawn'; -import { createHash } from 'node:crypto'; import { closeSync, existsSync, - mkdirSync, openSync, readFileSync, readdirSync, rmSync, statSync, - writeFileSync, } from 'node:fs'; import { homedir } from 'node:os'; import { join, resolve } from 'node:path'; import { deflateRawSync, constants as zlib } from 'node:zlib'; +import { ensureVerifiedFile } from './verified-download.ts'; export const ROOT = resolve(import.meta.dirname, '..'); export const IS_WINDOWS = process.platform === 'win32'; @@ -225,25 +223,14 @@ const BUNDLETOOL = { sha256: 'a099cfa1543f55593bc2ed16a70a7c67fe54b1747bb7301f37fdfd6d91028e29', } as const; -/** Google's bundletool jar, downloaded once into build/tools and verified against its checksum. */ +/** Google's bundletool jar in build/tools, downloaded when missing or when it fails its checksum. */ async function bundletoolJar(): Promise { const name = `bundletool-all-${BUNDLETOOL.version}.jar`; const jar = join(ROOT, 'build/tools', name); - if (!existsSync(jar)) { - const url = `https://github.com/google/bundletool/releases/download/${BUNDLETOOL.version}/${name}`; - const response = await fetch(url); - if (!response.ok) - throw new Error(`Downloading ${url} failed: HTTP ${response.status}`); - const bytes = Buffer.from(await response.arrayBuffer()); - const digest = createHash('sha256').update(bytes).digest('hex'); - if (digest !== BUNDLETOOL.sha256) { - throw new Error( - `${url} has checksum ${digest}, expected ${BUNDLETOOL.sha256}; refusing to run it.` - ); - } - mkdirSync(join(ROOT, 'build/tools'), { recursive: true }); - writeFileSync(jar, bytes); - } + await ensureVerifiedFile(jar, { + url: `https://github.com/google/bundletool/releases/download/${BUNDLETOOL.version}/${name}`, + sha256: BUNDLETOOL.sha256, + }); return jar; } diff --git a/scripts/verified-download.ts b/scripts/verified-download.ts new file mode 100644 index 0000000..d048e0d --- /dev/null +++ b/scripts/verified-download.ts @@ -0,0 +1,100 @@ +/** + * Pinned downloads: a file fetched from a URL is used only when its SHA-256 matches the pinned one. + * The one owner of this rule for the repository scripts (bundletool in lib.ts) and CI's tools + * (fetch-tool.ts, through .github/actions/fetch-tool). No dependencies beyond Node, so a CI job can + * run it without installing node_modules. + */ +import { createHash } from 'node:crypto'; +import { + existsSync, + mkdirSync, + readFileSync, + renameSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { dirname } from 'node:path'; + +export type Pinned = { + url: string; + /** The SHA-256 of the file, from its official release: 64 lowercase hex digits. */ + sha256: string; +}; + +export type DownloadOptions = { + /** Tries per download; a 5xx, 429 or network error is retried, anything else is not. */ + attempts?: number; + /** Milliseconds before the first retry; doubled for each further one. */ + retryDelayMs?: number; + /** Where a corrupted file that is being replaced is reported. */ + warn?: (message: string) => void; +}; + +const sha256Of = (bytes: Uint8Array) => + createHash('sha256').update(bytes).digest('hex'); + +/** + * Makes `file` hold the pinned download. A file already there is kept only when its checksum + * matches; one that does not (truncated, corrupted, another version) is reported and downloaded + * again. The download is checked before it is written, and written next to `file` and renamed, so + * `file` never holds bytes that failed the check. Returns whether it downloaded. + */ +export async function ensureVerifiedFile( + file: string, + pinned: Pinned, + options: DownloadOptions = {} +): Promise { + if (!/^[0-9a-f]{64}$/.test(pinned.sha256)) { + throw new Error( + `The pinned sha256 for ${pinned.url} must be 64 lowercase hex digits, got '${pinned.sha256}'.` + ); + } + if (existsSync(file)) { + const found = sha256Of(readFileSync(file)); + if (found === pinned.sha256) return false; + (options.warn ?? console.warn)( + `${file} has checksum ${found}, expected ${pinned.sha256}; downloading it again.` + ); + rmSync(file, { force: true }); + } + const bytes = await download(pinned.url, options); + const digest = sha256Of(bytes); + if (digest !== pinned.sha256) { + throw new Error( + `${pinned.url} has checksum ${digest}, expected ${pinned.sha256}; refusing to use it.` + ); + } + mkdirSync(dirname(file), { recursive: true }); + const partial = `${file}.part`; + writeFileSync(partial, bytes); + renameSync(partial, file); + return true; +} + +async function download( + url: string, + { attempts = 3, retryDelayMs = 1000 }: DownloadOptions +): Promise { + for (let attempt = 1; ; attempt++) { + let failure: string; + try { + const response = await fetch(url); + if (response.ok) return new Uint8Array(await response.arrayBuffer()); + failure = `HTTP ${String(response.status)}`; + const retryable = response.status >= 500 || response.status === 429; + if (!retryable) throw new Error(`Downloading ${url} failed: ${failure}`); + } catch (e) { + // fetch rejects with a TypeError on a network failure; anything else is final. + if (!(e instanceof TypeError)) throw e; + failure = e.cause instanceof Error ? e.cause.message : e.message; + } + if (attempt >= attempts) { + throw new Error( + `Downloading ${url} failed after ${String(attempts)} tries: ${failure}` + ); + } + await new Promise((done) => + setTimeout(done, retryDelayMs * 2 ** (attempt - 1)) + ); + } +} From f99899fc0a03c5f8c279541d4f32f5ec86e4115f Mon Sep 17 00:00:00 2001 From: "Artem Viter (ardmn)" Date: Tue, 24 Nov 2026 15:12:47 +0400 Subject: [PATCH 3/8] refactor(lint): fix the last 43 ESLint suppressions, drop bulk suppressions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit eslint-suppressions.json counted violations per file and rule, so fixing one violation let a new one of the same rule in that file through. The 43 left after the previous commit are fixed in code, except four lines that are right as they are and now carry an inline disable with the reason: - the two Metro asset require() calls for .rc files in documents.ts (Metro bundles an asset only through require()); - the two `=== null` checks in convert.ts that the types call impossible but JavaScript callers can still reach (a test passes a null source). The fixes that change behaviour: - productCardJson is deleted: no screen used it, it stayed only behind @knipignore, and it bundled product_card.json into both demos. The JSON stays as the source of product_card.rc. pulse.json is now a typed import, not an untyped require(). - PerformanceScreen: a run that throws logs RC_PERF_FAILED and stops showing "running…", instead of an unhandled rejection; measure-perf's timeout message names that marker. - App: a failing Linking.getInitialURL() is logged instead of an unhandled rejection. - convert.ts describe(): a function is described as "a function", not printed as its source. - measure-perf reads request bodies as UTF-8 across chunk boundaries and rejects only with Errors. - generate-native-contract: an enum without values or a struct without fields throws a message instead of a non-null assertion; list errors are joined with ", ". An unused inline disable is reported and fails yarn lint (--max-warnings 0), so each one is removed together with the finding it covers. Refs ardmn/work#16 --- eslint-suppressions.json | 99 ------------------- eslint.config.mjs | 4 +- example-shared/src/App.tsx | 5 +- example-shared/src/documents.ts | 18 ++-- example-shared/src/screens/JsonScreen.tsx | 20 ++-- example-shared/src/screens/NetworkScreen.tsx | 2 +- .../src/screens/PerformanceScreen.tsx | 15 ++- scripts/generate-native-contract.ts | 29 ++++-- scripts/lib.ts | 18 ++-- scripts/measure-perf.ts | 10 +- scripts/stats.ts | 9 +- src/RemoteComposeView.native.tsx | 2 +- src/__tests__/RemoteComposeView.test.tsx | 31 +++--- src/__tests__/index.test.ts | 2 +- src/__tests__/unsupportedPlatform.test.tsx | 3 +- src/convert.ts | 20 +++- 16 files changed, 124 insertions(+), 163 deletions(-) delete mode 100644 eslint-suppressions.json diff --git a/eslint-suppressions.json b/eslint-suppressions.json deleted file mode 100644 index 0e4613c..0000000 --- a/eslint-suppressions.json +++ /dev/null @@ -1,99 +0,0 @@ -{ - "example-shared/src/App.tsx": { - "@typescript-eslint/no-floating-promises": { - "count": 1 - } - }, - "example-shared/src/documents.ts": { - "@typescript-eslint/no-require-imports": { - "count": 4 - }, - "@typescript-eslint/no-unsafe-assignment": { - "count": 4 - } - }, - "example-shared/src/screens/JsonScreen.tsx": { - "@typescript-eslint/no-misused-promises": { - "count": 1 - } - }, - "example-shared/src/screens/NetworkScreen.tsx": { - "@typescript-eslint/no-non-null-assertion": { - "count": 1 - } - }, - "example-shared/src/screens/PerformanceScreen.tsx": { - "@typescript-eslint/no-floating-promises": { - "count": 1 - }, - "@typescript-eslint/no-misused-promises": { - "count": 1 - } - }, - "scripts/generate-native-contract.ts": { - "@typescript-eslint/no-non-null-assertion": { - "count": 2 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 3 - } - }, - "scripts/lib.ts": { - "@typescript-eslint/no-non-null-assertion": { - "count": 1 - }, - "@typescript-eslint/no-unsafe-return": { - "count": 1 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 2 - } - }, - "scripts/measure-perf.ts": { - "@typescript-eslint/prefer-promise-reject-errors": { - "count": 2 - }, - "@typescript-eslint/restrict-plus-operands": { - "count": 1 - } - }, - "scripts/stats.ts": { - "@typescript-eslint/no-non-null-assertion": { - "count": 3 - } - }, - "src/RemoteComposeView.native.tsx": { - "@typescript-eslint/no-empty-object-type": { - "count": 1 - } - }, - "src/__tests__/RemoteComposeView.test.tsx": { - "@typescript-eslint/no-non-null-assertion": { - "count": 2 - }, - "@typescript-eslint/no-unsafe-assignment": { - "count": 6 - }, - "@typescript-eslint/no-unsafe-member-access": { - "count": 1 - } - }, - "src/__tests__/index.test.ts": { - "@typescript-eslint/require-await": { - "count": 1 - } - }, - "src/__tests__/unsupportedPlatform.test.tsx": { - "@typescript-eslint/no-unsafe-assignment": { - "count": 1 - } - }, - "src/convert.ts": { - "@typescript-eslint/no-base-to-string": { - "count": 1 - }, - "@typescript-eslint/no-unnecessary-condition": { - "count": 2 - } - } -} \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs index 20e6d5b..a5bc763 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -44,8 +44,8 @@ export default defineConfig([ }, }, { - // Type-aware rules for TypeScript. Findings that predate them are recorded in - // eslint-suppressions.json (ESLint bulk suppressions), so only new code has to pass. + // Type-aware rules for TypeScript. No bulk suppressions (eslint-suppressions.json): a finding + // is fixed, or disabled on its line with `-- reason`; an unused disable fails (max-warnings 0). files: ['**/*.{ts,tsx}'], extends: tseslint.configs.strictTypeChecked.map(withoutTsPlugin), languageOptions: { diff --git a/example-shared/src/App.tsx b/example-shared/src/App.tsx index 99271a1..78b3a76 100644 --- a/example-shared/src/App.tsx +++ b/example-shared/src/App.tsx @@ -65,7 +65,10 @@ export function DemoApp({ title }: { title: string }) { const launchLink: unknown = Platform.OS === 'ios' ? Settings.get('rcdemoLink') : undefined; if (typeof launchLink === 'string' && launchLink) apply(launchLink); - else Linking.getInitialURL().then(apply); + else + Linking.getInitialURL().then(apply, (error: unknown) => { + console.warn(`Could not read the launch link: ${String(error)}`); + }); const sub = Linking.addEventListener('url', ({ url }) => { apply(url); }); diff --git a/example-shared/src/documents.ts b/example-shared/src/documents.ts index edede15..60b16b1 100644 --- a/example-shared/src/documents.ts +++ b/example-shared/src/documents.ts @@ -1,16 +1,18 @@ /** * Demo documents. The JSON files are the source; `yarn documents` turns them into `.rc` with - * AndroidX's parser (tools/remote-compose-json), and both are bundled so the JSON path (Android) - * and the `.rc` path (both platforms) can be compared on the same screen. + * AndroidX's parser (tools/remote-compose-json). The `.rc` files are bundled for both platforms; + * pulse.json is bundled too, so the JSON path (Android) and the `.rc` path can be compared on the + * same screen. */ +import pulseJsonDocument from '../documents/json/pulse.json'; + +// Metro bundles a `.rc` file as an asset only through require(), which returns its asset id; the +// require() is untyped, hence the inline exceptions. +// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-assignment -- Metro asset require export const productCardRc: number = require('../documents/rc/product_card.rc'); +// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-assignment -- Metro asset require export const pulseRc: number = require('../documents/rc/pulse.rc'); -/** - * Bundled for a JSON-vs-`.rc` comparison that no screen shows yet. - * @knipignore - */ -export const productCardJson: object = require('../documents/json/product_card.json'); -export const pulseJson: object = require('../documents/json/pulse.json'); +export const pulseJson: object = pulseJsonDocument; /** Real AndroidX-captured documents, pinned to the rc-players 3.12.1 tag. */ const FIXTURES = diff --git a/example-shared/src/screens/JsonScreen.tsx b/example-shared/src/screens/JsonScreen.tsx index d3bc815..0b5915a 100644 --- a/example-shared/src/screens/JsonScreen.tsx +++ b/example-shared/src/screens/JsonScreen.tsx @@ -18,16 +18,18 @@ export function JsonScreen() { const [label, setLabel] = useState('Tap the circle'); const [status, setStatus] = useState(''); - const convert = async () => { + const convert = () => { const start = Date.now(); - try { - const base64 = await convertJsonToRc(pulseJson); - setStatus( - `converted: ${Math.floor((base64.length * 3) / 4)} bytes in ${Date.now() - start} ms` - ); - } catch (e) { - setStatus(`rejected: ${(e as Error).message}`); - } + convertJsonToRc(pulseJson).then( + (base64) => { + setStatus( + `converted: ${Math.floor((base64.length * 3) / 4)} bytes in ${Date.now() - start} ms` + ); + }, + (e: unknown) => { + setStatus(`rejected: ${e instanceof Error ? e.message : String(e)}`); + } + ); }; return ( diff --git a/example-shared/src/screens/NetworkScreen.tsx b/example-shared/src/screens/NetworkScreen.tsx index d4a2a26..ebe823e 100644 --- a/example-shared/src/screens/NetworkScreen.tsx +++ b/example-shared/src/screens/NetworkScreen.tsx @@ -11,7 +11,7 @@ export function NetworkScreen() { const [index, setIndex] = useState(0); const [lenient, setLenient] = useState(true); const [status, setStatus] = useState('loading…'); - const doc = networkDocuments[index]!; + const doc = networkDocuments[index] ?? networkDocuments[0]; const onLoad = (e: RemoteComposeLoadEvent) => { setStatus( diff --git a/example-shared/src/screens/PerformanceScreen.tsx b/example-shared/src/screens/PerformanceScreen.tsx index 9918183..1e33843 100644 --- a/example-shared/src/screens/PerformanceScreen.tsx +++ b/example-shared/src/screens/PerformanceScreen.tsx @@ -176,9 +176,18 @@ export function PerformanceScreen({ setRunning(false); }, [phase, post]); + // A run that throws would leave the screen "running…" and the benchmark script waiting for + // RC_PERF until its timeout; say why instead. + const start = useCallback(() => { + run().catch((error: unknown) => { + console.warn(`RC_PERF_FAILED ${String(error)}`); + setRunning(false); + }); + }, [run]); + useEffect(() => { - if (autorun) run(); - }, [autorun, run]); + if (autorun) start(); + }, [autorun, start]); return ( <> @@ -187,7 +196,7 @@ export function PerformanceScreen({