diff --git a/.bazelignore b/.bazelignore deleted file mode 100644 index 52ebdac6af4a..000000000000 --- a/.bazelignore +++ /dev/null @@ -1,20 +0,0 @@ -.git -dist -node_modules -packages/angular/cli/node_modules -packages/angular/create/node_modules -packages/angular/pwa/node_modules -packages/angular/build/node_modules -packages/angular/ssr/node_modules -packages/angular_devkit/architect/node_modules -packages/angular_devkit/architect_cli/node_modules -packages/angular_devkit/build_angular/node_modules -packages/angular_devkit/build_webpack/node_modules -packages/angular_devkit/core/node_modules -packages/angular_devkit/schematics/node_modules -packages/angular_devkit/schematics_cli/node_modules -packages/ngtools/webpack/node_modules -packages/schematics/angular/node_modules -modules/testing/builder/node_modules -tests/node_modules -tools/baseline_browserslist/node_modules diff --git a/.bazelrc b/.bazelrc index 4f79c86cf3b4..92e60820829a 100644 --- a/.bazelrc +++ b/.bazelrc @@ -16,6 +16,9 @@ test:debug --test_arg=--node_options=--inspect-brk --test_output=streamed --test # The below is useful to while using `fit` and `fdescribe` to avoid sharing and re-runs of failed flaky tests. test:no-sharding --flaky_test_attempts=1 --test_sharding_strategy=disabled +# Frozen lockfile +common --lockfile_mode=error + ############################### # Filesystem interactions # ############################### @@ -50,7 +53,7 @@ test --incompatible_strict_action_env build --experimental_remote_merkle_tree_cache # Ensure that tags applied in BUILDs propagate to actions -common --experimental_allow_tags_propagation +common --incompatible_allow_tags_propagation # Ensure sandboxing is enabled even for exclusive tests test --incompatible_exclusive_test_sandboxed diff --git a/.bazelversion b/.bazelversion index e8be68404bcb..f9c71a52e2fd 100644 --- a/.bazelversion +++ b/.bazelversion @@ -1 +1 @@ -7.6.1 +8.5.1 diff --git a/.github/shared-actions/windows-bazel-test/action.yml b/.github/shared-actions/windows-bazel-test/action.yml index cb72d4febd61..7a5cf7c0297b 100644 --- a/.github/shared-actions/windows-bazel-test/action.yml +++ b/.github/shared-actions/windows-bazel-test/action.yml @@ -1,78 +1,42 @@ -name: 'Native Windows Bazel e2e test' -description: 'Runs an Angular CLI e2e Bazel test on native Windows (dispatched from inside WSL)' -author: 'Angular' +name: Native Windows Bazel E2E test +description: Runs an Angular CLI e2e Bazel test on native Windows +author: Angular inputs: test_target_name: - description: E2E test target name + description: E2E test target name. required: true - test_args: - description: | - Text representing the command line arguments that - should be passed to the e2e test runner. + e2e_temp_dir: + description: 'The temporary directory path for E2E tests.' required: false - default: '' + # Use D:\\ by default as it's much faster + # See: https://devblogs.microsoft.com/commandline/share-environment-vars-between-wsl-and-windows + default: 'D:\\tmp_dir' runs: - using: composite + using: 'composite' steps: - - name: Initialize WSL - id: init_wsl - uses: angular/dev-infra/github-actions/setup-wsl@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 - with: - wsl_firewall_interface: 'vEthernet (WSL (Hyper-V firewall))' - - - name: Installing pnpm (in WSL) - run: npm install -g pnpm@9 - shell: wsl-bash {0} - - - name: Install node modules in WSL (re-using from previous install/cache restore) - run: | - cd ${{steps.init_wsl.outputs.repo_path}} - pnpm install --frozen-lockfile - shell: wsl-bash {0} - - - name: Build test binary for Windows (inside WSL) - shell: wsl-bash {0} - run: | - cd ${{steps.init_wsl.outputs.repo_path}} - pnpm bazel \ - build --config=e2e //tests/legacy-cli:${{inputs.test_target_name}} --platforms=tools:windows_x64 - env: - # See: https://devblogs.microsoft.com/commandline/share-environment-vars-between-wsl-and-windows - WSLENV: 'GOOGLE_APPLICATION_CREDENTIALS/p' - - - name: Copying binary artifact to host - shell: wsl-bash {0} + - name: Set up temp directory + shell: bash run: | - cd ${{steps.init_wsl.outputs.repo_path}} - tar -cf /tmp/test.tar.gz dist/bin/tests/legacy-cli/${{inputs.test_target_name}}_ - mkdir /mnt/c/test - mv /tmp/test.tar.gz /mnt/c/test - (cd /mnt/c/test && tar -xf /mnt/c/test/test.tar.gz) + mkdir ${{ inputs.e2e_temp_dir }} - name: Convert symlinks for Windows host - shell: wsl-bash {0} + shell: pwsh run: | - cd ${{steps.init_wsl.outputs.repo_path}} - - runfiles_dir="/mnt/c/test/dist/bin/tests/legacy-cli/${{inputs.test_target_name}}_/${{inputs.test_target_name}}.bat.runfiles" - - # Make WSL symlinks compatible on Windows native file system. - node scripts/windows-testing/convert-symlinks.mjs $runfiles_dir "${{steps.init_wsl.outputs.cmd_path}}" + $runfiles_dir = "./dist/bin/tests/${{inputs.test_target_name}}_/${{inputs.test_target_name}}.bat.runfiles" # Needed for resolution because Aspect/Bazel looks for repositories at `/external`. # TODO(devversion): consult with Aspect on why this is needed. - (cd $runfiles_dir/_main && ${{steps.init_wsl.outputs.cmd_path}} /C "mklink /D external ..") + Set-Location -Path "${runfiles_dir}\_main" + New-Item -ItemType SymbolicLink -Path "external" -Target ".." - - name: Run tests - # Note: This is Git Bash. + - name: Run CLI E2E tests shell: bash env: BAZEL_BINDIR: '.' - working-directory: "C:\\test" + E2E_TEMP: ${{ inputs.e2e_temp_dir }} run: | - node "${{github.workspace}}\\scripts\\windows-testing\\parallel-executor.mjs" \ - $PWD/dist/bin/tests/legacy-cli/${{inputs.test_target_name}}_/${{inputs.test_target_name}}.bat.runfiles \ - ${{inputs.test_target_name}} \ - "${{inputs.test_args}}" \ + node ./scripts/windows-testing/parallel-executor.mjs \ + "./dist/bin/tests/${{ inputs.test_target_name }}_/${{ inputs.test_target_name }}.bat.runfiles" \ + ${{ inputs.test_target_name }} diff --git a/.github/workflows/assistant-to-the-branch-manager.yml b/.github/workflows/assistant-to-the-branch-manager.yml index f55b9c8510c9..60208dd095ca 100644 --- a/.github/workflows/assistant-to-the-branch-manager.yml +++ b/.github/workflows/assistant-to-the-branch-manager.yml @@ -12,10 +12,11 @@ permissions: jobs: assistant_to_the_branch_manager: runs-on: ubuntu-latest + if: github.event.repository.fork == false steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 with: persist-credentials: false - - uses: angular/dev-infra/github-actions/branch-manager@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + - uses: angular/dev-infra/github-actions/branch-manager@8ce8257f740613a7291256173e2706fb2ed8aefa with: angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 882250aa1c95..3197a86069a9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,14 +21,14 @@ jobs: runs-on: ubuntu-latest steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Install node modules run: pnpm install --frozen-lockfile - name: Generate JSON schema types # Schema types are required to correctly lint the TypeScript code - run: pnpm admin build-schema + run: pnpm run build-schema - name: Run ESLint run: pnpm lint --cache-strategy content - name: Validate NgBot Configuration @@ -44,11 +44,11 @@ jobs: runs-on: ubuntu-latest steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel RBE - uses: angular/dev-infra/github-actions/bazel/configure-remote@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/configure-remote@8ce8257f740613a7291256173e2706fb2ed8aefa with: google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} - name: Install node modules @@ -58,66 +58,93 @@ jobs: test: needs: build - runs-on: ubuntu-latest-4core + runs-on: ubuntu-latest steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel RBE - uses: angular/dev-infra/github-actions/bazel/configure-remote@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/configure-remote@8ce8257f740613a7291256173e2706fb2ed8aefa with: google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} - name: Install node modules run: pnpm install --frozen-lockfile - name: Run module and package tests - run: pnpm bazel test //modules/... //packages/... - env: - ASPECT_RULES_JS_FROZEN_PNPM_LOCK: '1' + run: pnpm bazel test -- //... -//tests/... e2e: needs: test strategy: fail-fast: false matrix: - os: [ubuntu-latest] node: [20, 22, 24] - subset: [npm, esbuild] + subset: [esbuild, webpack] shard: [0, 1, 2, 3, 4, 5] - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Install node modules run: pnpm install --frozen-lockfile - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel RBE - uses: angular/dev-infra/github-actions/bazel/configure-remote@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/configure-remote@8ce8257f740613a7291256173e2706fb2ed8aefa with: google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} - name: Run CLI E2E tests - run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=6 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests/legacy-cli:e2e.${{ matrix.subset }}_node${{ matrix.node }} + run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=6 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests:e2e.${{ matrix.subset }}_node${{ matrix.node }} + + build-e2e-windows: + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@8ce8257f740613a7291256173e2706fb2ed8aefa + with: + google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Build E2E tests for Windows on Linux + run: | + pnpm bazel build \ + --config=e2e \ + //tests:e2e.webpack_node22 \ + //tests:e2e.esbuild_node22 \ + --platforms=tools:windows_x64 + - name: Store built Windows E2E tests + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 + with: + name: win-e2e-build-artifacts + path: | + dist/bin/tests/** + !**/node_modules/** + retention-days: 1 + if-no-files-found: 'error' - e2e_windows: + e2e-windows: + needs: build-e2e-windows strategy: fail-fast: false matrix: - os: [windows-2025] node: [22] - subset: [npm, esbuild] + subset: [esbuild, webpack] shard: [0, 1, 2, 3, 4, 5] - runs-on: ${{ matrix.os }} + runs-on: windows-2025 steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 - - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 - - name: Setup Bazel RBE - uses: angular/dev-infra/github-actions/bazel/configure-remote@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Download built Windows E2E tests + uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: - allow_windows_rbe: true - google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} + name: win-e2e-build-artifacts + path: dist/bin/tests/ - name: Run CLI E2E tests uses: ./.github/shared-actions/windows-bazel-test with: @@ -131,24 +158,23 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest] node: [22] - subset: [yarn, pnpm] + subset: [yarn, pnpm, bun] shard: [0, 1, 2] - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Install node modules run: pnpm install --frozen-lockfile - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel RBE - uses: angular/dev-infra/github-actions/bazel/configure-remote@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/configure-remote@8ce8257f740613a7291256173e2706fb2ed8aefa with: google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} - name: Run CLI E2E tests - run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=3 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests/legacy-cli:e2e.${{ matrix.subset }}_node${{ matrix.node }} + run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=3 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests:e2e.${{ matrix.subset }}_node${{ matrix.node }} e2e-snapshots: needs: test @@ -156,24 +182,23 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest] node: [22] - subset: [npm, esbuild] + subset: [esbuild, webpack] shard: [0, 1, 2, 3, 4, 5] - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Install node modules run: pnpm install --frozen-lockfile - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel RBE - uses: angular/dev-infra/github-actions/bazel/configure-remote@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/configure-remote@8ce8257f740613a7291256173e2706fb2ed8aefa with: google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} - name: Run CLI E2E tests - run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=6 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests/legacy-cli:e2e.snapshots.${{ matrix.subset }}_node${{ matrix.node }} + run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=6 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests:e2e.snapshots.${{ matrix.subset }}_node${{ matrix.node }} browsers: needs: build @@ -183,13 +208,13 @@ jobs: SAUCE_TUNNEL_IDENTIFIER: angular-cli-${{ github.workflow }}-${{ github.run_number }} steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Install node modules run: pnpm install --frozen-lockfile - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel RBE - uses: angular/dev-infra/github-actions/bazel/configure-remote@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/configure-remote@8ce8257f740613a7291256173e2706fb2ed8aefa with: google_credential: ${{ secrets.RBE_TRUSTED_BUILDS_USER }} - name: Run E2E Browser tests @@ -204,9 +229,9 @@ jobs: run: | ./scripts/saucelabs/start-tunnel.sh & ./scripts/saucelabs/wait-for-tunnel.sh - pnpm bazel test --config=saucelabs //tests/legacy-cli:e2e.saucelabs + pnpm bazel test --config=saucelabs //tests:e2e.saucelabs ./scripts/saucelabs/stop-tunnel.sh - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 if: ${{ failure() }} with: name: sauce-connect-log @@ -219,11 +244,11 @@ jobs: CIRCLE_BRANCH: ${{ github.ref_name }} steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Install node modules run: pnpm install --frozen-lockfile - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - run: pnpm admin snapshots --verbose env: SNAPSHOT_BUILDS_GITHUB_TOKEN: ${{ secrets.SNAPSHOT_BUILDS_GITHUB_TOKEN }} diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index f2bb3940a3b6..3932ccf6a3b8 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -19,16 +19,16 @@ jobs: fail-fast: false steps: - name: Checkout repository - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 with: persist-credentials: false - name: Initialize CodeQL - uses: github/codeql-action/init@df559355d593797519d70b90fc8edd5db049e7a2 # v3.29.9 + uses: github/codeql-action/init@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9 with: languages: javascript-typescript build-mode: none config-file: .github/codeql/config.yml - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@df559355d593797519d70b90fc8edd5db049e7a2 # v3.29.9 + uses: github/codeql-action/analyze@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9 with: category: '/language:javascript-typescript' diff --git a/.github/workflows/dev-infra.yml b/.github/workflows/dev-infra.yml index 7d8f337c4225..1e7e5cdb9bd6 100644 --- a/.github/workflows/dev-infra.yml +++ b/.github/workflows/dev-infra.yml @@ -12,14 +12,14 @@ jobs: labels: runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 - - uses: angular/dev-infra/github-actions/pull-request-labeling@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 + - uses: angular/dev-infra/github-actions/pull-request-labeling@8ce8257f740613a7291256173e2706fb2ed8aefa with: angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }} post_approval_changes: runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 - - uses: angular/dev-infra/github-actions/post-approval-changes@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 + - uses: angular/dev-infra/github-actions/post-approval-changes@8ce8257f740613a7291256173e2706fb2ed8aefa with: angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }} diff --git a/.github/workflows/feature-requests.yml b/.github/workflows/feature-requests.yml index 032707e874f5..0eff82b705ea 100644 --- a/.github/workflows/feature-requests.yml +++ b/.github/workflows/feature-requests.yml @@ -16,6 +16,6 @@ jobs: if: github.repository == 'angular/angular-cli' runs-on: ubuntu-latest steps: - - uses: angular/dev-infra/github-actions/feature-request@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + - uses: angular/dev-infra/github-actions/feature-request@8ce8257f740613a7291256173e2706fb2ed8aefa with: angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }} diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml index ea9aa9331c1d..7bd1c9b434bb 100644 --- a/.github/workflows/perf.yml +++ b/.github/workflows/perf.yml @@ -23,7 +23,7 @@ jobs: workflows: ${{ steps.workflows.outputs.workflows }} steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Install node modules run: pnpm install --frozen-lockfile - id: workflows @@ -38,16 +38,16 @@ jobs: workflow: ${{ fromJSON(needs.list.outputs.workflows) }} steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Install node modules run: pnpm install --frozen-lockfile # We utilize the google-github-actions/auth action to allow us to get an active credential using workflow # identity federation. This allows us to request short lived credentials on demand, rather than storing # credentials in secrets long term. More information can be found at: # https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-google-cloud-platform - - uses: google-github-actions/auth@b7593ed2efd1c1617e1b0254da33b86225adb2a5 # v2.1.12 + - uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0 with: project_id: 'internal-200822' workload_identity_provider: 'projects/823469418460/locations/global/workloadIdentityPools/measurables-tracking/providers/angular' diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 2adae6939dbb..cc2c80342aa9 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -20,7 +20,7 @@ jobs: outputs: snapshots: ${{ steps.filter.outputs.snapshots }} steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 with: persist-credentials: false - uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2 @@ -28,17 +28,17 @@ jobs: with: filters: | snapshots: - - 'tests/legacy-cli/e2e/ng-snapshot/package.json' + - 'tests/e2e/ng-snapshot/package.json' lint: runs-on: ubuntu-latest steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup ESLint Caching - uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4 + uses: actions/cache@9255dc7a253b0ccc959486e2bca901246202afeb # v5.0.1 with: path: .eslintcache key: ${{ runner.os }}-${{ hashFiles('.eslintrc.json') }} @@ -46,7 +46,7 @@ jobs: run: pnpm install --frozen-lockfile - name: Generate JSON schema types # Schema types are required to correctly lint the TypeScript code - run: pnpm admin build-schema + run: pnpm run build-schema - name: Run ESLint run: pnpm lint --cache-strategy content - name: Validate NgBot Configuration @@ -55,8 +55,6 @@ jobs: run: pnpm ts-circular-deps check - name: Run Validation run: pnpm admin validate - - name: Check Package Licenses - uses: angular/dev-infra/github-actions/linting/licenses@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 - name: Check tooling setup run: pnpm check-tooling-setup - name: Check commit message @@ -67,22 +65,24 @@ jobs: # Code formatting checks are only done on pull requests as its too late to validate once # it has been merged. run: pnpm ng-dev format changed --check ${{ github.event.pull_request.base.sha }} + - name: Check Package Licenses + uses: angular/dev-infra/github-actions/linting/licenses@8ce8257f740613a7291256173e2706fb2ed8aefa build: runs-on: ubuntu-latest steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel RBE - uses: angular/dev-infra/github-actions/bazel/configure-remote@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/configure-remote@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Install node modules run: pnpm install --frozen-lockfile - name: Build release targets run: pnpm ng-dev release build - name: Store PR release packages - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: name: packages path: dist/releases/*.tgz @@ -90,83 +90,108 @@ jobs: test: needs: build - runs-on: ubuntu-latest-16core + runs-on: ubuntu-latest steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel RBE - uses: angular/dev-infra/github-actions/bazel/configure-remote@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/configure-remote@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Install node modules run: pnpm install --frozen-lockfile - name: Run module and package tests - run: pnpm bazel test //modules/... //packages/... - env: - ASPECT_RULES_JS_FROZEN_PNPM_LOCK: '1' + run: pnpm bazel test -- //... -//tests/... e2e: needs: build strategy: fail-fast: false matrix: - os: [ubuntu-latest] node: [22] - subset: [npm, esbuild] + subset: [esbuild, webpack] shard: [0, 1, 2, 3, 4, 5] - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Install node modules run: pnpm install --frozen-lockfile - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel RBE - uses: angular/dev-infra/github-actions/bazel/configure-remote@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/configure-remote@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Run CLI E2E tests - run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=6 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests/legacy-cli:e2e.${{ matrix.subset }}_node${{ matrix.node }} + run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=6 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests:e2e.${{ matrix.subset }}_node${{ matrix.node }} + + build-e2e-windows-subset: + runs-on: ubuntu-latest + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa + - name: Setup Bazel + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa + - name: Setup Bazel RBE + uses: angular/dev-infra/github-actions/bazel/configure-remote@8ce8257f740613a7291256173e2706fb2ed8aefa + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Build E2E tests for Windows on Linux + run: | + pnpm bazel build \ + --config=e2e \ + //tests:e2e.esbuild_node22 \ + --platforms=tools:windows_x64 + - name: Store built Windows E2E tests + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 + with: + name: win-e2e-build-artifacts + path: | + dist/bin/tests/** + !**/node_modules/** + retention-days: 1 + if-no-files-found: 'error' - # Temporarily disabled due to https://github.com/Vampire/setup-wsl/issues/76. - # e2e-windows-subset: - # needs: build - # runs-on: windows-2025 - # steps: - # - name: Initialize environment - # uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@59c46175bf3a8870c0c2ceb9de1eb741fd50d415 - # - name: Setup Bazel - # uses: angular/dev-infra/github-actions/bazel/setup@59c46175bf3a8870c0c2ceb9de1eb741fd50d415 - # - name: Setup Bazel RBE - # uses: angular/dev-infra/github-actions/bazel/configure-remote@59c46175bf3a8870c0c2ceb9de1eb741fd50d415 - # with: - # allow_windows_rbe: true - # - name: Run CLI E2E tests - # uses: ./.github/shared-actions/windows-bazel-test - # with: - # test_target_name: e2e_node22 - # test_args: --esbuild --glob "tests/basic/{build,rebuild}.ts" + e2e-windows-subset: + needs: build-e2e-windows-subset + runs-on: windows-2025 + steps: + - name: Initialize environment + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa + - name: Install node modules + run: pnpm install --frozen-lockfile + - name: Download built Windows E2E tests + uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: win-e2e-build-artifacts + path: dist/bin/tests/ + - name: Run CLI E2E tests + uses: ./.github/shared-actions/windows-bazel-test + with: + test_target_name: e2e.esbuild_node22 + env: + E2E_SHARD_TOTAL: 1 + TESTBRIDGE_TEST_ONLY: tests/basic/{build,rebuild,serve}.ts e2e-package-managers: needs: build strategy: fail-fast: false matrix: - os: [ubuntu-latest] node: [22] - subset: [yarn, pnpm] + subset: [yarn, pnpm, bun] shard: [0, 1, 2] - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Install node modules run: pnpm install --frozen-lockfile - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel RBE - uses: angular/dev-infra/github-actions/bazel/configure-remote@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/configure-remote@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Run CLI E2E tests - run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=3 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests/legacy-cli:e2e.${{ matrix.subset }}_node${{ matrix.node }} + run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=3 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests:e2e.${{ matrix.subset }}_node${{ matrix.node }} e2e-snapshots: needs: [analyze, build] @@ -174,19 +199,18 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest] node: [22] - subset: [npm, esbuild] + subset: [esbuild, webpack] shard: [0, 1, 2, 3, 4, 5] - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Initialize environment - uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/npm/checkout-and-setup-node@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Install node modules run: pnpm install --frozen-lockfile - name: Setup Bazel - uses: angular/dev-infra/github-actions/bazel/setup@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/setup@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Setup Bazel RBE - uses: angular/dev-infra/github-actions/bazel/configure-remote@fbdd8b7df383ae8fb34907a98353c1e8f0f5e528 + uses: angular/dev-infra/github-actions/bazel/configure-remote@8ce8257f740613a7291256173e2706fb2ed8aefa - name: Run CLI E2E tests - run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=6 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests/legacy-cli:e2e.snapshots.${{ matrix.subset }}_node${{ matrix.node }} + run: pnpm bazel test --test_env=E2E_SHARD_TOTAL=6 --test_env=E2E_SHARD_INDEX=${{ matrix.shard }} --config=e2e //tests:e2e.snapshots.${{ matrix.subset }}_node${{ matrix.node }} diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index b2ed77eab147..63ad55057037 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -25,12 +25,12 @@ jobs: steps: - name: 'Checkout code' - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 with: persist-credentials: false - name: 'Run analysis' - uses: ossf/scorecard-action@05b42c624433fc40578a4040d5cf5e36ddca8cde # v2.4.2 + uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3 with: results_file: results.sarif results_format: sarif @@ -38,7 +38,7 @@ jobs: # Upload the results as artifacts. - name: 'Upload artifact' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: name: SARIF file path: results.sarif @@ -46,6 +46,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: 'Upload to code-scanning' - uses: github/codeql-action/upload-sarif@df559355d593797519d70b90fc8edd5db049e7a2 # v3.29.9 + uses: github/codeql-action/upload-sarif@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9 with: sarif_file: results.sarif diff --git a/.gitignore b/.gitignore index de3ad9a9154d..83582f8ece43 100644 --- a/.gitignore +++ b/.gitignore @@ -31,7 +31,7 @@ jsconfig.json # VSCode # https://github.com/github/gitignore/blob/master/Global/VisualStudioCode.gitignore -.vscode/ +.vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json diff --git a/.ng-dev/caretaker.mjs b/.ng-dev/caretaker.mjs index a16e023b1cd0..d21e783f4af5 100644 --- a/.ng-dev/caretaker.mjs +++ b/.ng-dev/caretaker.mjs @@ -1,6 +1,6 @@ /** * The configuration for `ng-dev caretaker` commands. - * + * * @type { import("@angular/ng-dev").CaretakerConfig } */ export const caretaker = { @@ -14,5 +14,4 @@ export const caretaker = { query: `is:pr is:open label:"action: merge-assistance"`, }, ], - caretakerGroup: 'angular-cli-caretaker', }; diff --git a/.ng-dev/commit-message.mjs b/.ng-dev/commit-message.mjs index 94fe91d8f727..d30060674355 100644 --- a/.ng-dev/commit-message.mjs +++ b/.ng-dev/commit-message.mjs @@ -1,4 +1,4 @@ -import { packages } from '../scripts/packages.mjs'; +import { packages } from '../scripts/packages.mts'; /** * The configuration for `ng-dev commit-message` commands. @@ -9,7 +9,6 @@ export const commitMessage = { maxLineLength: Infinity, minBodyLength: 0, minBodyLengthTypeExcludes: ['docs'], - disallowFixup: true, // Note: When changing this logic, also change the `contributing.ejs` file. scopes: packages.map(({ name }) => name), }; diff --git a/.ng-dev/format.mjs b/.ng-dev/format.mjs index 98115c626abd..c750eeea395c 100644 --- a/.ng-dev/format.mjs +++ b/.ng-dev/format.mjs @@ -4,8 +4,6 @@ * @type { import("@angular/ng-dev").FormatConfig } */ export const format = { - 'prettier': { - matchers: ['**/*.{mts,cts,ts,mjs,cjs,js,json,yml,yaml,md}'], - }, + 'prettier': true, 'buildifier': true, }; diff --git a/.ng-dev/github.mjs b/.ng-dev/github.mjs index 15e228fb5ae3..467741f70f83 100644 --- a/.ng-dev/github.mjs +++ b/.ng-dev/github.mjs @@ -1,7 +1,7 @@ /** * Github configuration for the ng-dev command. This repository is * used as remote for the merge script. - * + * * @type { import("@angular/ng-dev").GithubConfig } */ export const github = { @@ -9,4 +9,5 @@ export const github = { name: 'angular-cli', mainBranchName: 'main', useNgDevAuthService: true, + mergeMode: 'team-only', }; diff --git a/.ng-dev/pull-request.mjs b/.ng-dev/pull-request.mjs index 8beefa10c5fd..1f2d84d7ccba 100644 --- a/.ng-dev/pull-request.mjs +++ b/.ng-dev/pull-request.mjs @@ -1,12 +1,12 @@ /** * Configuration for the merge tool in `ng-dev`. This sets up the labels which * are respected by the merge script (e.g. the target labels). - * + * * @type { import("@angular/ng-dev").PullRequestConfig } */ export const pullRequest = { githubApiMerge: { - default: 'rebase', + default: 'auto', labels: [{ pattern: 'merge: squash commits', method: 'squash' }], }, }; diff --git a/.ng-dev/release.mjs b/.ng-dev/release.mjs index 3d097ea80b11..2aadf9db122c 100644 --- a/.ng-dev/release.mjs +++ b/.ng-dev/release.mjs @@ -1,5 +1,5 @@ import semver from 'semver'; -import { releasePackages } from '../scripts/packages.mjs'; +import { releasePackages } from '../scripts/packages.mts'; /** * Configuration for the `ng-dev release` command. @@ -12,14 +12,13 @@ export const release = { buildPackages: async () => { // The `performNpmReleaseBuild` function is loaded at runtime to avoid loading additional // files and dependencies unless a build is required. - const { performNpmReleaseBuild } = await import('../scripts/build-packages-dist.mjs'); + const { performNpmReleaseBuild } = await import('../scripts/build-packages-dist.mts'); return performNpmReleaseBuild(); }, prereleaseCheck: async (newVersionStr) => { const newVersion = new semver.SemVer(newVersionStr); - const { assertValidDependencyRanges } = await import( - '../scripts/release-checks/dependency-ranges/index.mjs' - ); + const { assertValidDependencyRanges } = + await import('../scripts/release-checks/dependency-ranges/index.mts'); await assertValidDependencyRanges(newVersion, releasePackages); }, diff --git a/.ng-dev/tsconfig.json b/.ng-dev/tsconfig.json index 9f0a0f84be18..a250849eb673 100644 --- a/.ng-dev/tsconfig.json +++ b/.ng-dev/tsconfig.json @@ -3,6 +3,9 @@ "compilerOptions": { "resolveJsonModule": true, "allowJs": true, + "rewriteRelativeImportExtensions": true, + "erasableSyntaxOnly": true, + "verbatimModuleSyntax": true, "module": "Node16", "moduleResolution": "Node16", "checkJs": true, diff --git a/.nvmrc b/.nvmrc index 91d5f6ff8e3f..85e502778f62 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -22.18.0 +22.22.0 diff --git a/.prettierignore b/.prettierignore index b0b71acaf241..1adbf7759080 100644 --- a/.prettierignore +++ b/.prettierignore @@ -11,8 +11,7 @@ /packages/schematics/angular/third_party/ /README.md /CONTRIBUTING.md -.yarn/ dist/ -/tests/legacy-cli/e2e/assets/ +/tests/e2e/assets/ /tools/test/*.json pnpm-lock.yaml diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 000000000000..6f3e0e3d3375 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,49 @@ +// A launch configuration that compiles the extension and then opens it inside a new window +{ + "version": "0.2.0", + "configurations": [ + { + "name": "DEBUG: Attach to bazel test", + "type": "node", + "request": "attach", + "port": 9229, + "restart": true, + "timeout": 600000, + "sourceMaps": true, + "skipFiles": ["/**"], + "sourceMapPathOverrides": { + "?:*@0.0.0/node_modules/@angular-devkit/build-angular/*": "${workspaceFolder}/packages/angular_devkit/build_angular/*", + "?:*@0.0.0/node_modules/@angular-devkit/build-webpack/*": "${workspaceFolder}/packages/angular_devkit/build_webpack/*", + "?:*@0.0.0/node_modules/@angular-devkit/*": "${workspaceFolder}/packages/angular_devkit/*", + "?:*@0.0.0/node_modules/@angular/*": "${workspaceFolder}/packages/angular/*", + "?:*/bin/*": "${workspaceFolder}/*" + }, + "resolveSourceMapLocations": ["*/**", "!**/rxjs**"] + }, + { + "name": "DEBUG: Run bazel test (Custom Target)", + "type": "node", + "request": "launch", + "restart": true, + "timeout": 600000, + "runtimeExecutable": "pnpm", + "runtimeArgs": ["bazel", "test", "${input:bazelTarget}", "--config=debug"], + "console": "integratedTerminal", + "cwd": "${workspaceFolder}" + } + ], + "compounds": [ + { + "name": "DEBUG: Run bazel test (Custom Target) + Attach", + "configurations": ["DEBUG: Attach to bazel test", "DEBUG: Run bazel test (Custom Target)"] + } + ], + "inputs": [ + { + "id": "bazelTarget", + "type": "promptString", + "description": "Enter the Bazel test target (e.g., //path/to/my:unit_test)", + "default": "//packages/..." + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000000..b98a874af297 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,26 @@ +{ + "[javascript]": { + "editor.formatOnSave": true + }, + "[typescript]": { + "editor.formatOnSave": true + }, + // Exclude third party modules and build artifacts from the editor watchers/searches. + "files.watcherExclude": { + "**/.git/objects/**": true, + "**/.git/subtree-cache/**": true, + "**/node_modules/**": true, + "**/bazel-out/**": true, + "**/dist/**": true, + "**/dist-schema/**": true + }, + "search.exclude": { + "**/node_modules": true, + "**/bazel-out": true, + "**/dist": true, + "**/dist-schema": true, + ".history": true + }, + "git.ignoreLimitWarning": true, + "gitlens.advanced.blame.customArguments": ["--ignore-revs-file .git-blame-ignore-revs"] +} diff --git a/BUILD.bazel b/BUILD.bazel index 9518c3a6f0bb..99bc6eb0355f 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -1,5 +1,6 @@ load("@aspect_rules_ts//ts:defs.bzl", rules_js_tsconfig = "ts_config") load("@bazel_skylib//rules:common_settings.bzl", "bool_flag") +load("@devinfra//bazel/validation:defs.bzl", "validate_ts_version_matching") load("@npm//:defs.bzl", "npm_link_all_packages") load("//tools:defaults.bzl", "copy_to_bin") @@ -18,11 +19,19 @@ exports_files([ npm_link_all_packages() +rules_js_tsconfig( + name = "tsconfig", + src = "tsconfig.json", + visibility = [ + "//:__pkg__", + ], +) + rules_js_tsconfig( name = "build-tsconfig", src = "tsconfig-build.json", deps = [ - "tsconfig.json", + ":tsconfig", "//:node_modules/@types/node", ], ) @@ -31,7 +40,7 @@ rules_js_tsconfig( name = "test-tsconfig", src = "tsconfig-test.json", deps = [ - "tsconfig.json", + ":tsconfig", "//:node_modules/@types/jasmine", "//:node_modules/@types/node", ], @@ -41,7 +50,7 @@ rules_js_tsconfig( name = "build-tsconfig-esm", src = "tsconfig-build-esm.json", deps = [ - "tsconfig.json", + ":tsconfig", ], ) @@ -94,3 +103,8 @@ config_setting( ":enable_snapshot_repo_deps": "true", }, ) + +validate_ts_version_matching( + module_lock_file = "MODULE.bazel.lock", + package_json = "package.json", +) diff --git a/CHANGELOG.md b/CHANGELOG.md index 605cddd12017..f8d16573e589 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,103 +1,830 @@ - + + +# 21.1.0 (2026-01-14) + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------------------- | +| [772e6efe7](https://github.com/angular/angular-cli/commit/772e6efe7acb2d2318a57ba77092a85fc286c51b) | feat | add 'test' and 'e2e' MCP tools | +| [8efb86318](https://github.com/angular/angular-cli/commit/8efb8631842401e219e20dd7955512d4a90a28a3) | feat | Add "all" as an experimental tool group | +| [c3c9ac506](https://github.com/angular/angular-cli/commit/c3c9ac5067275461e2d8caefba81ac9701949776) | feat | Add MCP tools for building and running devservers | +| [d635a6c63](https://github.com/angular/angular-cli/commit/d635a6c6335d0838fc0977f6742f6aa9f769c527) | feat | add signal forms lessons | +| [d8b76e93d](https://github.com/angular/angular-cli/commit/d8b76e93d3e9e4e7bd7ad6e12fdf59cd663cbb8e) | fix | correctly handle yarn classic tag manifest fetching | +| [7ab5c0b0a](https://github.com/angular/angular-cli/commit/7ab5c0b0a1c637f3e0adb71486e5e7e8716561e4) | fix | correctly spawn package managers on Windows in new abstraction | +| [348096623](https://github.com/angular/angular-cli/commit/348096623326857a5d8cf77d56712776e1190180) | fix | enhance list_projects MCP tool file system traversal and symlink handling | +| [316fca862](https://github.com/angular/angular-cli/commit/316fca8626d51b28ea8cd840f3815b7c6dfcfffa) | fix | handle array output from npm view in manifest parser | +| [032257a6d](https://github.com/angular/angular-cli/commit/032257a6d00360d2c4e6d5406409dcfa5b27d1d5) | fix | improve signal forms lesson examples in AI tutor | +| [18d74dde8](https://github.com/angular/angular-cli/commit/18d74dde8938dbe566df80753d5c148c19040179) | fix | rename mcp devserver tools to comply with naming spec | +| [1ad773671](https://github.com/angular/angular-cli/commit/1ad773671afa2849a966f9974cb30e7c8e8ed7d4) | fix | update dependency @modelcontextprotocol/sdk to v1.25.2 | +| [45d4f5668](https://github.com/angular/angular-cli/commit/45d4f5668018362f90fcc4cdc487470286f03c02) | fix | update yarn berry package manager configuration | +| [122ed27c9](https://github.com/angular/angular-cli/commit/122ed27c906613b7966cbda8fe2f36dbe6f60198) | fix | use project-local temporary directory in ng add | +| [a15db28b2](https://github.com/angular/angular-cli/commit/a15db28b29f6f43bef1ed1ca7c6a963d9943f801) | perf | cache resolved specific version in package manager abstraction | +| [240588b7e](https://github.com/angular/angular-cli/commit/240588b7e3c8698c83110793ab98d20caee4e1a4) | perf | optimize `ng add` version discovery | + +### @schematics/angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------------------- | +| [36cf3afb4](https://github.com/angular/angular-cli/commit/36cf3afb485a01f86c4c90f136b38a3cf338e313) | feat | add browserMode option to jasmine-vitest schematic | +| [e71a72ffd](https://github.com/angular/angular-cli/commit/e71a72ffdc426e26bfb4f0bb92e8f5795a621c18) | feat | generate detailed migration report for `refactor-jasmine-vitest` | +| [18cf6c51b](https://github.com/angular/angular-cli/commit/18cf6c51b72ce5c7f23012585ed992cf91cef5ed) | fix | add MCP configuration file to new workspaces | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------------------------------------------------- | +| [1eda0a99f](https://github.com/angular/angular-cli/commit/1eda0a99f89f625f8db1ecfe4873a7672e625401) | feat | directly support ng-packagr in unit-test builder | +| [87175f9dc](https://github.com/angular/angular-cli/commit/87175f9dcdb7349dc8701fa1d5cf61c1b8542d42) | feat | disable TestBed teardown during debugging in Vitest | +| [1e39c77a4](https://github.com/angular/angular-cli/commit/1e39c77a4fe272ccab1a1d8bd58eef1ce608a6c7) | fix | inject source-map-support for Vitest browser tests | +| [3fd7dcd76](https://github.com/angular/angular-cli/commit/3fd7dcd764be0d0afb9cd792d53268d6f314df83) | fix | normalize roots to POSIX in test discovery for Windows compatibility | +| [164e7dbbc](https://github.com/angular/angular-cli/commit/164e7dbbc2b06bbd5aab84937c903e0590591c60) | fix | resolve test files correctly on Windows when using non-C drives | +| [ad99e00ad](https://github.com/angular/angular-cli/commit/ad99e00ad7edd17e369777c8d38b4137ea736121) | fix | simplify SSL handling for `ng serve` with SSR ([#31722](https://github.com/angular/angular-cli/pull/31722)) | + + + + + +# 21.0.5 (2026-01-07) + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------------- | +| [249563749](https://github.com/angular/angular-cli/commit/24956374941f3753a24470bfdafaf6d3645a3ddb) | fix | use narrower types for new MCP TS SDK compatibility | + +### @schematics/angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------------------------------------------------- | +| [cbd0718b9](https://github.com/angular/angular-cli/commit/cbd0718b93c0d51331af772f578b6e0dc3dfbe9e) | fix | move 'provideZoneChangeDetection' to the root module | +| [33f7cf761](https://github.com/angular/angular-cli/commit/33f7cf761aa222e1754e039533831c729895e5e6) | fix | update application schematics for module-based apps to use 'provideZoneChangeDetection' | +| [37b14d1f7](https://github.com/angular/angular-cli/commit/37b14d1f7b18a607ada3e9a113c16f5e8a7669ef) | fix | update default app component message | +| [c37dccb09](https://github.com/angular/angular-cli/commit/c37dccb093f7b48027fac27bd78abe7f3e3e15ad) | fix | update default app component welcome message | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------------------------------- | +| [2b9be3a7c](https://github.com/angular/angular-cli/commit/2b9be3a7cadc444e67d629c2a74c54f0c65f4a54) | fix | ensure correct project targeting during Vitest debugging | + + + + + +# 20.3.14 (2026-01-07) + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------ | +| [ff366499e](https://github.com/angular/angular-cli/commit/ff366499eff87e9943e25904fd06d109a0fa0075) | fix | update dependency @modelcontextprotocol/sdk to v1.25.2 | + + + + + +# 21.0.4 (2025-12-18) + +### @schematics/angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------------- | +| [b671245b9](https://github.com/angular/angular-cli/commit/b671245b9d3ba98ac0f66dbd34f272539113be61) | fix | improve VS Code background compilation start/end detection | +| [85a28dec7](https://github.com/angular/angular-cli/commit/85a28dec771cce77a3ffee35f419b5fedca807b8) | fix | remove `inlineSources` from library tsconfig template | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------------------------------- | +| [deb4fff61](https://github.com/angular/angular-cli/commit/deb4fff6196d2eb147e358a7143e2ada2b6114c9) | fix | add browser condition to resolver for vitest | +| [570ce8d3e](https://github.com/angular/angular-cli/commit/570ce8d3eeb280eeb6dca6ba54593c9325674741) | fix | allow non-prefixed requests when using SSR and base href | +| [4dd3c1a32](https://github.com/angular/angular-cli/commit/4dd3c1a324c8e90808cc1c5febf65c8fa49dd3b9) | fix | conditionally manage Vitest UI option | +| [4b8b7caec](https://github.com/angular/angular-cli/commit/4b8b7caece41f86746321a98786dfdff499582b6) | fix | ensure tests run when compilation error is resolved | +| [bef4fcecb](https://github.com/angular/angular-cli/commit/bef4fcecb6d116f9f022da845f06708cf29be02a) | fix | remove LmdbCacheStore export from private API | + +### @angular/ssr + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------------------------------------------- | +| [bb54747da](https://github.com/angular/angular-cli/commit/bb54747da69fb15b6c2ebb52b45a83cbff3231c8) | fix | add leading slash to well-known non-Angular URLs | +| [0cfe2e749](https://github.com/angular/angular-cli/commit/0cfe2e749f50b832c64bbba322eb0cef7ad40365) | fix | propagate status code to redirect | +| [eadadb848](https://github.com/angular/angular-cli/commit/eadadb848ca7fa45c4dda835af39400e017bbe1c) | fix | skip SSR processing for well-known non-Angular URLs like favicon.ico | + + + + + +# 21.0.3 (2025-12-10) + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------------------- | +| [5d85f416f](https://github.com/angular/angular-cli/commit/5d85f416f43b6bcd07b28ab920cb40c61a83ebdd) | fix | conditionally provide Zone.js change detection in the built-in test main file | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------------------------------------------------- | +| [778b4cffc](https://github.com/angular/angular-cli/commit/778b4cffc03e7c137940e3b8c89f290fd226cf17) | fix | Add custom middleware for to present an Angular-tailored message | +| [9b02ab2ee](https://github.com/angular/angular-cli/commit/9b02ab2ee0a36aa6aafd94ea8059b48679845860) | fix | Ensure disposal of close-javascript-transformer | +| [0fc7d576e](https://github.com/angular/angular-cli/commit/0fc7d576e53f45601fdbeb95f4a853ebceae4fad) | fix | ensure locale base href retains leading slash ([#32040](https://github.com/angular/angular-cli/pull/32040)) | +| [b141670a2](https://github.com/angular/angular-cli/commit/b141670a2453dd0ea5fe6aa22ddae7175893d813) | fix | inject testing polyfills in Karma unit-test executor | +| [88c18ce68](https://github.com/angular/angular-cli/commit/88c18ce68585726652b88b10ce090039fbe1829f) | fix | support NODE_EXTRA_CA_CERTS in SSR SSL plugin | + + + + + +# 21.0.2 (2025-12-03) + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------- | +| [f1a7116cd](https://github.com/angular/angular-cli/commit/f1a7116cdff1bd83b26b0d64cea14ec4e8084583) | fix | update `@modelcontextprotocol/sdk` to v1.24.0 | + +### @angular-devkit/schematics + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------- | +| [dc6d9469e](https://github.com/angular/angular-cli/commit/dc6d9469ea494bbfee7da191774e9fa3c0baf30a) | fix | remove lazy imports in node tasks | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------------- | +| [f8a1939fd](https://github.com/angular/angular-cli/commit/f8a1939fdf5abbc1de439d288d9357d4f92a72a9) | fix | add filename truncation to test discovery | +| [86dd3297f](https://github.com/angular/angular-cli/commit/86dd3297f7ad81788713cfd8dae48c0fad4b89ab) | fix | allow overriding Vitest coverage `reportsDirectory` option | + + + + + +# 20.3.13 (2025-12-03) + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------- | +| [cfbb61602](https://github.com/angular/angular-cli/commit/cfbb61602daf32c5b942ea84702fc3638aa111e7) | fix | update `@modelcontextprotocol/sdk` to v1.24.0 | + + + + + +# 21.0.1 (2025-11-26) + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------------------------------------- | +| [363496ae0](https://github.com/angular/angular-cli/commit/363496ae0d2850545274cd7fe4dc6902ccb64e10) | fix | ensure dependencies are resolved correctly for node modules directory check | + +### @schematics/angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------------------- | +| [2f58705cb](https://github.com/angular/angular-cli/commit/2f58705cb5389019ceb49616a0e4ec3f92a558ed) | fix | add missing imports for lifecycle hooks in jasmine-vitest migration | +| [c973bb9ca](https://github.com/angular/angular-cli/commit/c973bb9cafc8d59b901a9d763347f4b615257867) | fix | add mock names to createSpyObj transformation | +| [4534c9848](https://github.com/angular/angular-cli/commit/4534c9848745eea516bdb58d86914252c35b5b9c) | fix | do not set `esModuleInterop` and `moduleResolution` when module is `preserve` | +| [16d898e75](https://github.com/angular/angular-cli/commit/16d898e7587036d68786cebe764da08304559d41) | fix | fix migration of `jasmine.clock().mockDate()` | +| [21c3eac72](https://github.com/angular/angular-cli/commit/21c3eac726c198132af760ffacc0dab9dfccb430) | fix | handle createSpyObj without base name on refactor-jasmine-vitest | +| [b8c99aa4c](https://github.com/angular/angular-cli/commit/b8c99aa4c909647285d1dcc61a2bb97a36100c63) | fix | improve safety of done callback transformation | +| [4a71e06fc](https://github.com/angular/angular-cli/commit/4a71e06fcafaadbcb820d285c0c186aa0e92f158) | fix | silently skip when the build target already uses one of the new builders | +| [2ffdae421](https://github.com/angular/angular-cli/commit/2ffdae42149b0f3da44f96271af1bca6d09b7ed5) | fix | support testRunner option in library schematic | +| [145de4a58](https://github.com/angular/angular-cli/commit/145de4a584ce8f72746704547282299306d9bafb) | fix | warn about loose matching in arrayWithExactContents | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------------------------------------- | +| [d097df2d7](https://github.com/angular/angular-cli/commit/d097df2d7088dd2bb97643c3acfc1f977a767dd9) | fix | correct Vitest coverage path resolution for JSDOM on Windows | +| [cdb607ada](https://github.com/angular/angular-cli/commit/cdb607ada4bf9aaec6ed8aafd8826d782fd13109) | fix | correctly configure per-browser headless mode in Vitest runner | +| [244931ece](https://github.com/angular/angular-cli/commit/244931ece877a1cacd1cfce64314e04a52526f80) | fix | correctly invoke `isTTY` as a function | +| [54d542738](https://github.com/angular/angular-cli/commit/54d542738e23c275ac6827f19da92213c405f9e2) | fix | ensure correct URL joining for prerender routes | +| [a28b38bbe](https://github.com/angular/angular-cli/commit/a28b38bbeba0977e99142a15d1ecc77c15abc416) | fix | force dev-server to use HTTP/1.1 when using SSR with SSL | +| [59ff867f0](https://github.com/angular/angular-cli/commit/59ff867f0d2e7f7f88480deefa0ee470c037197a) | fix | normalize `--include` paths to posix | + +### @angular/ssr + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| [03e231216](https://github.com/angular/angular-cli/commit/03e231216d3b8ba0de81da53a446eff0c701658d) | fix | handle `X-Forwarded-Prefix` and `APP_BASE_HREF` in redirects | +| [3cac01882](https://github.com/angular/angular-cli/commit/3cac0188271175e12cc238c6610b542f3ae14db3) | fix | prevent redirect loop with encoded query parameters | + + + + + +# 20.3.12 (2025-11-25) + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------- | +| [25bb7e65c](https://github.com/angular/angular-cli/commit/25bb7e65c4fc7e401c658126c53b0b7a13d62965) | fix | ensure correct URL joining for prerender routes | + +### @angular/ssr + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| [cceb86296](https://github.com/angular/angular-cli/commit/cceb862969e541a5f54b689a6439e32773eafe65) | fix | handle `X-Forwarded-Prefix` and `APP_BASE_HREF` in redirects | +| [1abe68ad8](https://github.com/angular/angular-cli/commit/1abe68ad87f9b892734117a087b5775068bd232b) | fix | prevent redirect loop with encoded query parameters | + + + + + +# 21.0.0 (2025-11-19) + +## Breaking Changes + +### @angular/cli + +- The `ng` commands will no longer automatically detect and use `cnpm` as the package manager. As an alternative use the `.npmrc` file to ensure npm uses the cnpm registry. + +### @angular/build + +- - TypeScript versions older than 5.9 are no longer supported. +- The `javascriptEnabled` option for Less is no longer supported. Projects relying on inline JavaScript within Less files will need to refactor their stylesheets to remove this dependency. + +### @schematics/angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------------ | +| [e417c89f9](https://github.com/angular/angular-cli/commit/e417c89f9e9cfe0ce50ffbc72ef555793605aea1) | feat | Add `addTypeToClassName` option to relevant schematics | +| [ede5e52bc](https://github.com/angular/angular-cli/commit/ede5e52bc701c42948bd98826cd4fa901350015c) | feat | add `include` option to jasmine-to-vitest schematic | +| [c119910f4](https://github.com/angular/angular-cli/commit/c119910f4505e280eea83ea6647b6d279a46f36d) | feat | add AGENTS.md support to ai-config schematic | +| [d0d2a17b8](https://github.com/angular/angular-cli/commit/d0d2a17b8adb2c1ce6eee70494f5d2298622c40e) | feat | add Jasmine spy API transformations to jasmine-to-vitest schematic | +| [e7d955bed](https://github.com/angular/angular-cli/commit/e7d955bedd5ca6957903cb73f8ebe06823a808da) | feat | add matcher transformations to jasmine-to-vitest schematic | +| [629f5cb18](https://github.com/angular/angular-cli/commit/629f5cb181fee562645baf02b44ebb3b39f3fb06) | feat | add misc transformations to jasmine-to-vitest schematic | +| [4912f3990](https://github.com/angular/angular-cli/commit/4912f39906b11a3212f11d5a00d577e2a0bacab4) | feat | add Tailwind CSS option to application schematic and `ng new` | +| [2a518016d](https://github.com/angular/angular-cli/commit/2a518016d9585dd4d16f90102d5409459ebba024) | feat | Applications are zoneless by default | +| [2ffc527b1](https://github.com/angular/angular-cli/commit/2ffc527b1bbe237e9f732d3506ce3a75ca1ca9d0) | feat | configure Vitest for new projects and allow runner choice | +| [58474ec7d](https://github.com/angular/angular-cli/commit/58474ec7dd85fc34639c138d9b8d545affb50e3e) | feat | introduce initial jasmine-to-vitest unit test refactor schematic | +| [9f255f2b3](https://github.com/angular/angular-cli/commit/9f255f2b3cc435f3bea2f0266a137176ca599aef) | feat | set `packageManager` in `package.json` on new projects | +| [4e6c94f21](https://github.com/angular/angular-cli/commit/4e6c94f21e882c593cf11197900c29d693af9297) | feat | support different file name style guides in `ng new` | +| [77741f5ee](https://github.com/angular/angular-cli/commit/77741f5eec735f23b0f2865101471e045e4889b8) | fix | add 'update-typescript-lib' migration | +| [f89750b27](https://github.com/angular/angular-cli/commit/f89750b27866c307da546fe4f33da980693ca5c1) | fix | add `addImports` option to jasmine-vitest schematic | +| [9dab5780a](https://github.com/angular/angular-cli/commit/9dab5780a1befbd76ee9ba4c4e6ac2d3fd714bb9) | fix | add fixture.whenStable in spec files when zoneless apps | +| [8f0f6a5f1](https://github.com/angular/angular-cli/commit/8f0f6a5f113ffc9e81d99eeeba71f8054e2d3686) | fix | add migration to update `moduleResolution` to `bundler` | +| [e8feba9ee](https://github.com/angular/angular-cli/commit/e8feba9ee163f688c51d6463336474591e886647) | fix | add missing typeSeparator to main.ts.template file | +| [515b09c4f](https://github.com/angular/angular-cli/commit/515b09c4f28ef1c2eb911cb73135a6086dcab3c9) | fix | add Vitest config generation and runner checks | +| [0e83fe1a8](https://github.com/angular/angular-cli/commit/0e83fe1a87cc3dcbc9daa4440a050ae6aafc8042) | fix | add warnings and improve Karma config generation | +| [b91fa31f2](https://github.com/angular/angular-cli/commit/b91fa31f20b49ead021c72c271f67da38b340584) | fix | align Karma project generation with unified unit-test builder | +| [c967a447c](https://github.com/angular/angular-cli/commit/c967a447ce755fbf582ec35aa24bb6e0fa0043cf) | fix | correct spacing in application spec tsconfig | +| [00d941c43](https://github.com/angular/angular-cli/commit/00d941c433de718cf3c38033d5d68dd86f790291) | fix | correct style guide paths for standalone components | +| [e33e77d12](https://github.com/angular/angular-cli/commit/e33e77d12984446fe7bc77deb7438806817ba8a7) | fix | flag '--file-name-style-guide=2016' - wrong import in main.ts | +| [f35b9f331](https://github.com/angular/angular-cli/commit/f35b9f3310995b05d501f2abaec58dcd283e3aa0) | fix | improve comment preservation in jasmine-to-vitest | +| [6615fcf03](https://github.com/angular/angular-cli/commit/6615fcf037686cd96e97b469937b7f0736afaa77) | fix | issues in apps generated with '--file-name-style-guide=2016' flag | +| [e304821d5](https://github.com/angular/angular-cli/commit/e304821d5d789fab2725d3152612d3e5b6bd0dc7) | fix | make ai-config schematic non-destructive | +| [512ad282a](https://github.com/angular/angular-cli/commit/512ad282aecbfdf1e5c9e9700cc722addb949b68) | fix | preserve blank lines in jasmine-to-vitest schematic | +| [b524ba426](https://github.com/angular/angular-cli/commit/b524ba42625cd690177a300ca4843ef4edce035f) | fix | remove empty i18n-extract target for new projects | +| [8e6e0a293](https://github.com/angular/angular-cli/commit/8e6e0a2931bfb178e77cf2c9ca7f92a56c673449) | fix | remove explicit flag for host bindings | +| [afb4d3e37](https://github.com/angular/angular-cli/commit/afb4d3e377b11315a03563cb8c143c35d37f113a) | fix | remove extra space before async in spec templates | +| [b983ea8e5](https://github.com/angular/angular-cli/commit/b983ea8e5107420a910dbbc05c6b74f0ff6fbddd) | fix | respect skip-install for tailwind schematic | +| [54c4eae2a](https://github.com/angular/angular-cli/commit/54c4eae2aa49c6b45c41f0718a5915a10d426cb4) | fix | transform Jasmine type annotations in jasmine-to-vitest schematic | +| [14c0a9bac](https://github.com/angular/angular-cli/commit/14c0a9bacbb66b1db714ea7906c7d33f49c710fc) | perf | optimize AST traversal utilities | + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------------- | +| [58d101d5e](https://github.com/angular/angular-cli/commit/58d101d5e78cf4c158dbaf52103639d56b84f9ed) | feat | add `--json` output to `ng version` | +| [d014630fa](https://github.com/angular/angular-cli/commit/d014630fad765ae3928b698122038cbe00d37102) | feat | add advanced filtering to MCP example search | +| [6d3a3c579](https://github.com/angular/angular-cli/commit/6d3a3c5799bde1bab5c3878e0783ffa6854e36ad) | feat | add ai-tutor mcp tool | +| [1c06b16a9](https://github.com/angular/angular-cli/commit/1c06b16a962d3c2cc122dc40e01c64bc8a8d754d) | feat | add builder info to `list_projects` MCP tool | +| [301b50da4](https://github.com/angular/angular-cli/commit/301b50da4cf99b3cd87940606121d076b4f241c6) | feat | add fallback support for packages without direct `ng add` functionality | +| [3040b777e](https://github.com/angular/angular-cli/commit/3040b777e40bc90fd1ed961e3d134875b3f9b464) | feat | add style language detection to list_projects tool | +| [45024e836](https://github.com/angular/angular-cli/commit/45024e836b4006cc48b18bb99d025ae1a572db12) | feat | add unit test framework detection to list_projects tool | +| [104c90768](https://github.com/angular/angular-cli/commit/104c90768000b3e0052ee7e7de2c5e04c1bffdaf) | feat | enhance `ng version` output with more details | +| [286b6204c](https://github.com/angular/angular-cli/commit/286b6204c825c990761a0d5e5b91bb439dd13655) | feat | make documentation search tool version-aware | +| [406315d09](https://github.com/angular/angular-cli/commit/406315d0939c62d9f4f39ce64b168e72bbdd588c) | feat | make find_examples tool version-aware | +| [68e711307](https://github.com/angular/angular-cli/commit/68e711307eae88a621698c2a9cc2abc30d44efc8) | feat | make get_best_practices tool version-aware | +| [50453fdee](https://github.com/angular/angular-cli/commit/50453fdeec4a00d88deada49d2dd0867bdb784fb) | feat | overhaul `ng version` command output | +| [1ee9ce3c9](https://github.com/angular/angular-cli/commit/1ee9ce3c93caff419f8095a91cf58601e3df3f74) | feat | promote MCP `find_examples` tool to a stable tool | +| [0d53e82d5](https://github.com/angular/angular-cli/commit/0d53e82d5ed8986603c2005fc06041dd076b08c6) | feat | provide detailed peer dependency conflict errors in ng add | +| [f513089e2](https://github.com/angular/angular-cli/commit/f513089e276acf5a7c4f6879a95e2d6ed78ae67d) | feat | remove direct support for `cnpm` | +| [c17d7a929](https://github.com/angular/angular-cli/commit/c17d7a929adccb77f3c2c33e70005f50032d8cae) | fix | add schema versioning and metadata to example database | +| [dbf1aaf70](https://github.com/angular/angular-cli/commit/dbf1aaf70bc3e3dd0de05d760bafacc43b34dce8) | fix | add snippet support to example search MCP tool | +| [dfb4242b3](https://github.com/angular/angular-cli/commit/dfb4242b347365f3a2c6d006f07a16c982ff4dbe) | fix | add vitest to version command output | +| [11cee1acb](https://github.com/angular/angular-cli/commit/11cee1acb59afbad1ef88d8340b5438f7dbefe57) | fix | correct boolean parsing in MCP example front matter | +| [122a8c0e2](https://github.com/angular/angular-cli/commit/122a8c0e27342db79eb4d38e23032548054709b9) | fix | correct frontmatter parsing in MCP examples tool | +| [431106559](https://github.com/angular/angular-cli/commit/431106559d6e75f5113876a3f92fdf4dc4b2114d) | fix | correct query in find_examples to prevent runtime error | +| [def412a55](https://github.com/angular/angular-cli/commit/def412a558d71cb51fa16d826418bd0ed0a085cf) | fix | enhance find_examples MCP tool with structured output | +| [0922a033f](https://github.com/angular/angular-cli/commit/0922a033f546b38f83d1cae524cf7237dd37a2ac) | fix | improve JSON schema parsing for command options | +| [f099c9157](https://github.com/angular/angular-cli/commit/f099c91570b3cd748d7138bd18a4898a345549db) | fix | improve list_projects MCP tool to find all workspaces in monorepos | +| [1be35b343](https://github.com/angular/angular-cli/commit/1be35b3433179481be85ea1cb892d66170e0aebe) | fix | promote zoneless migration MCP tool to stable | +| [e5aed6d65](https://github.com/angular/angular-cli/commit/e5aed6d655ed92ea6eb3ac03716b8a02a5f731d6) | fix | show planned actions in `ng add` dry run | +| [4deac3ec7](https://github.com/angular/angular-cli/commit/4deac3ec785b1a53156aac90441d0ed129df71ef) | fix | support multi-database search in find_examples MCP tool | +| [aeb49dd52](https://github.com/angular/angular-cli/commit/aeb49dd52bf88785a193fcb6caa0b36aaeef1d37) | perf | cache dependency lookups during `ng add` | +| [5e534090e](https://github.com/angular/angular-cli/commit/5e534090e25e00a9fafbce2867030e7fdb0efbf6) | perf | parallelize peer dependency checks in `ng add` | + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------------------------------------- | +| [6e395fc0c](https://github.com/angular/angular-cli/commit/6e395fc0c4505dd32b3237ea116e8db6bde25758) | fix | ensure vitest code coverage handles virtual files correctly | +| [53899511a](https://github.com/angular/angular-cli/commit/53899511afe5665541984085914a313390af6ce2) | fix | expand `jest` and `jest-environment-jsdom` to allow version 30 | +| [7a8c94615](https://github.com/angular/angular-cli/commit/7a8c94615164e114533fae0f84796a374dc1b47b) | fix | make zone.js optional in server and app-shell builders | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------------------------------------------------- | +| [00426e315](https://github.com/angular/angular-cli/commit/00426e3150c846913a5aa31510b5a1126df9e570) | feat | add --list-tests flag to unit-test builder | +| [a908bf3d4](https://github.com/angular/angular-cli/commit/a908bf3d4e8a59f3546f117bcc1f12fd69ad2d0b) | feat | add 'filter' option to unit-test builder | +| [3e0209d0a](https://github.com/angular/angular-cli/commit/3e0209d0a6bc6d7985d6294fc1430cdbe4d2d9a6) | feat | add `browserViewport` option for vitest browser tests | +| [3b7dabbf1](https://github.com/angular/angular-cli/commit/3b7dabbf1df9b2b6ca9ffc6c038abb6e40b6df2b) | feat | add advanced coverage options to unit-test builder | +| [c0b00d78e](https://github.com/angular/angular-cli/commit/c0b00d78ec37426f4474f473ddf9e627a0dd23df) | feat | add reporter output file option for unit-test | +| [66dd6dd83](https://github.com/angular/angular-cli/commit/66dd6dd835d6b489e6b4be2138aa443e11bfa076) | feat | allow options for unit test reporters | +| [a90bea5b5](https://github.com/angular/angular-cli/commit/a90bea5b51c6978441919ed2af85c090fe99fd38) | feat | support `.test.ts` files by default in unit test builder | +| [b2f048773](https://github.com/angular/angular-cli/commit/b2f048773c6014022983e7ccc52cb760619d8a1b) | fix | add --ui option for Vitest runner | +| [530d9270e](https://github.com/angular/angular-cli/commit/530d9270e87786594dd8d1956b0806a28650db25) | fix | add `define` option to dev-server | +| [b554bd73a](https://github.com/angular/angular-cli/commit/b554bd73a9c248d986ed718028edf52ab5da6ccf) | fix | add temporary directory cleanup for Vitest executor | +| [c6176f6df](https://github.com/angular/angular-cli/commit/c6176f6dffdae5c8d8708a1dd20fb51ca72e3c24) | fix | add upfront dependency validation for unit-test runners | +| [63c98741a](https://github.com/angular/angular-cli/commit/63c98741adcd21701b8bc572e9410cc1cf4f91c3) | fix | add webcontainer support for Vitest browser provider | +| [fcdbf6c19](https://github.com/angular/angular-cli/commit/fcdbf6c19b5a8549011aebec9e517feb12a99895) | fix | allow `globals` to be set to false | +| [542d52868](https://github.com/angular/angular-cli/commit/542d528683cc0e51fd5a55ed6dbf43168f7a51a5) | fix | allow custom runner configuration file for unit-test | +| [0505f954d](https://github.com/angular/angular-cli/commit/0505f954dcf3b3339749ff461592d46d8ecc5e23) | fix | allow unit-test progress option passthrough for building | +| [931c62d20](https://github.com/angular/angular-cli/commit/931c62d20915c6c772b61d76ab88657c0858f6bd) | fix | allow unit-test runner config with absolute path | +| [a11dd31f0](https://github.com/angular/angular-cli/commit/a11dd31f0c80a189e7dcb3172c89a731cfc34702) | fix | configure Vitest cache to use Angular cache | +| [abf003268](https://github.com/angular/angular-cli/commit/abf003268c6cb18f0944665b0b3f2794c9469c3e) | fix | correct Vitest builder watch mode execution | +| [f05ffd104](https://github.com/angular/angular-cli/commit/f05ffd104255e86fe93f3736e1430f940cb83007) | fix | correct Vitest coverage include handling for virtual files | +| [cd5c92b99](https://github.com/angular/angular-cli/commit/cd5c92b99a5d8e9cb991a2551f564353c3df0fbe) | fix | correct Vitest coverage reporting for test files | +| [07f712253](https://github.com/angular/angular-cli/commit/07f712253bb6c37d27ae7be9845f497002b0780c) | fix | correctly handle absolute paths and casing in test discovery | +| [bf468e1eb](https://github.com/angular/angular-cli/commit/bf468e1eb1050c60359b6f52692ce0db286982c2) | fix | direct check include file exists in unit-test discovery | +| [50e330d33](https://github.com/angular/angular-cli/commit/50e330d331fc8cfc4c12f7258012305ecb419d2d) | fix | disable glob directory expansion when finding tests | +| [49b65aba8](https://github.com/angular/angular-cli/commit/49b65aba8d7cd2839776e987366b981d7762760c) | fix | disable Vitest test isolation by default | +| [1529595d4](https://github.com/angular/angular-cli/commit/1529595d4a8d8ff9251d1680b1a23bf4ef817db0) | fix | drop support for TypeScript 5.8 | +| [a44f8fa94](https://github.com/angular/angular-cli/commit/a44f8fa94bbf6ce8cdee05552dc56124507c6971) | fix | dynamically select Vitest DOM environment | +| [ae35543af](https://github.com/angular/angular-cli/commit/ae35543af7f5b3a5328c39fd4617d61b48067357) | fix | enhance Vitest config merging and validation | +| [fec106b60](https://github.com/angular/angular-cli/commit/fec106b60553394aab51d713e5437a713085089b) | fix | enhance Vitest dependency externalization and pre-bundling | +| [f7c4a4c1d](https://github.com/angular/angular-cli/commit/f7c4a4c1dcd575dec82cc06597e3d6620b1be729) | fix | enhance Vitest resolution for optimal package loading | +| [ee5e127d5](https://github.com/angular/angular-cli/commit/ee5e127d551269fa9a3e39b9b28e38d7ab35806f) | fix | ensure `ɵgetOrCreateAngularServerApp` is always defined after errors | +| [0830f4fb5](https://github.com/angular/angular-cli/commit/0830f4fb549e2c45b1ef752dd42f002a1347d7c8) | fix | ensure TestBed cleanup hooks are always registered | +| [41b12509a](https://github.com/angular/angular-cli/commit/41b12509a9db8bca637e0c67d21301a75774129c) | fix | ensure TestBed setup is robust in non-isolated Vitest | +| [55145f582](https://github.com/angular/angular-cli/commit/55145f582253b4ecb47add7ff2ef459b7535dfdb) | fix | ensure Vitest setup files are executed in order | +| [3478aa332](https://github.com/angular/angular-cli/commit/3478aa332ef0241c04e7eeef9dd74b017292b2c4) | fix | exclude .angular from coverage instrumentation | +| [7c529c1bc](https://github.com/angular/angular-cli/commit/7c529c1bc606101ab8c506e0b7845d2e9f509db4) | fix | externalize Angular dependencies in Vitest runner | +| [69c3b1226](https://github.com/angular/angular-cli/commit/69c3b1226880835fd8087cea5684ababb92b1c05) | fix | improve error handling in unit-test builder | +| [bab5806c2](https://github.com/angular/angular-cli/commit/bab5806c281fd4cdd63b7969e691d703ed1e7680) | fix | introduce vitest-base.config for test configuration | +| [73621998f](https://github.com/angular/angular-cli/commit/73621998f91db189ad9b1ab006681404e30f7900) | fix | normalize paths for Vitest runner output files | +| [fa5c92346](https://github.com/angular/angular-cli/commit/fa5c92346d14a6ad03aa30ad6392fc649038605e) | fix | prioritize string type for runnerConfig schema | +| [d0787c11d](https://github.com/angular/angular-cli/commit/d0787c11d68841c36ef28bc3f15963406d1209a9) | fix | provide default excludes for vitest coverage | +| [ac10f323e](https://github.com/angular/angular-cli/commit/ac10f323ece9f4a35068e510f10786fbcb15adbb) | fix | relax requirement for files to be in TS compilation | +| [139758586](https://github.com/angular/angular-cli/commit/13975858683421a5712bbfccee57cf141a0b96f6) | fix | remove deprecated `javascriptEnabled` option for Less | +| [6576bb598](https://github.com/angular/angular-cli/commit/6576bb5985c18dca7cecd9509939c2a78bf9758a) | fix | remove explicit test isolation configuration | +| [9132e6af9](https://github.com/angular/angular-cli/commit/9132e6af9fd573d8b39c69a50b4b93e256145fd4) | fix | resolve browser provider packages using project resolver | +| [26127bd3b](https://github.com/angular/angular-cli/commit/26127bd3bb2c4b9aacf2a8f4c2cbdf732512bafb) | fix | resolve PostCSS plugins relative to config file | +| [dae732059](https://github.com/angular/angular-cli/commit/dae732059d17e9e374ac7635fbca9480751f70b3) | fix | serve build assets and styles in vitest | +| [705af2278](https://github.com/angular/angular-cli/commit/705af22788102eeade08404d357582c39de8900b) | fix | set coverage report directory to coverage/project-name | +| [0851d2eae](https://github.com/angular/angular-cli/commit/0851d2eae1e5b854a0a8a7df3a47b00693508a0f) | fix | show full aggregate errors from vitest | +| [cc2668f57](https://github.com/angular/angular-cli/commit/cc2668f5744588f9c3d847d2450dd1361e73c690) | fix | simplify SSL handling for `ng serve` with SSR ([#31723](https://github.com/angular/angular-cli/pull/31723)) | +| [907eabdd3](https://github.com/angular/angular-cli/commit/907eabdd3c7447ed2c211b6d6c2719b04443c545) | fix | support ESM PostCSS plugins | +| [62938e799](https://github.com/angular/angular-cli/commit/62938e79977d14045b7883d459d786dbb8d4d7ee) | fix | update vitest to 4.0.6 and remove coverage workaround | + + + + + +# 20.3.11 (2025-11-19) + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------------------------------------------- | +| [8053f2d92](https://github.com/angular/angular-cli/commit/8053f2d92a68a8bd01854eb81aa472249f5a83b2) | fix | ensure `ɵgetOrCreateAngularServerApp` is always defined after errors | + + + + + +# 20.3.10 (2025-11-12) + +### @schematics/angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------------- | +| [c854a719b](https://github.com/angular/angular-cli/commit/c854a719bb3a8d92fe42c8fba4b0b1789081b21c) | fix | correct `tsconfig.spec.json` include for spec files | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------------------------------------------------------------------- | +| [b3908f68e](https://github.com/angular/angular-cli/commit/b3908f68ed2f05cee56cbf0d9895dcfc3dc0ac25) | fix | do not remove `@angular/localize` when having external packages ([#31721](https://github.com/angular/angular-cli/pull/31721)) | + + + + + +# 20.3.9 (2025-11-05) + +### @angular/ssr + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------ | +| [08e07e338](https://github.com/angular/angular-cli/commit/08e07e338edd799400e18cd62cd131b6d408f4cf) | fix | improve locale handling in app-engine | +| [683697ebc](https://github.com/angular/angular-cli/commit/683697ebc5e129d2b17bded9e4ff318d598e0bd3) | fix | improve route matching for wildcard routes | + + + + + +# 20.3.8 (2025-10-29) + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------------- | +| [813cba9b9](https://github.com/angular/angular-cli/commit/813cba9b9bfe60e874595ce25608ca85a890f6bf) | fix | expand jest and jest-environment-jsdom to allow version 30 | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------------- | +| [542973ab0](https://github.com/angular/angular-cli/commit/542973ab074ccd9a5f09f73ee7f2706a21db45fc) | fix | add adapters to new reporter | +| [f0885691d](https://github.com/angular/angular-cli/commit/f0885691d18b6575351774fcc50d746d981285f6) | fix | ensure locale data plugin runs before other plugins | +| [45e498f95](https://github.com/angular/angular-cli/commit/45e498f9576ff83eebe02deb235d36498ce06bde) | fix | handle redirects from guards during prerendering | + + + + + +# 19.2.19 (2025-10-29) + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------- | +| [4d8ea27a1](https://github.com/angular/angular-cli/commit/4d8ea27a1726709b8398a26915395e7611571dae) | fix | update vite to v6.4.1 | + + + + + +# 20.3.7 (2025-10-22) + +### @angular-devkit/schematics + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------------------------------------- | +| [a31533cf4](https://github.com/angular/angular-cli/commit/a31533cf492048f62a41b9c09e53779269ee172d) | fix | respect `--force` option when schematic contains `host.create` | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------ | +| [8cdda111c](https://github.com/angular/angular-cli/commit/8cdda111cc0b343aa5eb6a7ccbad93302a543226) | fix | resolve Angular locale data namespace in esbuild | +| [5847ccc54](https://github.com/angular/angular-cli/commit/5847ccc545e54eb77a78b2435db7970faf748156) | fix | update `vite` to `7.11.1` | + +### @angular/ssr + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------- | +| [3a28fb6a1](https://github.com/angular/angular-cli/commit/3a28fb6a13061215b881c49232db979fc3c2f641) | fix | correctly handle routes with matrix parameters | +| [5db6d6487](https://github.com/angular/angular-cli/commit/5db6d64870c7ce0b883722a07c828946b7d2217d) | fix | ensure server-side navigation triggers a redirect | + + + + + +# 20.3.6 (2025-10-15) + +### @angular/ssr + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------ | +| [5271547c8](https://github.com/angular/angular-cli/commit/5271547c80662de10cb3bcb648779a83f6efedfb) | fix | prevent malicious URL from overriding host | + + + + + +# 19.2.18 (2025-10-15) + +### @angular/ssr + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------ | +| [9136a5d13](https://github.com/angular/angular-cli/commit/9136a5d1302bb224ea245460ae29474bd2a3a10b) | fix | prevent malicious URL from overriding host | + + + + + +# 20.3.5 (2025-10-08) + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------- | +| [7f7140680](https://github.com/angular/angular-cli/commit/7f7140680b75ff6b41f7f04349fe10cd928f1a23) | fix | cleanup karma temporary directory after process exit | + + -# 20.1.6 (2025-08-13) + + +# 20.3.4 (2025-10-02) ### @schematics/angular -| Commit | Type | Description | -| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------------------------------------- | -| [584bc1d41](https://github.com/angular/angular-cli/commit/584bc1d4173e7f129aa20e829f1dfb03e1e0dc9e) | fix | add extra prettier config | -| [02b0506fd](https://github.com/angular/angular-cli/commit/02b0506fde638b89510e5a78b3d190ba60a8d6ba) | fix | correct configure the `typeSeparator` in the library schematic | +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------- | +| [c94bf7ff0](https://github.com/angular/angular-cli/commit/c94bf7ff0845fe325c39737057ff1ed4ea553011) | fix | Out of the box support for PM2 | +| [465436c9f](https://github.com/angular/angular-cli/commit/465436c9fa21173befe5e39b61afb7f29435c2aa) | fix | use bracket notation for `process.env['pm_id']` | + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------- | +| [bc6b63114](https://github.com/angular/angular-cli/commit/bc6b631146c719a337c937e95c7cc5ebca29254b) | fix | mark `InjectionToken` as pure for improved tree-shaking | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------- | +| [e510ff828](https://github.com/angular/angular-cli/commit/e510ff828f033478d8e1720050a7b3d75d551e16) | fix | mark `InjectionToken` as pure for improved tree-shaking | - + -# 20.2.0-next.3 (2025-08-08) +# 20.3.3 (2025-09-24) -### @angular/cli +### @schematics/angular -| Commit | Type | Description | -| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------------------- | -| [51d56f770](https://github.com/angular/angular-cli/commit/51d56f770714a015aa7621d53c4a1634e8a01cc8) | fix | cache MCP best practices content and add tool annotations | +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------------- | +| [b7f92da78](https://github.com/angular/angular-cli/commit/b7f92da7835c14b568d07dfb3313802704f28cfd) | fix | add `__screenshots__/` to `.gitignore` | + +### @angular/ssr + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------- | +| [a4c9a2007](https://github.com/angular/angular-cli/commit/a4c9a2007ab3e33b2c97fa63f0df8f8662427031) | fix | avoid retaining rendered HTML in memory post-request | - + -# 20.1.5 (2025-08-06) +# 20.3.2 (2025-09-17) -### @angular/cli + -| Commit | Type | Description | -| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------------------- | -| [48ca04474](https://github.com/angular/angular-cli/commit/48ca044745f49bc7fc365a621827294f4cc82c50) | fix | cache MCP best practices content and add tool annotations | + + +# 19.2.17 (2025-09-17) + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------ | +| [365d525b5](https://github.com/angular/angular-cli/commit/365d525b596b437ad0b1a74b1417eaae6aa8694e) | fix | update `vite` to `6.3.6` | + + + + + +# 20.3.1 (2025-09-11) + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------------- | +| [be60be499](https://github.com/angular/angular-cli/commit/be60be4997ea0f7be3a4fb993f87b1bd29fc1493) | fix | add timestamp to bundle generation log | +| [d60f4e53d](https://github.com/angular/angular-cli/commit/d60f4e53d8f511d313e517161dc26eb3cc005f1c) | fix | update vite to version `7.1.5` | + + + + + +# 18.2.21 (2025-09-10) + +## Breaking Changes + +### @angular/ssr + +- The server-side bootstrapping process has been changed to eliminate the reliance on a global platform injector. + + Before: + + ```ts + const bootstrap = () => bootstrapApplication(AppComponent, config); + ``` + + After: + + ```ts + const bootstrap = (context: BootstrapContext) => + bootstrapApplication(AppComponent, config, context); + ``` + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------ | +| [700e6bc01](https://github.com/angular/angular-cli/commit/700e6bc0177a3e345a88e31be22496cc3054349b) | fix | avoid extra tick in SSR builds | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------- | +| [cccc91b91](https://github.com/angular/angular-cli/commit/cccc91b919b4a8365efce9ee691940e351349075) | fix | avoid extra tick in SSR dev-server builds | + +### @angular/ssr + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------- | +| [4af385201](https://github.com/angular/angular-cli/commit/4af385201bf8ba05352faec26c6efa866b69d999) | feat | introduce BootstrapContext for isolated server-side rendering | + + + + + +# 19.2.16 (2025-09-10) + +## Breaking Changes + +### @angular/ssr + +- The server-side bootstrapping process has been changed to eliminate the reliance on a global platform injector. + + Before: + + ```ts + const bootstrap = () => bootstrapApplication(AppComponent, config); + ``` + + After: + + ```ts + const bootstrap = (context: BootstrapContext) => + bootstrapApplication(AppComponent, config, context); + ``` + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------ | +| [b0f4330a9](https://github.com/angular/angular-cli/commit/b0f4330a9a2f598b71f12d07e49b6c7c6891febd) | fix | avoid extra tick in SSR builds | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------- | +| [ee5c5f823](https://github.com/angular/angular-cli/commit/ee5c5f823c87a36c9bcb92db2fc9b4e652dc16c2) | fix | avoid extra tick in SSR dev-server builds | + +### @angular/ssr + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------- | +| [32980f7e7](https://github.com/angular/angular-cli/commit/32980f7e7a5821bc9bd311dda6e134970e735722) | feat | introduce BootstrapContext for isolated server-side rendering | - + + +# 20.3.0 (2025-09-10) + +## Breaking Changes + +### @angular/ssr + +- The server-side bootstrapping process has been changed to eliminate the reliance on a global platform injector. + + Before: + + ```ts + const bootstrap = () => bootstrapApplication(AppComponent, config); + ``` + + After: + + ```ts + const bootstrap = (context: BootstrapContext) => + bootstrapApplication(AppComponent, config, context); + ``` + +### @schematics/angular -# 20.2.0-next.2 (2025-07-30) +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------- | +| [ef20a278d](https://github.com/angular/angular-cli/commit/ef20a278d1455b9cdffc5102b13d0b2206ef1ecb) | fix | align labels in ai-config schema | ### @angular/cli -| Commit | Type | Description | -| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------ | -| [193b39416](https://github.com/angular/angular-cli/commit/193b39416731fa439fea7da8c06d5d287df99bc1) | fix | skip workspace-specific tools when outside a workspace | +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------- | +| [f6ad41c13](https://github.com/angular/angular-cli/commit/f6ad41c134c7ae938ccda908967e7cc863b3db16) | fix | improve bun lockfile detection and optimize lockfile checks | + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------ | +| [1a7890873](https://github.com/angular/angular-cli/commit/1a789087344aa94d061839122e6a63efbfc9c905) | fix | avoid extra tick in SSR builds | ### @angular/build -| Commit | Type | Description | -| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------- | -| [7a183730c](https://github.com/angular/angular-cli/commit/7a183730c77689fb9e63625f5ef20aef1cefb88b) | fix | skip vite transformation of CSS-like assets | +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| [5d46d6ec1](https://github.com/angular/angular-cli/commit/5d46d6ec114052715a8bd17761a4f258961ad26b) | fix | preserve names in esbuild for improved debugging in dev mode | + +### @angular/ssr + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------- | +| [7eacb4187](https://github.com/angular/angular-cli/commit/7eacb41878f5fdac8d40aedfcca6794b77eda5ff) | feat | introduce BootstrapContext for isolated server-side rendering | - + -# 20.1.4 (2025-07-30) +# 20.2.2 (2025-09-03) ### @angular/cli | Commit | Type | Description | | --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------ | -| [2d753cc62](https://github.com/angular/angular-cli/commit/2d753cc62c9a801c40923a43e4af5f74b22700e0) | fix | skip workspace-specific tools when outside a workspace | +| [a793bbc47](https://github.com/angular/angular-cli/commit/a793bbc473dfaddf3fe6ed15805dc4fc84f52865) | fix | don't set a default for array options when length is 0 | +| [2736599e2](https://github.com/angular/angular-cli/commit/2736599e2f6c61032810d8e336c1646db4066392) | fix | set process title when running architect commands | ### @angular/build -| Commit | Type | Description | -| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------- | -| [42d72ef4d](https://github.com/angular/angular-cli/commit/42d72ef4d99380dbb1c0e03e3e3abfb2223fa539) | fix | skip vite transformation of CSS-like assets | +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------ | +| [5c2abffea](https://github.com/angular/angular-cli/commit/5c2abffea6cf3f672ee256a944dba56dd257665b) | fix | avoid extra tick in SSR dev-server builds | +| [f3c826853](https://github.com/angular/angular-cli/commit/f3c826853501c9cf6d07a1c8ee3363eb79f53005) | fix | maintain media output hashing with vitest unit-testing | - + -# 20.1.3 (2025-07-24) +# 20.2.1 (2025-08-27) + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------- | +| [3b693e09e](https://github.com/angular/angular-cli/commit/3b693e09e8148ef22031aab8f6bc70c928aabc03) | fix | correctly set default array values | + +### @schematics/angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------------------------------ | +| [6937123a3](https://github.com/angular/angular-cli/commit/6937123a393e2ba9221962b0174056c14437a988) | fix | directly resolve karma config template in migration | +| [5d6dd4425](https://github.com/angular/angular-cli/commit/5d6dd44259a0d89098c2a0c784e726b43ce32316) | fix | prevent AI config schematic from failing when 'none' and other AI tools are selected | + +### @angular-devkit/schematics-cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------- | +| [e93919dea](https://github.com/angular/angular-cli/commit/e93919dea7df55a3aac2fa5c93c4560c50a2d749) | fix | correctly set default array values | ### @angular/build -| Commit | Type | Description | -| --------------------------------------------------------------------------------------------------- | ---- | ------------------------ | -| [ea5cd0e81](https://github.com/angular/angular-cli/commit/ea5cd0e81196467ea66f50c106cffec1cd8a1a56) | fix | update `vite` to `7.0.6` | +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------- | +| [06a6ddc10](https://github.com/angular/angular-cli/commit/06a6ddc102f5dc9018ec982f6e4cf56259cc4b52) | fix | correct JS/TS file paths when running under Bazel | +| [b6816b0cb](https://github.com/angular/angular-cli/commit/b6816b0cbaf1262d7015b9d7f7fb425f53995947) | fix | ensure karma polyfills reporter factory returns a value | - + -# 20.2.0-next.1 (2025-07-23) +# 20.2.0 (2025-08-20) ### @angular/cli -| Commit | Type | Description | -| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------- | -| [fefa7a46f](https://github.com/angular/angular-cli/commit/fefa7a46f5733fd77852a61fddc3120b1bb4b202) | fix | `define` option is being included multiple times in the JSON help | +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------------------------------- | +| [b4de9a1bf](https://github.com/angular/angular-cli/commit/b4de9a1bf50a35404fb79eb3f120faafd0ce825a) | feat | add --experimental-tool option to mcp command | +| [755ba70fd](https://github.com/angular/angular-cli/commit/755ba70fd7ef38793d15797ba402020c375c3295) | feat | add --local-only option to mcp command | +| [59d7ef343](https://github.com/angular/angular-cli/commit/59d7ef343b6f1feea37a019935578c560d3d5e41) | feat | add --read-only option to mcp command | +| [4e92eb6f1](https://github.com/angular/angular-cli/commit/4e92eb6f17cb30259bc8e8d1979bbd9989bc5ad0) | feat | add modernize tool to the MCP server | +| [a3b25f675](https://github.com/angular/angular-cli/commit/a3b25f675283fdd8cc5689e3ec88f27aa1386390) | fix | add choices to command line parser when type is array and has an enum | +| [e19eee614](https://github.com/angular/angular-cli/commit/e19eee61404a9ca6268ebbc69f671a422d81df9b) | fix | address Node.js deprecation DEP0190 | +| [4ee6f327a](https://github.com/angular/angular-cli/commit/4ee6f327a206f8ff2ad5eeab43193df56b92b5e0) | fix | apply default to array types | +| [8ba6b0bcc](https://github.com/angular/angular-cli/commit/8ba6b0bcc8c8087875d14a0aefc6b7b52f39ce2a) | fix | use correct path for MCP get_best_practices tool | -### @angular-devkit/core +### @schematics/angular -| Commit | Type | Description | -| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------------------- | -| [7595e1f88](https://github.com/angular/angular-cli/commit/7595e1f8887bafd344ec939e647e3fca8bbd98be) | fix | use crypto.randomUUID instead of Date.now for unique string in tmp file names | +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------------- | +| [2e3cfd598](https://github.com/angular/angular-cli/commit/2e3cfd598c9366d0036a52cd18024317b33e6fca) | feat | add migration to remove default Karma configurations | +| [d80dae276](https://github.com/angular/angular-cli/commit/d80dae276e9554c13e0c37640d0db8acafc9d48b) | feat | add schematics to generate ai context files. | +| [ffe6fb916](https://github.com/angular/angular-cli/commit/ffe6fb916d496da1c6c20942f6e6b05a679b0f7d) | fix | allow AI config prompt to be skipped without selecting a value | +| [ae2802b7d](https://github.com/angular/angular-cli/commit/ae2802b7db358c5a3f0590feea212a768a710353) | fix | improve AI config prompt wording | +| [b017f84fd](https://github.com/angular/angular-cli/commit/b017f84fdaf36bc0fcad2241846665c73b52b6d8) | fix | improve coverage directory handling for Karma configuration comparisons | +| [6a79f9a75](https://github.com/angular/angular-cli/commit/6a79f9a75cdcbb0761c4044066748f4eb788a57f) | fix | zoneless is now stable | + +### @angular-devkit/schematics + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------- | +| [c43504d8d](https://github.com/angular/angular-cli/commit/c43504d8d96a4436ce71c23d957aec2d080106b8) | fix | address Node.js deprecation DEP0190 | ### @angular/build @@ -107,6 +834,61 @@ + + +# 20.1.6 (2025-08-13) + +### @schematics/angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------------------------------------- | +| [584bc1d41](https://github.com/angular/angular-cli/commit/584bc1d4173e7f129aa20e829f1dfb03e1e0dc9e) | fix | add extra prettier config | +| [02b0506fd](https://github.com/angular/angular-cli/commit/02b0506fde638b89510e5a78b3d190ba60a8d6ba) | fix | correct configure the `typeSeparator` in the library schematic | + + + + + +# 20.1.5 (2025-08-06) + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------------------- | +| [48ca04474](https://github.com/angular/angular-cli/commit/48ca044745f49bc7fc365a621827294f4cc82c50) | fix | cache MCP best practices content and add tool annotations | + + + + + +# 20.1.4 (2025-07-30) + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------ | +| [2d753cc62](https://github.com/angular/angular-cli/commit/2d753cc62c9a801c40923a43e4af5f74b22700e0) | fix | skip workspace-specific tools when outside a workspace | + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------- | +| [42d72ef4d](https://github.com/angular/angular-cli/commit/42d72ef4d99380dbb1c0e03e3e3abfb2223fa539) | fix | skip vite transformation of CSS-like assets | + + + + + +# 20.1.3 (2025-07-24) + +### @angular/build + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------ | +| [ea5cd0e81](https://github.com/angular/angular-cli/commit/ea5cd0e81196467ea66f50c106cffec1cd8a1a56) | fix | update `vite` to `7.0.6` | + + + # 20.1.2 (2025-07-23) @@ -125,12 +907,6 @@ - - -# 20.2.0-next.0 (2025-07-16) - - - # 20.1.1 (2025-07-16) @@ -4222,6 +4998,7 @@ Alan Agius, Charles Lyding, Doug Parker, Joey Perrott and Piotr Wysocki ```scss @import 'font-awesome/scss/font-awesome'; ``` + - By default the CLI will use Sass modern API, While not recommended, users can still opt to use legacy API by setting `NG_BUILD_LEGACY_SASS=1`. - Internally the Angular CLI now always set the TypeScript `target` to `ES2022` and `useDefineForClassFields` to `false` unless the target is set to `ES2022` or later in the TypeScript configuration. To control ECMA version and features use the Browerslist configuration. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0642e0b7ff65..06db9756c89d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -294,22 +294,10 @@ changes to be accepted, the CLA must be signed. It's a quick process, we promise [coc]: https://github.com/angular/code-of-conduct/blob/main/CODE_OF_CONDUCT.md [commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit# [corporate-cla]: https://code.google.com/legal/corporate-cla-v1.0.html -[dev-doc]: https://github.com/angular/angular-cli/blob/main/packages/angular/cli/README.md#development-hints-for-working-on-angular-cli +[dev-doc]: https://github.com/angular/angular-cli/blob/main/docs/DEVELOPER.md [GitHub]: https://github.com/angular/angular-cli [gitter]: https://gitter.im/angular/angular-cli [individual-cla]: https://code.google.com/legal/individual-cla-v1.0.html [js-style-guide]: https://google.github.io/styleguide/jsguide.html [stackoverflow]: https://stackoverflow.com/questions/tagged/angular-devkit -## Updating the Public API -Our Public API surface is tracked using golden files. - -You check all golden files by running: -```bash -pnpm public-api:check -``` - -If you modified the public API, the test will fail. To update the golden files you need to run: -```bash -pnpm public-api:update -``` diff --git a/LICENSE b/LICENSE index 48adc1eb1829..5ec8e26b9eec 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License -Copyright (c) 2010-2025 Google LLC. https://angular.dev/license +Copyright (c) 2010-2026 Google LLC. https://angular.dev/license Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/MODULE.bazel b/MODULE.bazel index f90ed9010d4c..9afa261507e6 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,5 +1,184 @@ -# TODO(devversion): Investigate bzlmod and use it where possible. +"""Rules/toolchains for angular_cli with Bazel.""" module( name = "angular_cli", ) + +bazel_dep(name = "platforms", version = "1.0.0") +bazel_dep(name = "yq.bzl", version = "0.3.4") +bazel_dep(name = "rules_nodejs", version = "6.6.2") +bazel_dep(name = "aspect_rules_js", version = "2.8.3") +bazel_dep(name = "aspect_rules_ts", version = "3.8.1") +bazel_dep(name = "rules_pkg", version = "1.2.0") +bazel_dep(name = "rules_cc", version = "0.2.16") +bazel_dep(name = "aspect_bazel_lib", version = "2.22.2") +bazel_dep(name = "bazel_skylib", version = "1.9.0") +bazel_dep(name = "aspect_rules_esbuild", version = "0.25.0") +bazel_dep(name = "aspect_rules_jasmine", version = "2.0.2") +bazel_dep(name = "rules_angular") +git_override( + module_name = "rules_angular", + commit = "7133b97252508f8528e5c5818a9a73cacc2e2a0e", + remote = "https://github.com/devversion/rules_angular.git", +) + +bazel_dep(name = "devinfra") +git_override( + module_name = "devinfra", + commit = "8ce8257f740613a7291256173e2706fb2ed8aefa", + remote = "https://github.com/angular/dev-infra.git", +) + +bazel_dep(name = "rules_sass") +git_override( + module_name = "rules_sass", + commit = "1184a80751a21af8348f308abc5b38a41f26850e", + remote = "https://github.com/devversion/rules_sass.git", +) + +bazel_dep(name = "rules_browsers") +git_override( + module_name = "rules_browsers", + commit = "5f0e50d17d15c70e6ab5546f1659338ae94c4072", + remote = "https://github.com/devversion/rules_browsers.git", +) + +node = use_extension("@rules_nodejs//nodejs:extensions.bzl", "node") +node.toolchain( + node_repositories = { + "22.22.0-darwin_arm64": ("node-v22.22.0-darwin-arm64.tar.gz", "node-v22.22.0-darwin-arm64", "5ed4db0fcf1eaf84d91ad12462631d73bf4576c1377e192d222e48026a902640"), + "22.22.0-darwin_amd64": ("node-v22.22.0-darwin-x64.tar.gz", "node-v22.22.0-darwin-x64", "5ea50c9d6dea3dfa3abb66b2656f7a4e1c8cef23432b558d45fb538c7b5dedce"), + "22.22.0-linux_arm64": ("node-v22.22.0-linux-arm64.tar.xz", "node-v22.22.0-linux-arm64", "1bf1eb9ee63ffc4e5d324c0b9b62cf4a289f44332dfef9607cea1a0d9596ba6f"), + "22.22.0-linux_ppc64le": ("node-v22.22.0-linux-ppc64le.tar.xz", "node-v22.22.0-linux-ppc64le", "d83b9957431cc18e1fc143a4b99f89cde7b8a18f53ef392231b4336afd058865"), + "22.22.0-linux_s390x": ("node-v22.22.0-linux-s390x.tar.xz", "node-v22.22.0-linux-s390x", "5aa0e520689448c4233e8d73f284e8e0634fdcd32b479735698494be5641f3e4"), + "22.22.0-linux_amd64": ("node-v22.22.0-linux-x64.tar.xz", "node-v22.22.0-linux-x64", "9aa8e9d2298ab68c600bd6fb86a6c13bce11a4eca1ba9b39d79fa021755d7c37"), + "22.22.0-windows_amd64": ("node-v22.22.0-win-x64.zip", "node-v22.22.0-win-x64", "c97fa376d2becdc8863fcd3ca2dd9a83a9f3468ee7ccf7a6d076ec66a645c77a"), + }, + node_version = "22.22.0", +) +use_repo( + node, + "nodejs_darwin_amd64", + "nodejs_darwin_arm64", + "nodejs_linux_amd64", + "nodejs_linux_arm64", + "nodejs_toolchains", + "nodejs_windows_amd64", +) + +node_dev = use_extension("@rules_nodejs//nodejs:extensions.bzl", "node", dev_dependency = True) + +# Node.js 20 +node_dev.toolchain( + name = "node20", + node_version = "20.19.0", +) + +# Node.js 22 +node_dev.toolchain( + name = "node22", + node_version = "22.12.0", +) + +# Node.js 24 +node_dev.toolchain( + name = "node24", + node_version = "24.0.0", +) +use_repo( + node_dev, + "node20_darwin_amd64", + "node20_darwin_arm64", + "node20_linux_amd64", + "node20_linux_arm64", + "node20_toolchains", + "node20_windows_amd64", + "node22_darwin_amd64", + "node22_darwin_arm64", + "node22_linux_amd64", + "node22_linux_arm64", + "node22_toolchains", + "node22_windows_amd64", + "node24_darwin_amd64", + "node24_darwin_arm64", + "node24_linux_amd64", + "node24_linux_arm64", + "node24_toolchains", + "node24_windows_amd64", +) + +pnpm = use_extension("@aspect_rules_js//npm:extensions.bzl", "pnpm") +pnpm.pnpm( + name = "pnpm", + pnpm_version = "10.28.0", + pnpm_version_integrity = "sha512-Bd9x0UIfITmeBT/eVnzqNNRG+gLHZXFEG/wceVbpjjYwiJgtlARl/TRIDU2QoGaLwSNi+KqIAApk6D0LDke+SA==", +) +use_repo(pnpm, "pnpm") + +npm = use_extension("@aspect_rules_js//npm:extensions.bzl", "npm") +npm.npm_translate_lock( + name = "npm", + custom_postinstalls = { + # TODO: Standardize browser management for `rules_js` + "webdriver-manager": "node ./bin/webdriver-manager update --standalone false --gecko false --versions.chrome 106.0.5249.21", + }, + data = [ + "//:package.json", + "//:pnpm-workspace.yaml", + "//modules/testing/builder:package.json", + "//packages/angular/build:package.json", + "//packages/angular/cli:package.json", + "//packages/angular/create/package.json", + "//packages/angular/pwa:package.json", + "//packages/angular/ssr:package.json", + "//packages/angular_devkit/architect:package.json", + "//packages/angular_devkit/architect_cli:package.json", + "//packages/angular_devkit/build_angular:package.json", + "//packages/angular_devkit/build_webpack:package.json", + "//packages/angular_devkit/core:package.json", + "//packages/angular_devkit/schematics:package.json", + "//packages/angular_devkit/schematics_cli:package.json", + "//packages/ngtools/webpack:package.json", + "//packages/schematics/angular:package.json", + "//tests:package.json", + ], + lifecycle_hooks_envs = { + # TODO: Standardize browser management for `rules_js` + "puppeteer": ["PUPPETEER_DOWNLOAD_PATH=./downloads"], + }, + lifecycle_hooks_execution_requirements = { + # Needed for downloading chromedriver. + # Also `update-config` of webdriver manager would store an absolute path; + # which would then break execution. + "webdriver-manager": ["local"], + }, + npmrc = "//:.npmrc", + pnpm_lock = "//:pnpm-lock.yaml", +) +use_repo(npm, "npm") + +rules_ts_ext = use_extension("@aspect_rules_ts//ts:extensions.bzl", "ext") +rules_ts_ext.deps( + name = "angular_cli_npm_typescript", + # Obtained by: npm info typescript@5.9.3 dist.integrity + ts_integrity = "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + ts_version = "5.9.3", +) +use_repo(rules_ts_ext, **{"npm_typescript": "angular_cli_npm_typescript"}) + +rules_angular = use_extension("@rules_angular//setup:extensions.bzl", "rules_angular") +rules_angular.setup( + name = "components_rules_angular_configurable_deps", + angular_compiler_cli = "//:node_modules/@angular/compiler-cli", + typescript = "//:node_modules/typescript", +) +use_repo(rules_angular, **{"rules_angular_configurable_deps": "components_rules_angular_configurable_deps"}) + +register_toolchains( + "@devinfra//bazel/git-toolchain:git_linux_toolchain", + "@devinfra//bazel/git-toolchain:git_macos_x86_toolchain", + "@devinfra//bazel/git-toolchain:git_macos_arm64_toolchain", + "@devinfra//bazel/git-toolchain:git_windows_toolchain", + "//tools/toolchains:dummy_cc_windows_no_exec_toolchain", + "//tools/toolchains:node22_windows_no_exec_toolchain", +) diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 3137c9f1d3fc..f6759b68854e 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -1,110 +1,4758 @@ { - "lockFileVersion": 13, + "lockFileVersion": 24, "registryFileHashes": { "https://bcr.bazel.build/bazel_registry.json": "8a28e4aff06ee60aed2a8c281907fb8bcbf3b753c91fb5a5c57da3215d5b3497", "https://bcr.bazel.build/modules/abseil-cpp/20210324.2/MODULE.bazel": "7cd0312e064fde87c8d1cd79ba06c876bd23630c83466e9500321be55c96ace2", "https://bcr.bazel.build/modules/abseil-cpp/20211102.0/MODULE.bazel": "70390338f7a5106231d20620712f7cccb659cd0e9d073d1991c038eb9fc57589", - "https://bcr.bazel.build/modules/abseil-cpp/20211102.0/source.json": "7e3a9adf473e9af076ae485ed649d5641ad50ec5c11718103f34de03170d94ad", - "https://bcr.bazel.build/modules/apple_support/1.5.0/MODULE.bazel": "50341a62efbc483e8a2a6aec30994a58749bd7b885e18dd96aa8c33031e558ef", - "https://bcr.bazel.build/modules/apple_support/1.5.0/source.json": "eb98a7627c0bc486b57f598ad8da50f6625d974c8f723e9ea71bd39f709c9862", + "https://bcr.bazel.build/modules/abseil-cpp/20230125.1/MODULE.bazel": "89047429cb0207707b2dface14ba7f8df85273d484c2572755be4bab7ce9c3a0", + "https://bcr.bazel.build/modules/abseil-cpp/20230802.0.bcr.1/MODULE.bazel": "1c8cec495288dccd14fdae6e3f95f772c1c91857047a098fad772034264cc8cb", + "https://bcr.bazel.build/modules/abseil-cpp/20230802.0/MODULE.bazel": "d253ae36a8bd9ee3c5955384096ccb6baf16a1b1e93e858370da0a3b94f77c16", + "https://bcr.bazel.build/modules/abseil-cpp/20230802.1/MODULE.bazel": "fa92e2eb41a04df73cdabeec37107316f7e5272650f81d6cc096418fe647b915", + "https://bcr.bazel.build/modules/abseil-cpp/20240116.1/MODULE.bazel": "37bcdb4440fbb61df6a1c296ae01b327f19e9bb521f9b8e26ec854b6f97309ed", + "https://bcr.bazel.build/modules/abseil-cpp/20240116.1/source.json": "9be551b8d4e3ef76875c0d744b5d6a504a27e3ae67bc6b28f46415fd2d2957da", + "https://bcr.bazel.build/modules/aspect_bazel_lib/2.0.0/MODULE.bazel": "e118477db5c49419a88d78ebc7a2c2cea9d49600fe0f490c1903324a2c16ecd9", + "https://bcr.bazel.build/modules/aspect_bazel_lib/2.14.0/MODULE.bazel": "2b31ffcc9bdc8295b2167e07a757dbbc9ac8906e7028e5170a3708cecaac119f", + "https://bcr.bazel.build/modules/aspect_bazel_lib/2.17.1/MODULE.bazel": "9b027af55f619c7c444cead71061578fab6587e5e1303fa4ed61d49d2b1a7262", + "https://bcr.bazel.build/modules/aspect_bazel_lib/2.19.3/MODULE.bazel": "253d739ba126f62a5767d832765b12b59e9f8d2bc88cc1572f4a73e46eb298ca", + "https://bcr.bazel.build/modules/aspect_bazel_lib/2.22.2/MODULE.bazel": "6b735f3fdd64978e217c9725f4ff0d84bf606554c8e77d20e90977841d7ff2ed", + "https://bcr.bazel.build/modules/aspect_bazel_lib/2.22.2/source.json": "58fffa2d722cff47cb8d921c8bbed7701c53f233009d9ca82beb4a0fb8fb9418", + "https://bcr.bazel.build/modules/aspect_bazel_lib/2.7.7/MODULE.bazel": "491f8681205e31bb57892d67442ce448cda4f472a8e6b3dc062865e29a64f89c", + "https://bcr.bazel.build/modules/aspect_bazel_lib/2.8.1/MODULE.bazel": "812d2dd42f65dca362152101fbec418029cc8fd34cbad1a2fde905383d705838", + "https://bcr.bazel.build/modules/aspect_bazel_lib/2.9.3/MODULE.bazel": "66baf724dbae7aff4787bf2245cc188d50cb08e07789769730151c0943587c14", + "https://bcr.bazel.build/modules/aspect_rules_esbuild/0.25.0/MODULE.bazel": "5fef5ec709c837312823f9bcf0f276661e2cb48ad52f17c4e01176bbf1e9bf58", + "https://bcr.bazel.build/modules/aspect_rules_esbuild/0.25.0/source.json": "5e42968c6d23ab8bd95c02634b16864d866334347827cb6a8425b86c11cc4363", + "https://bcr.bazel.build/modules/aspect_rules_jasmine/2.0.2/MODULE.bazel": "45f054400ff242c4433f6d7f20f6123a9a72739cb7a1f44247d738db1644f46c", + "https://bcr.bazel.build/modules/aspect_rules_jasmine/2.0.2/source.json": "3ed399a5654259a822448f9cdbf21f6c738f16ccd7f89249c7507e374cbdd1e3", + "https://bcr.bazel.build/modules/aspect_rules_js/2.0.0/MODULE.bazel": "b45b507574aa60a92796e3e13c195cd5744b3b8aff516a9c0cb5ae6a048161c5", + "https://bcr.bazel.build/modules/aspect_rules_js/2.4.2/MODULE.bazel": "0d01db38b96d25df7ed952a5e96eac4b3802723d146961974bf020f6dd07591d", + "https://bcr.bazel.build/modules/aspect_rules_js/2.6.2/MODULE.bazel": "ed2a871f4ab8fbde0cab67c425745069d84ea64b64313fa1a2954017326511f5", + "https://bcr.bazel.build/modules/aspect_rules_js/2.8.3/MODULE.bazel": "807ce5f624124a8bc586c743394d174e85f0f9c6c4e0e2410b4088aebe790ac8", + "https://bcr.bazel.build/modules/aspect_rules_js/2.8.3/source.json": "c35cb4e04f61a09c17f8c569894b80de884b1e3dee2d33829704786e3f778037", + "https://bcr.bazel.build/modules/aspect_rules_ts/3.6.3/MODULE.bazel": "d09db394970f076176ce7bab5b5fa7f0d560fd4f30b8432ea5e2c2570505b130", + "https://bcr.bazel.build/modules/aspect_rules_ts/3.7.0/MODULE.bazel": "5aace216caf88638950ef061245d23c36f57c8359e56e97f02a36f70bb09c50f", + "https://bcr.bazel.build/modules/aspect_rules_ts/3.8.1/MODULE.bazel": "796622c65ae3008374fc2d77c32ddb4ef6da9fe891826ce648f70033a48b3667", + "https://bcr.bazel.build/modules/aspect_rules_ts/3.8.1/source.json": "a7c4f332f5c21f4e63d073f8dda40bf278d5307499fb307b35058dba558f417a", + "https://bcr.bazel.build/modules/aspect_tools_telemetry/0.2.3/MODULE.bazel": "20f53b145f40957a51077ae90b37b7ce83582a1daf9350349f0f86179e19dd0d", + "https://bcr.bazel.build/modules/aspect_tools_telemetry/0.2.6/MODULE.bazel": "cafb8781ad591bc57cc765dca5fefab08cf9f65af363d162b79d49205c7f8af7", + "https://bcr.bazel.build/modules/aspect_tools_telemetry/0.2.8/MODULE.bazel": "aa975a83e72bcaac62ee61ab12b788ea324a1d05c4aab28aadb202f647881679", + "https://bcr.bazel.build/modules/aspect_tools_telemetry/0.3.3/MODULE.bazel": "37c764292861c2f70314efa9846bb6dbb44fc0308903b3285da6528305450183", + "https://bcr.bazel.build/modules/aspect_tools_telemetry/0.3.3/source.json": "605086bbc197743a0d360f7ddc550a1d4dfa0441bc807236e17170f636153348", + "https://bcr.bazel.build/modules/bazel_features/1.1.1/MODULE.bazel": "27b8c79ef57efe08efccbd9dd6ef70d61b4798320b8d3c134fd571f78963dbcd", "https://bcr.bazel.build/modules/bazel_features/1.11.0/MODULE.bazel": "f9382337dd5a474c3b7d334c2f83e50b6eaedc284253334cf823044a26de03e8", - "https://bcr.bazel.build/modules/bazel_features/1.11.0/source.json": "c9320aa53cd1c441d24bd6b716da087ad7e4ff0d9742a9884587596edfe53015", + "https://bcr.bazel.build/modules/bazel_features/1.15.0/MODULE.bazel": "d38ff6e517149dc509406aca0db3ad1efdd890a85e049585b7234d04238e2a4d", + "https://bcr.bazel.build/modules/bazel_features/1.17.0/MODULE.bazel": "039de32d21b816b47bd42c778e0454217e9c9caac4a3cf8e15c7231ee3ddee4d", + "https://bcr.bazel.build/modules/bazel_features/1.18.0/MODULE.bazel": "1be0ae2557ab3a72a57aeb31b29be347bcdc5d2b1eb1e70f39e3851a7e97041a", + "https://bcr.bazel.build/modules/bazel_features/1.19.0/MODULE.bazel": "59adcdf28230d220f0067b1f435b8537dd033bfff8db21335ef9217919c7fb58", + "https://bcr.bazel.build/modules/bazel_features/1.21.0/MODULE.bazel": "675642261665d8eea09989aa3b8afb5c37627f1be178382c320d1b46afba5e3b", + "https://bcr.bazel.build/modules/bazel_features/1.28.0/MODULE.bazel": "4b4200e6cbf8fa335b2c3f43e1d6ef3e240319c33d43d60cc0fbd4b87ece299d", + "https://bcr.bazel.build/modules/bazel_features/1.30.0/MODULE.bazel": "a14b62d05969a293b80257e72e597c2da7f717e1e69fa8b339703ed6731bec87", + "https://bcr.bazel.build/modules/bazel_features/1.34.0/MODULE.bazel": "e8475ad7c8965542e0c7aac8af68eb48c4af904be3d614b6aa6274c092c2ea1e", + "https://bcr.bazel.build/modules/bazel_features/1.34.0/source.json": "dfa5c4b01110313153b484a735764d247fee5624bbab63d25289e43b151a657a", + "https://bcr.bazel.build/modules/bazel_features/1.4.1/MODULE.bazel": "e45b6bb2350aff3e442ae1111c555e27eac1d915e77775f6fdc4b351b758b5d7", + "https://bcr.bazel.build/modules/bazel_features/1.9.0/MODULE.bazel": "885151d58d90d8d9c811eb75e3288c11f850e1d6b481a8c9f766adee4712358b", + "https://bcr.bazel.build/modules/bazel_features/1.9.1/MODULE.bazel": "8f679097876a9b609ad1f60249c49d68bfab783dd9be012faf9d82547b14815a", + "https://bcr.bazel.build/modules/bazel_lib/3.0.0-beta.1/MODULE.bazel": "407729e232f611c3270005b016b437005daa7b1505826798ea584169a476e878", + "https://bcr.bazel.build/modules/bazel_lib/3.0.0/MODULE.bazel": "22b70b80ac89ad3f3772526cd9feee2fa412c2b01933fea7ed13238a448d370d", + "https://bcr.bazel.build/modules/bazel_lib/3.0.0/source.json": "895f21909c6fba01d7c17914bb6c8e135982275a1b18cdaa4e62272217ef1751", "https://bcr.bazel.build/modules/bazel_skylib/1.0.3/MODULE.bazel": "bcb0fd896384802d1ad283b4e4eb4d718eebd8cb820b0a2c3a347fb971afd9d8", + "https://bcr.bazel.build/modules/bazel_skylib/1.1.1/MODULE.bazel": "1add3e7d93ff2e6998f9e118022c84d163917d912f5afafb3058e3d2f1545b5e", + "https://bcr.bazel.build/modules/bazel_skylib/1.2.0/MODULE.bazel": "44fe84260e454ed94ad326352a698422dbe372b21a1ac9f3eab76eb531223686", "https://bcr.bazel.build/modules/bazel_skylib/1.2.1/MODULE.bazel": "f35baf9da0efe45fa3da1696ae906eea3d615ad41e2e3def4aeb4e8bc0ef9a7a", "https://bcr.bazel.build/modules/bazel_skylib/1.3.0/MODULE.bazel": "20228b92868bf5cfc41bda7afc8a8ba2a543201851de39d990ec957b513579c5", + "https://bcr.bazel.build/modules/bazel_skylib/1.4.0/MODULE.bazel": "2ab127ef8d56a739a99bb2ce00ec4c7d1ecc7977d4370c0ca6efd0d8f03d6d99", + "https://bcr.bazel.build/modules/bazel_skylib/1.4.1/MODULE.bazel": "a0dcb779424be33100dcae821e9e27e4f2901d9dfd5333efe5ac6a8d7ab75e1d", + "https://bcr.bazel.build/modules/bazel_skylib/1.4.2/MODULE.bazel": "3bd40978e7a1fac911d5989e6b09d8f64921865a45822d8b09e815eaa726a651", + "https://bcr.bazel.build/modules/bazel_skylib/1.5.0/MODULE.bazel": "32880f5e2945ce6a03d1fbd588e9198c0a959bb42297b2cfaf1685b7bc32e138", "https://bcr.bazel.build/modules/bazel_skylib/1.6.1/MODULE.bazel": "8fdee2dbaace6c252131c00e1de4b165dc65af02ea278476187765e1a617b917", - "https://bcr.bazel.build/modules/bazel_skylib/1.6.1/source.json": "082ed5f9837901fada8c68c2f3ddc958bb22b6d654f71dd73f3df30d45d4b749", + "https://bcr.bazel.build/modules/bazel_skylib/1.7.0/MODULE.bazel": "0db596f4563de7938de764cc8deeabec291f55e8ec15299718b93c4423e9796d", + "https://bcr.bazel.build/modules/bazel_skylib/1.7.1/MODULE.bazel": "3120d80c5861aa616222ec015332e5f8d3171e062e3e804a2a0253e1be26e59b", + "https://bcr.bazel.build/modules/bazel_skylib/1.8.1/MODULE.bazel": "88ade7293becda963e0e3ea33e7d54d3425127e0a326e0d17da085a5f1f03ff6", + "https://bcr.bazel.build/modules/bazel_skylib/1.8.2/MODULE.bazel": "69ad6927098316848b34a9142bcc975e018ba27f08c4ff403f50c1b6e646ca67", + "https://bcr.bazel.build/modules/bazel_skylib/1.9.0/MODULE.bazel": "72997b29dfd95c3fa0d0c48322d05590418edef451f8db8db5509c57875fb4b7", + "https://bcr.bazel.build/modules/bazel_skylib/1.9.0/source.json": "7ad77c1e8c1b84222d9b3f3cae016a76639435744c19330b0b37c0a3c9da7dc0", "https://bcr.bazel.build/modules/buildozer/7.1.2/MODULE.bazel": "2e8dd40ede9c454042645fd8d8d0cd1527966aa5c919de86661e62953cd73d84", "https://bcr.bazel.build/modules/buildozer/7.1.2/source.json": "c9028a501d2db85793a6996205c8de120944f50a0d570438fcae0457a5f9d1f8", + "https://bcr.bazel.build/modules/gawk/5.3.2.bcr.1/MODULE.bazel": "cdf8cbe5ee750db04b78878c9633cc76e80dcf4416cbe982ac3a9222f80713c8", + "https://bcr.bazel.build/modules/gawk/5.3.2.bcr.1/source.json": "fa7b512dfcb5eafd90ce3959cf42a2a6fe96144ebbb4b3b3928054895f2afac2", + "https://bcr.bazel.build/modules/google_benchmark/1.8.2/MODULE.bazel": "a70cf1bba851000ba93b58ae2f6d76490a9feb74192e57ab8e8ff13c34ec50cb", "https://bcr.bazel.build/modules/googletest/1.11.0/MODULE.bazel": "3a83f095183f66345ca86aa13c58b59f9f94a2f81999c093d4eeaa2d262d12f4", - "https://bcr.bazel.build/modules/googletest/1.11.0/source.json": "c73d9ef4268c91bd0c1cd88f1f9dfa08e814b1dbe89b5f594a9f08ba0244d206", + "https://bcr.bazel.build/modules/googletest/1.14.0.bcr.1/MODULE.bazel": "22c31a561553727960057361aa33bf20fb2e98584bc4fec007906e27053f80c6", + "https://bcr.bazel.build/modules/googletest/1.14.0.bcr.1/source.json": "41e9e129f80d8c8bf103a7acc337b76e54fad1214ac0a7084bf24f4cd924b8b4", + "https://bcr.bazel.build/modules/googletest/1.14.0/MODULE.bazel": "cfbcbf3e6eac06ef9d85900f64424708cc08687d1b527f0ef65aa7517af8118f", + "https://bcr.bazel.build/modules/jq.bzl/0.1.0/MODULE.bazel": "2ce69b1af49952cd4121a9c3055faa679e748ce774c7f1fda9657f936cae902f", + "https://bcr.bazel.build/modules/jq.bzl/0.1.0/source.json": "746bf13cac0860f091df5e4911d0c593971cd8796b5ad4e809b2f8e133eee3d5", + "https://bcr.bazel.build/modules/jsoncpp/1.9.5/MODULE.bazel": "31271aedc59e815656f5736f282bb7509a97c7ecb43e927ac1a37966e0578075", + "https://bcr.bazel.build/modules/jsoncpp/1.9.5/source.json": "4108ee5085dd2885a341c7fab149429db457b3169b86eb081fa245eadf69169d", + "https://bcr.bazel.build/modules/libpfm/4.11.0/MODULE.bazel": "45061ff025b301940f1e30d2c16bea596c25b176c8b6b3087e92615adbd52902", + "https://bcr.bazel.build/modules/package_metadata/0.0.2/MODULE.bazel": "fb8d25550742674d63d7b250063d4580ca530499f045d70748b1b142081ebb92", + "https://bcr.bazel.build/modules/package_metadata/0.0.2/source.json": "e53a759a72488d2c0576f57491ef2da0cf4aab05ac0997314012495935531b73", + "https://bcr.bazel.build/modules/platforms/0.0.10/MODULE.bazel": "8cb8efaf200bdeb2150d93e162c40f388529a25852b332cec879373771e48ed5", + "https://bcr.bazel.build/modules/platforms/0.0.11/MODULE.bazel": "0daefc49732e227caa8bfa834d65dc52e8cc18a2faf80df25e8caea151a9413f", "https://bcr.bazel.build/modules/platforms/0.0.4/MODULE.bazel": "9b328e31ee156f53f3c416a64f8491f7eb731742655a47c9eec4703a71644aee", "https://bcr.bazel.build/modules/platforms/0.0.5/MODULE.bazel": "5733b54ea419d5eaf7997054bb55f6a1d0b5ff8aedf0176fef9eea44f3acda37", "https://bcr.bazel.build/modules/platforms/0.0.6/MODULE.bazel": "ad6eeef431dc52aefd2d77ed20a4b353f8ebf0f4ecdd26a807d2da5aa8cd0615", "https://bcr.bazel.build/modules/platforms/0.0.7/MODULE.bazel": "72fd4a0ede9ee5c021f6a8dd92b503e089f46c227ba2813ff183b71616034814", - "https://bcr.bazel.build/modules/platforms/0.0.9/MODULE.bazel": "4a87a60c927b56ddd67db50c89acaa62f4ce2a1d2149ccb63ffd871d5ce29ebc", - "https://bcr.bazel.build/modules/platforms/0.0.9/source.json": "cd74d854bf16a9e002fb2ca7b1a421f4403cda29f824a765acd3a8c56f8d43e6", + "https://bcr.bazel.build/modules/platforms/0.0.8/MODULE.bazel": "9f142c03e348f6d263719f5074b21ef3adf0b139ee4c5133e2aa35664da9eb2d", + "https://bcr.bazel.build/modules/platforms/1.0.0/MODULE.bazel": "f05feb42b48f1b3c225e4ccf351f367be0371411a803198ec34a389fb22aa580", + "https://bcr.bazel.build/modules/platforms/1.0.0/source.json": "f4ff1fd412e0246fd38c82328eb209130ead81d62dcd5a9e40910f867f733d96", "https://bcr.bazel.build/modules/protobuf/21.7/MODULE.bazel": "a5a29bb89544f9b97edce05642fac225a808b5b7be74038ea3640fae2f8e66a7", - "https://bcr.bazel.build/modules/protobuf/21.7/source.json": "bbe500720421e582ff2d18b0802464205138c06056f443184de39fbb8187b09b", + "https://bcr.bazel.build/modules/protobuf/27.0/MODULE.bazel": "7873b60be88844a0a1d8f80b9d5d20cfbd8495a689b8763e76c6372998d3f64c", + "https://bcr.bazel.build/modules/protobuf/27.1/MODULE.bazel": "703a7b614728bb06647f965264967a8ef1c39e09e8f167b3ca0bb1fd80449c0d", + "https://bcr.bazel.build/modules/protobuf/29.0-rc2/MODULE.bazel": "6241d35983510143049943fc0d57937937122baf1b287862f9dc8590fc4c37df", + "https://bcr.bazel.build/modules/protobuf/29.0-rc3/MODULE.bazel": "33c2dfa286578573afc55a7acaea3cada4122b9631007c594bf0729f41c8de92", + "https://bcr.bazel.build/modules/protobuf/29.0/MODULE.bazel": "319dc8bf4c679ff87e71b1ccfb5a6e90a6dbc4693501d471f48662ac46d04e4e", + "https://bcr.bazel.build/modules/protobuf/29.0/source.json": "b857f93c796750eef95f0d61ee378f3420d00ee1dd38627b27193aa482f4f981", "https://bcr.bazel.build/modules/protobuf/3.19.0/MODULE.bazel": "6b5fbb433f760a99a22b18b6850ed5784ef0e9928a72668b66e4d7ccd47db9b0", - "https://bcr.bazel.build/modules/protobuf/3.19.6/MODULE.bazel": "9233edc5e1f2ee276a60de3eaa47ac4132302ef9643238f23128fea53ea12858", + "https://bcr.bazel.build/modules/pybind11_bazel/2.11.1/MODULE.bazel": "88af1c246226d87e65be78ed49ecd1e6f5e98648558c14ce99176da041dc378e", + "https://bcr.bazel.build/modules/pybind11_bazel/2.11.1/source.json": "be4789e951dd5301282729fe3d4938995dc4c1a81c2ff150afc9f1b0504c6022", + "https://bcr.bazel.build/modules/re2/2023-09-01/MODULE.bazel": "cb3d511531b16cfc78a225a9e2136007a48cf8a677e4264baeab57fe78a80206", + "https://bcr.bazel.build/modules/re2/2023-09-01/source.json": "e044ce89c2883cd957a2969a43e79f7752f9656f6b20050b62f90ede21ec6eb4", + "https://bcr.bazel.build/modules/rules_android/0.1.1/MODULE.bazel": "48809ab0091b07ad0182defb787c4c5328bd3a278938415c00a7b69b50c4d3a8", + "https://bcr.bazel.build/modules/rules_android/0.1.1/source.json": "e6986b41626ee10bdc864937ffb6d6bf275bb5b9c65120e6137d56e6331f089e", "https://bcr.bazel.build/modules/rules_cc/0.0.1/MODULE.bazel": "cb2aa0747f84c6c3a78dad4e2049c154f08ab9d166b1273835a8174940365647", + "https://bcr.bazel.build/modules/rules_cc/0.0.10/MODULE.bazel": "ec1705118f7eaedd6e118508d3d26deba2a4e76476ada7e0e3965211be012002", + "https://bcr.bazel.build/modules/rules_cc/0.0.13/MODULE.bazel": "0e8529ed7b323dad0775ff924d2ae5af7640b23553dfcd4d34344c7e7a867191", + "https://bcr.bazel.build/modules/rules_cc/0.0.14/MODULE.bazel": "5e343a3aac88b8d7af3b1b6d2093b55c347b8eefc2e7d1442f7a02dc8fea48ac", + "https://bcr.bazel.build/modules/rules_cc/0.0.15/MODULE.bazel": "6704c35f7b4a72502ee81f61bf88706b54f06b3cbe5558ac17e2e14666cd5dcc", + "https://bcr.bazel.build/modules/rules_cc/0.0.16/MODULE.bazel": "7661303b8fc1b4d7f532e54e9d6565771fea666fbdf839e0a86affcd02defe87", "https://bcr.bazel.build/modules/rules_cc/0.0.2/MODULE.bazel": "6915987c90970493ab97393024c156ea8fb9f3bea953b2f3ec05c34f19b5695c", + "https://bcr.bazel.build/modules/rules_cc/0.0.6/MODULE.bazel": "abf360251023dfe3efcef65ab9d56beefa8394d4176dd29529750e1c57eaa33f", "https://bcr.bazel.build/modules/rules_cc/0.0.8/MODULE.bazel": "964c85c82cfeb6f3855e6a07054fdb159aced38e99a5eecf7bce9d53990afa3e", "https://bcr.bazel.build/modules/rules_cc/0.0.9/MODULE.bazel": "836e76439f354b89afe6a911a7adf59a6b2518fafb174483ad78a2a2fde7b1c5", - "https://bcr.bazel.build/modules/rules_cc/0.0.9/source.json": "1f1ba6fea244b616de4a554a0f4983c91a9301640c8fe0dd1d410254115c8430", + "https://bcr.bazel.build/modules/rules_cc/0.1.1/MODULE.bazel": "2f0222a6f229f0bf44cd711dc13c858dad98c62d52bd51d8fc3a764a83125513", + "https://bcr.bazel.build/modules/rules_cc/0.2.16/MODULE.bazel": "9242fa89f950c6ef7702801ab53922e99c69b02310c39fb6e62b2bd30df2a1d4", + "https://bcr.bazel.build/modules/rules_cc/0.2.16/source.json": "d03d5cde49376d87e14ec14b666c56075e5e3926930327fd5d0484a1ff2ac1cc", + "https://bcr.bazel.build/modules/rules_foreign_cc/0.9.0/MODULE.bazel": "c9e8c682bf75b0e7c704166d79b599f93b72cfca5ad7477df596947891feeef6", + "https://bcr.bazel.build/modules/rules_fuzzing/0.5.2/MODULE.bazel": "40c97d1144356f52905566c55811f13b299453a14ac7769dfba2ac38192337a8", + "https://bcr.bazel.build/modules/rules_fuzzing/0.5.2/source.json": "c8b1e2c717646f1702290959a3302a178fb639d987ab61d548105019f11e527e", "https://bcr.bazel.build/modules/rules_java/4.0.0/MODULE.bazel": "5a78a7ae82cd1a33cef56dc578c7d2a46ed0dca12643ee45edbb8417899e6f74", - "https://bcr.bazel.build/modules/rules_java/7.6.5/MODULE.bazel": "481164be5e02e4cab6e77a36927683263be56b7e36fef918b458d7a8a1ebadb1", - "https://bcr.bazel.build/modules/rules_java/7.6.5/source.json": "a805b889531d1690e3c72a7a7e47a870d00323186a9904b36af83aa3d053ee8d", + "https://bcr.bazel.build/modules/rules_java/5.3.5/MODULE.bazel": "a4ec4f2db570171e3e5eb753276ee4b389bae16b96207e9d3230895c99644b86", + "https://bcr.bazel.build/modules/rules_java/6.0.0/MODULE.bazel": "8a43b7df601a7ec1af61d79345c17b31ea1fedc6711fd4abfd013ea612978e39", + "https://bcr.bazel.build/modules/rules_java/6.3.0/MODULE.bazel": "a97c7678c19f236a956ad260d59c86e10a463badb7eb2eda787490f4c969b963", + "https://bcr.bazel.build/modules/rules_java/6.4.0/MODULE.bazel": "e986a9fe25aeaa84ac17ca093ef13a4637f6107375f64667a15999f77db6c8f6", + "https://bcr.bazel.build/modules/rules_java/6.5.2/MODULE.bazel": "1d440d262d0e08453fa0c4d8f699ba81609ed0e9a9a0f02cd10b3e7942e61e31", + "https://bcr.bazel.build/modules/rules_java/7.10.0/MODULE.bazel": "530c3beb3067e870561739f1144329a21c851ff771cd752a49e06e3dc9c2e71a", + "https://bcr.bazel.build/modules/rules_java/7.12.2/MODULE.bazel": "579c505165ee757a4280ef83cda0150eea193eed3bef50b1004ba88b99da6de6", + "https://bcr.bazel.build/modules/rules_java/7.2.0/MODULE.bazel": "06c0334c9be61e6cef2c8c84a7800cef502063269a5af25ceb100b192453d4ab", + "https://bcr.bazel.build/modules/rules_java/7.3.2/MODULE.bazel": "50dece891cfdf1741ea230d001aa9c14398062f2b7c066470accace78e412bc2", + "https://bcr.bazel.build/modules/rules_java/7.6.1/MODULE.bazel": "2f14b7e8a1aa2f67ae92bc69d1ec0fa8d9f827c4e17ff5e5f02e91caa3b2d0fe", + "https://bcr.bazel.build/modules/rules_java/8.14.0/MODULE.bazel": "717717ed40cc69994596a45aec6ea78135ea434b8402fb91b009b9151dd65615", + "https://bcr.bazel.build/modules/rules_java/8.14.0/source.json": "8a88c4ca9e8759da53cddc88123880565c520503321e2566b4e33d0287a3d4bc", + "https://bcr.bazel.build/modules/rules_java/8.3.2/MODULE.bazel": "7336d5511ad5af0b8615fdc7477535a2e4e723a357b6713af439fe8cf0195017", + "https://bcr.bazel.build/modules/rules_java/8.5.1/MODULE.bazel": "d8a9e38cc5228881f7055a6079f6f7821a073df3744d441978e7a43e20226939", "https://bcr.bazel.build/modules/rules_jvm_external/4.4.2/MODULE.bazel": "a56b85e418c83eb1839819f0b515c431010160383306d13ec21959ac412d2fe7", - "https://bcr.bazel.build/modules/rules_jvm_external/4.4.2/source.json": "a075731e1b46bc8425098512d038d416e966ab19684a10a34f4741295642fc35", + "https://bcr.bazel.build/modules/rules_jvm_external/5.1/MODULE.bazel": "33f6f999e03183f7d088c9be518a63467dfd0be94a11d0055fe2d210f89aa909", + "https://bcr.bazel.build/modules/rules_jvm_external/5.2/MODULE.bazel": "d9351ba35217ad0de03816ef3ed63f89d411349353077348a45348b096615036", + "https://bcr.bazel.build/modules/rules_jvm_external/5.3/MODULE.bazel": "bf93870767689637164657731849fb887ad086739bd5d360d90007a581d5527d", + "https://bcr.bazel.build/modules/rules_jvm_external/6.1/MODULE.bazel": "75b5fec090dbd46cf9b7d8ea08cf84a0472d92ba3585b476f44c326eda8059c4", + "https://bcr.bazel.build/modules/rules_jvm_external/6.3/MODULE.bazel": "c998e060b85f71e00de5ec552019347c8bca255062c990ac02d051bb80a38df0", + "https://bcr.bazel.build/modules/rules_jvm_external/6.3/source.json": "6f5f5a5a4419ae4e37c35a5bb0a6ae657ed40b7abc5a5189111b47fcebe43197", + "https://bcr.bazel.build/modules/rules_kotlin/1.9.0/MODULE.bazel": "ef85697305025e5a61f395d4eaede272a5393cee479ace6686dba707de804d59", + "https://bcr.bazel.build/modules/rules_kotlin/1.9.6/MODULE.bazel": "d269a01a18ee74d0335450b10f62c9ed81f2321d7958a2934e44272fe82dcef3", + "https://bcr.bazel.build/modules/rules_kotlin/1.9.6/source.json": "2faa4794364282db7c06600b7e5e34867a564ae91bda7cae7c29c64e9466b7d5", "https://bcr.bazel.build/modules/rules_license/0.0.3/MODULE.bazel": "627e9ab0247f7d1e05736b59dbb1b6871373de5ad31c3011880b4133cafd4bd0", "https://bcr.bazel.build/modules/rules_license/0.0.7/MODULE.bazel": "088fbeb0b6a419005b89cf93fe62d9517c0a2b8bb56af3244af65ecfe37e7d5d", - "https://bcr.bazel.build/modules/rules_license/0.0.7/source.json": "355cc5737a0f294e560d52b1b7a6492d4fff2caf0bef1a315df5a298fca2d34a", + "https://bcr.bazel.build/modules/rules_license/1.0.0/MODULE.bazel": "a7fda60eefdf3d8c827262ba499957e4df06f659330bbe6cdbdb975b768bb65c", + "https://bcr.bazel.build/modules/rules_license/1.0.0/source.json": "a52c89e54cc311196e478f8382df91c15f7a2bfdf4c6cd0e2675cc2ff0b56efb", + "https://bcr.bazel.build/modules/rules_nodejs/6.2.0/MODULE.bazel": "ec27907f55eb34705adb4e8257952162a2d4c3ed0f0b3b4c3c1aad1fac7be35e", + "https://bcr.bazel.build/modules/rules_nodejs/6.3.0/MODULE.bazel": "45345e4aba35dd6e4701c1eebf5a4e67af4ed708def9ebcdc6027585b34ee52d", + "https://bcr.bazel.build/modules/rules_nodejs/6.5.0/MODULE.bazel": "546d0cf79f36f9f6e080816045f97234b071c205f4542e3351bd4424282a8810", + "https://bcr.bazel.build/modules/rules_nodejs/6.5.2/MODULE.bazel": "7f9ea68a0ce6d82905ce9f74e76ab8a8b4531ed4c747018c9d76424ad0b3370d", + "https://bcr.bazel.build/modules/rules_nodejs/6.6.2/MODULE.bazel": "9fdb5e1d50246a25761f150fcc820dc47e4052330a8408451e628804f9ca64a6", + "https://bcr.bazel.build/modules/rules_nodejs/6.6.2/source.json": "6e8c1ecc64ff8da147c1620f862ad77d7b19c5d1b52b3aa5e847d5b3d0de4cc3", "https://bcr.bazel.build/modules/rules_pkg/0.7.0/MODULE.bazel": "df99f03fc7934a4737122518bb87e667e62d780b610910f0447665a7e2be62dc", - "https://bcr.bazel.build/modules/rules_pkg/0.7.0/source.json": "c2557066e0c0342223ba592510ad3d812d4963b9024831f7f66fd0584dd8c66c", + "https://bcr.bazel.build/modules/rules_pkg/1.0.1/MODULE.bazel": "5b1df97dbc29623bccdf2b0dcd0f5cb08e2f2c9050aab1092fd39a41e82686ff", + "https://bcr.bazel.build/modules/rules_pkg/1.2.0/MODULE.bazel": "c7db3c2b407e673c7a39e3625dc05dc9f12d6682cbd82a3a5924a13b491eda7e", + "https://bcr.bazel.build/modules/rules_pkg/1.2.0/source.json": "9062e00845bf91a4247465d371baa837adf9b6ff44c542f73ba084f07667e1dc", "https://bcr.bazel.build/modules/rules_proto/4.0.0/MODULE.bazel": "a7a7b6ce9bee418c1a760b3d84f83a299ad6952f9903c67f19e4edd964894e06", "https://bcr.bazel.build/modules/rules_proto/5.3.0-21.7/MODULE.bazel": "e8dff86b0971688790ae75528fe1813f71809b5afd57facb44dad9e8eca631b7", - "https://bcr.bazel.build/modules/rules_proto/5.3.0-21.7/source.json": "d57902c052424dfda0e71646cb12668d39c4620ee0544294d9d941e7d12bc3a9", + "https://bcr.bazel.build/modules/rules_proto/6.0.0/MODULE.bazel": "b531d7f09f58dce456cd61b4579ce8c86b38544da75184eadaf0a7cb7966453f", + "https://bcr.bazel.build/modules/rules_proto/6.0.2/MODULE.bazel": "ce916b775a62b90b61888052a416ccdda405212b6aaeb39522f7dc53431a5e73", + "https://bcr.bazel.build/modules/rules_proto/7.0.2/MODULE.bazel": "bf81793bd6d2ad89a37a40693e56c61b0ee30f7a7fdbaf3eabbf5f39de47dea2", + "https://bcr.bazel.build/modules/rules_proto/7.0.2/source.json": "1e5e7260ae32ef4f2b52fd1d0de8d03b606a44c91b694d2f1afb1d3b28a48ce1", "https://bcr.bazel.build/modules/rules_python/0.10.2/MODULE.bazel": "cc82bc96f2997baa545ab3ce73f196d040ffb8756fd2d66125a530031cd90e5f", - "https://bcr.bazel.build/modules/rules_python/0.22.1/MODULE.bazel": "26114f0c0b5e93018c0c066d6673f1a2c3737c7e90af95eff30cfee38d0bbac7", - "https://bcr.bazel.build/modules/rules_python/0.22.1/source.json": "57226905e783bae7c37c2dd662be078728e48fa28ee4324a7eabcafb5a43d014", + "https://bcr.bazel.build/modules/rules_python/0.23.1/MODULE.bazel": "49ffccf0511cb8414de28321f5fcf2a31312b47c40cc21577144b7447f2bf300", + "https://bcr.bazel.build/modules/rules_python/0.25.0/MODULE.bazel": "72f1506841c920a1afec76975b35312410eea3aa7b63267436bfb1dd91d2d382", + "https://bcr.bazel.build/modules/rules_python/0.28.0/MODULE.bazel": "cba2573d870babc976664a912539b320cbaa7114cd3e8f053c720171cde331ed", + "https://bcr.bazel.build/modules/rules_python/0.31.0/MODULE.bazel": "93a43dc47ee570e6ec9f5779b2e64c1476a6ce921c48cc9a1678a91dd5f8fd58", "https://bcr.bazel.build/modules/rules_python/0.4.0/MODULE.bazel": "9208ee05fd48bf09ac60ed269791cf17fb343db56c8226a720fbb1cdf467166c", + "https://bcr.bazel.build/modules/rules_python/0.40.0/MODULE.bazel": "9d1a3cd88ed7d8e39583d9ffe56ae8a244f67783ae89b60caafc9f5cf318ada7", + "https://bcr.bazel.build/modules/rules_python/1.0.0/MODULE.bazel": "898a3d999c22caa585eb062b600f88654bf92efb204fa346fb55f6f8edffca43", + "https://bcr.bazel.build/modules/rules_python/1.0.0/source.json": "b0162a65c6312e45e7912e39abd1a7f8856c2c7e41ecc9b6dc688a6f6400a917", + "https://bcr.bazel.build/modules/rules_shell/0.2.0/MODULE.bazel": "fda8a652ab3c7d8fee214de05e7a9916d8b28082234e8d2c0094505c5268ed3c", + "https://bcr.bazel.build/modules/rules_shell/0.4.1/MODULE.bazel": "00e501db01bbf4e3e1dd1595959092c2fadf2087b2852d3f553b5370f5633592", + "https://bcr.bazel.build/modules/rules_shell/0.4.1/source.json": "4757bd277fe1567763991c4425b483477bb82e35e777a56fd846eb5cceda324a", "https://bcr.bazel.build/modules/stardoc/0.5.1/MODULE.bazel": "1a05d92974d0c122f5ccf09291442580317cdd859f07a8655f1db9a60374f9f8", - "https://bcr.bazel.build/modules/stardoc/0.5.1/source.json": "a96f95e02123320aa015b956f29c00cb818fa891ef823d55148e1a362caacf29", + "https://bcr.bazel.build/modules/stardoc/0.5.3/MODULE.bazel": "c7f6948dae6999bf0db32c1858ae345f112cacf98f174c7a8bb707e41b974f1c", + "https://bcr.bazel.build/modules/stardoc/0.5.4/MODULE.bazel": "6569966df04610b8520957cb8e97cf2e9faac2c0309657c537ab51c16c18a2a4", + "https://bcr.bazel.build/modules/stardoc/0.5.6/MODULE.bazel": "c43dabc564990eeab55e25ed61c07a1aadafe9ece96a4efabb3f8bf9063b71ef", + "https://bcr.bazel.build/modules/stardoc/0.6.2/MODULE.bazel": "7060193196395f5dd668eda046ccbeacebfd98efc77fed418dbe2b82ffaa39fd", + "https://bcr.bazel.build/modules/stardoc/0.7.0/MODULE.bazel": "05e3d6d30c099b6770e97da986c53bd31844d7f13d41412480ea265ac9e8079c", + "https://bcr.bazel.build/modules/stardoc/0.7.1/MODULE.bazel": "3548faea4ee5dda5580f9af150e79d0f6aea934fc60c1cc50f4efdd9420759e7", + "https://bcr.bazel.build/modules/stardoc/0.7.2/MODULE.bazel": "fc152419aa2ea0f51c29583fab1e8c99ddefd5b3778421845606ee628629e0e5", + "https://bcr.bazel.build/modules/stardoc/0.7.2/source.json": "58b029e5e901d6802967754adf0a9056747e8176f017cfe3607c0851f4d42216", + "https://bcr.bazel.build/modules/tar.bzl/0.2.1/MODULE.bazel": "52d1c00a80a8cc67acbd01649e83d8dd6a9dc426a6c0b754a04fe8c219c76468", + "https://bcr.bazel.build/modules/tar.bzl/0.5.1/MODULE.bazel": "7c2eb3dcfc53b0f3d6f9acdfd911ca803eaf92aadf54f8ca6e4c1f3aee288351", + "https://bcr.bazel.build/modules/tar.bzl/0.7.0/MODULE.bazel": "cc1acd85da33c80e430b65219a620d54d114628df24a618c3a5fa0b65e988da9", + "https://bcr.bazel.build/modules/tar.bzl/0.7.0/source.json": "9becb80306f42d4810bfa16379fb48aad0b01ce5342bc12fe47dcd6af3ac4d7a", "https://bcr.bazel.build/modules/upb/0.0.0-20220923-a547704/MODULE.bazel": "7298990c00040a0e2f121f6c32544bab27d4452f80d9ce51349b1a28f3005c43", - "https://bcr.bazel.build/modules/upb/0.0.0-20220923-a547704/source.json": "f1ef7d3f9e0e26d4b23d1c39b5f5de71f584dd7d1b4ef83d9bbba6ec7a6a6459", + "https://bcr.bazel.build/modules/yq.bzl/0.1.1/MODULE.bazel": "9039681f9bcb8958ee2c87ffc74bdafba9f4369096a2b5634b88abc0eaefa072", + "https://bcr.bazel.build/modules/yq.bzl/0.2.0/MODULE.bazel": "6f3a675677db8885be4d607fde14cc51829715e3a879fb016eb9bf336786ce6d", + "https://bcr.bazel.build/modules/yq.bzl/0.3.2/MODULE.bazel": "0384efa70e8033d842ea73aa4b7199fa099709e236a7264345c03937166670b6", + "https://bcr.bazel.build/modules/yq.bzl/0.3.4/MODULE.bazel": "d3a270662f5d766cd7229732d65a5a5bc485240c3007343dd279edfb60c9ae27", + "https://bcr.bazel.build/modules/yq.bzl/0.3.4/source.json": "786dafdc2843722da3416e4343ee1a05237227f068590779a6e8496a2064c0f9", "https://bcr.bazel.build/modules/zlib/1.2.11/MODULE.bazel": "07b389abc85fdbca459b69e2ec656ae5622873af3f845e1c9d80fe179f3effa0", - "https://bcr.bazel.build/modules/zlib/1.2.12/MODULE.bazel": "3b1a8834ada2a883674be8cbd36ede1b6ec481477ada359cd2d3ddc562340b27", - "https://bcr.bazel.build/modules/zlib/1.3.1.bcr.3/MODULE.bazel": "af322bc08976524477c79d1e45e241b6efbeb918c497e8840b8ab116802dda79", - "https://bcr.bazel.build/modules/zlib/1.3.1.bcr.3/source.json": "2be409ac3c7601245958cd4fcdff4288be79ed23bd690b4b951f500d54ee6e7d" + "https://bcr.bazel.build/modules/zlib/1.3.1.bcr.5/MODULE.bazel": "eec517b5bbe5492629466e11dae908d043364302283de25581e3eb944326c4ca", + "https://bcr.bazel.build/modules/zlib/1.3.1.bcr.5/source.json": "22bc55c47af97246cfc093d0acf683a7869377de362b5d1c552c2c2e16b7a806", + "https://bcr.bazel.build/modules/zlib/1.3.1/MODULE.bazel": "751c9940dcfe869f5f7274e1295422a34623555916eb98c174c1e945594bf198" }, "selectedYankedVersions": {}, "moduleExtensions": { - "@@apple_support~//crosstool:setup.bzl%apple_cc_configure_extension": { + "@@aspect_rules_esbuild+//esbuild:extensions.bzl%esbuild": { "general": { - "bzlTransitiveDigest": "PjIds3feoYE8SGbbIq2SFTZy3zmxeO2tQevJZNDo7iY=", - "usagesDigest": "+hz7IHWN6A1oVJJWNDB6yZRG+RYhF76wAYItpAeIUIg=", + "bzlTransitiveDigest": "9odiC0alKLq5PUYv/CZiw2yiMHsGpxvEhPsqt//fRRk=", + "usagesDigest": "ToTaCONCN/E05krnHXLM1kpV1zrHNxHrGpUip973II4=", "recordedFileInputs": {}, "recordedDirentsInputs": {}, "envVariables": {}, "generatedRepoSpecs": { - "local_config_apple_cc_toolchains": { - "bzlFile": "@@apple_support~//crosstool:setup.bzl", - "ruleClassName": "_apple_cc_autoconf_toolchains", - "attributes": {} + "esbuild_darwin-x64": { + "repoRuleId": "@@aspect_rules_esbuild+//esbuild:repositories.bzl%esbuild_repositories", + "attributes": { + "esbuild_version": "0.19.9", + "integrity": "", + "platform": "darwin-x64" + } + }, + "esbuild_darwin-arm64": { + "repoRuleId": "@@aspect_rules_esbuild+//esbuild:repositories.bzl%esbuild_repositories", + "attributes": { + "esbuild_version": "0.19.9", + "integrity": "", + "platform": "darwin-arm64" + } + }, + "esbuild_linux-x64": { + "repoRuleId": "@@aspect_rules_esbuild+//esbuild:repositories.bzl%esbuild_repositories", + "attributes": { + "esbuild_version": "0.19.9", + "integrity": "", + "platform": "linux-x64" + } + }, + "esbuild_linux-arm64": { + "repoRuleId": "@@aspect_rules_esbuild+//esbuild:repositories.bzl%esbuild_repositories", + "attributes": { + "esbuild_version": "0.19.9", + "integrity": "", + "platform": "linux-arm64" + } + }, + "esbuild_win32-x64": { + "repoRuleId": "@@aspect_rules_esbuild+//esbuild:repositories.bzl%esbuild_repositories", + "attributes": { + "esbuild_version": "0.19.9", + "integrity": "", + "platform": "win32-x64" + } + }, + "esbuild_toolchains": { + "repoRuleId": "@@aspect_rules_esbuild+//esbuild/private:toolchains_repo.bzl%toolchains_repo", + "attributes": { + "esbuild_version": "0.19.9", + "user_repository_name": "esbuild" + } + }, + "npm__esbuild_0.19.9": { + "repoRuleId": "@@aspect_rules_js+//npm/private:npm_import.bzl%npm_import_rule", + "attributes": { + "package": "esbuild", + "version": "0.19.9", + "root_package": "", + "link_workspace": "", + "link_packages": {}, + "integrity": "sha512-U9CHtKSy+EpPsEBa+/A2gMs/h3ylBC0H0KSqIg7tpztHerLi6nrrcoUJAkNCEPumx8yJ+Byic4BVwHgRbN0TBg==", + "url": "", + "commit": "", + "patch_args": [ + "-p0" + ], + "patches": [], + "custom_postinstall": "", + "npm_auth": "", + "npm_auth_basic": "", + "npm_auth_username": "", + "npm_auth_password": "", + "lifecycle_hooks": [], + "extra_build_content": "", + "generate_bzl_library_targets": false, + "extract_full_archive": false, + "exclude_package_contents": [] + } }, - "local_config_apple_cc": { - "bzlFile": "@@apple_support~//crosstool:setup.bzl", - "ruleClassName": "_apple_cc_autoconf", + "npm__esbuild_0.19.9__links": { + "repoRuleId": "@@aspect_rules_js+//npm/private:npm_import.bzl%npm_import_links", + "attributes": { + "package": "esbuild", + "version": "0.19.9", + "dev": false, + "root_package": "", + "link_packages": {}, + "deps": {}, + "transitive_closure": {}, + "lifecycle_build_target": false, + "lifecycle_hooks_env": [], + "lifecycle_hooks_execution_requirements": [ + "no-sandbox" + ], + "lifecycle_hooks_use_default_shell_env": false, + "bins": {}, + "package_visibility": [ + "//visibility:public" + ], + "replace_package": "", + "exclude_package_contents": [] + } + } + }, + "recordedRepoMappingEntries": [ + [ + "aspect_bazel_lib+", + "bazel_lib", + "bazel_lib+" + ], + [ + "aspect_bazel_lib+", + "bazel_skylib", + "bazel_skylib+" + ], + [ + "aspect_bazel_lib+", + "bazel_tools", + "bazel_tools" + ], + [ + "aspect_bazel_lib+", + "tar.bzl", + "tar.bzl+" + ], + [ + "aspect_rules_esbuild+", + "aspect_rules_js", + "aspect_rules_js+" + ], + [ + "aspect_rules_esbuild+", + "aspect_tools_telemetry_report", + "aspect_tools_telemetry++telemetry+aspect_tools_telemetry_report" + ], + [ + "aspect_rules_esbuild+", + "bazel_skylib", + "bazel_skylib+" + ], + [ + "aspect_rules_js+", + "aspect_bazel_lib", + "aspect_bazel_lib+" + ], + [ + "aspect_rules_js+", + "aspect_rules_js", + "aspect_rules_js+" + ], + [ + "aspect_rules_js+", + "aspect_tools_telemetry_report", + "aspect_tools_telemetry++telemetry+aspect_tools_telemetry_report" + ], + [ + "aspect_rules_js+", + "bazel_lib", + "bazel_lib+" + ], + [ + "aspect_rules_js+", + "bazel_skylib", + "bazel_skylib+" + ], + [ + "aspect_rules_js+", + "bazel_tools", + "bazel_tools" + ], + [ + "bazel_lib+", + "bazel_skylib", + "bazel_skylib+" + ], + [ + "bazel_lib+", + "bazel_tools", + "bazel_tools" + ], + [ + "tar.bzl+", + "bazel_lib", + "bazel_lib+" + ], + [ + "tar.bzl+", + "bazel_skylib", + "bazel_skylib+" + ], + [ + "tar.bzl+", + "tar.bzl", + "tar.bzl+" + ] + ] + } + }, + "@@aspect_rules_js+//npm:extensions.bzl%pnpm": { + "general": { + "bzlTransitiveDigest": "VaGKuK2sKVTWlq9QBZfNc4fhigCeN9Wt4YhnhdGUkv8=", + "usagesDigest": "/NqvQUP/nSwl7fsTFSQHEZJU5rTvs4M1h1n8n0KpF7Q=", + "recordedFileInputs": {}, + "recordedDirentsInputs": {}, + "envVariables": {}, + "generatedRepoSpecs": { + "pnpm": { + "repoRuleId": "@@aspect_rules_js+//npm/private:npm_import.bzl%npm_import_rule", + "attributes": { + "package": "pnpm", + "version": "10.28.0", + "root_package": "", + "link_workspace": "", + "link_packages": {}, + "integrity": "sha512-Bd9x0UIfITmeBT/eVnzqNNRG+gLHZXFEG/wceVbpjjYwiJgtlARl/TRIDU2QoGaLwSNi+KqIAApk6D0LDke+SA==", + "url": "", + "commit": "", + "patch_args": [ + "-p0" + ], + "patches": [], + "custom_postinstall": "", + "npm_auth": "", + "npm_auth_basic": "", + "npm_auth_username": "", + "npm_auth_password": "", + "lifecycle_hooks": [], + "extra_build_content": "load(\"@aspect_rules_js//js:defs.bzl\", \"js_binary\")\njs_binary(name = \"pnpm\", data = glob([\"package/**\"]), entry_point = \"package/dist/pnpm.cjs\", visibility = [\"//visibility:public\"])", + "generate_bzl_library_targets": false, + "extract_full_archive": true, + "exclude_package_contents": [] + } + }, + "pnpm__links": { + "repoRuleId": "@@aspect_rules_js+//npm/private:npm_import.bzl%npm_import_links", + "attributes": { + "package": "pnpm", + "version": "10.28.0", + "dev": false, + "root_package": "", + "link_packages": {}, + "deps": {}, + "transitive_closure": {}, + "lifecycle_build_target": false, + "lifecycle_hooks_env": [], + "lifecycle_hooks_execution_requirements": [ + "no-sandbox" + ], + "lifecycle_hooks_use_default_shell_env": false, + "bins": {}, + "package_visibility": [ + "//visibility:public" + ], + "replace_package": "", + "exclude_package_contents": [] + } + } + }, + "recordedRepoMappingEntries": [ + [ + "aspect_bazel_lib+", + "bazel_lib", + "bazel_lib+" + ], + [ + "aspect_bazel_lib+", + "bazel_skylib", + "bazel_skylib+" + ], + [ + "aspect_bazel_lib+", + "bazel_tools", + "bazel_tools" + ], + [ + "aspect_bazel_lib+", + "tar.bzl", + "tar.bzl+" + ], + [ + "aspect_rules_js+", + "aspect_bazel_lib", + "aspect_bazel_lib+" + ], + [ + "aspect_rules_js+", + "aspect_rules_js", + "aspect_rules_js+" + ], + [ + "aspect_rules_js+", + "aspect_tools_telemetry_report", + "aspect_tools_telemetry++telemetry+aspect_tools_telemetry_report" + ], + [ + "aspect_rules_js+", + "bazel_features", + "bazel_features+" + ], + [ + "aspect_rules_js+", + "bazel_lib", + "bazel_lib+" + ], + [ + "aspect_rules_js+", + "bazel_skylib", + "bazel_skylib+" + ], + [ + "aspect_rules_js+", + "bazel_tools", + "bazel_tools" + ], + [ + "bazel_features+", + "bazel_features_globals", + "bazel_features++version_extension+bazel_features_globals" + ], + [ + "bazel_features+", + "bazel_features_version", + "bazel_features++version_extension+bazel_features_version" + ], + [ + "bazel_lib+", + "bazel_skylib", + "bazel_skylib+" + ], + [ + "bazel_lib+", + "bazel_tools", + "bazel_tools" + ], + [ + "tar.bzl+", + "bazel_lib", + "bazel_lib+" + ], + [ + "tar.bzl+", + "bazel_skylib", + "bazel_skylib+" + ], + [ + "tar.bzl+", + "tar.bzl", + "tar.bzl+" + ] + ] + } + }, + "@@aspect_rules_ts+//ts:extensions.bzl%ext": { + "general": { + "bzlTransitiveDigest": "7k3bewVApw4Kc6Rpho1Rrs1nrW/5jphUA5Mh1iHE2U4=", + "usagesDigest": "aaqqxEFKCRGFkeAf0pKmXvZZTLGYIk3pQsDFG28ZbNg=", + "recordedFileInputs": { + "@@rules_browsers+//package.json": "84dc1ba9b1c667a25894e97218bd8f247d54f24bb694efb397a881be3c06a4c5" + }, + "recordedDirentsInputs": {}, + "envVariables": {}, + "generatedRepoSpecs": { + "angular_cli_npm_typescript": { + "repoRuleId": "@@aspect_rules_ts+//ts/private:npm_repositories.bzl%http_archive_version", + "attributes": { + "version": "5.9.3", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "urls": [ + "https://registry.npmjs.org/typescript/-/typescript-{}.tgz" + ] + } + }, + "rules_angular_npm_typescript": { + "repoRuleId": "@@aspect_rules_ts+//ts/private:npm_repositories.bzl%http_archive_version", + "attributes": { + "version": "5.9.2", + "integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==", + "urls": [ + "https://registry.npmjs.org/typescript/-/typescript-{}.tgz" + ] + } + }, + "npm_typescript": { + "repoRuleId": "@@aspect_rules_ts+//ts/private:npm_repositories.bzl%http_archive_version", + "attributes": { + "version": "5.9.3", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "urls": [ + "https://registry.npmjs.org/typescript/-/typescript-{}.tgz" + ] + } + }, + "npm_rules_browsers_typescript": { + "repoRuleId": "@@aspect_rules_ts+//ts/private:npm_repositories.bzl%http_archive_version", + "attributes": { + "version": "", + "version_from": "@@rules_browsers+//:package.json", + "integrity": "", + "urls": [ + "https://registry.npmjs.org/typescript/-/typescript-{}.tgz" + ] + } + } + }, + "recordedRepoMappingEntries": [ + [ + "aspect_rules_ts+", + "aspect_rules_ts", + "aspect_rules_ts+" + ], + [ + "aspect_rules_ts+", + "bazel_tools", + "bazel_tools" + ] + ] + } + }, + "@@aspect_tools_telemetry+//:extension.bzl%telemetry": { + "general": { + "bzlTransitiveDigest": "cl5A2O84vDL6Tt+Qga8FCj1DUDGqn+e7ly5rZ+4xvcc=", + "usagesDigest": "jHASCmhI+ziv94KZ5hlx6t1ixFDdVXFm2VnOVVbAqww=", + "recordedFileInputs": {}, + "recordedDirentsInputs": {}, + "envVariables": {}, + "generatedRepoSpecs": { + "aspect_tools_telemetry_report": { + "repoRuleId": "@@aspect_tools_telemetry+//:extension.bzl%tel_repository", + "attributes": { + "deps": { + "aspect_rules_js": "2.8.3", + "aspect_rules_ts": "3.8.1", + "aspect_rules_esbuild": "0.25.0", + "aspect_rules_jasmine": "2.0.2", + "aspect_tools_telemetry": "0.3.3" + } + } + } + }, + "recordedRepoMappingEntries": [ + [ + "aspect_tools_telemetry+", + "bazel_lib", + "bazel_lib+" + ], + [ + "aspect_tools_telemetry+", + "bazel_skylib", + "bazel_skylib+" + ] + ] + } + }, + "@@pybind11_bazel+//:python_configure.bzl%extension": { + "general": { + "bzlTransitiveDigest": "c9ZWWeXeu6bctL4/SsY2otFWyeFN0JJ20+ymGyJZtWk=", + "usagesDigest": "fycyB39YnXIJkfWCIXLUKJMZzANcuLy9ZE73hRucjFk=", + "recordedFileInputs": { + "@@pybind11_bazel+//MODULE.bazel": "88af1c246226d87e65be78ed49ecd1e6f5e98648558c14ce99176da041dc378e" + }, + "recordedDirentsInputs": {}, + "envVariables": {}, + "generatedRepoSpecs": { + "local_config_python": { + "repoRuleId": "@@pybind11_bazel+//:python_configure.bzl%python_configure", "attributes": {} + }, + "pybind11": { + "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", + "attributes": { + "build_file": "@@pybind11_bazel+//:pybind11.BUILD", + "strip_prefix": "pybind11-2.11.1", + "urls": [ + "https://github.com/pybind/pybind11/archive/v2.11.1.zip" + ] + } } }, "recordedRepoMappingEntries": [ [ - "apple_support~", + "pybind11_bazel+", "bazel_tools", "bazel_tools" ] ] } }, - "@@platforms//host:extension.bzl%host_platform": { + "@@rules_angular+//setup:extensions.bzl%rules_angular": { "general": { - "bzlTransitiveDigest": "xelQcPZH8+tmuOHVjL9vDxMnnQNMlwj0SlvgoqBkm4U=", - "usagesDigest": "pCYpDQmqMbmiiPI1p2Kd3VLm5T48rRAht5WdW0X2GlA=", + "bzlTransitiveDigest": "fkaH7HMicL3g7/NDaFzlq39kcLopMyQ3KdbDn+5CRzA=", + "usagesDigest": "ZinuLP7QHxaW5achD0Vz19qElMu4r2LvGvh96Z5zYlA=", "recordedFileInputs": {}, "recordedDirentsInputs": {}, "envVariables": {}, "generatedRepoSpecs": { - "host_platform": { - "bzlFile": "@@platforms//host:extension.bzl", - "ruleClassName": "host_platform_repo", + "components_rules_angular_configurable_deps": { + "repoRuleId": "@@rules_angular+//setup:repositories.bzl%configurable_deps_repo", + "attributes": { + "angular_compiler_cli": "@@rules_angular+//:node_modules/@angular/compiler-cli", + "typescript": "@@rules_angular+//:node_modules/typescript" + } + }, + "rules_angular_configurable_deps": { + "repoRuleId": "@@rules_angular+//setup:repositories.bzl%configurable_deps_repo", + "attributes": { + "angular_compiler_cli": "@@rules_angular+//:node_modules/@angular/compiler-cli", + "typescript": "@@rules_angular+//:node_modules/typescript-local" + } + }, + "dev_infra_rules_angular_configurable_deps": { + "repoRuleId": "@@rules_angular+//setup:repositories.bzl%configurable_deps_repo", + "attributes": { + "angular_compiler_cli": "@@rules_angular+//:node_modules/@angular/compiler-cli", + "typescript": "@@rules_angular+//:node_modules/typescript" + } + } + }, + "recordedRepoMappingEntries": [] + } + }, + "@@rules_browsers+//browsers:extensions.bzl%browsers": { + "general": { + "bzlTransitiveDigest": "agkaLQ8wE1r/5IX6pkERzFxI/z0M42Em+ICNO6TXsVo=", + "usagesDigest": "FS7q5WaIwg3KirS3njhuPFkTIBYvDaTInVGrlzu0XL8=", + "recordedFileInputs": {}, + "recordedDirentsInputs": {}, + "envVariables": {}, + "generatedRepoSpecs": { + "rules_browsers_chrome_linux": { + "repoRuleId": "@@rules_browsers+//browsers/private:browser_repo.bzl%browser_repo", + "attributes": { + "sha256": "0a2ff0fc9eb5958b7b420f20e3968f424be7423fef89739e71565a48aa073a57", + "urls": [ + "https://storage.googleapis.com/chrome-for-testing-public/145.0.7586.0/linux64/chrome-headless-shell-linux64.zip" + ], + "named_files": { + "CHROME-HEADLESS-SHELL": "chrome-headless-shell-linux64/chrome-headless-shell" + }, + "exclude_patterns": [ + "**/*.log" + ], + "exports_files": [ + "chrome-headless-shell-linux64/chrome-headless-shell" + ] + } + }, + "rules_browsers_chrome_mac": { + "repoRuleId": "@@rules_browsers+//browsers/private:browser_repo.bzl%browser_repo", + "attributes": { + "sha256": "e6076b1201d86f74c5eab982a239d5af83e66b1aa4d780bcb792698790e01d87", + "urls": [ + "https://storage.googleapis.com/chrome-for-testing-public/145.0.7586.0/mac-x64/chrome-headless-shell-mac-x64.zip" + ], + "named_files": { + "CHROME-HEADLESS-SHELL": "chrome-headless-shell-mac-x64/chrome-headless-shell" + }, + "exclude_patterns": [ + "**/*.log" + ], + "exports_files": [ + "chrome-headless-shell-mac-x64/chrome-headless-shell" + ] + } + }, + "rules_browsers_chrome_mac_arm": { + "repoRuleId": "@@rules_browsers+//browsers/private:browser_repo.bzl%browser_repo", + "attributes": { + "sha256": "b74dbcf5543d916b02d0a133e2e7c6a4de251f06733f72c2c15ea8c42213f63b", + "urls": [ + "https://storage.googleapis.com/chrome-for-testing-public/145.0.7586.0/mac-arm64/chrome-headless-shell-mac-arm64.zip" + ], + "named_files": { + "CHROME-HEADLESS-SHELL": "chrome-headless-shell-mac-arm64/chrome-headless-shell" + }, + "exclude_patterns": [ + "**/*.log" + ], + "exports_files": [ + "chrome-headless-shell-mac-arm64/chrome-headless-shell" + ] + } + }, + "rules_browsers_chrome_win64": { + "repoRuleId": "@@rules_browsers+//browsers/private:browser_repo.bzl%browser_repo", + "attributes": { + "sha256": "df1e612dc3b1615e182a1f11821052995913c39df37caa52699de21a68d030d2", + "urls": [ + "https://storage.googleapis.com/chrome-for-testing-public/145.0.7586.0/win64/chrome-headless-shell-win64.zip" + ], + "named_files": { + "CHROME-HEADLESS-SHELL": "chrome-headless-shell-win64/chrome-headless-shell.exe" + }, + "exclude_patterns": [ + "**/*.log" + ], + "exports_files": [ + "chrome-headless-shell-win64/chrome-headless-shell.exe" + ] + } + }, + "rules_browsers_chromedriver_linux": { + "repoRuleId": "@@rules_browsers+//browsers/private:browser_repo.bzl%browser_repo", + "attributes": { + "sha256": "69c504306399d979a2766fea603c3fb9d3d87d46c75bddc9f2a049b4f636d57c", + "urls": [ + "https://storage.googleapis.com/chrome-for-testing-public/145.0.7586.0/linux64/chromedriver-linux64.zip" + ], + "named_files": { + "CHROMEDRIVER": "chromedriver-linux64/chromedriver" + }, + "exclude_patterns": [], + "exports_files": [ + "chromedriver-linux64/chromedriver" + ] + } + }, + "rules_browsers_chromedriver_mac": { + "repoRuleId": "@@rules_browsers+//browsers/private:browser_repo.bzl%browser_repo", + "attributes": { + "sha256": "5fc9d6f594fc5f2568a15145f25116dd8e9c9a60baa8da4bb21a17650fb00e7e", + "urls": [ + "https://storage.googleapis.com/chrome-for-testing-public/145.0.7586.0/mac-x64/chromedriver-mac-x64.zip" + ], + "named_files": { + "CHROMEDRIVER": "chromedriver-mac-x64/chromedriver" + }, + "exclude_patterns": [], + "exports_files": [ + "chromedriver-mac-x64/chromedriver" + ] + } + }, + "rules_browsers_chromedriver_mac_arm": { + "repoRuleId": "@@rules_browsers+//browsers/private:browser_repo.bzl%browser_repo", + "attributes": { + "sha256": "14e92294c2c3639ca4e7d27e850588b619d698e2f8905cee368f07db2e1bf1e9", + "urls": [ + "https://storage.googleapis.com/chrome-for-testing-public/145.0.7586.0/mac-arm64/chromedriver-mac-arm64.zip" + ], + "named_files": { + "CHROMEDRIVER": "chromedriver-mac-arm64/chromedriver" + }, + "exclude_patterns": [], + "exports_files": [ + "chromedriver-mac-arm64/chromedriver" + ] + } + }, + "rules_browsers_chromedriver_win64": { + "repoRuleId": "@@rules_browsers+//browsers/private:browser_repo.bzl%browser_repo", + "attributes": { + "sha256": "cf641d2e176db95bcc158cd90eafd347ad4928fa0458a5f3bfd56c6d983e70db", + "urls": [ + "https://storage.googleapis.com/chrome-for-testing-public/145.0.7586.0/win64/chromedriver-win64.zip" + ], + "named_files": { + "CHROMEDRIVER": "chromedriver-win64/chromedriver.exe" + }, + "exclude_patterns": [], + "exports_files": [ + "chromedriver-win64/chromedriver.exe" + ] + } + }, + "rules_browsers_firefox_linux": { + "repoRuleId": "@@rules_browsers+//browsers/private:browser_repo.bzl%browser_repo", + "attributes": { + "sha256": "8d56f479cc398a537a60a3fa20dca92d8a41925113d3a67f534881a4e4d7e344", + "urls": [ + "https://archive.mozilla.org/pub/firefox/releases/146.0/linux-x86_64/en-US/firefox-146.0.tar.xz" + ], + "named_files": { + "FIREFOX": "firefox/firefox" + }, + "exclude_patterns": [], + "exports_files": [ + "firefox/firefox" + ] + } + }, + "rules_browsers_firefox_mac": { + "repoRuleId": "@@rules_browsers+//browsers/private:browser_repo.bzl%browser_repo", + "attributes": { + "sha256": "4b1645313887972d466cd82166ea571485c2c40a167f84624e3f3ca739993cc9", + "urls": [ + "https://archive.mozilla.org/pub/firefox/releases/146.0/mac/en-US/Firefox%20146.0.dmg" + ], + "named_files": { + "FIREFOX": "Firefox.app/Contents/MacOS/firefox" + }, + "exclude_patterns": [], + "exports_files": [ + "Firefox.app/Contents/MacOS/firefox" + ] + } + }, + "rules_browsers_firefox_mac_arm": { + "repoRuleId": "@@rules_browsers+//browsers/private:browser_repo.bzl%browser_repo", + "attributes": { + "sha256": "4b1645313887972d466cd82166ea571485c2c40a167f84624e3f3ca739993cc9", + "urls": [ + "https://archive.mozilla.org/pub/firefox/releases/146.0/mac/en-US/Firefox%20146.0.dmg" + ], + "named_files": { + "FIREFOX": "Firefox.app/Contents/MacOS/firefox" + }, + "exclude_patterns": [], + "exports_files": [ + "Firefox.app/Contents/MacOS/firefox" + ] + } + }, + "rules_browsers_firefox_win64": { + "repoRuleId": "@@rules_browsers+//browsers/private:browser_repo.bzl%browser_repo", + "attributes": { + "sha256": "216870c89648f32450cfefb5cec417fcd66d480d5dc83f894bf99f5fd7f38dbb", + "urls": [ + "https://archive.mozilla.org/pub/firefox/releases/146.0/win64/en-US/Firefox%20Setup%20146.0.exe" + ], + "named_files": { + "FIREFOX": "core/firefox.exe" + }, + "exclude_patterns": [], + "exports_files": [ + "core/firefox.exe" + ] + } + } + }, + "recordedRepoMappingEntries": [] + } + }, + "@@rules_fuzzing+//fuzzing/private:extensions.bzl%non_module_dependencies": { + "general": { + "bzlTransitiveDigest": "WHRlQQnxW7e7XMRBhq7SARkDarLDOAbg6iLaJpk5QYM=", + "usagesDigest": "wy6ISK6UOcBEjj/mvJ/S3WeXoO67X+1llb9yPyFtPgc=", + "recordedFileInputs": {}, + "recordedDirentsInputs": {}, + "envVariables": {}, + "generatedRepoSpecs": { + "platforms": { + "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", + "attributes": { + "urls": [ + "https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.8/platforms-0.0.8.tar.gz", + "https://github.com/bazelbuild/platforms/releases/download/0.0.8/platforms-0.0.8.tar.gz" + ], + "sha256": "8150406605389ececb6da07cbcb509d5637a3ab9a24bc69b1101531367d89d74" + } + }, + "rules_python": { + "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", + "attributes": { + "sha256": "d70cd72a7a4880f0000a6346253414825c19cdd40a28289bdf67b8e6480edff8", + "strip_prefix": "rules_python-0.28.0", + "url": "https://github.com/bazelbuild/rules_python/releases/download/0.28.0/rules_python-0.28.0.tar.gz" + } + }, + "bazel_skylib": { + "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", + "attributes": { + "sha256": "cd55a062e763b9349921f0f5db8c3933288dc8ba4f76dd9416aac68acee3cb94", + "urls": [ + "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz", + "https://github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz" + ] + } + }, + "com_google_absl": { + "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", + "attributes": { + "urls": [ + "https://github.com/abseil/abseil-cpp/archive/refs/tags/20240116.1.zip" + ], + "strip_prefix": "abseil-cpp-20240116.1", + "integrity": "sha256-7capMWOvWyoYbUaHF/b+I2U6XLMaHmky8KugWvfXYuk=" + } + }, + "rules_fuzzing_oss_fuzz": { + "repoRuleId": "@@rules_fuzzing+//fuzzing/private/oss_fuzz:repository.bzl%oss_fuzz_repository", "attributes": {} + }, + "honggfuzz": { + "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", + "attributes": { + "build_file": "@@rules_fuzzing+//:honggfuzz.BUILD", + "sha256": "6b18ba13bc1f36b7b950c72d80f19ea67fbadc0ac0bb297ec89ad91f2eaa423e", + "url": "https://github.com/google/honggfuzz/archive/2.5.zip", + "strip_prefix": "honggfuzz-2.5" + } + }, + "rules_fuzzing_jazzer": { + "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_jar", + "attributes": { + "sha256": "ee6feb569d88962d59cb59e8a31eb9d007c82683f3ebc64955fd5b96f277eec2", + "url": "https://repo1.maven.org/maven2/com/code-intelligence/jazzer/0.20.1/jazzer-0.20.1.jar" + } + }, + "rules_fuzzing_jazzer_api": { + "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_jar", + "attributes": { + "sha256": "f5a60242bc408f7fa20fccf10d6c5c5ea1fcb3c6f44642fec5af88373ae7aa1b", + "url": "https://repo1.maven.org/maven2/com/code-intelligence/jazzer-api/0.20.1/jazzer-api-0.20.1.jar" + } + } + }, + "recordedRepoMappingEntries": [ + [ + "rules_fuzzing+", + "bazel_tools", + "bazel_tools" + ] + ] + } + }, + "@@rules_kotlin+//src/main/starlark/core/repositories:bzlmod_setup.bzl%rules_kotlin_extensions": { + "general": { + "bzlTransitiveDigest": "rL/34P1aFDq2GqVC2zCFgQ8nTuOC6ziogocpvG50Qz8=", + "usagesDigest": "QI2z8ZUR+mqtbwsf2fLqYdJAkPOHdOV+tF2yVAUgRzw=", + "recordedFileInputs": {}, + "recordedDirentsInputs": {}, + "envVariables": {}, + "generatedRepoSpecs": { + "com_github_jetbrains_kotlin_git": { + "repoRuleId": "@@rules_kotlin+//src/main/starlark/core/repositories:compiler.bzl%kotlin_compiler_git_repository", + "attributes": { + "urls": [ + "https://github.com/JetBrains/kotlin/releases/download/v1.9.23/kotlin-compiler-1.9.23.zip" + ], + "sha256": "93137d3aab9afa9b27cb06a824c2324195c6b6f6179d8a8653f440f5bd58be88" + } + }, + "com_github_jetbrains_kotlin": { + "repoRuleId": "@@rules_kotlin+//src/main/starlark/core/repositories:compiler.bzl%kotlin_capabilities_repository", + "attributes": { + "git_repository_name": "com_github_jetbrains_kotlin_git", + "compiler_version": "1.9.23" + } + }, + "com_github_google_ksp": { + "repoRuleId": "@@rules_kotlin+//src/main/starlark/core/repositories:ksp.bzl%ksp_compiler_plugin_repository", + "attributes": { + "urls": [ + "https://github.com/google/ksp/releases/download/1.9.23-1.0.20/artifacts.zip" + ], + "sha256": "ee0618755913ef7fd6511288a232e8fad24838b9af6ea73972a76e81053c8c2d", + "strip_version": "1.9.23-1.0.20" + } + }, + "com_github_pinterest_ktlint": { + "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_file", + "attributes": { + "sha256": "01b2e0ef893383a50dbeb13970fe7fa3be36ca3e83259e01649945b09d736985", + "urls": [ + "https://github.com/pinterest/ktlint/releases/download/1.3.0/ktlint" + ], + "executable": true + } + }, + "rules_android": { + "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", + "attributes": { + "sha256": "cd06d15dd8bb59926e4d65f9003bfc20f9da4b2519985c27e190cddc8b7a7806", + "strip_prefix": "rules_android-0.1.1", + "urls": [ + "https://github.com/bazelbuild/rules_android/archive/v0.1.1.zip" + ] + } + } + }, + "recordedRepoMappingEntries": [ + [ + "rules_kotlin+", + "bazel_tools", + "bazel_tools" + ] + ] + } + }, + "@@rules_nodejs+//nodejs:extensions.bzl%node": { + "general": { + "bzlTransitiveDigest": "NwcLXHrbh2hoorA/Ybmcpjxsn/6avQmewDglodkDrgo=", + "usagesDigest": "oW5D6Ox6De/XR9eunsl7akWWBPexdZKf4h2iPvm7FoY=", + "recordedFileInputs": {}, + "recordedDirentsInputs": {}, + "envVariables": {}, + "generatedRepoSpecs": { + "nodejs_linux_amd64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": { + "22.22.0-darwin_arm64": [ + "node-v22.22.0-darwin-arm64.tar.gz", + "node-v22.22.0-darwin-arm64", + "5ed4db0fcf1eaf84d91ad12462631d73bf4576c1377e192d222e48026a902640" + ], + "22.22.0-darwin_amd64": [ + "node-v22.22.0-darwin-x64.tar.gz", + "node-v22.22.0-darwin-x64", + "5ea50c9d6dea3dfa3abb66b2656f7a4e1c8cef23432b558d45fb538c7b5dedce" + ], + "22.22.0-linux_arm64": [ + "node-v22.22.0-linux-arm64.tar.xz", + "node-v22.22.0-linux-arm64", + "1bf1eb9ee63ffc4e5d324c0b9b62cf4a289f44332dfef9607cea1a0d9596ba6f" + ], + "22.22.0-linux_ppc64le": [ + "node-v22.22.0-linux-ppc64le.tar.xz", + "node-v22.22.0-linux-ppc64le", + "d83b9957431cc18e1fc143a4b99f89cde7b8a18f53ef392231b4336afd058865" + ], + "22.22.0-linux_s390x": [ + "node-v22.22.0-linux-s390x.tar.xz", + "node-v22.22.0-linux-s390x", + "5aa0e520689448c4233e8d73f284e8e0634fdcd32b479735698494be5641f3e4" + ], + "22.22.0-linux_amd64": [ + "node-v22.22.0-linux-x64.tar.xz", + "node-v22.22.0-linux-x64", + "9aa8e9d2298ab68c600bd6fb86a6c13bce11a4eca1ba9b39d79fa021755d7c37" + ], + "22.22.0-windows_amd64": [ + "node-v22.22.0-win-x64.zip", + "node-v22.22.0-win-x64", + "c97fa376d2becdc8863fcd3ca2dd9a83a9f3468ee7ccf7a6d076ec66a645c77a" + ] + }, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.22.0", + "include_headers": false, + "platform": "linux_amd64" + } + }, + "nodejs_linux_arm64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": { + "22.22.0-darwin_arm64": [ + "node-v22.22.0-darwin-arm64.tar.gz", + "node-v22.22.0-darwin-arm64", + "5ed4db0fcf1eaf84d91ad12462631d73bf4576c1377e192d222e48026a902640" + ], + "22.22.0-darwin_amd64": [ + "node-v22.22.0-darwin-x64.tar.gz", + "node-v22.22.0-darwin-x64", + "5ea50c9d6dea3dfa3abb66b2656f7a4e1c8cef23432b558d45fb538c7b5dedce" + ], + "22.22.0-linux_arm64": [ + "node-v22.22.0-linux-arm64.tar.xz", + "node-v22.22.0-linux-arm64", + "1bf1eb9ee63ffc4e5d324c0b9b62cf4a289f44332dfef9607cea1a0d9596ba6f" + ], + "22.22.0-linux_ppc64le": [ + "node-v22.22.0-linux-ppc64le.tar.xz", + "node-v22.22.0-linux-ppc64le", + "d83b9957431cc18e1fc143a4b99f89cde7b8a18f53ef392231b4336afd058865" + ], + "22.22.0-linux_s390x": [ + "node-v22.22.0-linux-s390x.tar.xz", + "node-v22.22.0-linux-s390x", + "5aa0e520689448c4233e8d73f284e8e0634fdcd32b479735698494be5641f3e4" + ], + "22.22.0-linux_amd64": [ + "node-v22.22.0-linux-x64.tar.xz", + "node-v22.22.0-linux-x64", + "9aa8e9d2298ab68c600bd6fb86a6c13bce11a4eca1ba9b39d79fa021755d7c37" + ], + "22.22.0-windows_amd64": [ + "node-v22.22.0-win-x64.zip", + "node-v22.22.0-win-x64", + "c97fa376d2becdc8863fcd3ca2dd9a83a9f3468ee7ccf7a6d076ec66a645c77a" + ] + }, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.22.0", + "include_headers": false, + "platform": "linux_arm64" + } + }, + "nodejs_linux_s390x": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": { + "22.22.0-darwin_arm64": [ + "node-v22.22.0-darwin-arm64.tar.gz", + "node-v22.22.0-darwin-arm64", + "5ed4db0fcf1eaf84d91ad12462631d73bf4576c1377e192d222e48026a902640" + ], + "22.22.0-darwin_amd64": [ + "node-v22.22.0-darwin-x64.tar.gz", + "node-v22.22.0-darwin-x64", + "5ea50c9d6dea3dfa3abb66b2656f7a4e1c8cef23432b558d45fb538c7b5dedce" + ], + "22.22.0-linux_arm64": [ + "node-v22.22.0-linux-arm64.tar.xz", + "node-v22.22.0-linux-arm64", + "1bf1eb9ee63ffc4e5d324c0b9b62cf4a289f44332dfef9607cea1a0d9596ba6f" + ], + "22.22.0-linux_ppc64le": [ + "node-v22.22.0-linux-ppc64le.tar.xz", + "node-v22.22.0-linux-ppc64le", + "d83b9957431cc18e1fc143a4b99f89cde7b8a18f53ef392231b4336afd058865" + ], + "22.22.0-linux_s390x": [ + "node-v22.22.0-linux-s390x.tar.xz", + "node-v22.22.0-linux-s390x", + "5aa0e520689448c4233e8d73f284e8e0634fdcd32b479735698494be5641f3e4" + ], + "22.22.0-linux_amd64": [ + "node-v22.22.0-linux-x64.tar.xz", + "node-v22.22.0-linux-x64", + "9aa8e9d2298ab68c600bd6fb86a6c13bce11a4eca1ba9b39d79fa021755d7c37" + ], + "22.22.0-windows_amd64": [ + "node-v22.22.0-win-x64.zip", + "node-v22.22.0-win-x64", + "c97fa376d2becdc8863fcd3ca2dd9a83a9f3468ee7ccf7a6d076ec66a645c77a" + ] + }, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.22.0", + "include_headers": false, + "platform": "linux_s390x" + } + }, + "nodejs_linux_ppc64le": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": { + "22.22.0-darwin_arm64": [ + "node-v22.22.0-darwin-arm64.tar.gz", + "node-v22.22.0-darwin-arm64", + "5ed4db0fcf1eaf84d91ad12462631d73bf4576c1377e192d222e48026a902640" + ], + "22.22.0-darwin_amd64": [ + "node-v22.22.0-darwin-x64.tar.gz", + "node-v22.22.0-darwin-x64", + "5ea50c9d6dea3dfa3abb66b2656f7a4e1c8cef23432b558d45fb538c7b5dedce" + ], + "22.22.0-linux_arm64": [ + "node-v22.22.0-linux-arm64.tar.xz", + "node-v22.22.0-linux-arm64", + "1bf1eb9ee63ffc4e5d324c0b9b62cf4a289f44332dfef9607cea1a0d9596ba6f" + ], + "22.22.0-linux_ppc64le": [ + "node-v22.22.0-linux-ppc64le.tar.xz", + "node-v22.22.0-linux-ppc64le", + "d83b9957431cc18e1fc143a4b99f89cde7b8a18f53ef392231b4336afd058865" + ], + "22.22.0-linux_s390x": [ + "node-v22.22.0-linux-s390x.tar.xz", + "node-v22.22.0-linux-s390x", + "5aa0e520689448c4233e8d73f284e8e0634fdcd32b479735698494be5641f3e4" + ], + "22.22.0-linux_amd64": [ + "node-v22.22.0-linux-x64.tar.xz", + "node-v22.22.0-linux-x64", + "9aa8e9d2298ab68c600bd6fb86a6c13bce11a4eca1ba9b39d79fa021755d7c37" + ], + "22.22.0-windows_amd64": [ + "node-v22.22.0-win-x64.zip", + "node-v22.22.0-win-x64", + "c97fa376d2becdc8863fcd3ca2dd9a83a9f3468ee7ccf7a6d076ec66a645c77a" + ] + }, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.22.0", + "include_headers": false, + "platform": "linux_ppc64le" + } + }, + "nodejs_darwin_amd64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": { + "22.22.0-darwin_arm64": [ + "node-v22.22.0-darwin-arm64.tar.gz", + "node-v22.22.0-darwin-arm64", + "5ed4db0fcf1eaf84d91ad12462631d73bf4576c1377e192d222e48026a902640" + ], + "22.22.0-darwin_amd64": [ + "node-v22.22.0-darwin-x64.tar.gz", + "node-v22.22.0-darwin-x64", + "5ea50c9d6dea3dfa3abb66b2656f7a4e1c8cef23432b558d45fb538c7b5dedce" + ], + "22.22.0-linux_arm64": [ + "node-v22.22.0-linux-arm64.tar.xz", + "node-v22.22.0-linux-arm64", + "1bf1eb9ee63ffc4e5d324c0b9b62cf4a289f44332dfef9607cea1a0d9596ba6f" + ], + "22.22.0-linux_ppc64le": [ + "node-v22.22.0-linux-ppc64le.tar.xz", + "node-v22.22.0-linux-ppc64le", + "d83b9957431cc18e1fc143a4b99f89cde7b8a18f53ef392231b4336afd058865" + ], + "22.22.0-linux_s390x": [ + "node-v22.22.0-linux-s390x.tar.xz", + "node-v22.22.0-linux-s390x", + "5aa0e520689448c4233e8d73f284e8e0634fdcd32b479735698494be5641f3e4" + ], + "22.22.0-linux_amd64": [ + "node-v22.22.0-linux-x64.tar.xz", + "node-v22.22.0-linux-x64", + "9aa8e9d2298ab68c600bd6fb86a6c13bce11a4eca1ba9b39d79fa021755d7c37" + ], + "22.22.0-windows_amd64": [ + "node-v22.22.0-win-x64.zip", + "node-v22.22.0-win-x64", + "c97fa376d2becdc8863fcd3ca2dd9a83a9f3468ee7ccf7a6d076ec66a645c77a" + ] + }, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.22.0", + "include_headers": false, + "platform": "darwin_amd64" + } + }, + "nodejs_darwin_arm64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": { + "22.22.0-darwin_arm64": [ + "node-v22.22.0-darwin-arm64.tar.gz", + "node-v22.22.0-darwin-arm64", + "5ed4db0fcf1eaf84d91ad12462631d73bf4576c1377e192d222e48026a902640" + ], + "22.22.0-darwin_amd64": [ + "node-v22.22.0-darwin-x64.tar.gz", + "node-v22.22.0-darwin-x64", + "5ea50c9d6dea3dfa3abb66b2656f7a4e1c8cef23432b558d45fb538c7b5dedce" + ], + "22.22.0-linux_arm64": [ + "node-v22.22.0-linux-arm64.tar.xz", + "node-v22.22.0-linux-arm64", + "1bf1eb9ee63ffc4e5d324c0b9b62cf4a289f44332dfef9607cea1a0d9596ba6f" + ], + "22.22.0-linux_ppc64le": [ + "node-v22.22.0-linux-ppc64le.tar.xz", + "node-v22.22.0-linux-ppc64le", + "d83b9957431cc18e1fc143a4b99f89cde7b8a18f53ef392231b4336afd058865" + ], + "22.22.0-linux_s390x": [ + "node-v22.22.0-linux-s390x.tar.xz", + "node-v22.22.0-linux-s390x", + "5aa0e520689448c4233e8d73f284e8e0634fdcd32b479735698494be5641f3e4" + ], + "22.22.0-linux_amd64": [ + "node-v22.22.0-linux-x64.tar.xz", + "node-v22.22.0-linux-x64", + "9aa8e9d2298ab68c600bd6fb86a6c13bce11a4eca1ba9b39d79fa021755d7c37" + ], + "22.22.0-windows_amd64": [ + "node-v22.22.0-win-x64.zip", + "node-v22.22.0-win-x64", + "c97fa376d2becdc8863fcd3ca2dd9a83a9f3468ee7ccf7a6d076ec66a645c77a" + ] + }, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.22.0", + "include_headers": false, + "platform": "darwin_arm64" + } + }, + "nodejs_windows_amd64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": { + "22.22.0-darwin_arm64": [ + "node-v22.22.0-darwin-arm64.tar.gz", + "node-v22.22.0-darwin-arm64", + "5ed4db0fcf1eaf84d91ad12462631d73bf4576c1377e192d222e48026a902640" + ], + "22.22.0-darwin_amd64": [ + "node-v22.22.0-darwin-x64.tar.gz", + "node-v22.22.0-darwin-x64", + "5ea50c9d6dea3dfa3abb66b2656f7a4e1c8cef23432b558d45fb538c7b5dedce" + ], + "22.22.0-linux_arm64": [ + "node-v22.22.0-linux-arm64.tar.xz", + "node-v22.22.0-linux-arm64", + "1bf1eb9ee63ffc4e5d324c0b9b62cf4a289f44332dfef9607cea1a0d9596ba6f" + ], + "22.22.0-linux_ppc64le": [ + "node-v22.22.0-linux-ppc64le.tar.xz", + "node-v22.22.0-linux-ppc64le", + "d83b9957431cc18e1fc143a4b99f89cde7b8a18f53ef392231b4336afd058865" + ], + "22.22.0-linux_s390x": [ + "node-v22.22.0-linux-s390x.tar.xz", + "node-v22.22.0-linux-s390x", + "5aa0e520689448c4233e8d73f284e8e0634fdcd32b479735698494be5641f3e4" + ], + "22.22.0-linux_amd64": [ + "node-v22.22.0-linux-x64.tar.xz", + "node-v22.22.0-linux-x64", + "9aa8e9d2298ab68c600bd6fb86a6c13bce11a4eca1ba9b39d79fa021755d7c37" + ], + "22.22.0-windows_amd64": [ + "node-v22.22.0-win-x64.zip", + "node-v22.22.0-win-x64", + "c97fa376d2becdc8863fcd3ca2dd9a83a9f3468ee7ccf7a6d076ec66a645c77a" + ] + }, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.22.0", + "include_headers": false, + "platform": "windows_amd64" + } + }, + "nodejs_windows_arm64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": { + "22.22.0-darwin_arm64": [ + "node-v22.22.0-darwin-arm64.tar.gz", + "node-v22.22.0-darwin-arm64", + "5ed4db0fcf1eaf84d91ad12462631d73bf4576c1377e192d222e48026a902640" + ], + "22.22.0-darwin_amd64": [ + "node-v22.22.0-darwin-x64.tar.gz", + "node-v22.22.0-darwin-x64", + "5ea50c9d6dea3dfa3abb66b2656f7a4e1c8cef23432b558d45fb538c7b5dedce" + ], + "22.22.0-linux_arm64": [ + "node-v22.22.0-linux-arm64.tar.xz", + "node-v22.22.0-linux-arm64", + "1bf1eb9ee63ffc4e5d324c0b9b62cf4a289f44332dfef9607cea1a0d9596ba6f" + ], + "22.22.0-linux_ppc64le": [ + "node-v22.22.0-linux-ppc64le.tar.xz", + "node-v22.22.0-linux-ppc64le", + "d83b9957431cc18e1fc143a4b99f89cde7b8a18f53ef392231b4336afd058865" + ], + "22.22.0-linux_s390x": [ + "node-v22.22.0-linux-s390x.tar.xz", + "node-v22.22.0-linux-s390x", + "5aa0e520689448c4233e8d73f284e8e0634fdcd32b479735698494be5641f3e4" + ], + "22.22.0-linux_amd64": [ + "node-v22.22.0-linux-x64.tar.xz", + "node-v22.22.0-linux-x64", + "9aa8e9d2298ab68c600bd6fb86a6c13bce11a4eca1ba9b39d79fa021755d7c37" + ], + "22.22.0-windows_amd64": [ + "node-v22.22.0-win-x64.zip", + "node-v22.22.0-win-x64", + "c97fa376d2becdc8863fcd3ca2dd9a83a9f3468ee7ccf7a6d076ec66a645c77a" + ] + }, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.22.0", + "include_headers": false, + "platform": "windows_arm64" + } + }, + "nodejs": { + "repoRuleId": "@@rules_nodejs+//nodejs/private:nodejs_repo_host_os_alias.bzl%nodejs_repo_host_os_alias", + "attributes": { + "user_node_repository_name": "nodejs" + } + }, + "nodejs_host": { + "repoRuleId": "@@rules_nodejs+//nodejs/private:nodejs_repo_host_os_alias.bzl%nodejs_repo_host_os_alias", + "attributes": { + "user_node_repository_name": "nodejs" + } + }, + "nodejs_toolchains": { + "repoRuleId": "@@rules_nodejs+//nodejs/private:nodejs_toolchains_repo.bzl%nodejs_toolchains_repo", + "attributes": { + "user_node_repository_name": "nodejs" + } + }, + "node20_linux_amd64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "20.19.0", + "include_headers": false, + "platform": "linux_amd64" + } + }, + "node20_linux_arm64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "20.19.0", + "include_headers": false, + "platform": "linux_arm64" + } + }, + "node20_linux_s390x": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "20.19.0", + "include_headers": false, + "platform": "linux_s390x" + } + }, + "node20_linux_ppc64le": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "20.19.0", + "include_headers": false, + "platform": "linux_ppc64le" + } + }, + "node20_darwin_amd64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "20.19.0", + "include_headers": false, + "platform": "darwin_amd64" + } + }, + "node20_darwin_arm64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "20.19.0", + "include_headers": false, + "platform": "darwin_arm64" + } + }, + "node20_windows_amd64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "20.19.0", + "include_headers": false, + "platform": "windows_amd64" + } + }, + "node20_windows_arm64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "20.19.0", + "include_headers": false, + "platform": "windows_arm64" + } + }, + "node20": { + "repoRuleId": "@@rules_nodejs+//nodejs/private:nodejs_repo_host_os_alias.bzl%nodejs_repo_host_os_alias", + "attributes": { + "user_node_repository_name": "node20" + } + }, + "node20_host": { + "repoRuleId": "@@rules_nodejs+//nodejs/private:nodejs_repo_host_os_alias.bzl%nodejs_repo_host_os_alias", + "attributes": { + "user_node_repository_name": "node20" + } + }, + "node20_toolchains": { + "repoRuleId": "@@rules_nodejs+//nodejs/private:nodejs_toolchains_repo.bzl%nodejs_toolchains_repo", + "attributes": { + "user_node_repository_name": "node20" + } + }, + "node22_linux_amd64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.12.0", + "include_headers": false, + "platform": "linux_amd64" + } + }, + "node22_linux_arm64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.12.0", + "include_headers": false, + "platform": "linux_arm64" + } + }, + "node22_linux_s390x": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.12.0", + "include_headers": false, + "platform": "linux_s390x" + } + }, + "node22_linux_ppc64le": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.12.0", + "include_headers": false, + "platform": "linux_ppc64le" + } + }, + "node22_darwin_amd64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.12.0", + "include_headers": false, + "platform": "darwin_amd64" + } + }, + "node22_darwin_arm64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.12.0", + "include_headers": false, + "platform": "darwin_arm64" + } + }, + "node22_windows_amd64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.12.0", + "include_headers": false, + "platform": "windows_amd64" + } + }, + "node22_windows_arm64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "22.12.0", + "include_headers": false, + "platform": "windows_arm64" + } + }, + "node22": { + "repoRuleId": "@@rules_nodejs+//nodejs/private:nodejs_repo_host_os_alias.bzl%nodejs_repo_host_os_alias", + "attributes": { + "user_node_repository_name": "node22" + } + }, + "node22_host": { + "repoRuleId": "@@rules_nodejs+//nodejs/private:nodejs_repo_host_os_alias.bzl%nodejs_repo_host_os_alias", + "attributes": { + "user_node_repository_name": "node22" + } + }, + "node22_toolchains": { + "repoRuleId": "@@rules_nodejs+//nodejs/private:nodejs_toolchains_repo.bzl%nodejs_toolchains_repo", + "attributes": { + "user_node_repository_name": "node22" + } + }, + "node24_linux_amd64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "24.0.0", + "include_headers": false, + "platform": "linux_amd64" + } + }, + "node24_linux_arm64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "24.0.0", + "include_headers": false, + "platform": "linux_arm64" + } + }, + "node24_linux_s390x": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "24.0.0", + "include_headers": false, + "platform": "linux_s390x" + } + }, + "node24_linux_ppc64le": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "24.0.0", + "include_headers": false, + "platform": "linux_ppc64le" + } + }, + "node24_darwin_amd64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "24.0.0", + "include_headers": false, + "platform": "darwin_amd64" + } + }, + "node24_darwin_arm64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "24.0.0", + "include_headers": false, + "platform": "darwin_arm64" + } + }, + "node24_windows_amd64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "24.0.0", + "include_headers": false, + "platform": "windows_amd64" + } + }, + "node24_windows_arm64": { + "repoRuleId": "@@rules_nodejs+//nodejs:repositories.bzl%_nodejs_repositories", + "attributes": { + "node_download_auth": {}, + "node_repositories": {}, + "node_urls": [ + "https://nodejs.org/dist/v{version}/{filename}" + ], + "node_version": "24.0.0", + "include_headers": false, + "platform": "windows_arm64" + } + }, + "node24": { + "repoRuleId": "@@rules_nodejs+//nodejs/private:nodejs_repo_host_os_alias.bzl%nodejs_repo_host_os_alias", + "attributes": { + "user_node_repository_name": "node24" + } + }, + "node24_host": { + "repoRuleId": "@@rules_nodejs+//nodejs/private:nodejs_repo_host_os_alias.bzl%nodejs_repo_host_os_alias", + "attributes": { + "user_node_repository_name": "node24" + } + }, + "node24_toolchains": { + "repoRuleId": "@@rules_nodejs+//nodejs/private:nodejs_toolchains_repo.bzl%nodejs_toolchains_repo", + "attributes": { + "user_node_repository_name": "node24" + } + } + }, + "recordedRepoMappingEntries": [] + } + }, + "@@rules_python+//python/extensions:pip.bzl%pip": { + "general": { + "bzlTransitiveDigest": "rPZpN8uoLnuu3B+LRiijfMadoMlO1/dxOO8/emPCZV4=", + "usagesDigest": "AK1R124YPWwAs8z1CQYyjYuci8RO5Ofot+EP5ZCNQDc=", + "recordedFileInputs": { + "@@protobuf+//python/requirements.txt": "983be60d3cec4b319dcab6d48aeb3f5b2f7c3350f26b3a9e97486c37967c73c5", + "@@rules_fuzzing+//fuzzing/requirements.txt": "ab04664be026b632a0d2a2446c4f65982b7654f5b6851d2f9d399a19b7242a5b", + "@@rules_python+//tools/publish/requirements_darwin.txt": "2994136eab7e57b083c3de76faf46f70fad130bc8e7360a7fed2b288b69e79dc", + "@@rules_python+//tools/publish/requirements_linux.txt": "8175b4c8df50ae2f22d1706961884beeb54e7da27bd2447018314a175981997d", + "@@rules_python+//tools/publish/requirements_windows.txt": "7673adc71dc1a81d3661b90924d7a7c0fc998cd508b3cb4174337cef3f2de556" + }, + "recordedDirentsInputs": {}, + "envVariables": { + "RULES_PYTHON_REPO_DEBUG": null, + "RULES_PYTHON_REPO_DEBUG_VERBOSITY": null + }, + "generatedRepoSpecs": { + "pip_deps_310_numpy": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@pip_deps//{name}:{target}", + "python_interpreter_target": "@@rules_python++python+python_3_10_host//:python", + "repo": "pip_deps_310", + "requirement": "numpy<=1.26.1" + } + }, + "pip_deps_310_setuptools": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@pip_deps//{name}:{target}", + "python_interpreter_target": "@@rules_python++python+python_3_10_host//:python", + "repo": "pip_deps_310", + "requirement": "setuptools<=70.3.0" + } + }, + "pip_deps_311_numpy": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@pip_deps//{name}:{target}", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "pip_deps_311", + "requirement": "numpy<=1.26.1" + } + }, + "pip_deps_311_setuptools": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@pip_deps//{name}:{target}", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "pip_deps_311", + "requirement": "setuptools<=70.3.0" + } + }, + "pip_deps_312_numpy": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@pip_deps//{name}:{target}", + "python_interpreter_target": "@@rules_python++python+python_3_12_host//:python", + "repo": "pip_deps_312", + "requirement": "numpy<=1.26.1" + } + }, + "pip_deps_312_setuptools": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@pip_deps//{name}:{target}", + "python_interpreter_target": "@@rules_python++python+python_3_12_host//:python", + "repo": "pip_deps_312", + "requirement": "setuptools<=70.3.0" + } + }, + "pip_deps_38_numpy": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@pip_deps//{name}:{target}", + "python_interpreter_target": "@@rules_python++python+python_3_8_host//:python", + "repo": "pip_deps_38", + "requirement": "numpy<=1.26.1" + } + }, + "pip_deps_38_setuptools": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@pip_deps//{name}:{target}", + "python_interpreter_target": "@@rules_python++python+python_3_8_host//:python", + "repo": "pip_deps_38", + "requirement": "setuptools<=70.3.0" + } + }, + "pip_deps_39_numpy": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@pip_deps//{name}:{target}", + "python_interpreter_target": "@@rules_python++python+python_3_9_host//:python", + "repo": "pip_deps_39", + "requirement": "numpy<=1.26.1" + } + }, + "pip_deps_39_setuptools": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@pip_deps//{name}:{target}", + "python_interpreter_target": "@@rules_python++python+python_3_9_host//:python", + "repo": "pip_deps_39", + "requirement": "setuptools<=70.3.0" + } + }, + "rules_fuzzing_py_deps_310_absl_py": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_fuzzing_py_deps//{name}:{target}", + "extra_pip_args": [ + "--require-hashes" + ], + "python_interpreter_target": "@@rules_python++python+python_3_10_host//:python", + "repo": "rules_fuzzing_py_deps_310", + "requirement": "absl-py==2.0.0 --hash=sha256:9a28abb62774ae4e8edbe2dd4c49ffcd45a6a848952a5eccc6a49f3f0fc1e2f3" + } + }, + "rules_fuzzing_py_deps_310_six": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_fuzzing_py_deps//{name}:{target}", + "extra_pip_args": [ + "--require-hashes" + ], + "python_interpreter_target": "@@rules_python++python+python_3_10_host//:python", + "repo": "rules_fuzzing_py_deps_310", + "requirement": "six==1.16.0 --hash=sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254" + } + }, + "rules_fuzzing_py_deps_311_absl_py": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_fuzzing_py_deps//{name}:{target}", + "extra_pip_args": [ + "--require-hashes" + ], + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_fuzzing_py_deps_311", + "requirement": "absl-py==2.0.0 --hash=sha256:9a28abb62774ae4e8edbe2dd4c49ffcd45a6a848952a5eccc6a49f3f0fc1e2f3" + } + }, + "rules_fuzzing_py_deps_311_six": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_fuzzing_py_deps//{name}:{target}", + "extra_pip_args": [ + "--require-hashes" + ], + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_fuzzing_py_deps_311", + "requirement": "six==1.16.0 --hash=sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254" + } + }, + "rules_fuzzing_py_deps_312_absl_py": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_fuzzing_py_deps//{name}:{target}", + "extra_pip_args": [ + "--require-hashes" + ], + "python_interpreter_target": "@@rules_python++python+python_3_12_host//:python", + "repo": "rules_fuzzing_py_deps_312", + "requirement": "absl-py==2.0.0 --hash=sha256:9a28abb62774ae4e8edbe2dd4c49ffcd45a6a848952a5eccc6a49f3f0fc1e2f3" + } + }, + "rules_fuzzing_py_deps_312_six": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_fuzzing_py_deps//{name}:{target}", + "extra_pip_args": [ + "--require-hashes" + ], + "python_interpreter_target": "@@rules_python++python+python_3_12_host//:python", + "repo": "rules_fuzzing_py_deps_312", + "requirement": "six==1.16.0 --hash=sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254" + } + }, + "rules_fuzzing_py_deps_38_absl_py": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_fuzzing_py_deps//{name}:{target}", + "extra_pip_args": [ + "--require-hashes" + ], + "python_interpreter_target": "@@rules_python++python+python_3_8_host//:python", + "repo": "rules_fuzzing_py_deps_38", + "requirement": "absl-py==2.0.0 --hash=sha256:9a28abb62774ae4e8edbe2dd4c49ffcd45a6a848952a5eccc6a49f3f0fc1e2f3" + } + }, + "rules_fuzzing_py_deps_38_six": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_fuzzing_py_deps//{name}:{target}", + "extra_pip_args": [ + "--require-hashes" + ], + "python_interpreter_target": "@@rules_python++python+python_3_8_host//:python", + "repo": "rules_fuzzing_py_deps_38", + "requirement": "six==1.16.0 --hash=sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254" + } + }, + "rules_fuzzing_py_deps_39_absl_py": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_fuzzing_py_deps//{name}:{target}", + "extra_pip_args": [ + "--require-hashes" + ], + "python_interpreter_target": "@@rules_python++python+python_3_9_host//:python", + "repo": "rules_fuzzing_py_deps_39", + "requirement": "absl-py==2.0.0 --hash=sha256:9a28abb62774ae4e8edbe2dd4c49ffcd45a6a848952a5eccc6a49f3f0fc1e2f3" + } + }, + "rules_fuzzing_py_deps_39_six": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_fuzzing_py_deps//{name}:{target}", + "extra_pip_args": [ + "--require-hashes" + ], + "python_interpreter_target": "@@rules_python++python+python_3_9_host//:python", + "repo": "rules_fuzzing_py_deps_39", + "requirement": "six==1.16.0 --hash=sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254" + } + }, + "rules_python_publish_deps_311_backports_tarfile_py3_none_any_77e284d7": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "backports.tarfile-1.2.0-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "backports-tarfile==1.2.0", + "sha256": "77e284d754527b01fb1e6fa8a1afe577858ebe4e9dad8919e34c862cb399bc34", + "urls": [ + "https://files.pythonhosted.org/packages/b9/fa/123043af240e49752f1c4bd24da5053b6bd00cad78c2be53c0d1e8b975bc/backports.tarfile-1.2.0-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_backports_tarfile_sdist_d75e02c2": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "backports_tarfile-1.2.0.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "backports-tarfile==1.2.0", + "sha256": "d75e02c268746e1b8144c278978b6e98e85de6ad16f8e4b0844a154557eca991", + "urls": [ + "https://files.pythonhosted.org/packages/86/72/cd9b395f25e290e633655a100af28cb253e4393396264a98bd5f5951d50f/backports_tarfile-1.2.0.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_certifi_py3_none_any_922820b5": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "certifi-2024.8.30-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "certifi==2024.8.30", + "sha256": "922820b53db7a7257ffbda3f597266d435245903d80737e34f8a45ff3e3230d8", + "urls": [ + "https://files.pythonhosted.org/packages/12/90/3c9ff0512038035f59d279fddeb79f5f1eccd8859f06d6163c58798b9487/certifi-2024.8.30-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_certifi_sdist_bec941d2": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "certifi-2024.8.30.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "certifi==2024.8.30", + "sha256": "bec941d2aa8195e248a60b31ff9f0558284cf01a52591ceda73ea9afffd69fd9", + "urls": [ + "https://files.pythonhosted.org/packages/b0/ee/9b19140fe824b367c04c5e1b369942dd754c4c5462d5674002f75c4dedc1/certifi-2024.8.30.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_cffi_cp311_cp311_manylinux_2_17_aarch64_a1ed2dd2": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "cffi-1.17.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cffi==1.17.1", + "sha256": "a1ed2dd2972641495a3ec98445e09766f077aee98a1c896dcb4ad0d303628e41", + "urls": [ + "https://files.pythonhosted.org/packages/2e/ea/70ce63780f096e16ce8588efe039d3c4f91deb1dc01e9c73a287939c79a6/cffi-1.17.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl" + ] + } + }, + "rules_python_publish_deps_311_cffi_cp311_cp311_manylinux_2_17_ppc64le_46bf4316": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "cffi-1.17.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cffi==1.17.1", + "sha256": "46bf43160c1a35f7ec506d254e5c890f3c03648a4dbac12d624e4490a7046cd1", + "urls": [ + "https://files.pythonhosted.org/packages/1c/a0/a4fa9f4f781bda074c3ddd57a572b060fa0df7655d2a4247bbe277200146/cffi-1.17.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl" + ] + } + }, + "rules_python_publish_deps_311_cffi_cp311_cp311_manylinux_2_17_s390x_a24ed04c": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "cffi-1.17.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cffi==1.17.1", + "sha256": "a24ed04c8ffd54b0729c07cee15a81d964e6fee0e3d4d342a27b020d22959dc6", + "urls": [ + "https://files.pythonhosted.org/packages/62/12/ce8710b5b8affbcdd5c6e367217c242524ad17a02fe5beec3ee339f69f85/cffi-1.17.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl" + ] + } + }, + "rules_python_publish_deps_311_cffi_cp311_cp311_manylinux_2_17_x86_64_610faea7": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "cffi-1.17.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cffi==1.17.1", + "sha256": "610faea79c43e44c71e1ec53a554553fa22321b65fae24889706c0a84d4ad86d", + "urls": [ + "https://files.pythonhosted.org/packages/ff/6b/d45873c5e0242196f042d555526f92aa9e0c32355a1be1ff8c27f077fd37/cffi-1.17.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl" + ] + } + }, + "rules_python_publish_deps_311_cffi_cp311_cp311_musllinux_1_1_aarch64_a9b15d49": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "cffi-1.17.1-cp311-cp311-musllinux_1_1_aarch64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cffi==1.17.1", + "sha256": "a9b15d491f3ad5d692e11f6b71f7857e7835eb677955c00cc0aefcd0669adaf6", + "urls": [ + "https://files.pythonhosted.org/packages/1a/52/d9a0e523a572fbccf2955f5abe883cfa8bcc570d7faeee06336fbd50c9fc/cffi-1.17.1-cp311-cp311-musllinux_1_1_aarch64.whl" + ] + } + }, + "rules_python_publish_deps_311_cffi_cp311_cp311_musllinux_1_1_x86_64_fc48c783": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "cffi-1.17.1-cp311-cp311-musllinux_1_1_x86_64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cffi==1.17.1", + "sha256": "fc48c783f9c87e60831201f2cce7f3b2e4846bf4d8728eabe54d60700b318a0b", + "urls": [ + "https://files.pythonhosted.org/packages/f8/4a/34599cac7dfcd888ff54e801afe06a19c17787dfd94495ab0c8d35fe99fb/cffi-1.17.1-cp311-cp311-musllinux_1_1_x86_64.whl" + ] + } + }, + "rules_python_publish_deps_311_cffi_sdist_1c39c601": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "cffi-1.17.1.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cffi==1.17.1", + "sha256": "1c39c6016c32bc48dd54561950ebd6836e1670f2ae46128f67cf49e789c52824", + "urls": [ + "https://files.pythonhosted.org/packages/fc/97/c783634659c2920c3fc70419e3af40972dbaf758daa229a7d6ea6135c90d/cffi-1.17.1.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_cp311_cp311_macosx_10_9_universal2_0d99dd8f": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "charset_normalizer-3.4.0-cp311-cp311-macosx_10_9_universal2.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "0d99dd8ff461990f12d6e42c7347fd9ab2532fb70e9621ba520f9e8637161d7c", + "urls": [ + "https://files.pythonhosted.org/packages/9c/61/73589dcc7a719582bf56aae309b6103d2762b526bffe189d635a7fcfd998/charset_normalizer-3.4.0-cp311-cp311-macosx_10_9_universal2.whl" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_cp311_cp311_macosx_10_9_x86_64_c57516e5": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "charset_normalizer-3.4.0-cp311-cp311-macosx_10_9_x86_64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "c57516e58fd17d03ebe67e181a4e4e2ccab1168f8c2976c6a334d4f819fe5944", + "urls": [ + "https://files.pythonhosted.org/packages/77/d5/8c982d58144de49f59571f940e329ad6e8615e1e82ef84584c5eeb5e1d72/charset_normalizer-3.4.0-cp311-cp311-macosx_10_9_x86_64.whl" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_cp311_cp311_macosx_11_0_arm64_6dba5d19": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "charset_normalizer-3.4.0-cp311-cp311-macosx_11_0_arm64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "6dba5d19c4dfab08e58d5b36304b3f92f3bd5d42c1a3fa37b5ba5cdf6dfcbcee", + "urls": [ + "https://files.pythonhosted.org/packages/bf/19/411a64f01ee971bed3231111b69eb56f9331a769072de479eae7de52296d/charset_normalizer-3.4.0-cp311-cp311-macosx_11_0_arm64.whl" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_cp311_cp311_manylinux_2_17_aarch64_bf4475b8": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "charset_normalizer-3.4.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "bf4475b82be41b07cc5e5ff94810e6a01f276e37c2d55571e3fe175e467a1a1c", + "urls": [ + "https://files.pythonhosted.org/packages/4c/92/97509850f0d00e9f14a46bc751daabd0ad7765cff29cdfb66c68b6dad57f/charset_normalizer-3.4.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_cp311_cp311_manylinux_2_17_ppc64le_ce031db0": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "charset_normalizer-3.4.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "ce031db0408e487fd2775d745ce30a7cd2923667cf3b69d48d219f1d8f5ddeb6", + "urls": [ + "https://files.pythonhosted.org/packages/e2/29/d227805bff72ed6d6cb1ce08eec707f7cfbd9868044893617eb331f16295/charset_normalizer-3.4.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_cp311_cp311_manylinux_2_17_s390x_8ff4e7cd": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "charset_normalizer-3.4.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "8ff4e7cdfdb1ab5698e675ca622e72d58a6fa2a8aa58195de0c0061288e6e3ea", + "urls": [ + "https://files.pythonhosted.org/packages/13/bc/87c2c9f2c144bedfa62f894c3007cd4530ba4b5351acb10dc786428a50f0/charset_normalizer-3.4.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_cp311_cp311_manylinux_2_17_x86_64_3710a975": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "charset_normalizer-3.4.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "3710a9751938947e6327ea9f3ea6332a09bf0ba0c09cae9cb1f250bd1f1549bc", + "urls": [ + "https://files.pythonhosted.org/packages/eb/5b/6f10bad0f6461fa272bfbbdf5d0023b5fb9bc6217c92bf068fa5a99820f5/charset_normalizer-3.4.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_cp311_cp311_musllinux_1_2_aarch64_47334db7": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "charset_normalizer-3.4.0-cp311-cp311-musllinux_1_2_aarch64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "47334db71978b23ebcf3c0f9f5ee98b8d65992b65c9c4f2d34c2eaf5bcaf0594", + "urls": [ + "https://files.pythonhosted.org/packages/d7/a1/493919799446464ed0299c8eef3c3fad0daf1c3cd48bff9263c731b0d9e2/charset_normalizer-3.4.0-cp311-cp311-musllinux_1_2_aarch64.whl" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_cp311_cp311_musllinux_1_2_ppc64le_f1a2f519": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "charset_normalizer-3.4.0-cp311-cp311-musllinux_1_2_ppc64le.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "f1a2f519ae173b5b6a2c9d5fa3116ce16e48b3462c8b96dfdded11055e3d6365", + "urls": [ + "https://files.pythonhosted.org/packages/75/d2/0ab54463d3410709c09266dfb416d032a08f97fd7d60e94b8c6ef54ae14b/charset_normalizer-3.4.0-cp311-cp311-musllinux_1_2_ppc64le.whl" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_cp311_cp311_musllinux_1_2_s390x_63bc5c4a": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "charset_normalizer-3.4.0-cp311-cp311-musllinux_1_2_s390x.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "63bc5c4ae26e4bc6be6469943b8253c0fd4e4186c43ad46e713ea61a0ba49129", + "urls": [ + "https://files.pythonhosted.org/packages/8d/c9/27e41d481557be53d51e60750b85aa40eaf52b841946b3cdeff363105737/charset_normalizer-3.4.0-cp311-cp311-musllinux_1_2_s390x.whl" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_cp311_cp311_musllinux_1_2_x86_64_bcb4f8ea": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "charset_normalizer-3.4.0-cp311-cp311-musllinux_1_2_x86_64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "bcb4f8ea87d03bc51ad04add8ceaf9b0f085ac045ab4d74e73bbc2dc033f0236", + "urls": [ + "https://files.pythonhosted.org/packages/ee/44/4f62042ca8cdc0cabf87c0fc00ae27cd8b53ab68be3605ba6d071f742ad3/charset_normalizer-3.4.0-cp311-cp311-musllinux_1_2_x86_64.whl" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_cp311_cp311_win_amd64_cee4373f": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "charset_normalizer-3.4.0-cp311-cp311-win_amd64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "cee4373f4d3ad28f1ab6290684d8e2ebdb9e7a1b74fdc39e4c211995f77bec27", + "urls": [ + "https://files.pythonhosted.org/packages/0b/6e/b13bd47fa9023b3699e94abf565b5a2f0b0be6e9ddac9812182596ee62e4/charset_normalizer-3.4.0-cp311-cp311-win_amd64.whl" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_py3_none_any_fe9f97fe": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "charset_normalizer-3.4.0-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "fe9f97feb71aa9896b81973a7bbada8c49501dc73e58a10fcef6663af95e5079", + "urls": [ + "https://files.pythonhosted.org/packages/bf/9b/08c0432272d77b04803958a4598a51e2a4b51c06640af8b8f0f908c18bf2/charset_normalizer-3.4.0-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_charset_normalizer_sdist_223217c3": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "charset_normalizer-3.4.0.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "charset-normalizer==3.4.0", + "sha256": "223217c3d4f82c3ac5e29032b3f1c2eb0fb591b72161f86d93f5719079dae93e", + "urls": [ + "https://files.pythonhosted.org/packages/f2/4f/e1808dc01273379acc506d18f1504eb2d299bd4131743b9fc54d7be4df1e/charset_normalizer-3.4.0.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_cryptography_cp39_abi3_manylinux_2_17_aarch64_846da004": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "cryptography-43.0.3-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cryptography==43.0.3", + "sha256": "846da004a5804145a5f441b8530b4bf35afbf7da70f82409f151695b127213d5", + "urls": [ + "https://files.pythonhosted.org/packages/2f/78/55356eb9075d0be6e81b59f45c7b48df87f76a20e73893872170471f3ee8/cryptography-43.0.3-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl" + ] + } + }, + "rules_python_publish_deps_311_cryptography_cp39_abi3_manylinux_2_17_x86_64_0f996e72": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "cryptography-43.0.3-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cryptography==43.0.3", + "sha256": "0f996e7268af62598f2fc1204afa98a3b5712313a55c4c9d434aef49cadc91d4", + "urls": [ + "https://files.pythonhosted.org/packages/2a/2c/488776a3dc843f95f86d2f957ca0fc3407d0242b50bede7fad1e339be03f/cryptography-43.0.3-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl" + ] + } + }, + "rules_python_publish_deps_311_cryptography_cp39_abi3_manylinux_2_28_aarch64_f7b178f1": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "cryptography-43.0.3-cp39-abi3-manylinux_2_28_aarch64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cryptography==43.0.3", + "sha256": "f7b178f11ed3664fd0e995a47ed2b5ff0a12d893e41dd0494f406d1cf555cab7", + "urls": [ + "https://files.pythonhosted.org/packages/7c/04/2345ca92f7a22f601a9c62961741ef7dd0127c39f7310dffa0041c80f16f/cryptography-43.0.3-cp39-abi3-manylinux_2_28_aarch64.whl" + ] + } + }, + "rules_python_publish_deps_311_cryptography_cp39_abi3_manylinux_2_28_x86_64_c2e6fc39": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "cryptography-43.0.3-cp39-abi3-manylinux_2_28_x86_64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cryptography==43.0.3", + "sha256": "c2e6fc39c4ab499049df3bdf567f768a723a5e8464816e8f009f121a5a9f4405", + "urls": [ + "https://files.pythonhosted.org/packages/ac/25/e715fa0bc24ac2114ed69da33adf451a38abb6f3f24ec207908112e9ba53/cryptography-43.0.3-cp39-abi3-manylinux_2_28_x86_64.whl" + ] + } + }, + "rules_python_publish_deps_311_cryptography_cp39_abi3_musllinux_1_2_aarch64_e1be4655": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "cryptography-43.0.3-cp39-abi3-musllinux_1_2_aarch64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cryptography==43.0.3", + "sha256": "e1be4655c7ef6e1bbe6b5d0403526601323420bcf414598955968c9ef3eb7d16", + "urls": [ + "https://files.pythonhosted.org/packages/21/ce/b9c9ff56c7164d8e2edfb6c9305045fbc0df4508ccfdb13ee66eb8c95b0e/cryptography-43.0.3-cp39-abi3-musllinux_1_2_aarch64.whl" + ] + } + }, + "rules_python_publish_deps_311_cryptography_cp39_abi3_musllinux_1_2_x86_64_df6b6c6d": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "cryptography-43.0.3-cp39-abi3-musllinux_1_2_x86_64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cryptography==43.0.3", + "sha256": "df6b6c6d742395dd77a23ea3728ab62f98379eff8fb61be2744d4679ab678f73", + "urls": [ + "https://files.pythonhosted.org/packages/2a/33/b3682992ab2e9476b9c81fff22f02c8b0a1e6e1d49ee1750a67d85fd7ed2/cryptography-43.0.3-cp39-abi3-musllinux_1_2_x86_64.whl" + ] + } + }, + "rules_python_publish_deps_311_cryptography_sdist_315b9001": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "cryptography-43.0.3.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "cryptography==43.0.3", + "sha256": "315b9001266a492a6ff443b61238f956b214dbec9910a081ba5b6646a055a805", + "urls": [ + "https://files.pythonhosted.org/packages/0d/05/07b55d1fa21ac18c3a8c79f764e2514e6f6a9698f1be44994f5adf0d29db/cryptography-43.0.3.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_docutils_py3_none_any_dafca5b9": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "docutils-0.21.2-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "docutils==0.21.2", + "sha256": "dafca5b9e384f0e419294eb4d2ff9fa826435bf15f15b7bd45723e8ad76811b2", + "urls": [ + "https://files.pythonhosted.org/packages/8f/d7/9322c609343d929e75e7e5e6255e614fcc67572cfd083959cdef3b7aad79/docutils-0.21.2-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_docutils_sdist_3a6b1873": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "docutils-0.21.2.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "docutils==0.21.2", + "sha256": "3a6b18732edf182daa3cd12775bbb338cf5691468f91eeeb109deff6ebfa986f", + "urls": [ + "https://files.pythonhosted.org/packages/ae/ed/aefcc8cd0ba62a0560c3c18c33925362d46c6075480bfa4df87b28e169a9/docutils-0.21.2.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_idna_py3_none_any_946d195a": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "idna-3.10-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "idna==3.10", + "sha256": "946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", + "urls": [ + "https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_idna_sdist_12f65c9b": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "idna-3.10.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "idna==3.10", + "sha256": "12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9", + "urls": [ + "https://files.pythonhosted.org/packages/f1/70/7703c29685631f5a7590aa73f1f1d3fa9a380e654b86af429e0934a32f7d/idna-3.10.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_importlib_metadata_py3_none_any_45e54197": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "importlib_metadata-8.5.0-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "importlib-metadata==8.5.0", + "sha256": "45e54197d28b7a7f1559e60b95e7c567032b602131fbd588f1497f47880aa68b", + "urls": [ + "https://files.pythonhosted.org/packages/a0/d9/a1e041c5e7caa9a05c925f4bdbdfb7f006d1f74996af53467bc394c97be7/importlib_metadata-8.5.0-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_importlib_metadata_sdist_71522656": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "importlib_metadata-8.5.0.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "importlib-metadata==8.5.0", + "sha256": "71522656f0abace1d072b9e5481a48f07c138e00f079c38c8f883823f9c26bd7", + "urls": [ + "https://files.pythonhosted.org/packages/cd/12/33e59336dca5be0c398a7482335911a33aa0e20776128f038019f1a95f1b/importlib_metadata-8.5.0.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_jaraco_classes_py3_none_any_f662826b": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "jaraco.classes-3.4.0-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "jaraco-classes==3.4.0", + "sha256": "f662826b6bed8cace05e7ff873ce0f9283b5c924470fe664fff1c2f00f581790", + "urls": [ + "https://files.pythonhosted.org/packages/7f/66/b15ce62552d84bbfcec9a4873ab79d993a1dd4edb922cbfccae192bd5b5f/jaraco.classes-3.4.0-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_jaraco_classes_sdist_47a024b5": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "jaraco.classes-3.4.0.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "jaraco-classes==3.4.0", + "sha256": "47a024b51d0239c0dd8c8540c6c7f484be3b8fcf0b2d85c13825780d3b3f3acd", + "urls": [ + "https://files.pythonhosted.org/packages/06/c0/ed4a27bc5571b99e3cff68f8a9fa5b56ff7df1c2251cc715a652ddd26402/jaraco.classes-3.4.0.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_jaraco_context_py3_none_any_f797fc48": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "jaraco.context-6.0.1-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "jaraco-context==6.0.1", + "sha256": "f797fc481b490edb305122c9181830a3a5b76d84ef6d1aef2fb9b47ab956f9e4", + "urls": [ + "https://files.pythonhosted.org/packages/ff/db/0c52c4cf5e4bd9f5d7135ec7669a3a767af21b3a308e1ed3674881e52b62/jaraco.context-6.0.1-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_jaraco_context_sdist_9bae4ea5": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "jaraco_context-6.0.1.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "jaraco-context==6.0.1", + "sha256": "9bae4ea555cf0b14938dc0aee7c9f32ed303aa20a3b73e7dc80111628792d1b3", + "urls": [ + "https://files.pythonhosted.org/packages/df/ad/f3777b81bf0b6e7bc7514a1656d3e637b2e8e15fab2ce3235730b3e7a4e6/jaraco_context-6.0.1.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_jaraco_functools_py3_none_any_ad159f13": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "jaraco.functools-4.1.0-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "jaraco-functools==4.1.0", + "sha256": "ad159f13428bc4acbf5541ad6dec511f91573b90fba04df61dafa2a1231cf649", + "urls": [ + "https://files.pythonhosted.org/packages/9f/4f/24b319316142c44283d7540e76c7b5a6dbd5db623abd86bb7b3491c21018/jaraco.functools-4.1.0-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_jaraco_functools_sdist_70f7e0e2": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "jaraco_functools-4.1.0.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "jaraco-functools==4.1.0", + "sha256": "70f7e0e2ae076498e212562325e805204fc092d7b4c17e0e86c959e249701a9d", + "urls": [ + "https://files.pythonhosted.org/packages/ab/23/9894b3df5d0a6eb44611c36aec777823fc2e07740dabbd0b810e19594013/jaraco_functools-4.1.0.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_jeepney_py3_none_any_c0a454ad": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "jeepney-0.8.0-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "jeepney==0.8.0", + "sha256": "c0a454ad016ca575060802ee4d590dd912e35c122fa04e70306de3d076cce755", + "urls": [ + "https://files.pythonhosted.org/packages/ae/72/2a1e2290f1ab1e06f71f3d0f1646c9e4634e70e1d37491535e19266e8dc9/jeepney-0.8.0-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_jeepney_sdist_5efe48d2": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "jeepney-0.8.0.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "jeepney==0.8.0", + "sha256": "5efe48d255973902f6badc3ce55e2aa6c5c3b3bc642059ef3a91247bcfcc5806", + "urls": [ + "https://files.pythonhosted.org/packages/d6/f4/154cf374c2daf2020e05c3c6a03c91348d59b23c5366e968feb198306fdf/jeepney-0.8.0.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_keyring_py3_none_any_5426f817": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "keyring-25.4.1-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "keyring==25.4.1", + "sha256": "5426f817cf7f6f007ba5ec722b1bcad95a75b27d780343772ad76b17cb47b0bf", + "urls": [ + "https://files.pythonhosted.org/packages/83/25/e6d59e5f0a0508d0dca8bb98c7f7fd3772fc943ac3f53d5ab18a218d32c0/keyring-25.4.1-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_keyring_sdist_b07ebc55": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "keyring-25.4.1.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "keyring==25.4.1", + "sha256": "b07ebc55f3e8ed86ac81dd31ef14e81ace9dd9c3d4b5d77a6e9a2016d0d71a1b", + "urls": [ + "https://files.pythonhosted.org/packages/a5/1c/2bdbcfd5d59dc6274ffb175bc29aa07ecbfab196830e0cfbde7bd861a2ea/keyring-25.4.1.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_markdown_it_py_py3_none_any_35521684": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "markdown_it_py-3.0.0-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "markdown-it-py==3.0.0", + "sha256": "355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1", + "urls": [ + "https://files.pythonhosted.org/packages/42/d7/1ec15b46af6af88f19b8e5ffea08fa375d433c998b8a7639e76935c14f1f/markdown_it_py-3.0.0-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_markdown_it_py_sdist_e3f60a94": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "markdown-it-py-3.0.0.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "markdown-it-py==3.0.0", + "sha256": "e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb", + "urls": [ + "https://files.pythonhosted.org/packages/38/71/3b932df36c1a044d397a1f92d1cf91ee0a503d91e470cbd670aa66b07ed0/markdown-it-py-3.0.0.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_mdurl_py3_none_any_84008a41": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "mdurl-0.1.2-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "mdurl==0.1.2", + "sha256": "84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", + "urls": [ + "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_mdurl_sdist_bb413d29": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "mdurl-0.1.2.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "mdurl==0.1.2", + "sha256": "bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", + "urls": [ + "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_more_itertools_py3_none_any_037b0d32": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "more_itertools-10.5.0-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "more-itertools==10.5.0", + "sha256": "037b0d3203ce90cca8ab1defbbdac29d5f993fc20131f3664dc8d6acfa872aef", + "urls": [ + "https://files.pythonhosted.org/packages/48/7e/3a64597054a70f7c86eb0a7d4fc315b8c1ab932f64883a297bdffeb5f967/more_itertools-10.5.0-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_more_itertools_sdist_5482bfef": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "more-itertools-10.5.0.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "more-itertools==10.5.0", + "sha256": "5482bfef7849c25dc3c6dd53a6173ae4795da2a41a80faea6700d9f5846c5da6", + "urls": [ + "https://files.pythonhosted.org/packages/51/78/65922308c4248e0eb08ebcbe67c95d48615cc6f27854b6f2e57143e9178f/more-itertools-10.5.0.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_nh3_cp37_abi3_macosx_10_12_x86_64_14c5a72e": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "nh3-0.2.18-cp37-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "nh3==0.2.18", + "sha256": "14c5a72e9fe82aea5fe3072116ad4661af5cf8e8ff8fc5ad3450f123e4925e86", + "urls": [ + "https://files.pythonhosted.org/packages/b3/89/1daff5d9ba5a95a157c092c7c5f39b8dd2b1ddb4559966f808d31cfb67e0/nh3-0.2.18-cp37-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl" + ] + } + }, + "rules_python_publish_deps_311_nh3_cp37_abi3_macosx_10_12_x86_64_7b7c2a3c": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "nh3-0.2.18-cp37-abi3-macosx_10_12_x86_64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "nh3==0.2.18", + "sha256": "7b7c2a3c9eb1a827d42539aa64091640bd275b81e097cd1d8d82ef91ffa2e811", + "urls": [ + "https://files.pythonhosted.org/packages/2c/b6/42fc3c69cabf86b6b81e4c051a9b6e249c5ba9f8155590222c2622961f58/nh3-0.2.18-cp37-abi3-macosx_10_12_x86_64.whl" + ] + } + }, + "rules_python_publish_deps_311_nh3_cp37_abi3_manylinux_2_17_aarch64_42c64511": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "nh3-0.2.18-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "nh3==0.2.18", + "sha256": "42c64511469005058cd17cc1537578eac40ae9f7200bedcfd1fc1a05f4f8c200", + "urls": [ + "https://files.pythonhosted.org/packages/45/b9/833f385403abaf0023c6547389ec7a7acf141ddd9d1f21573723a6eab39a/nh3-0.2.18-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl" + ] + } + }, + "rules_python_publish_deps_311_nh3_cp37_abi3_manylinux_2_17_armv7l_0411beb0": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "nh3-0.2.18-cp37-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "nh3==0.2.18", + "sha256": "0411beb0589eacb6734f28d5497ca2ed379eafab8ad8c84b31bb5c34072b7164", + "urls": [ + "https://files.pythonhosted.org/packages/05/2b/85977d9e11713b5747595ee61f381bc820749daf83f07b90b6c9964cf932/nh3-0.2.18-cp37-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl" + ] + } + }, + "rules_python_publish_deps_311_nh3_cp37_abi3_manylinux_2_17_ppc64_5f36b271": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "nh3-0.2.18-cp37-abi3-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "nh3==0.2.18", + "sha256": "5f36b271dae35c465ef5e9090e1fdaba4a60a56f0bb0ba03e0932a66f28b9189", + "urls": [ + "https://files.pythonhosted.org/packages/72/f2/5c894d5265ab80a97c68ca36f25c8f6f0308abac649aaf152b74e7e854a8/nh3-0.2.18-cp37-abi3-manylinux_2_17_ppc64.manylinux2014_ppc64.whl" + ] + } + }, + "rules_python_publish_deps_311_nh3_cp37_abi3_manylinux_2_17_ppc64le_34c03fa7": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "nh3-0.2.18-cp37-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "nh3==0.2.18", + "sha256": "34c03fa78e328c691f982b7c03d4423bdfd7da69cd707fe572f544cf74ac23ad", + "urls": [ + "https://files.pythonhosted.org/packages/ab/a7/375afcc710dbe2d64cfbd69e31f82f3e423d43737258af01f6a56d844085/nh3-0.2.18-cp37-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl" + ] + } + }, + "rules_python_publish_deps_311_nh3_cp37_abi3_manylinux_2_17_s390x_19aaba96": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "nh3-0.2.18-cp37-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "nh3==0.2.18", + "sha256": "19aaba96e0f795bd0a6c56291495ff59364f4300d4a39b29a0abc9cb3774a84b", + "urls": [ + "https://files.pythonhosted.org/packages/c2/a8/3bb02d0c60a03ad3a112b76c46971e9480efa98a8946677b5a59f60130ca/nh3-0.2.18-cp37-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl" + ] + } + }, + "rules_python_publish_deps_311_nh3_cp37_abi3_manylinux_2_17_x86_64_de3ceed6": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "nh3-0.2.18-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "nh3==0.2.18", + "sha256": "de3ceed6e661954871d6cd78b410213bdcb136f79aafe22aa7182e028b8c7307", + "urls": [ + "https://files.pythonhosted.org/packages/1b/63/6ab90d0e5225ab9780f6c9fb52254fa36b52bb7c188df9201d05b647e5e1/nh3-0.2.18-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl" + ] + } + }, + "rules_python_publish_deps_311_nh3_cp37_abi3_musllinux_1_2_aarch64_f0eca9ca": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "nh3-0.2.18-cp37-abi3-musllinux_1_2_aarch64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "nh3==0.2.18", + "sha256": "f0eca9ca8628dbb4e916ae2491d72957fdd35f7a5d326b7032a345f111ac07fe", + "urls": [ + "https://files.pythonhosted.org/packages/a3/da/0c4e282bc3cff4a0adf37005fa1fb42257673fbc1bbf7d1ff639ec3d255a/nh3-0.2.18-cp37-abi3-musllinux_1_2_aarch64.whl" + ] + } + }, + "rules_python_publish_deps_311_nh3_cp37_abi3_musllinux_1_2_armv7l_3a157ab1": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "nh3-0.2.18-cp37-abi3-musllinux_1_2_armv7l.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "nh3==0.2.18", + "sha256": "3a157ab149e591bb638a55c8c6bcb8cdb559c8b12c13a8affaba6cedfe51713a", + "urls": [ + "https://files.pythonhosted.org/packages/de/81/c291231463d21da5f8bba82c8167a6d6893cc5419b0639801ee5d3aeb8a9/nh3-0.2.18-cp37-abi3-musllinux_1_2_armv7l.whl" + ] + } + }, + "rules_python_publish_deps_311_nh3_cp37_abi3_musllinux_1_2_x86_64_36c95d4b": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "nh3-0.2.18-cp37-abi3-musllinux_1_2_x86_64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "nh3==0.2.18", + "sha256": "36c95d4b70530b320b365659bb5034341316e6a9b30f0b25fa9c9eff4c27a204", + "urls": [ + "https://files.pythonhosted.org/packages/eb/61/73a007c74c37895fdf66e0edcd881f5eaa17a348ff02f4bb4bc906d61085/nh3-0.2.18-cp37-abi3-musllinux_1_2_x86_64.whl" + ] + } + }, + "rules_python_publish_deps_311_nh3_cp37_abi3_win_amd64_8ce0f819": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "nh3-0.2.18-cp37-abi3-win_amd64.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "nh3==0.2.18", + "sha256": "8ce0f819d2f1933953fca255db2471ad58184a60508f03e6285e5114b6254844", + "urls": [ + "https://files.pythonhosted.org/packages/26/8d/53c5b19c4999bdc6ba95f246f4ef35ca83d7d7423e5e38be43ad66544e5d/nh3-0.2.18-cp37-abi3-win_amd64.whl" + ] + } + }, + "rules_python_publish_deps_311_nh3_sdist_94a16692": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "nh3-0.2.18.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "nh3==0.2.18", + "sha256": "94a166927e53972a9698af9542ace4e38b9de50c34352b962f4d9a7d4c927af4", + "urls": [ + "https://files.pythonhosted.org/packages/62/73/10df50b42ddb547a907deeb2f3c9823022580a7a47281e8eae8e003a9639/nh3-0.2.18.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_pkginfo_py3_none_any_889a6da2": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "pkginfo-1.10.0-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "pkginfo==1.10.0", + "sha256": "889a6da2ed7ffc58ab5b900d888ddce90bce912f2d2de1dc1c26f4cb9fe65097", + "urls": [ + "https://files.pythonhosted.org/packages/56/09/054aea9b7534a15ad38a363a2bd974c20646ab1582a387a95b8df1bfea1c/pkginfo-1.10.0-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_pkginfo_sdist_5df73835": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "pkginfo-1.10.0.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "pkginfo==1.10.0", + "sha256": "5df73835398d10db79f8eecd5cd86b1f6d29317589ea70796994d49399af6297", + "urls": [ + "https://files.pythonhosted.org/packages/2f/72/347ec5be4adc85c182ed2823d8d1c7b51e13b9a6b0c1aae59582eca652df/pkginfo-1.10.0.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_pycparser_py3_none_any_c3702b6d": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "pycparser-2.22-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "pycparser==2.22", + "sha256": "c3702b6d3dd8c7abc1afa565d7e63d53a1d0bd86cdc24edd75470f4de499cfcc", + "urls": [ + "https://files.pythonhosted.org/packages/13/a3/a812df4e2dd5696d1f351d58b8fe16a405b234ad2886a0dab9183fb78109/pycparser-2.22-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_pycparser_sdist_491c8be9": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "pycparser-2.22.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "pycparser==2.22", + "sha256": "491c8be9c040f5390f5bf44a5b07752bd07f56edf992381b05c701439eec10f6", + "urls": [ + "https://files.pythonhosted.org/packages/1d/b2/31537cf4b1ca988837256c910a668b553fceb8f069bedc4b1c826024b52c/pycparser-2.22.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_pygments_py3_none_any_b8e6aca0": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "pygments-2.18.0-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "pygments==2.18.0", + "sha256": "b8e6aca0523f3ab76fee51799c488e38782ac06eafcf95e7ba832985c8e7b13a", + "urls": [ + "https://files.pythonhosted.org/packages/f7/3f/01c8b82017c199075f8f788d0d906b9ffbbc5a47dc9918a945e13d5a2bda/pygments-2.18.0-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_pygments_sdist_786ff802": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "pygments-2.18.0.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "pygments==2.18.0", + "sha256": "786ff802f32e91311bff3889f6e9a86e81505fe99f2735bb6d60ae0c5004f199", + "urls": [ + "https://files.pythonhosted.org/packages/8e/62/8336eff65bcbc8e4cb5d05b55faf041285951b6e80f33e2bff2024788f31/pygments-2.18.0.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_pywin32_ctypes_py3_none_any_8a151337": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_windows_x86_64" + ], + "filename": "pywin32_ctypes-0.2.3-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "pywin32-ctypes==0.2.3", + "sha256": "8a1513379d709975552d202d942d9837758905c8d01eb82b8bcc30918929e7b8", + "urls": [ + "https://files.pythonhosted.org/packages/de/3d/8161f7711c017e01ac9f008dfddd9410dff3674334c233bde66e7ba65bbf/pywin32_ctypes-0.2.3-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_pywin32_ctypes_sdist_d162dc04": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "pywin32-ctypes-0.2.3.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "pywin32-ctypes==0.2.3", + "sha256": "d162dc04946d704503b2edc4d55f3dba5c1d539ead017afa00142c38b9885755", + "urls": [ + "https://files.pythonhosted.org/packages/85/9f/01a1a99704853cb63f253eea009390c88e7131c67e66a0a02099a8c917cb/pywin32-ctypes-0.2.3.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_readme_renderer_py3_none_any_2fbca89b": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "readme_renderer-44.0-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "readme-renderer==44.0", + "sha256": "2fbca89b81a08526aadf1357a8c2ae889ec05fb03f5da67f9769c9a592166151", + "urls": [ + "https://files.pythonhosted.org/packages/e1/67/921ec3024056483db83953ae8e48079ad62b92db7880013ca77632921dd0/readme_renderer-44.0-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_readme_renderer_sdist_8712034e": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "readme_renderer-44.0.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "readme-renderer==44.0", + "sha256": "8712034eabbfa6805cacf1402b4eeb2a73028f72d1166d6f5cb7f9c047c5d1e1", + "urls": [ + "https://files.pythonhosted.org/packages/5a/a9/104ec9234c8448c4379768221ea6df01260cd6c2ce13182d4eac531c8342/readme_renderer-44.0.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_requests_py3_none_any_70761cfe": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "requests-2.32.3-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "requests==2.32.3", + "sha256": "70761cfe03c773ceb22aa2f671b4757976145175cdfca038c02654d061d6dcc6", + "urls": [ + "https://files.pythonhosted.org/packages/f9/9b/335f9764261e915ed497fcdeb11df5dfd6f7bf257d4a6a2a686d80da4d54/requests-2.32.3-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_requests_sdist_55365417": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "requests-2.32.3.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "requests==2.32.3", + "sha256": "55365417734eb18255590a9ff9eb97e9e1da868d4ccd6402399eaf68af20a760", + "urls": [ + "https://files.pythonhosted.org/packages/63/70/2bf7780ad2d390a8d301ad0b550f1581eadbd9a20f896afe06353c2a2913/requests-2.32.3.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_requests_toolbelt_py2_none_any_cccfdd66": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "requests_toolbelt-1.0.0-py2.py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "requests-toolbelt==1.0.0", + "sha256": "cccfdd665f0a24fcf4726e690f65639d272bb0637b9b92dfd91a5568ccf6bd06", + "urls": [ + "https://files.pythonhosted.org/packages/3f/51/d4db610ef29373b879047326cbf6fa98b6c1969d6f6dc423279de2b1be2c/requests_toolbelt-1.0.0-py2.py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_requests_toolbelt_sdist_7681a0a3": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "requests-toolbelt-1.0.0.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "requests-toolbelt==1.0.0", + "sha256": "7681a0a3d047012b5bdc0ee37d7f8f07ebe76ab08caeccfc3921ce23c88d5bc6", + "urls": [ + "https://files.pythonhosted.org/packages/f3/61/d7545dafb7ac2230c70d38d31cbfe4cc64f7144dc41f6e4e4b78ecd9f5bb/requests-toolbelt-1.0.0.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_rfc3986_py2_none_any_50b1502b": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "rfc3986-2.0.0-py2.py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "rfc3986==2.0.0", + "sha256": "50b1502b60e289cb37883f3dfd34532b8873c7de9f49bb546641ce9cbd256ebd", + "urls": [ + "https://files.pythonhosted.org/packages/ff/9a/9afaade874b2fa6c752c36f1548f718b5b83af81ed9b76628329dab81c1b/rfc3986-2.0.0-py2.py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_rfc3986_sdist_97aacf9d": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "rfc3986-2.0.0.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "rfc3986==2.0.0", + "sha256": "97aacf9dbd4bfd829baad6e6309fa6573aaf1be3f6fa735c8ab05e46cecb261c", + "urls": [ + "https://files.pythonhosted.org/packages/85/40/1520d68bfa07ab5a6f065a186815fb6610c86fe957bc065754e47f7b0840/rfc3986-2.0.0.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_rich_py3_none_any_9836f509": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "rich-13.9.3-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "rich==13.9.3", + "sha256": "9836f5096eb2172c9e77df411c1b009bace4193d6a481d534fea75ebba758283", + "urls": [ + "https://files.pythonhosted.org/packages/9a/e2/10e9819cf4a20bd8ea2f5dabafc2e6bf4a78d6a0965daeb60a4b34d1c11f/rich-13.9.3-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_rich_sdist_bc1e01b8": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "rich-13.9.3.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "rich==13.9.3", + "sha256": "bc1e01b899537598cf02579d2b9f4a415104d3fc439313a7a2c165d76557a08e", + "urls": [ + "https://files.pythonhosted.org/packages/d9/e9/cf9ef5245d835065e6673781dbd4b8911d352fb770d56cf0879cf11b7ee1/rich-13.9.3.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_secretstorage_py3_none_any_f356e662": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "filename": "SecretStorage-3.3.3-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "secretstorage==3.3.3", + "sha256": "f356e6628222568e3af06f2eba8df495efa13b3b63081dafd4f7d9a7b7bc9f99", + "urls": [ + "https://files.pythonhosted.org/packages/54/24/b4293291fa1dd830f353d2cb163295742fa87f179fcc8a20a306a81978b7/SecretStorage-3.3.3-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_secretstorage_sdist_2403533e": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "SecretStorage-3.3.3.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "secretstorage==3.3.3", + "sha256": "2403533ef369eca6d2ba81718576c5e0f564d5cca1b58f73a8b23e7d4eeebd77", + "urls": [ + "https://files.pythonhosted.org/packages/53/a4/f48c9d79cb507ed1373477dbceaba7401fd8a23af63b837fa61f1dcd3691/SecretStorage-3.3.3.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_twine_py3_none_any_215dbe7b": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "twine-5.1.1-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "twine==5.1.1", + "sha256": "215dbe7b4b94c2c50a7315c0275d2258399280fbb7d04182c7e55e24b5f93997", + "urls": [ + "https://files.pythonhosted.org/packages/5d/ec/00f9d5fd040ae29867355e559a94e9a8429225a0284a3f5f091a3878bfc0/twine-5.1.1-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_twine_sdist_9aa08251": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "twine-5.1.1.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "twine==5.1.1", + "sha256": "9aa0825139c02b3434d913545c7b847a21c835e11597f5255842d457da2322db", + "urls": [ + "https://files.pythonhosted.org/packages/77/68/bd982e5e949ef8334e6f7dcf76ae40922a8750aa2e347291ae1477a4782b/twine-5.1.1.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_urllib3_py3_none_any_ca899ca0": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "urllib3-2.2.3-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "urllib3==2.2.3", + "sha256": "ca899ca043dcb1bafa3e262d73aa25c465bfb49e0bd9dd5d59f1d0acba2f8fac", + "urls": [ + "https://files.pythonhosted.org/packages/ce/d9/5f4c13cecde62396b0d3fe530a50ccea91e7dfc1ccf0e09c228841bb5ba8/urllib3-2.2.3-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_urllib3_sdist_e7d814a8": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "urllib3-2.2.3.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "urllib3==2.2.3", + "sha256": "e7d814a81dad81e6caf2ec9fdedb284ecc9c73076b62654547cc64ccdcae26e9", + "urls": [ + "https://files.pythonhosted.org/packages/ed/63/22ba4ebfe7430b76388e7cd448d5478814d3032121827c12a2cc287e2260/urllib3-2.2.3.tar.gz" + ] + } + }, + "rules_python_publish_deps_311_zipp_py3_none_any_a817ac80": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "filename": "zipp-3.20.2-py3-none-any.whl", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "zipp==3.20.2", + "sha256": "a817ac80d6cf4b23bf7f2828b7cabf326f15a001bea8b1f9b49631780ba28350", + "urls": [ + "https://files.pythonhosted.org/packages/62/8b/5ba542fa83c90e09eac972fc9baca7a88e7e7ca4b221a89251954019308b/zipp-3.20.2-py3-none-any.whl" + ] + } + }, + "rules_python_publish_deps_311_zipp_sdist_bc9eb26f": { + "repoRuleId": "@@rules_python+//python/private/pypi:whl_library.bzl%whl_library", + "attributes": { + "dep_template": "@rules_python_publish_deps//{name}:{target}", + "experimental_target_platforms": [ + "cp311_linux_aarch64", + "cp311_linux_arm", + "cp311_linux_ppc", + "cp311_linux_s390x", + "cp311_linux_x86_64", + "cp311_osx_aarch64", + "cp311_osx_x86_64", + "cp311_windows_x86_64" + ], + "extra_pip_args": [ + "--index-url", + "https://pypi.org/simple" + ], + "filename": "zipp-3.20.2.tar.gz", + "python_interpreter_target": "@@rules_python++python+python_3_11_host//:python", + "repo": "rules_python_publish_deps_311", + "requirement": "zipp==3.20.2", + "sha256": "bc9eb26f4506fda01b81bcde0ca78103b6e62f991b381fec825435c836edbc29", + "urls": [ + "https://files.pythonhosted.org/packages/54/bf/5c0000c44ebc80123ecbdddba1f5dcd94a5ada602a9c225d84b5aaa55e86/zipp-3.20.2.tar.gz" + ] + } + }, + "pip_deps": { + "repoRuleId": "@@rules_python+//python/private/pypi:hub_repository.bzl%hub_repository", + "attributes": { + "repo_name": "pip_deps", + "extra_hub_aliases": {}, + "whl_map": { + "numpy": "{\"pip_deps_310_numpy\":[{\"version\":\"3.10\"}],\"pip_deps_311_numpy\":[{\"version\":\"3.11\"}],\"pip_deps_312_numpy\":[{\"version\":\"3.12\"}],\"pip_deps_38_numpy\":[{\"version\":\"3.8\"}],\"pip_deps_39_numpy\":[{\"version\":\"3.9\"}]}", + "setuptools": "{\"pip_deps_310_setuptools\":[{\"version\":\"3.10\"}],\"pip_deps_311_setuptools\":[{\"version\":\"3.11\"}],\"pip_deps_312_setuptools\":[{\"version\":\"3.12\"}],\"pip_deps_38_setuptools\":[{\"version\":\"3.8\"}],\"pip_deps_39_setuptools\":[{\"version\":\"3.9\"}]}" + }, + "packages": [ + "numpy", + "setuptools" + ], + "groups": {} + } + }, + "rules_fuzzing_py_deps": { + "repoRuleId": "@@rules_python+//python/private/pypi:hub_repository.bzl%hub_repository", + "attributes": { + "repo_name": "rules_fuzzing_py_deps", + "extra_hub_aliases": {}, + "whl_map": { + "absl_py": "{\"rules_fuzzing_py_deps_310_absl_py\":[{\"version\":\"3.10\"}],\"rules_fuzzing_py_deps_311_absl_py\":[{\"version\":\"3.11\"}],\"rules_fuzzing_py_deps_312_absl_py\":[{\"version\":\"3.12\"}],\"rules_fuzzing_py_deps_38_absl_py\":[{\"version\":\"3.8\"}],\"rules_fuzzing_py_deps_39_absl_py\":[{\"version\":\"3.9\"}]}", + "six": "{\"rules_fuzzing_py_deps_310_six\":[{\"version\":\"3.10\"}],\"rules_fuzzing_py_deps_311_six\":[{\"version\":\"3.11\"}],\"rules_fuzzing_py_deps_312_six\":[{\"version\":\"3.12\"}],\"rules_fuzzing_py_deps_38_six\":[{\"version\":\"3.8\"}],\"rules_fuzzing_py_deps_39_six\":[{\"version\":\"3.9\"}]}" + }, + "packages": [ + "absl_py", + "six" + ], + "groups": {} + } + }, + "rules_python_publish_deps": { + "repoRuleId": "@@rules_python+//python/private/pypi:hub_repository.bzl%hub_repository", + "attributes": { + "repo_name": "rules_python_publish_deps", + "extra_hub_aliases": {}, + "whl_map": { + "backports_tarfile": "{\"rules_python_publish_deps_311_backports_tarfile_py3_none_any_77e284d7\":[{\"filename\":\"backports.tarfile-1.2.0-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_backports_tarfile_sdist_d75e02c2\":[{\"filename\":\"backports_tarfile-1.2.0.tar.gz\",\"version\":\"3.11\"}]}", + "certifi": "{\"rules_python_publish_deps_311_certifi_py3_none_any_922820b5\":[{\"filename\":\"certifi-2024.8.30-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_certifi_sdist_bec941d2\":[{\"filename\":\"certifi-2024.8.30.tar.gz\",\"version\":\"3.11\"}]}", + "cffi": "{\"rules_python_publish_deps_311_cffi_cp311_cp311_manylinux_2_17_aarch64_a1ed2dd2\":[{\"filename\":\"cffi-1.17.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_cffi_cp311_cp311_manylinux_2_17_ppc64le_46bf4316\":[{\"filename\":\"cffi-1.17.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_cffi_cp311_cp311_manylinux_2_17_s390x_a24ed04c\":[{\"filename\":\"cffi-1.17.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_cffi_cp311_cp311_manylinux_2_17_x86_64_610faea7\":[{\"filename\":\"cffi-1.17.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_cffi_cp311_cp311_musllinux_1_1_aarch64_a9b15d49\":[{\"filename\":\"cffi-1.17.1-cp311-cp311-musllinux_1_1_aarch64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_cffi_cp311_cp311_musllinux_1_1_x86_64_fc48c783\":[{\"filename\":\"cffi-1.17.1-cp311-cp311-musllinux_1_1_x86_64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_cffi_sdist_1c39c601\":[{\"filename\":\"cffi-1.17.1.tar.gz\",\"version\":\"3.11\"}]}", + "charset_normalizer": "{\"rules_python_publish_deps_311_charset_normalizer_cp311_cp311_macosx_10_9_universal2_0d99dd8f\":[{\"filename\":\"charset_normalizer-3.4.0-cp311-cp311-macosx_10_9_universal2.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_charset_normalizer_cp311_cp311_macosx_10_9_x86_64_c57516e5\":[{\"filename\":\"charset_normalizer-3.4.0-cp311-cp311-macosx_10_9_x86_64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_charset_normalizer_cp311_cp311_macosx_11_0_arm64_6dba5d19\":[{\"filename\":\"charset_normalizer-3.4.0-cp311-cp311-macosx_11_0_arm64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_charset_normalizer_cp311_cp311_manylinux_2_17_aarch64_bf4475b8\":[{\"filename\":\"charset_normalizer-3.4.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_charset_normalizer_cp311_cp311_manylinux_2_17_ppc64le_ce031db0\":[{\"filename\":\"charset_normalizer-3.4.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_charset_normalizer_cp311_cp311_manylinux_2_17_s390x_8ff4e7cd\":[{\"filename\":\"charset_normalizer-3.4.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_charset_normalizer_cp311_cp311_manylinux_2_17_x86_64_3710a975\":[{\"filename\":\"charset_normalizer-3.4.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_charset_normalizer_cp311_cp311_musllinux_1_2_aarch64_47334db7\":[{\"filename\":\"charset_normalizer-3.4.0-cp311-cp311-musllinux_1_2_aarch64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_charset_normalizer_cp311_cp311_musllinux_1_2_ppc64le_f1a2f519\":[{\"filename\":\"charset_normalizer-3.4.0-cp311-cp311-musllinux_1_2_ppc64le.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_charset_normalizer_cp311_cp311_musllinux_1_2_s390x_63bc5c4a\":[{\"filename\":\"charset_normalizer-3.4.0-cp311-cp311-musllinux_1_2_s390x.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_charset_normalizer_cp311_cp311_musllinux_1_2_x86_64_bcb4f8ea\":[{\"filename\":\"charset_normalizer-3.4.0-cp311-cp311-musllinux_1_2_x86_64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_charset_normalizer_cp311_cp311_win_amd64_cee4373f\":[{\"filename\":\"charset_normalizer-3.4.0-cp311-cp311-win_amd64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_charset_normalizer_py3_none_any_fe9f97fe\":[{\"filename\":\"charset_normalizer-3.4.0-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_charset_normalizer_sdist_223217c3\":[{\"filename\":\"charset_normalizer-3.4.0.tar.gz\",\"version\":\"3.11\"}]}", + "cryptography": "{\"rules_python_publish_deps_311_cryptography_cp39_abi3_manylinux_2_17_aarch64_846da004\":[{\"filename\":\"cryptography-43.0.3-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_cryptography_cp39_abi3_manylinux_2_17_x86_64_0f996e72\":[{\"filename\":\"cryptography-43.0.3-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_cryptography_cp39_abi3_manylinux_2_28_aarch64_f7b178f1\":[{\"filename\":\"cryptography-43.0.3-cp39-abi3-manylinux_2_28_aarch64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_cryptography_cp39_abi3_manylinux_2_28_x86_64_c2e6fc39\":[{\"filename\":\"cryptography-43.0.3-cp39-abi3-manylinux_2_28_x86_64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_cryptography_cp39_abi3_musllinux_1_2_aarch64_e1be4655\":[{\"filename\":\"cryptography-43.0.3-cp39-abi3-musllinux_1_2_aarch64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_cryptography_cp39_abi3_musllinux_1_2_x86_64_df6b6c6d\":[{\"filename\":\"cryptography-43.0.3-cp39-abi3-musllinux_1_2_x86_64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_cryptography_sdist_315b9001\":[{\"filename\":\"cryptography-43.0.3.tar.gz\",\"version\":\"3.11\"}]}", + "docutils": "{\"rules_python_publish_deps_311_docutils_py3_none_any_dafca5b9\":[{\"filename\":\"docutils-0.21.2-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_docutils_sdist_3a6b1873\":[{\"filename\":\"docutils-0.21.2.tar.gz\",\"version\":\"3.11\"}]}", + "idna": "{\"rules_python_publish_deps_311_idna_py3_none_any_946d195a\":[{\"filename\":\"idna-3.10-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_idna_sdist_12f65c9b\":[{\"filename\":\"idna-3.10.tar.gz\",\"version\":\"3.11\"}]}", + "importlib_metadata": "{\"rules_python_publish_deps_311_importlib_metadata_py3_none_any_45e54197\":[{\"filename\":\"importlib_metadata-8.5.0-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_importlib_metadata_sdist_71522656\":[{\"filename\":\"importlib_metadata-8.5.0.tar.gz\",\"version\":\"3.11\"}]}", + "jaraco_classes": "{\"rules_python_publish_deps_311_jaraco_classes_py3_none_any_f662826b\":[{\"filename\":\"jaraco.classes-3.4.0-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_jaraco_classes_sdist_47a024b5\":[{\"filename\":\"jaraco.classes-3.4.0.tar.gz\",\"version\":\"3.11\"}]}", + "jaraco_context": "{\"rules_python_publish_deps_311_jaraco_context_py3_none_any_f797fc48\":[{\"filename\":\"jaraco.context-6.0.1-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_jaraco_context_sdist_9bae4ea5\":[{\"filename\":\"jaraco_context-6.0.1.tar.gz\",\"version\":\"3.11\"}]}", + "jaraco_functools": "{\"rules_python_publish_deps_311_jaraco_functools_py3_none_any_ad159f13\":[{\"filename\":\"jaraco.functools-4.1.0-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_jaraco_functools_sdist_70f7e0e2\":[{\"filename\":\"jaraco_functools-4.1.0.tar.gz\",\"version\":\"3.11\"}]}", + "jeepney": "{\"rules_python_publish_deps_311_jeepney_py3_none_any_c0a454ad\":[{\"filename\":\"jeepney-0.8.0-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_jeepney_sdist_5efe48d2\":[{\"filename\":\"jeepney-0.8.0.tar.gz\",\"version\":\"3.11\"}]}", + "keyring": "{\"rules_python_publish_deps_311_keyring_py3_none_any_5426f817\":[{\"filename\":\"keyring-25.4.1-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_keyring_sdist_b07ebc55\":[{\"filename\":\"keyring-25.4.1.tar.gz\",\"version\":\"3.11\"}]}", + "markdown_it_py": "{\"rules_python_publish_deps_311_markdown_it_py_py3_none_any_35521684\":[{\"filename\":\"markdown_it_py-3.0.0-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_markdown_it_py_sdist_e3f60a94\":[{\"filename\":\"markdown-it-py-3.0.0.tar.gz\",\"version\":\"3.11\"}]}", + "mdurl": "{\"rules_python_publish_deps_311_mdurl_py3_none_any_84008a41\":[{\"filename\":\"mdurl-0.1.2-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_mdurl_sdist_bb413d29\":[{\"filename\":\"mdurl-0.1.2.tar.gz\",\"version\":\"3.11\"}]}", + "more_itertools": "{\"rules_python_publish_deps_311_more_itertools_py3_none_any_037b0d32\":[{\"filename\":\"more_itertools-10.5.0-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_more_itertools_sdist_5482bfef\":[{\"filename\":\"more-itertools-10.5.0.tar.gz\",\"version\":\"3.11\"}]}", + "nh3": "{\"rules_python_publish_deps_311_nh3_cp37_abi3_macosx_10_12_x86_64_14c5a72e\":[{\"filename\":\"nh3-0.2.18-cp37-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_nh3_cp37_abi3_macosx_10_12_x86_64_7b7c2a3c\":[{\"filename\":\"nh3-0.2.18-cp37-abi3-macosx_10_12_x86_64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_nh3_cp37_abi3_manylinux_2_17_aarch64_42c64511\":[{\"filename\":\"nh3-0.2.18-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_nh3_cp37_abi3_manylinux_2_17_armv7l_0411beb0\":[{\"filename\":\"nh3-0.2.18-cp37-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_nh3_cp37_abi3_manylinux_2_17_ppc64_5f36b271\":[{\"filename\":\"nh3-0.2.18-cp37-abi3-manylinux_2_17_ppc64.manylinux2014_ppc64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_nh3_cp37_abi3_manylinux_2_17_ppc64le_34c03fa7\":[{\"filename\":\"nh3-0.2.18-cp37-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_nh3_cp37_abi3_manylinux_2_17_s390x_19aaba96\":[{\"filename\":\"nh3-0.2.18-cp37-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_nh3_cp37_abi3_manylinux_2_17_x86_64_de3ceed6\":[{\"filename\":\"nh3-0.2.18-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_nh3_cp37_abi3_musllinux_1_2_aarch64_f0eca9ca\":[{\"filename\":\"nh3-0.2.18-cp37-abi3-musllinux_1_2_aarch64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_nh3_cp37_abi3_musllinux_1_2_armv7l_3a157ab1\":[{\"filename\":\"nh3-0.2.18-cp37-abi3-musllinux_1_2_armv7l.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_nh3_cp37_abi3_musllinux_1_2_x86_64_36c95d4b\":[{\"filename\":\"nh3-0.2.18-cp37-abi3-musllinux_1_2_x86_64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_nh3_cp37_abi3_win_amd64_8ce0f819\":[{\"filename\":\"nh3-0.2.18-cp37-abi3-win_amd64.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_nh3_sdist_94a16692\":[{\"filename\":\"nh3-0.2.18.tar.gz\",\"version\":\"3.11\"}]}", + "pkginfo": "{\"rules_python_publish_deps_311_pkginfo_py3_none_any_889a6da2\":[{\"filename\":\"pkginfo-1.10.0-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_pkginfo_sdist_5df73835\":[{\"filename\":\"pkginfo-1.10.0.tar.gz\",\"version\":\"3.11\"}]}", + "pycparser": "{\"rules_python_publish_deps_311_pycparser_py3_none_any_c3702b6d\":[{\"filename\":\"pycparser-2.22-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_pycparser_sdist_491c8be9\":[{\"filename\":\"pycparser-2.22.tar.gz\",\"version\":\"3.11\"}]}", + "pygments": "{\"rules_python_publish_deps_311_pygments_py3_none_any_b8e6aca0\":[{\"filename\":\"pygments-2.18.0-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_pygments_sdist_786ff802\":[{\"filename\":\"pygments-2.18.0.tar.gz\",\"version\":\"3.11\"}]}", + "pywin32_ctypes": "{\"rules_python_publish_deps_311_pywin32_ctypes_py3_none_any_8a151337\":[{\"filename\":\"pywin32_ctypes-0.2.3-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_pywin32_ctypes_sdist_d162dc04\":[{\"filename\":\"pywin32-ctypes-0.2.3.tar.gz\",\"version\":\"3.11\"}]}", + "readme_renderer": "{\"rules_python_publish_deps_311_readme_renderer_py3_none_any_2fbca89b\":[{\"filename\":\"readme_renderer-44.0-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_readme_renderer_sdist_8712034e\":[{\"filename\":\"readme_renderer-44.0.tar.gz\",\"version\":\"3.11\"}]}", + "requests": "{\"rules_python_publish_deps_311_requests_py3_none_any_70761cfe\":[{\"filename\":\"requests-2.32.3-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_requests_sdist_55365417\":[{\"filename\":\"requests-2.32.3.tar.gz\",\"version\":\"3.11\"}]}", + "requests_toolbelt": "{\"rules_python_publish_deps_311_requests_toolbelt_py2_none_any_cccfdd66\":[{\"filename\":\"requests_toolbelt-1.0.0-py2.py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_requests_toolbelt_sdist_7681a0a3\":[{\"filename\":\"requests-toolbelt-1.0.0.tar.gz\",\"version\":\"3.11\"}]}", + "rfc3986": "{\"rules_python_publish_deps_311_rfc3986_py2_none_any_50b1502b\":[{\"filename\":\"rfc3986-2.0.0-py2.py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_rfc3986_sdist_97aacf9d\":[{\"filename\":\"rfc3986-2.0.0.tar.gz\",\"version\":\"3.11\"}]}", + "rich": "{\"rules_python_publish_deps_311_rich_py3_none_any_9836f509\":[{\"filename\":\"rich-13.9.3-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_rich_sdist_bc1e01b8\":[{\"filename\":\"rich-13.9.3.tar.gz\",\"version\":\"3.11\"}]}", + "secretstorage": "{\"rules_python_publish_deps_311_secretstorage_py3_none_any_f356e662\":[{\"filename\":\"SecretStorage-3.3.3-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_secretstorage_sdist_2403533e\":[{\"filename\":\"SecretStorage-3.3.3.tar.gz\",\"version\":\"3.11\"}]}", + "twine": "{\"rules_python_publish_deps_311_twine_py3_none_any_215dbe7b\":[{\"filename\":\"twine-5.1.1-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_twine_sdist_9aa08251\":[{\"filename\":\"twine-5.1.1.tar.gz\",\"version\":\"3.11\"}]}", + "urllib3": "{\"rules_python_publish_deps_311_urllib3_py3_none_any_ca899ca0\":[{\"filename\":\"urllib3-2.2.3-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_urllib3_sdist_e7d814a8\":[{\"filename\":\"urllib3-2.2.3.tar.gz\",\"version\":\"3.11\"}]}", + "zipp": "{\"rules_python_publish_deps_311_zipp_py3_none_any_a817ac80\":[{\"filename\":\"zipp-3.20.2-py3-none-any.whl\",\"version\":\"3.11\"}],\"rules_python_publish_deps_311_zipp_sdist_bc9eb26f\":[{\"filename\":\"zipp-3.20.2.tar.gz\",\"version\":\"3.11\"}]}" + }, + "packages": [ + "backports_tarfile", + "certifi", + "charset_normalizer", + "docutils", + "idna", + "importlib_metadata", + "jaraco_classes", + "jaraco_context", + "jaraco_functools", + "keyring", + "markdown_it_py", + "mdurl", + "more_itertools", + "nh3", + "pkginfo", + "pygments", + "readme_renderer", + "requests", + "requests_toolbelt", + "rfc3986", + "rich", + "twine", + "urllib3", + "zipp" + ], + "groups": {} + } + } + }, + "recordedRepoMappingEntries": [ + [ + "bazel_features+", + "bazel_features_globals", + "bazel_features++version_extension+bazel_features_globals" + ], + [ + "bazel_features+", + "bazel_features_version", + "bazel_features++version_extension+bazel_features_version" + ], + [ + "rules_python+", + "bazel_features", + "bazel_features+" + ], + [ + "rules_python+", + "bazel_skylib", + "bazel_skylib+" + ], + [ + "rules_python+", + "bazel_tools", + "bazel_tools" + ], + [ + "rules_python+", + "pypi__build", + "rules_python++internal_deps+pypi__build" + ], + [ + "rules_python+", + "pypi__click", + "rules_python++internal_deps+pypi__click" + ], + [ + "rules_python+", + "pypi__colorama", + "rules_python++internal_deps+pypi__colorama" + ], + [ + "rules_python+", + "pypi__importlib_metadata", + "rules_python++internal_deps+pypi__importlib_metadata" + ], + [ + "rules_python+", + "pypi__installer", + "rules_python++internal_deps+pypi__installer" + ], + [ + "rules_python+", + "pypi__more_itertools", + "rules_python++internal_deps+pypi__more_itertools" + ], + [ + "rules_python+", + "pypi__packaging", + "rules_python++internal_deps+pypi__packaging" + ], + [ + "rules_python+", + "pypi__pep517", + "rules_python++internal_deps+pypi__pep517" + ], + [ + "rules_python+", + "pypi__pip", + "rules_python++internal_deps+pypi__pip" + ], + [ + "rules_python+", + "pypi__pip_tools", + "rules_python++internal_deps+pypi__pip_tools" + ], + [ + "rules_python+", + "pypi__pyproject_hooks", + "rules_python++internal_deps+pypi__pyproject_hooks" + ], + [ + "rules_python+", + "pypi__setuptools", + "rules_python++internal_deps+pypi__setuptools" + ], + [ + "rules_python+", + "pypi__tomli", + "rules_python++internal_deps+pypi__tomli" + ], + [ + "rules_python+", + "pypi__wheel", + "rules_python++internal_deps+pypi__wheel" + ], + [ + "rules_python+", + "pypi__zipp", + "rules_python++internal_deps+pypi__zipp" + ], + [ + "rules_python+", + "pythons_hub", + "rules_python++python+pythons_hub" + ], + [ + "rules_python++python+pythons_hub", + "python_3_10_host", + "rules_python++python+python_3_10_host" + ], + [ + "rules_python++python+pythons_hub", + "python_3_11_host", + "rules_python++python+python_3_11_host" + ], + [ + "rules_python++python+pythons_hub", + "python_3_12_host", + "rules_python++python+python_3_12_host" + ], + [ + "rules_python++python+pythons_hub", + "python_3_8_host", + "rules_python++python+python_3_8_host" + ], + [ + "rules_python++python+pythons_hub", + "python_3_9_host", + "rules_python++python+python_3_9_host" + ] + ] + } + }, + "@@rules_sass+//src/toolchain:extensions.bzl%sass": { + "general": { + "bzlTransitiveDigest": "RA58Nyrsn03Z5YmQnpmBw3mqlVck++XIrx34amsqU/E=", + "usagesDigest": "R0KshhzIouLWuexMUCrl4HY+FUDwlVVgF9Z7UnwyUWA=", + "recordedFileInputs": {}, + "recordedDirentsInputs": {}, + "envVariables": {}, + "generatedRepoSpecs": { + "linux_amd64_sass": { + "repoRuleId": "@@rules_sass+//src/toolchain:configure_sass.bzl%configure_sass", + "attributes": { + "file": "@rules_sass//src/compiler/built:sass_linux_x64", + "sha256": "", + "constraints": [ + "@@platforms//os:linux", + "@@platforms//cpu:x86_64" + ] + } + }, + "linux_arm64_sass": { + "repoRuleId": "@@rules_sass+//src/toolchain:configure_sass.bzl%configure_sass", + "attributes": { + "file": "@rules_sass//src/compiler/built:sass_linux_arm", + "sha256": "", + "constraints": [ + "@@platforms//os:linux", + "@@platforms//cpu:arm64" + ] + } + }, + "darwin_amd64_sass": { + "repoRuleId": "@@rules_sass+//src/toolchain:configure_sass.bzl%configure_sass", + "attributes": { + "file": "@rules_sass//src/compiler/built:sass_mac_x64", + "sha256": "", + "constraints": [ + "@@platforms//os:macos", + "@@platforms//cpu:x86_64" + ] + } + }, + "darwin_arm64_sass": { + "repoRuleId": "@@rules_sass+//src/toolchain:configure_sass.bzl%configure_sass", + "attributes": { + "file": "@rules_sass//src/compiler/built:sass_mac_arm", + "sha256": "", + "constraints": [ + "@@platforms//os:macos", + "@@platforms//cpu:arm64" + ] + } + } + }, + "recordedRepoMappingEntries": [] + } + }, + "@@yq.bzl+//yq:extensions.bzl%yq": { + "general": { + "bzlTransitiveDigest": "tDqk+ntWTdxNAWPDjRY1uITgHbti2jcXR5ZdinltBs0=", + "usagesDigest": "4oq89IijqhFzPJc0F7hJ32lOqQzIvApwF7B2cT0spTc=", + "recordedFileInputs": {}, + "recordedDirentsInputs": {}, + "envVariables": {}, + "generatedRepoSpecs": { + "yq_darwin_amd64": { + "repoRuleId": "@@yq.bzl+//yq/toolchain:platforms.bzl%yq_platform_repo", + "attributes": { + "platform": "darwin_amd64", + "version": "4.45.2" + } + }, + "yq_darwin_arm64": { + "repoRuleId": "@@yq.bzl+//yq/toolchain:platforms.bzl%yq_platform_repo", + "attributes": { + "platform": "darwin_arm64", + "version": "4.45.2" + } + }, + "yq_linux_amd64": { + "repoRuleId": "@@yq.bzl+//yq/toolchain:platforms.bzl%yq_platform_repo", + "attributes": { + "platform": "linux_amd64", + "version": "4.45.2" + } + }, + "yq_linux_arm64": { + "repoRuleId": "@@yq.bzl+//yq/toolchain:platforms.bzl%yq_platform_repo", + "attributes": { + "platform": "linux_arm64", + "version": "4.45.2" + } + }, + "yq_linux_s390x": { + "repoRuleId": "@@yq.bzl+//yq/toolchain:platforms.bzl%yq_platform_repo", + "attributes": { + "platform": "linux_s390x", + "version": "4.45.2" + } + }, + "yq_linux_riscv64": { + "repoRuleId": "@@yq.bzl+//yq/toolchain:platforms.bzl%yq_platform_repo", + "attributes": { + "platform": "linux_riscv64", + "version": "4.45.2" + } + }, + "yq_linux_ppc64le": { + "repoRuleId": "@@yq.bzl+//yq/toolchain:platforms.bzl%yq_platform_repo", + "attributes": { + "platform": "linux_ppc64le", + "version": "4.45.2" + } + }, + "yq_windows_amd64": { + "repoRuleId": "@@yq.bzl+//yq/toolchain:platforms.bzl%yq_platform_repo", + "attributes": { + "platform": "windows_amd64", + "version": "4.45.2" + } + }, + "yq_windows_arm64": { + "repoRuleId": "@@yq.bzl+//yq/toolchain:platforms.bzl%yq_platform_repo", + "attributes": { + "platform": "windows_arm64", + "version": "4.45.2" + } + }, + "yq_toolchains": { + "repoRuleId": "@@yq.bzl+//yq/toolchain:toolchain.bzl%yq_toolchains_repo", + "attributes": { + "user_repository_name": "yq" + } } }, "recordedRepoMappingEntries": [] } } - } + }, + "facts": {} } diff --git a/README.md b/README.md index 21a7d3f13398..f14224e1cac7 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,7 @@ This is a monorepo which contains many tools and packages: [quickstart]: https://angular.dev/tutorials/learn-angular [changelog]: CHANGELOG.md [documentation]: https://angular.dev/overview -[angularmaterial]: https://material.angular.io/ +[angularmaterial]: https://material.angular.dev/ [cli]: https://angular.dev/tools/cli [adev]: https://angular.dev/ [workspaceconfig]: https://angular.dev/reference/configs/workspace-config diff --git a/REPO.bazel b/REPO.bazel new file mode 100644 index 000000000000..9eb8128879bd --- /dev/null +++ b/REPO.bazel @@ -0,0 +1,5 @@ +ignore_directories([ + ".git", + "dist", + "**/node_modules/**", +]) diff --git a/WORKSPACE b/WORKSPACE deleted file mode 100644 index bdd6ac8c8c37..000000000000 --- a/WORKSPACE +++ /dev/null @@ -1,294 +0,0 @@ -workspace(name = "angular_cli") - -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file") - -http_archive( - name = "bazel_skylib", - sha256 = "51b5105a760b353773f904d2bbc5e664d0987fbaf22265164de65d43e910d8ac", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.8.1/bazel-skylib-1.8.1.tar.gz", - "https://github.com/bazelbuild/bazel-skylib/releases/download/1.8.1/bazel-skylib-1.8.1.tar.gz", - ], -) - -http_archive( - name = "io_bazel_rules_webtesting", - sha256 = "e9abb7658b6a129740c0b3ef6f5a2370864e102a5ba5ffca2cea565829ed825a", - urls = ["https://github.com/bazelbuild/rules_webtesting/releases/download/0.3.5/rules_webtesting.tar.gz"], -) - -http_archive( - name = "aspect_rules_js", - sha256 = "b71565da7a811964e30cccb405544d551561e4b56c65f0c0aeabe85638920bd6", - strip_prefix = "rules_js-2.4.2", - url = "https://github.com/aspect-build/rules_js/releases/download/v2.4.2/rules_js-v2.4.2.tar.gz", -) - -load("@aspect_rules_js//js:repositories.bzl", "rules_js_dependencies") - -rules_js_dependencies() - -http_archive( - name = "rules_pkg", - sha256 = "8c20f74bca25d2d442b327ae26768c02cf3c99e93fad0381f32be9aab1967675", - urls = ["https://github.com/bazelbuild/rules_pkg/releases/download/0.8.1/rules_pkg-0.8.1.tar.gz"], -) - -load("@bazel_tools//tools/sh:sh_configure.bzl", "sh_configure") - -sh_configure() - -load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace") - -bazel_skylib_workspace() - -load("@rules_pkg//:deps.bzl", "rules_pkg_dependencies") - -rules_pkg_dependencies() - -# Setup the Node.js toolchain -load("@rules_nodejs//nodejs:repositories.bzl", "nodejs_register_toolchains") - -# Set the default nodejs toolchain to the latest supported major version - -NODE_24_VERSION = "24.0.0" - -NODE_24_REPO = { - "24.0.0-darwin_arm64": ("node-v24.0.0-darwin-arm64.tar.gz", "node-v24.0.0-darwin-arm64", "194e2f3dd3ec8c2adcaa713ed40f44c5ca38467880e160974ceac1659be60121"), - "24.0.0-darwin_amd64": ("node-v24.0.0-darwin-x64.tar.gz", "node-v24.0.0-darwin-x64", "f716b3ce14a7e37a6cbf97c9de10d444d7da07ef833cd8da81dd944d111e6a4a"), - "24.0.0-linux_arm64": ("node-v24.0.0-linux-arm64.tar.xz", "node-v24.0.0-linux-arm64", "d40ec7ffe0b82b02dce94208c84351424099bd70fa3a42b65c46d95322305040"), - "24.0.0-linux_ppc64le": ("node-v24.0.0-linux-ppc64le.tar.xz", "node-v24.0.0-linux-ppc64le", "cfa0e8d51a2f9a446f1bfb81cdf4c7e95336ad622e2aa230e3fa1d093c63d77d"), - "24.0.0-linux_s390x": ("node-v24.0.0-linux-s390x.tar.xz", "node-v24.0.0-linux-s390x", "e37a04c7ee05416ec1234fd3255e05b6b81287eb0424a57441c8b69f0a155021"), - "24.0.0-linux_amd64": ("node-v24.0.0-linux-x64.tar.xz", "node-v24.0.0-linux-x64", "59b8af617dccd7f9f68cc8451b2aee1e86d6bd5cb92cd51dd6216a31b707efd7"), - "24.0.0-windows_amd64": ("node-v24.0.0-win-x64.zip", "node-v24.0.0-win-x64", "3d0fff80c87bb9a8d7f49f2f27832aa34a1477d137af46f5b14df5498be81304"), -} - -nodejs_register_toolchains( - name = "nodejs", - node_repositories = NODE_24_REPO, - node_version = NODE_24_VERSION, -) - -nodejs_register_toolchains( - name = "node20", - node_repositories = { - "20.19.0-darwin_arm64": ("node-v20.19.0-darwin-arm64.tar.gz", "node-v20.19.0-darwin-arm64", "c016cd1975a264a29dc1b07c6fbe60d5df0a0c2beb4113c0450e3d998d1a0d9c"), - "20.19.0-darwin_amd64": ("node-v20.19.0-darwin-x64.tar.gz", "node-v20.19.0-darwin-x64", "a8554af97d6491fdbdabe63d3a1cfb9571228d25a3ad9aed2df856facb131b20"), - "20.19.0-linux_arm64": ("node-v20.19.0-linux-arm64.tar.xz", "node-v20.19.0-linux-arm64", "dbe339e55eb393955a213e6b872066880bb9feceaa494f4d44c7aac205ec2ab9"), - "20.19.0-linux_ppc64le": ("node-v20.19.0-linux-ppc64le.tar.xz", "node-v20.19.0-linux-ppc64le", "84937108f005679e60b486ed8e801cebfe923f02b76d8e710463d32f82181f65"), - "20.19.0-linux_s390x": ("node-v20.19.0-linux-s390x.tar.xz", "node-v20.19.0-linux-s390x", "11f8ee99d792a83bba7b29911e0229dd6cd5e88987d7416346067db1cc76d89a"), - "20.19.0-linux_amd64": ("node-v20.19.0-linux-x64.tar.xz", "node-v20.19.0-linux-x64", "b4e336584d62abefad31baecff7af167268be9bb7dd11f1297112e6eed3ca0d5"), - "20.19.0-windows_amd64": ("node-v20.19.0-win-x64.zip", "node-v20.19.0-win-x64", "be72284c7bc62de07d5a9fd0ae196879842c085f11f7f2b60bf8864c0c9d6a4f"), - }, - node_version = "20.19.0", -) - -nodejs_register_toolchains( - name = "node22", - node_repositories = { - "22.12.0-darwin_arm64": ("node-v22.12.0-darwin-arm64.tar.gz", "node-v22.12.0-darwin-arm64", "293dcc6c2408da21562d135b0412525e381bb6fe150d688edb58fe850d0f3e13"), - "22.12.0-darwin_amd64": ("node-v22.12.0-darwin-x64.tar.gz", "node-v22.12.0-darwin-x64", "52bc25dd026db7247c3c00439afdb83e95087248267f02d6c1a7250d1f896173"), - "22.12.0-linux_arm64": ("node-v22.12.0-linux-arm64.tar.xz", "node-v22.12.0-linux-arm64", "8cfd5a8b9afae5a2e0bd86b0148ca31d2589c0ea669c2d0b11c132e35d90ed68"), - "22.12.0-linux_ppc64le": ("node-v22.12.0-linux-ppc64le.tar.xz", "node-v22.12.0-linux-ppc64le", "199a606ba1ee86cce6d6b369c71f9d00873d2836a6662592afc3b6a5923e2004"), - "22.12.0-linux_s390x": ("node-v22.12.0-linux-s390x.tar.xz", "node-v22.12.0-linux-s390x", "9b517f8006eb4b451d40c461cbe64f93c6455566dbe2613387ab02412bc06d35"), - "22.12.0-linux_amd64": ("node-v22.12.0-linux-x64.tar.xz", "node-v22.12.0-linux-x64", "22982235e1b71fa8850f82edd09cdae7e3f32df1764a9ec298c72d25ef2c164f"), - "22.12.0-windows_amd64": ("node-v22.12.0-win-x64.zip", "node-v22.12.0-win-x64", "2b8f2256382f97ad51e29ff71f702961af466c4616393f767455501e6aece9b8"), - }, - node_version = "22.12.0", -) - -nodejs_register_toolchains( - name = "node24", - node_repositories = NODE_24_REPO, - node_version = NODE_24_VERSION, -) - -load("@aspect_rules_js//js:toolchains.bzl", "rules_js_register_toolchains") - -rules_js_register_toolchains( - node_repositories = NODE_24_REPO, - node_version = NODE_24_VERSION, -) - -http_archive( - name = "aspect_bazel_lib", - sha256 = "3522895fa13b97e8b27e3b642045682aa4233ae1a6b278aad6a3b483501dc9f2", - strip_prefix = "bazel-lib-2.20.0", - url = "https://github.com/aspect-build/bazel-lib/releases/download/v2.20.0/bazel-lib-v2.20.0.tar.gz", -) - -load("@aspect_bazel_lib//lib:repositories.bzl", "aspect_bazel_lib_dependencies", "aspect_bazel_lib_register_toolchains") - -aspect_bazel_lib_dependencies() - -aspect_bazel_lib_register_toolchains() - -load("@aspect_rules_js//npm:repositories.bzl", "npm_translate_lock") - -npm_translate_lock( - name = "npm", - custom_postinstalls = { - # TODO: Standardize browser management for `rules_js` - "webdriver-manager": "node ./bin/webdriver-manager update --standalone false --gecko false --versions.chrome 106.0.5249.21", - }, - data = [ - "//:package.json", - "//:pnpm-workspace.yaml", - "//modules/testing/builder:package.json", - "//packages/angular/build:package.json", - "//packages/angular/cli:package.json", - "//packages/angular/pwa:package.json", - "//packages/angular/ssr:package.json", - "//packages/angular_devkit/architect:package.json", - "//packages/angular_devkit/architect_cli:package.json", - "//packages/angular_devkit/build_angular:package.json", - "//packages/angular_devkit/build_webpack:package.json", - "//packages/angular_devkit/core:package.json", - "//packages/angular_devkit/schematics:package.json", - "//packages/angular_devkit/schematics_cli:package.json", - "//packages/ngtools/webpack:package.json", - "//packages/schematics/angular:package.json", - "//tests:package.json", - "//tools/baseline_browserslist:package.json", - ], - lifecycle_hooks_envs = { - # TODO: Standardize browser management for `rules_js` - "puppeteer": ["PUPPETEER_DOWNLOAD_PATH=./downloads"], - }, - lifecycle_hooks_execution_requirements = { - # Needed for downloading chromedriver. - # Also `update-config` of webdriver manager would store an absolute path; - # which would then break execution. - "webdriver-manager": ["local"], - }, - npmrc = "//:.npmrc", - patches = { - # Note: Patches not needed as the existing patches are only - # for `rules_nodejs` dependencies :) - }, - pnpm_lock = "//:pnpm-lock.yaml", - public_hoist_packages = { - # TODO: Remove when https://github.com/verdaccio/verdaccio/commit/bf0e09a509e8e0a74167b0307d129202bc3f40d2 is available. - "@verdaccio/config": [""], - }, - verify_node_modules_ignored = "//:.bazelignore", -) - -load("@npm//:repositories.bzl", "npm_repositories") - -npm_repositories() - -http_archive( - name = "aspect_rules_ts", - sha256 = "09af62a0d46918d815b5f48b5ed0f5349b62c15fc42fcc3fef5c246504ff8d99", - strip_prefix = "rules_ts-3.6.3", - url = "https://github.com/aspect-build/rules_ts/releases/download/v3.6.3/rules_ts-v3.6.3.tar.gz", -) - -load("@aspect_rules_ts//ts:repositories.bzl", "rules_ts_dependencies") - -rules_ts_dependencies( - # Obtained by: curl --silent https://registry.npmjs.org/typescript/5.9.2 | jq -r '.dist.integrity' - ts_integrity = "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==", - ts_version_from = "//:package.json", -) - -http_file( - name = "tsc_worker", - sha256 = "5a5c46846ecda83e05b9da26f1672ad51c59bce08fed88419850d0e29c993b30", - urls = ["https://raw.githubusercontent.com/devversion/rules_angular/4b7532ba2b29078d005899cd15b415593d03cceb/dist/worker.mjs"], -) - -http_archive( - name = "aspect_rules_jasmine", - sha256 = "0d2f9c977842685895020cac721d8cc4f1b37aae15af46128cf619741dc61529", - strip_prefix = "rules_jasmine-2.0.0", - url = "https://github.com/aspect-build/rules_jasmine/releases/download/v2.0.0/rules_jasmine-v2.0.0.tar.gz", -) - -load("@aspect_rules_jasmine//jasmine:dependencies.bzl", "rules_jasmine_dependencies") - -rules_jasmine_dependencies() - -load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository") - -git_repository( - name = "devinfra", - commit = "fbdd8b7df383ae8fb34907a98353c1e8f0f5e528", - remote = "https://github.com/angular/dev-infra.git", -) - -load("@devinfra//bazel:setup_dependencies_1.bzl", "setup_dependencies_1") - -setup_dependencies_1() - -load("@devinfra//bazel:setup_dependencies_2.bzl", "setup_dependencies_2") - -setup_dependencies_2() - -register_toolchains( - "@devinfra//bazel/git-toolchain:git_linux_toolchain", - "@devinfra//bazel/git-toolchain:git_macos_x86_toolchain", - "@devinfra//bazel/git-toolchain:git_macos_arm64_toolchain", - "@devinfra//bazel/git-toolchain:git_windows_toolchain", -) - -http_archive( - name = "aspect_rules_esbuild", - sha256 = "530adfeae30bbbd097e8af845a44a04b641b680c5703b3bf885cbd384ffec779", - strip_prefix = "rules_esbuild-0.22.1", - url = "https://github.com/aspect-build/rules_esbuild/releases/download/v0.22.1/rules_esbuild-v0.22.1.tar.gz", -) - -load("@aspect_rules_esbuild//esbuild:dependencies.bzl", "rules_esbuild_dependencies") - -rules_esbuild_dependencies() - -load("@aspect_rules_esbuild//esbuild:repositories.bzl", "LATEST_ESBUILD_VERSION", "esbuild_register_toolchains") - -esbuild_register_toolchains( - name = "esbuild", - esbuild_version = LATEST_ESBUILD_VERSION, -) - -git_repository( - name = "rules_angular", - commit = "c8af5c0d27c66387e9e7df3c4dd3155ce7582609", - remote = "https://github.com/devversion/rules_angular.git", -) - -load("@rules_angular//setup:step_1.bzl", "rules_angular_step1") - -rules_angular_step1() - -load("@rules_angular//setup:step_2.bzl", "rules_angular_step2") - -rules_angular_step2() - -load("@rules_angular//setup:step_3.bzl", "rules_angular_step3") - -rules_angular_step3( - angular_compiler_cli = "//:node_modules/@angular/compiler-cli", - typescript = "//:node_modules/typescript", -) - -http_archive( - name = "aspect_rules_rollup", - sha256 = "0b8ac7d97cd660eb9a275600227e9c4268f5904cba962939d1a6ce9a0a059d2e", - strip_prefix = "rules_rollup-2.0.1", - url = "https://github.com/aspect-build/rules_rollup/releases/download/v2.0.1/rules_rollup-v2.0.1.tar.gz", -) - -git_repository( - name = "rules_browsers", - commit = "56ef8007ea07cd1916429bca8bb523433b0e9cdc", - remote = "https://github.com/devversion/rules_browsers.git", -) - -load("@rules_browsers//setup:step_1.bzl", "rules_browsers_setup_1") - -rules_browsers_setup_1() - -load("@rules_browsers//setup:step_2.bzl", "rules_browsers_setup_2") - -rules_browsers_setup_2() diff --git a/constants.bzl b/constants.bzl index 76b8d7e1dccb..5110e9e1b4a5 100644 --- a/constants.bzl +++ b/constants.bzl @@ -3,17 +3,17 @@ RELEASE_ENGINES_NODE = "^20.19.0 || ^22.12.0 || >=24.0.0" RELEASE_ENGINES_NPM = "^6.11.0 || ^7.5.6 || >=8.0.0" RELEASE_ENGINES_YARN = ">= 1.13.0" -NG_PACKAGR_VERSION = "^20.2.0-next.0" -ANGULAR_FW_VERSION = "^20.2.0-next.0" -ANGULAR_FW_PEER_DEP = "^20.0.0 || ^20.2.0-next.0" -NG_PACKAGR_PEER_DEP = "^20.0.0 || ^20.2.0-next.0" +NG_PACKAGR_VERSION = "^21.1.0" +ANGULAR_FW_VERSION = "^21.1.0" +ANGULAR_FW_PEER_DEP = "^21.0.0" +NG_PACKAGR_PEER_DEP = "^21.0.0" # Baseline widely-available date in `YYYY-MM-DD` format which defines Angular's # browser support. This date serves as the source of truth for the Angular CLI's # default browser set used to determine what downleveling is necessary. # # See: https://web.dev/baseline -BASELINE_DATE = "2025-04-30" +BASELINE_DATE = "2025-10-20" SNAPSHOT_REPOS = { "@angular/cli": "angular/cli-builds", diff --git a/docs/DEVELOPER.md b/docs/DEVELOPER.md index bd0c9bdf1ee3..8204bd7dcbce 100644 --- a/docs/DEVELOPER.md +++ b/docs/DEVELOPER.md @@ -89,8 +89,8 @@ You can find more info about debugging [tests with Bazel in the docs.](https://g ### End to end tests - For a complete list of test targets use the following Bazel query: `pnpm bazel query "tests(//tests/...)"` -- Run a subset of the tests: `pnpm bazel test //tests/legacy-cli:e2e_node22 --config=e2e --test_filter="tests/i18n/ivy-localize-*"` -- Use `bazel run` to debug failing tests debugging: `pnpm bazel run //tests/legacy-cli:e2e_node22 --config=e2e --test_arg="--glob=tests/basic/aot.ts"` +- Run a subset of the tests: `pnpm bazel test //tests:e2e_node22 --config=e2e --test_filter="tests/i18n/ivy-localize-*"` +- Use `bazel run` to debug failing tests debugging: `pnpm bazel run //tests:e2e_node22 --config=e2e --test_arg="--glob=tests/basic/aot.ts"` - Provide additional `e2e_runner` options using `--test_arg`: `--test_arg="--package-manager=yarn"` When running the debug commands, Node will stop and wait for a debugger to attach. diff --git a/docs/process/release.md b/docs/process/release.md index e8867c909ce3..5490e48e8279 100644 --- a/docs/process/release.md +++ b/docs/process/release.md @@ -69,10 +69,15 @@ Releasing is performed using Angular's unified release tooling. Each week, two r Once FW releases the actual minor/major release (for example: `13.0.0` or `13.1.0`), update dependencies with the following: -1. Update [`constants.bzl`](../../constants.bzl) so `@angular/core` and `ng-packagr` are using the release version (drop `-next.0`). +1. Update [`constants.bzl`](../../constants.bzl) so `@angular/core` and `ng-packagr` are using the release version (drop `-rc.*`). +2. Update all `package.json` dependencies on framework packages to to the release version (drop `-rc.*`). + - Components packages release _after_ CLI, so those should be left as `-rc.*`. +3. `pnpm install` to update the `pnpm-lock.yaml` file. -Merge the above change in a separate PR which lands _after_ FW releases (or else CI will fail) but _before_ the CLI -release PR. Releases are built before the PR is sent for review, so any changes after that point won't be included in the release. +Create a PR with the above changes ([example](https://github.com/angular/angular-cli/pull/31872)) and merge it directly to the RC +branch. This PR must land _after_ FW releases (or else CI will fail) but _before_ the CLI release PR. Releases are built before +the PR is sent for review, so any changes after that point won't be included in the release and this cannot be combined with the +release PR. **AFTER a minor OR major CLI release:** @@ -123,12 +128,15 @@ will block the next weekly release. pnpm ng-dev release build ``` 1. Log in to NPM as `angular`. + ```shell npm login ``` + - See these two Valentine entries for authentication details: - https://valentine.corp.google.com/#/show/1460636514618735 - https://valentine.corp.google.com/#/show/1531867371192103 + 1. Publish the release. ```shell (cd dist/releases/my-scope/my-pkg/ && npm publish --access public) @@ -161,17 +169,10 @@ A few weeks before a major (around feature freeze): - Picking a date at the end of a month makes it easier to cross-reference Angular's support with other tools (like MDN) which state Baseline support using month specificity. - - You can view the generated `browserlist` configuration with: - ```shell - bazel build //packages/angular/build:angular_browserslist - cat dist/bin/packages/angular/build/.browserslistrc - ``` - Commit and merge the change, no other alterations or automation is necessary in the CLI repo. -2. Update - [`/.browserslistrc`](https://github.com/ng-packagr/ng-packagr/tree/main/.browserslistrc) - in the `ng-packagr` repo. - - Use the generated configuration from above. +2. Update the date in the `ng-packagr` repo. + [`/.stylesheet-processor.ts`](https://github.com/ng-packagr/ng-packagr/blob/main/src/lib/styles/stylesheet-processor.ts#L25). 3. Update [`angular.dev` documentation](https://github.com/angular/angular/tree/main/adev/src/content/reference/versions.md#browser-support) to specify the date used and link to [browsersl.ist](https://browsersl.ist) diff --git a/eslint.config.mjs b/eslint.config.mjs index eeb7f6c60cd2..192ba19f2007 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,19 +1,23 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + import { fixupConfigRules, fixupPluginRules } from '@eslint/compat'; +import { FlatCompat } from '@eslint/eslintrc'; +import js from '@eslint/js'; import stylistic from '@stylistic/eslint-plugin'; import typescriptEslint from '@typescript-eslint/eslint-plugin'; -import _import from 'eslint-plugin-import'; +import tsParser from '@typescript-eslint/parser'; import header from 'eslint-plugin-header'; +import _import from 'eslint-plugin-import'; import globals from 'globals'; -import tsParser from '@typescript-eslint/parser'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import js from '@eslint/js'; -import { FlatCompat } from '@eslint/eslintrc'; -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); const compat = new FlatCompat({ - baseDirectory: __dirname, + baseDirectory: import.meta.dirname, recommendedConfig: js.configs.recommended, allConfig: js.configs.all, }); @@ -185,9 +189,8 @@ export default [ }, ], - '@typescript-eslint/ban-types': 'off', + '@typescript-eslint/await-thenable': 'off', '@typescript-eslint/no-implied-eval': 'off', - '@typescript-eslint/no-var-requires': 'off', '@typescript-eslint/no-unsafe-argument': 'off', '@typescript-eslint/no-unsafe-assignment': 'off', '@typescript-eslint/no-unsafe-call': 'off', diff --git a/goldens/public-api/angular/build/index.api.md b/goldens/public-api/angular/build/index.api.md index 19869c39699c..a51449319e47 100644 --- a/goldens/public-api/angular/build/index.api.md +++ b/goldens/public-api/angular/build/index.api.md @@ -112,6 +112,9 @@ export enum BuildOutputFileType { export type DevServerBuilderOptions = { allowedHosts?: AllowedHosts; buildTarget: string; + define?: { + [key: string]: string; + }; headers?: { [key: string]: string; }; @@ -215,19 +218,30 @@ export type NgPackagrBuilderOptions = { // @public export type UnitTestBuilderOptions = { + browserViewport?: string; browsers?: string[]; - buildTarget: string; - codeCoverage?: boolean; - codeCoverageExclude?: string[]; - codeCoverageReporters?: SchemaCodeCoverageReporter[]; + buildTarget?: string; + coverage?: boolean; + coverageExclude?: string[]; + coverageInclude?: string[]; + coverageReporters?: SchemaCoverageReporter[]; + coverageThresholds?: CoverageThresholds; + coverageWatermarks?: CoverageWatermarks; debug?: boolean; + dumpVirtualFiles?: boolean; exclude?: string[]; + filter?: string; include?: string[]; + listTests?: boolean; + outputFile?: string; + progress?: boolean; providersFile?: string; - reporters?: string[]; - runner: Runner; + reporters?: SchemaReporter[]; + runner?: Runner; + runnerConfig?: RunnerConfig; setupFiles?: string[]; - tsConfig: string; + tsConfig?: string; + ui?: boolean; watch?: boolean; }; diff --git a/goldens/public-api/angular/ssr/node/index.api.md b/goldens/public-api/angular/ssr/node/index.api.md index 0f30fa7e99c5..eccb6396938e 100644 --- a/goldens/public-api/angular/ssr/node/index.api.md +++ b/goldens/public-api/angular/ssr/node/index.api.md @@ -5,6 +5,7 @@ ```ts import { ApplicationRef } from '@angular/core'; +import { BootstrapContext } from '@angular/platform-browser'; import { Http2ServerRequest } from 'node:http2'; import { Http2ServerResponse } from 'node:http2'; import { IncomingMessage } from 'node:http'; @@ -26,14 +27,14 @@ export class CommonEngine { // @public (undocumented) export interface CommonEngineOptions { - bootstrap?: Type<{}> | (() => Promise); + bootstrap?: Type<{}> | ((context: BootstrapContext) => Promise); enablePerformanceProfiler?: boolean; providers?: StaticProvider[]; } // @public (undocumented) export interface CommonEngineRenderOptions { - bootstrap?: Type<{}> | (() => Promise); + bootstrap?: Type<{}> | ((context: BootstrapContext) => Promise); // (undocumented) document?: string; // (undocumented) diff --git a/goldens/public-api/angular_devkit/build_angular/index.api.md b/goldens/public-api/angular_devkit/build_angular/index.api.md index cb46b4458351..0208e998a300 100644 --- a/goldens/public-api/angular_devkit/build_angular/index.api.md +++ b/goldens/public-api/angular_devkit/build_angular/index.api.md @@ -49,7 +49,7 @@ export type BrowserBuilderOptions = { i18nDuplicateTranslation?: I18NTranslation; i18nMissingTranslation?: I18NTranslation; index: IndexUnion; - inlineStyleLanguage?: InlineStyleLanguage; + inlineStyleLanguage?: InlineStyleLanguage_2; localize?: Localize; main: string; namedChunks?: boolean; @@ -58,16 +58,16 @@ export type BrowserBuilderOptions = { outputHashing?: OutputHashing; outputPath: string; poll?: number; - polyfills?: Polyfills; + polyfills?: Polyfills_2; preserveSymlinks?: boolean; progress?: boolean; resourcesOutputPath?: string; - scripts?: ScriptElement[]; + scripts?: ScriptElement_2[]; serviceWorker?: boolean; sourceMap?: SourceMapUnion; statsJson?: boolean; stylePreprocessorOptions?: StylePreprocessorOptions; - styles?: StyleElement[]; + styles?: StyleElement_2[]; subresourceIntegrity?: boolean; tsConfig: string; vendorChunk?: boolean; @@ -216,18 +216,18 @@ export type KarmaBuilderOptions = { exclude?: string[]; fileReplacements?: FileReplacement_2[]; include?: string[]; - inlineStyleLanguage?: InlineStyleLanguage_2; + inlineStyleLanguage?: InlineStyleLanguage; karmaConfig?: string; main?: string; poll?: number; - polyfills?: Polyfills_2; + polyfills?: Polyfills; preserveSymlinks?: boolean; progress?: boolean; reporters?: string[]; - scripts?: ScriptElement_2[]; + scripts?: ScriptElement[]; sourceMap?: SourceMapUnion_2; stylePreprocessorOptions?: StylePreprocessorOptions_2; - styles?: StyleElement_2[]; + styles?: StyleElement[]; tsConfig: string; watch?: boolean; webWorkerTsConfig?: string; diff --git a/goldens/public-api/angular_devkit/build_webpack/index.api.md b/goldens/public-api/angular_devkit/build_webpack/index.api.md index db2b47c9ed74..0d60187627d5 100644 --- a/goldens/public-api/angular_devkit/build_webpack/index.api.md +++ b/goldens/public-api/angular_devkit/build_webpack/index.api.md @@ -7,8 +7,8 @@ import { BuilderContext } from '@angular-devkit/architect'; import { BuilderOutput } from '@angular-devkit/architect'; import { Observable } from 'rxjs'; -import webpack from 'webpack'; -import WebpackDevServer from 'webpack-dev-server'; +import type webpack from 'webpack'; +import type WebpackDevServer from 'webpack-dev-server'; // @public (undocumented) export type BuildResult = BuilderOutput & { diff --git a/goldens/public-api/angular_devkit/schematics/tools/index.api.md b/goldens/public-api/angular_devkit/schematics/tools/index.api.md index 6a32d88e9ec0..c93e3ec27762 100644 --- a/goldens/public-api/angular_devkit/schematics/tools/index.api.md +++ b/goldens/public-api/angular_devkit/schematics/tools/index.api.md @@ -203,7 +203,7 @@ export class NodeModulesTestEngineHost extends NodeModulesEngineHost { // (undocumented) protected _resolveCollectionPath(name: string, requester?: string): string; // (undocumented) - get tasks(): TaskConfiguration<{}>[]; + get tasks(): TaskConfiguration[]; // (undocumented) transformContext(context: FileSystemSchematicContext): FileSystemSchematicContext; } diff --git a/goldens/public-api/manage.js b/goldens/public-api/manage.js deleted file mode 100644 index 569f2a6bd1e3..000000000000 --- a/goldens/public-api/manage.js +++ /dev/null @@ -1,54 +0,0 @@ -const {exec} = require('shelljs'); -const {Parser: parser} = require('yargs/helpers'); - -// Remove all command line flags from the arguments. -const argv = parser(process.argv.slice(2)); -// The command the user would like to run, either 'accept' or 'test' -const USER_COMMAND = argv._[0]; -// The shell command to query for all Public API guard tests. -const BAZEL_PUBLIC_API_TARGET_QUERY_CMD = - `pnpm -s bazel query --output label 'kind(nodejs_test, ...) intersect attr("tags", "api_guard", ...)'` -// Bazel targets for testing Public API goldens -process.stdout.write('Gathering all Public API targets'); -const ALL_PUBLIC_API_TESTS = exec(BAZEL_PUBLIC_API_TARGET_QUERY_CMD, {silent: true}) - .trim() - .split('\n') - .map(test => test.trim()); -process.stdout.clearLine(); -process.stdout.cursorTo(0); -// Bazel targets for generating Public API goldens -const ALL_PUBLIC_API_ACCEPTS = ALL_PUBLIC_API_TESTS.map(test => `${test}.accept`); - -/** - * Run the provided bazel commands on each provided target individually. - */ -function runBazelCommandOnTargets(command, targets, present) { - for (const target of targets) { - process.stdout.write(`${present}: ${target}`); - const commandResult = exec(`pnpm -s bazel ${command} ${target}`, {silent: true}); - process.stdout.clearLine(); - process.stdout.cursorTo(0); - if (commandResult.code) { - console.error(`Failed ${command}: ${target}`); - console.group(); - console.error(commandResult.stdout || commandResult.stderr); - console.groupEnd(); - } else { - console.log(`Successful ${command}: ${target}`); - } - } -} - -switch (USER_COMMAND) { - case 'accept': - runBazelCommandOnTargets('run', ALL_PUBLIC_API_ACCEPTS, 'Running'); - break; - case 'test': - runBazelCommandOnTargets('test', ALL_PUBLIC_API_TESTS, 'Testing'); - break; - default: - console.warn('Invalid command provided.'); - console.warn(); - console.warn(`Run this script with either "accept" and "test"`); - break; -} diff --git a/modules/testing/builder/BUILD.bazel b/modules/testing/builder/BUILD.bazel index 154f494af35f..7f542efb0138 100644 --- a/modules/testing/builder/BUILD.bazel +++ b/modules/testing/builder/BUILD.bazel @@ -20,7 +20,10 @@ ts_project( # Needed at runtime by some builder tests relying on SSR being # resolvable in the test project. ":node_modules/@angular/ssr", + ":node_modules/browser-sync", + ":node_modules/jsdom", ":node_modules/vitest", + ":node_modules/@vitest/coverage-v8", ] + glob(["projects/**/*"]), deps = [ ":node_modules/@angular-devkit/architect", diff --git a/modules/testing/builder/package.json b/modules/testing/builder/package.json index 6d5b445b0c8e..ec43c0d86eb7 100644 --- a/modules/testing/builder/package.json +++ b/modules/testing/builder/package.json @@ -4,7 +4,10 @@ "@angular-devkit/architect": "workspace:*", "@angular/ssr": "workspace:*", "@angular-devkit/build-angular": "workspace:*", + "browser-sync": "3.0.4", + "@vitest/coverage-v8": "4.0.16", + "jsdom": "27.4.0", "rxjs": "7.8.2", - "vitest": "3.2.4" + "vitest": "4.0.16" } } diff --git a/modules/testing/builder/projects/hello-world-app/tsconfig.json b/modules/testing/builder/projects/hello-world-app/tsconfig.json index 8019279a7006..8f8859a21d4f 100644 --- a/modules/testing/builder/projects/hello-world-app/tsconfig.json +++ b/modules/testing/builder/projects/hello-world-app/tsconfig.json @@ -5,7 +5,7 @@ "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, - "moduleResolution": "node", + "moduleResolution": "bundler", "emitDecoratorMetadata": true, "experimentalDecorators": true, "skipLibCheck": true, diff --git a/modules/testing/builder/src/builder-harness.ts b/modules/testing/builder/src/builder-harness.ts index ec4973efa021..67b5f760d148 100644 --- a/modules/testing/builder/src/builder-harness.ts +++ b/modules/testing/builder/src/builder-harness.ts @@ -162,6 +162,24 @@ export class BuilderHarness { return this; } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + modifyTarget( + targetName: string, + modifier: (options: O) => O | void, + ): this { + const target = this.builderTargets.get(targetName); + if (!target) { + throw new Error(`Target "${targetName}" not found.`); + } + + const newOptions = modifier(target.options as O); + if (newOptions) { + target.options = newOptions as json.JsonObject; + } + + return this; + } + execute( options: Partial = {}, ): Observable { diff --git a/modules/testing/builder/src/index.ts b/modules/testing/builder/src/index.ts index 8f4687f9fdca..3ee4220781d9 100644 --- a/modules/testing/builder/src/index.ts +++ b/modules/testing/builder/src/index.ts @@ -15,5 +15,7 @@ export { type HarnessFileMatchers, JasmineBuilderHarness, describeBuilder, + expectLog, + expectNoLog, } from './jasmine-helpers'; export * from './test-utils'; diff --git a/modules/testing/builder/src/jasmine-helpers.ts b/modules/testing/builder/src/jasmine-helpers.ts index 94fdbeb38fe1..b31f2e273333 100644 --- a/modules/testing/builder/src/jasmine-helpers.ts +++ b/modules/testing/builder/src/jasmine-helpers.ts @@ -7,7 +7,7 @@ */ import { BuilderHandlerFn } from '@angular-devkit/architect'; -import { json } from '@angular-devkit/core'; +import { json, logging } from '@angular-devkit/core'; import { readFileSync } from 'node:fs'; import { concatMap, count, debounceTime, firstValueFrom, take, timeout } from 'rxjs'; import { @@ -196,3 +196,25 @@ export function expectDirectory( }, }; } + +export function expectLog(logs: readonly logging.LogEntry[], message: string | RegExp) { + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(message), + }), + ); +} + +export function expectNoLog( + logs: readonly logging.LogEntry[], + message: string | RegExp, + failureMessage?: string, +) { + expect(logs) + .withContext(failureMessage ?? '') + .not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(message), + }), + ); +} diff --git a/package.json b/package.json index e1790e8c7e32..0de37781a7c2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "20.2.0-next.3", + "version": "21.1.0", "private": true, "description": "Software Development Kit for Angular", "keywords": [ @@ -11,33 +11,29 @@ "Angular DevKit" ], "scripts": { - "admin": "node --no-warnings=ExperimentalWarning --loader ts-node/esm/transpile-only ./scripts/devkit-admin.mjs", + "admin": "node --no-warnings=ExperimentalWarning --experimental-transform-types ./scripts/devkit-admin.mts", "bazel": "bazelisk", "test": "bazel test //packages/...", "build": "pnpm -s admin build", + "build-schema": "bazel build //... --build_tag_filters schema --symlink_prefix dist-schema/", "lint": "eslint --cache --max-warnings=0 \"**/*.@(ts|mts|cts)\"", "templates": "pnpm -s admin templates", "validate": "pnpm -s admin validate", - "postinstall": "pnpm -s webdriver-update && husky", - "//webdriver-update-README": "ChromeDriver version must match Puppeteer Chromium version, see https://github.com/GoogleChrome/puppeteer/releases http://chromedriver.chromium.org/downloads", - "webdriver-update": "webdriver-manager update --standalone false --gecko false --versions.chrome 106.0.5249.21", - "public-api:check": "node goldens/public-api/manage.js test", - "ng-dev": "node --no-warnings=ExperimentalWarning --loader ts-node/esm/transpile-only node_modules/@angular/ng-dev/bundles/cli.mjs", - "public-api:update": "node goldens/public-api/manage.js accept", - "ts-circular-deps": "pnpm -s ng-dev ts-circular-deps --config ./scripts/circular-deps-test.conf.mjs", + "postinstall": "husky", + "ts-circular-deps": "ng-dev ts-circular-deps --config ./scripts/circular-deps-test.conf.mjs", "check-tooling-setup": "tsc --project .ng-dev/tsconfig.json", - "diff-release-package": "node --no-warnings=ExperimentalWarning --loader ts-node/esm/transpile-only scripts/diff-release-package.mts" + "diff-release-package": "node scripts/diff-release-package.mts" }, "repository": { "type": "git", "url": "https://github.com/angular/angular-cli.git" }, - "packageManager": "pnpm@10.14.0", + "packageManager": "pnpm@10.28.0", "engines": { "node": "^20.19.0 || ^22.12.0 || >=24.0.0", "npm": "Please use pnpm instead of NPM to install dependencies", "yarn": "Please use pnpm instead of Yarn to install dependencies", - "pnpm": "^10.0.0" + "pnpm": "10.28.0" }, "author": "Angular Authors", "license": "MIT", @@ -46,29 +42,30 @@ }, "homepage": "https://github.com/angular/angular-cli", "devDependencies": { - "@angular/animations": "20.2.0-rc.0", - "@angular/cdk": "20.2.0-next.3", - "@angular/common": "20.2.0-rc.0", - "@angular/compiler": "20.2.0-rc.0", - "@angular/compiler-cli": "20.2.0-rc.0", - "@angular/core": "20.2.0-rc.0", - "@angular/forms": "20.2.0-rc.0", - "@angular/localize": "20.2.0-rc.0", - "@angular/material": "20.2.0-next.3", - "@angular/ng-dev": "https://github.com/angular/dev-infra-private-ng-dev-builds.git#e16e229975bd41d66ec49905d5896b8f61068a19", - "@angular/platform-browser": "20.2.0-rc.0", - "@angular/platform-server": "20.2.0-rc.0", - "@angular/router": "20.2.0-rc.0", - "@angular/service-worker": "20.2.0-rc.0", + "@angular/animations": "21.1.0", + "@angular/cdk": "21.1.0-next.4", + "@angular/common": "21.1.0", + "@angular/compiler": "21.1.0", + "@angular/compiler-cli": "21.1.0", + "@angular/core": "21.1.0", + "@angular/forms": "21.1.0", + "@angular/localize": "21.1.0", + "@angular/material": "21.1.0-next.4", + "@angular/ng-dev": "https://github.com/angular/dev-infra-private-ng-dev-builds.git#486b075a283ef0c169475b981de1bd229114a000", + "@angular/platform-browser": "21.1.0", + "@angular/platform-server": "21.1.0", + "@angular/router": "21.1.0", + "@angular/service-worker": "21.1.0", + "@babel/core": "7.28.5", "@bazel/bazelisk": "1.26.0", "@bazel/buildifier": "8.2.1", - "@eslint/compat": "1.3.2", - "@eslint/eslintrc": "3.3.1", - "@eslint/js": "9.33.0", - "@rollup/plugin-alias": "^5.1.1", - "@rollup/plugin-commonjs": "^28.0.0", + "@eslint/compat": "2.0.0", + "@eslint/eslintrc": "3.3.3", + "@eslint/js": "9.39.2", + "@rollup/plugin-alias": "^6.0.0", + "@rollup/plugin-commonjs": "^29.0.0", "@rollup/plugin-json": "^6.1.0", - "@rollup/plugin-node-resolve": "16.0.1", + "@rollup/plugin-node-resolve": "16.0.3", "@stylistic/eslint-plugin": "^5.0.0", "@types/babel__core": "7.20.5", "@types/babel__generator": "^7.6.8", @@ -80,7 +77,7 @@ "@types/jasmine-reporters": "^2", "@types/karma": "^6.3.0", "@types/less": "^3.0.3", - "@types/loader-utils": "^2.0.0", + "@types/loader-utils": "^3.0.0", "@types/lodash": "^4.17.0", "@types/node": "^22.12.0", "@types/npm-package-arg": "^6.1.0", @@ -89,31 +86,28 @@ "@types/progress": "^2.0.3", "@types/resolve": "^1.17.1", "@types/semver": "^7.3.12", - "@types/shelljs": "^0.8.11", "@types/watchpack": "^2.4.4", "@types/yargs": "^17.0.20", "@types/yargs-parser": "^21.0.0", "@types/yarnpkg__lockfile": "^1.1.5", - "@typescript-eslint/eslint-plugin": "8.39.1", - "@typescript-eslint/parser": "8.39.1", + "@typescript-eslint/eslint-plugin": "8.52.0", + "@typescript-eslint/parser": "8.52.0", "ajv": "8.17.1", - "ansi-colors": "4.1.3", - "beasties": "0.3.5", "buffer": "6.0.3", - "esbuild": "0.25.9", - "esbuild-wasm": "0.25.9", - "eslint": "9.33.0", + "esbuild": "0.27.2", + "esbuild-wasm": "0.27.2", + "eslint": "9.39.2", "eslint-config-prettier": "10.1.8", "eslint-plugin-header": "3.1.1", "eslint-plugin-import": "2.32.0", - "express": "5.1.0", + "express": "5.2.1", "fast-glob": "3.3.3", - "globals": "16.3.0", + "globals": "17.0.0", "http-proxy": "^1.18.1", "http-proxy-middleware": "3.0.5", "husky": "9.1.7", - "jasmine": "~5.9.0", - "jasmine-core": "~5.9.0", + "jasmine": "~5.13.0", + "jasmine-core": "~5.13.0", "jasmine-reporters": "^2.5.2", "jasmine-spec-reporter": "~7.0.0", "karma": "~6.4.0", @@ -122,31 +116,26 @@ "karma-jasmine": "~5.1.0", "karma-jasmine-html-reporter": "~2.1.0", "karma-source-map-support": "1.4.0", - "listr2": "9.0.1", "lodash": "^4.17.21", - "npm": "^11.0.0", - "magic-string": "0.30.17", - "rollup-plugin-dts": "6.2.1", - "rollup-plugin-sourcemaps2": "0.5.3", + "magic-string": "0.30.21", "prettier": "^3.0.0", "protractor": "~7.0.0", "puppeteer": "18.2.1", "quicktype-core": "23.2.6", - "rollup": "4.46.2", - "rollup-license-plugin": "~3.0.1", - "semver": "7.7.2", - "shelljs": "^0.10.0", + "rollup": "4.55.1", + "rollup-license-plugin": "~3.1.0", + "rollup-plugin-dts": "6.3.0", + "rollup-plugin-sourcemaps2": "0.5.4", + "semver": "7.7.3", "source-map-support": "0.5.21", - "tar": "^7.0.0", "ts-node": "^10.9.1", "tslib": "2.8.1", - "typescript": "5.9.2", - "undici": "7.13.0", + "typescript": "5.9.3", + "undici": "7.18.0", "unenv": "^1.10.0", - "verdaccio": "6.1.6", + "verdaccio": "6.2.4", "verdaccio-auth-memory": "^10.0.0", - "yargs-parser": "22.0.0", - "zone.js": "^0.15.0" + "zone.js": "^0.16.0" }, "dependenciesMeta": { "esbuild": { @@ -173,6 +162,6 @@ } }, "resolutions": { - "typescript": "5.9.2" + "undici-types": "^7.16.0" } } diff --git a/packages/angular/build/BUILD.bazel b/packages/angular/build/BUILD.bazel index fbbe5e86ee12..2f74117ff850 100644 --- a/packages/angular/build/BUILD.bazel +++ b/packages/angular/build/BUILD.bazel @@ -1,9 +1,7 @@ load("@devinfra//bazel/api-golden:index.bzl", "api_golden_test_npm_package") load("@npm//:defs.bzl", "npm_link_all_packages") -load("//:constants.bzl", "BASELINE_DATE") load("//tools:defaults.bzl", "copy_to_bin", "jasmine_test", "npm_package", "ts_project") load("//tools:ts_json_schema.bzl", "ts_json_schema") -load("//tools/baseline_browserslist:baseline_browserslist.bzl", "baseline_browserslist") licenses(["notice"]) @@ -46,23 +44,14 @@ copy_to_bin( srcs = glob(["**/schema.json"]), ) -baseline_browserslist( - name = "angular_browserslist", - out = ".browserslistrc", - baseline = BASELINE_DATE, -) - RUNTIME_ASSETS = glob( include = [ "src/**/schema.json", "src/**/*.js", - "src/**/*.mjs", - "src/**/*.html", ], ) + [ "builders.json", "package.json", - ":angular_browserslist", ] ts_project( @@ -97,6 +86,7 @@ ts_project( ":node_modules/@babel/helper-split-export-declaration", ":node_modules/@inquirer/confirm", ":node_modules/@vitejs/plugin-basic-ssl", + ":node_modules/beasties", ":node_modules/browserslist", ":node_modules/https-proxy-agent", ":node_modules/istanbul-lib-instrument", @@ -115,6 +105,7 @@ ts_project( ":node_modules/sass", ":node_modules/source-map-support", ":node_modules/tinyglobby", + ":node_modules/undici", ":node_modules/vite", ":node_modules/vitest", ":node_modules/watchpack", @@ -123,6 +114,7 @@ ts_project( "//:node_modules/@angular/compiler-cli", "//:node_modules/@angular/core", "//:node_modules/@angular/localize", + "//:node_modules/@angular/platform-browser", "//:node_modules/@angular/platform-server", "//:node_modules/@angular/service-worker", "//:node_modules/@types/babel__core", @@ -132,7 +124,6 @@ ts_project( "//:node_modules/@types/picomatch", "//:node_modules/@types/semver", "//:node_modules/@types/watchpack", - "//:node_modules/beasties", "//:node_modules/esbuild", "//:node_modules/esbuild-wasm", "//:node_modules/karma", @@ -301,6 +292,10 @@ jasmine_test( name = "dev-server_integration_tests", size = "medium", data = [":dev-server_integration_test_lib"], + env = { + # Force IPv4 to resolve RBE resolution issues + "NODE_OPTIONS": "--dns-result-order=ipv4first", + }, flaky = True, shard_count = 10, ) @@ -320,8 +315,9 @@ jasmine_test( jasmine_test( name = "unit-test_integration_tests", - size = "small", + size = "medium", data = [":unit-test_integration_test_lib"], + flaky = True, shard_count = 5, ) @@ -341,6 +337,7 @@ npm_package( "src/utils/version.js", "src/tools/esbuild/utils.js", "src/utils/normalize-cache.js", + "src/utils/supported-browsers.js", ], tags = ["release-package"], deps = RUNTIME_ASSETS + [ diff --git a/packages/angular/build/package.json b/packages/angular/build/package.json index 2491bace216e..1038580b2465 100644 --- a/packages/angular/build/package.json +++ b/packages/angular/build/package.json @@ -20,48 +20,49 @@ "dependencies": { "@ampproject/remapping": "2.3.0", "@angular-devkit/architect": "workspace:0.0.0-EXPERIMENTAL-PLACEHOLDER", - "@babel/core": "7.28.0", + "@babel/core": "7.28.5", "@babel/helper-annotate-as-pure": "7.27.3", "@babel/helper-split-export-declaration": "7.24.7", - "@inquirer/confirm": "5.1.14", + "@inquirer/confirm": "5.1.21", "@vitejs/plugin-basic-ssl": "2.1.0", "beasties": "0.3.5", - "browserslist": "^4.23.0", - "esbuild": "0.25.9", + "browserslist": "^4.26.0", + "esbuild": "0.27.2", "https-proxy-agent": "7.0.6", "istanbul-lib-instrument": "6.0.3", "jsonc-parser": "3.3.1", - "listr2": "9.0.1", - "magic-string": "0.30.17", + "listr2": "9.0.5", + "magic-string": "0.30.21", "mrmime": "2.0.1", "parse5-html-rewriting-stream": "8.0.0", "picomatch": "4.0.3", - "piscina": "5.1.3", - "rolldown": "1.0.0-beta.32", - "sass": "1.90.0", - "semver": "7.7.2", + "piscina": "5.1.4", + "rolldown": "1.0.0-beta.58", + "sass": "1.97.1", + "semver": "7.7.3", "source-map-support": "0.5.21", - "tinyglobby": "0.2.14", - "vite": "7.1.2", - "watchpack": "2.4.4" + "tinyglobby": "0.2.15", + "undici": "7.18.0", + "vite": "7.3.0", + "watchpack": "2.5.0" }, "optionalDependencies": { - "lmdb": "3.4.2" + "lmdb": "3.4.4" }, "devDependencies": { - "@angular/ssr": "workspace:*", "@angular-devkit/core": "workspace:*", - "jsdom": "26.1.0", - "less": "4.4.0", - "ng-packagr": "20.2.0-next.1", + "@angular/ssr": "workspace:*", + "jsdom": "27.4.0", + "less": "4.4.2", + "ng-packagr": "21.1.0", "postcss": "8.5.6", "rxjs": "7.8.2", - "vitest": "3.2.4" + "vitest": "4.0.16" }, "peerDependencies": { - "@angular/core": "0.0.0-ANGULAR-FW-PEER-DEP", "@angular/compiler": "0.0.0-ANGULAR-FW-PEER-DEP", "@angular/compiler-cli": "0.0.0-ANGULAR-FW-PEER-DEP", + "@angular/core": "0.0.0-ANGULAR-FW-PEER-DEP", "@angular/localize": "0.0.0-ANGULAR-FW-PEER-DEP", "@angular/platform-browser": "0.0.0-ANGULAR-FW-PEER-DEP", "@angular/platform-server": "0.0.0-ANGULAR-FW-PEER-DEP", @@ -73,8 +74,8 @@ "postcss": "^8.4.0", "tailwindcss": "^2.0.0 || ^3.0.0 || ^4.0.0", "tslib": "^2.3.0", - "typescript": ">=5.8 <6.0", - "vitest": "^3.1.1" + "typescript": ">=5.9 <6.0", + "vitest": "^4.0.8" }, "peerDependenciesMeta": { "@angular/core": { diff --git a/packages/angular/build/src/builders/application/chunk-optimizer.ts b/packages/angular/build/src/builders/application/chunk-optimizer.ts index 4e37a11e03f9..e6827479b784 100644 --- a/packages/angular/build/src/builders/application/chunk-optimizer.ts +++ b/packages/angular/build/src/builders/application/chunk-optimizer.ts @@ -252,7 +252,7 @@ export async function optimizeChunks( }); const result = await bundle.generate({ - minify: { mangle: false, compress: false, removeWhitespace: true }, + minify: { mangle: false, compress: false }, sourcemap, chunkFileNames: (chunkInfo) => `${chunkInfo.name.replace(/-[a-zA-Z0-9]{8}$/, '')}-[hash].js`, }); diff --git a/packages/angular/build/src/builders/application/index.ts b/packages/angular/build/src/builders/application/index.ts index 80261c41277f..b83e3b48f270 100644 --- a/packages/angular/build/src/builders/application/index.ts +++ b/packages/angular/build/src/builders/application/index.ts @@ -14,7 +14,7 @@ import { BuildOutputFileType } from '../../tools/esbuild/bundler-context'; import { createJsonBuildManifest, emitFilesToDisk } from '../../tools/esbuild/utils'; import { colors as ansiColors } from '../../utils/color'; import { deleteOutputDir } from '../../utils/delete-output-dir'; -import { useJSONBuildLogs } from '../../utils/environment-options'; +import { bazelEsbuildPluginPath, useJSONBuildLogs } from '../../utils/environment-options'; import { purgeStaleBuildCache } from '../../utils/purge-cache'; import { assertCompatibleAngularVersion } from '../../utils/version'; import { runEsBuildBuildAction } from './build-action'; @@ -56,6 +56,14 @@ export async function* buildApplicationInternal( return; } + if (bazelEsbuildPluginPath) { + extensions ??= {}; + extensions.codePlugins ??= []; + + const { default: bazelEsbuildPlugin } = await import(bazelEsbuildPluginPath); + extensions.codePlugins.push(bazelEsbuildPlugin); + } + const normalizedOptions = await normalizeOptions(context, projectName, options, extensions); if (!normalizedOptions.outputOptions.ignoreServer) { @@ -109,7 +117,8 @@ export async function* buildApplicationInternal( const hasError = result.errors.length > 0; result.addLog( - `Application bundle generation ${hasError ? 'failed' : 'complete'}. [${buildTime.toFixed(3)} seconds]\n`, + `Application bundle generation ${hasError ? 'failed' : 'complete'}.` + + ` [${buildTime.toFixed(3)} seconds] - ${new Date().toISOString()}\n`, ); } diff --git a/packages/angular/build/src/builders/application/options.ts b/packages/angular/build/src/builders/application/options.ts index 1b3a15b8cd56..83b7ea428f35 100644 --- a/packages/angular/build/src/builders/application/options.ts +++ b/packages/angular/build/src/builders/application/options.ts @@ -25,7 +25,7 @@ import { loadPostcssConfiguration, } from '../../utils/postcss-configuration'; import { getProjectRootPaths, normalizeDirectoryPath } from '../../utils/project-metadata'; -import { urlJoin } from '../../utils/url'; +import { addTrailingSlash, joinUrlParts, stripLeadingSlash } from '../../utils/url'; import { Schema as ApplicationBuilderOptions, ExperimentalPlatform, @@ -681,7 +681,16 @@ export function getLocaleBaseHref( const baseHrefSuffix = localeData.baseHref ?? localeData.subPath + '/'; - return baseHrefSuffix !== '' ? urlJoin(baseHref, baseHrefSuffix) : undefined; + let joinedBaseHref: string | undefined; + if (baseHrefSuffix !== '') { + joinedBaseHref = addTrailingSlash(joinUrlParts(baseHref, baseHrefSuffix)); + + if (baseHref && baseHref[0] !== '/') { + joinedBaseHref = stripLeadingSlash(joinedBaseHref); + } + } + + return joinedBaseHref; } /** diff --git a/packages/angular/build/src/builders/application/options_spec.ts b/packages/angular/build/src/builders/application/options_spec.ts new file mode 100644 index 000000000000..ac6320905019 --- /dev/null +++ b/packages/angular/build/src/builders/application/options_spec.ts @@ -0,0 +1,106 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { NormalizedApplicationBuildOptions, getLocaleBaseHref } from './options'; + +describe('getLocaleBaseHref', () => { + const baseI18nOptions: NormalizedApplicationBuildOptions['i18nOptions'] = { + inlineLocales: new Set(), + sourceLocale: 'en-US', + locales: {}, + flatOutput: false, + shouldInline: false, + hasDefinedSourceLocale: false, + }; + + it('should return undefined if flatOutput is true', () => { + const result = getLocaleBaseHref(undefined, { ...baseI18nOptions, flatOutput: true }, 'fr'); + expect(result).toBeUndefined(); + }); + + it('should return undefined if locale is not found', () => { + const result = getLocaleBaseHref(undefined, baseI18nOptions, 'fr'); + expect(result).toBeUndefined(); + }); + + it('should return baseHref from locale data if present', () => { + const i18nOptions = { + ...baseI18nOptions, + locales: { + fr: { + files: [], + translation: {}, + subPath: 'fr', + baseHref: '/fr/', + }, + }, + }; + const result = getLocaleBaseHref(undefined, i18nOptions, 'fr'); + expect(result).toBe('/fr/'); + }); + + it('should join baseHref and locale subPath if baseHref is provided', () => { + const i18nOptions = { + ...baseI18nOptions, + locales: { + fr: { + files: [], + translation: {}, + subPath: 'fr', + }, + }, + }; + const result = getLocaleBaseHref('/app/', i18nOptions, 'fr'); + expect(result).toBe('/app/fr/'); + }); + + it('should handle missing baseHref (undefined) correctly', () => { + const i18nOptions = { + ...baseI18nOptions, + locales: { + fr: { + files: [], + translation: {}, + subPath: 'fr', + }, + }, + }; + const result = getLocaleBaseHref(undefined, i18nOptions, 'fr'); + expect(result).toBe('/fr/'); + }); + + it('should handle empty baseHref correctly', () => { + const i18nOptions = { + ...baseI18nOptions, + locales: { + fr: { + files: [], + translation: {}, + subPath: 'fr', + }, + }, + }; + const result = getLocaleBaseHref('', i18nOptions, 'fr'); + expect(result).toBe('/fr/'); + }); + + it('should strip leading slash if baseHref does not start with slash', () => { + const i18nOptions = { + ...baseI18nOptions, + locales: { + fr: { + files: [], + translation: {}, + subPath: 'fr', + }, + }, + }; + const result = getLocaleBaseHref('app/', i18nOptions, 'fr'); + expect(result).toBe('app/fr/'); + }); +}); diff --git a/packages/angular/build/src/builders/application/schema.json b/packages/angular/build/src/builders/application/schema.json index 3ee8699e097f..8db4e6145b3f 100644 --- a/packages/angular/build/src/builders/application/schema.json +++ b/packages/angular/build/src/builders/application/schema.json @@ -6,7 +6,7 @@ "properties": { "assets": { "type": "array", - "description": "List of static application assets.", + "description": "Define the assets to be copied to the output directory. These assets are copied as-is without any further processing or hashing.", "default": [], "items": { "$ref": "#/definitions/assetPattern" @@ -441,7 +441,7 @@ }, "outputHashing": { "type": "string", - "description": "Define the output filename cache-busting hashing mode.", + "description": "Define the output filename cache-busting hashing mode.\n\n- `none`: No hashing.\n- `all`: Hash for all output bundles. \n- `media`: Hash for all output media (e.g., images, fonts, etc. that are referenced in CSS files).\n- `bundles`: Hash for output of lazy and main bundles.", "default": "none", "enum": ["none", "all", "media", "bundles"] }, @@ -611,7 +611,7 @@ }, "outputMode": { "type": "string", - "description": "Defines the build output target. 'static': Generates a static site for deployment on any static hosting service. 'server': Produces an application designed for deployment on a server that supports server-side rendering (SSR).", + "description": "Defines the type of build output artifact. 'static': Generates a static site build artifact for deployment on any static hosting service. 'server': Generates a server application build artifact, required for applications using hybrid rendering or APIs.", "enum": ["static", "server"] } }, diff --git a/packages/angular/build/src/builders/application/tests/behavior/component-stylesheets_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/component-stylesheets_spec.ts index ecc460bcb405..ddae750a64a4 100644 --- a/packages/angular/build/src/builders/application/tests/behavior/component-stylesheets_spec.ts +++ b/packages/angular/build/src/builders/application/tests/behavior/component-stylesheets_spec.ts @@ -11,7 +11,7 @@ import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setu describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Component Stylesheets"', () => { - it('should successfuly compile with an empty inline style', async () => { + it('should successfully compile with an empty inline style', async () => { await harness.modifyFile('src/app/app.component.ts', (content) => { return content.replace('styleUrls', 'styles').replace('./app.component.css', ''); }); diff --git a/packages/angular/build/src/builders/application/tests/behavior/rebuild-errors_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/rebuild-errors_spec.ts index e2105fd13de7..fa384be88080 100644 --- a/packages/angular/build/src/builders/application/tests/behavior/rebuild-errors_spec.ts +++ b/packages/angular/build/src/builders/application/tests/behavior/rebuild-errors_spec.ts @@ -6,9 +6,14 @@ * found in the LICENSE file at https://angular.dev/license */ -import { logging } from '@angular-devkit/core'; import { buildApplication } from '../../index'; -import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; +import { + APPLICATION_BUILDER_INFO, + BASE_OPTIONS, + describeBuilder, + expectLog, + expectNoLog, +} from '../setup'; /** * Maximum time in milliseconds for single build/rebuild @@ -92,11 +97,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { }, async ({ result, logs }) => { expect(result?.success).toBeFalse(); - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(typeErrorText), - }), - ); + expectLog(logs, typeErrorText); // Make an unrelated change to verify error cache was updated // Should persist error in the next rebuild @@ -104,11 +105,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { }, async ({ result, logs }) => { expect(result?.success).toBeFalse(); - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(typeErrorText), - }), - ); + expectLog(logs, typeErrorText); // Revert the directive change that caused the error // Should remove the error @@ -116,11 +113,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { }, async ({ result, logs }) => { expect(result?.success).toBeTrue(); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(typeErrorText), - }), - ); + expectNoLog(logs, typeErrorText); // Make an unrelated change to verify error cache was updated // Should continue showing no error @@ -128,11 +121,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { }, ({ result, logs }) => { expect(result?.success).toBeTrue(); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(typeErrorText), - }), - ); + expectNoLog(logs, typeErrorText); }, ], { outputLogsOnFailure: false }, @@ -152,78 +141,38 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { await harness.appendToFile('src/app/app.component.html', '@if-one'); }, async ({ logs }) => { - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringContaining('@if-one'), - }), - ); + expectLog(logs, '@if-one'); // Make an unrelated change to verify error cache was updated // Should persist error in the next rebuild await harness.modifyFile('src/main.ts', (content) => content + '\n'); }, async ({ logs }) => { - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringContaining('@if-one'), - }), - ); + expectLog(logs, '@if-one'); // Add more invalid block syntax await harness.appendToFile('src/app/app.component.html', '@if-two'); }, async ({ logs }) => { - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringContaining('@if-one'), - }), - ); - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringContaining('@if-two'), - }), - ); + expectLog(logs, '@if-one'); + expectLog(logs, '@if-two'); // Add more invalid block syntax await harness.appendToFile('src/app/app.component.html', '@if-three'); }, async ({ logs }) => { - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringContaining('@if-one'), - }), - ); - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringContaining('@if-two'), - }), - ); - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringContaining('@if-three'), - }), - ); + expectLog(logs, '@if-one'); + expectLog(logs, '@if-two'); + expectLog(logs, '@if-three'); // Revert the changes that caused the error // Should remove the error await harness.writeFile('src/app/app.component.html', '

GOOD

'); }, ({ logs }) => { - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringContaining('@if-one'), - }), - ); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringContaining('@if-two'), - }), - ); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringContaining('@if-three'), - }), - ); + expectNoLog(logs, '@if-one'); + expectNoLog(logs, '@if-two'); + expectNoLog(logs, '@if-three'); }, ], { outputLogsOnFailure: false }, @@ -243,20 +192,12 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { await harness.writeFile('src/app/app.component.css', 'invalid-css-content'); }, async ({ logs }) => { - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching('invalid-css-content'), - }), - ); + expectLog(logs, 'invalid-css-content'); await harness.writeFile('src/app/app.component.css', 'p { color: green }'); }, ({ logs }) => { - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching('invalid-css-content'), - }), - ); + expectNoLog(logs, 'invalid-css-content'); harness .expectFile('dist/browser/main.js') @@ -280,20 +221,12 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { await harness.appendToFile('src/app/app.component.html', '
Hello, world! { - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching('Unexpected character "EOF"'), - }), - ); + expectLog(logs, 'Unexpected character "EOF"'); await harness.appendToFile('src/app/app.component.html', '>'); }, async ({ logs }) => { - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching('Unexpected character "EOF"'), - }), - ); + expectNoLog(logs, 'Unexpected character "EOF"'); harness.expectFile('dist/browser/main.js').content.toContain('Hello, world!'); @@ -301,11 +234,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { await harness.appendToFile('src/app/app.component.html', '
Guten Tag
'); }, ({ logs }) => { - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching('invalid-css-content'), - }), - ); + expectNoLog(logs, 'invalid-css-content'); harness.expectFile('dist/browser/main.js').content.toContain('Hello, world!'); harness.expectFile('dist/browser/main.js').content.toContain('Guten Tag'); diff --git a/packages/angular/build/src/builders/application/tests/behavior/rebuild-web-workers_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/rebuild-web-workers_spec.ts index 4e167f2994c6..2fdad10f8d8d 100644 --- a/packages/angular/build/src/builders/application/tests/behavior/rebuild-web-workers_spec.ts +++ b/packages/angular/build/src/builders/application/tests/behavior/rebuild-web-workers_spec.ts @@ -6,9 +6,14 @@ * found in the LICENSE file at https://angular.dev/license */ -import { logging } from '@angular-devkit/core'; import { buildApplication } from '../../index'; -import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; +import { + APPLICATION_BUILDER_INFO, + BASE_OPTIONS, + describeBuilder, + expectLog, + expectNoLog, +} from '../setup'; /** * A regular expression used to check if a built worker is correctly referenced in application code. @@ -62,22 +67,14 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { }, async ({ result, logs }) => { expect(result?.success).toBeFalse(); - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(errorText), - }), - ); + expectLog(logs, errorText); // Make an unrelated change to verify error cache was updated // Should persist error in the next rebuild await harness.modifyFile('src/main.ts', (content) => content + '\n'); }, async ({ logs }) => { - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(errorText), - }), - ); + expectLog(logs, errorText); // Revert the change that caused the error // Should remove the error @@ -85,11 +82,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { }, async ({ result, logs }) => { expect(result?.success).toBeTrue(); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(errorText), - }), - ); + expectNoLog(logs, errorText); // Make an unrelated change to verify error cache was updated // Should continue showing no error @@ -97,11 +90,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { }, ({ result, logs }) => { expect(result?.success).toBeTrue(); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(errorText), - }), - ); + expectNoLog(logs, errorText); // Ensure built worker is referenced in the application code harness.expectFile('dist/browser/main.js').content.toMatch(REFERENCED_WORKER_REGEXP); diff --git a/packages/angular/build/src/builders/application/tests/behavior/typescript-incremental_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/typescript-incremental_spec.ts index 2c73e66d9f8b..cc74b9549e9d 100644 --- a/packages/angular/build/src/builders/application/tests/behavior/typescript-incremental_spec.ts +++ b/packages/angular/build/src/builders/application/tests/behavior/typescript-incremental_spec.ts @@ -3,7 +3,7 @@ * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license + * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; diff --git a/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-lazy_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-lazy_spec.ts index 1f1efafaf3c5..ba01e2a27dce 100644 --- a/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-lazy_spec.ts +++ b/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-lazy_spec.ts @@ -6,10 +6,9 @@ * found in the LICENSE file at https://angular.dev/license */ -import type { logging } from '@angular-devkit/core'; import { buildApplication } from '../../index'; import { OutputHashing } from '../../schema'; -import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder, expectLog } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { beforeEach(async () => { @@ -57,13 +56,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { }, async ({ result, logs }) => { expect(result?.success).toBeFalse(); - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching( - `Type 'number' is not assignable to type 'string'.`, - ), - }), - ); + expectLog(logs, `Type 'number' is not assignable to type 'string'.`); // Fix TS error await harness.writeFile('src/lazy.ts', `export const foo: string = "1";`); diff --git a/packages/angular/build/src/builders/application/tests/behavior/typescript-resolve-json_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/typescript-resolve-json_spec.ts index e7d060de1262..cf21d5545f7a 100644 --- a/packages/angular/build/src/builders/application/tests/behavior/typescript-resolve-json_spec.ts +++ b/packages/angular/build/src/builders/application/tests/behavior/typescript-resolve-json_spec.ts @@ -20,6 +20,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { // Enable tsconfig resolveJsonModule option in tsconfig await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.moduleResolution = 'node'; tsconfig.compilerOptions.resolveJsonModule = true; return JSON.stringify(tsconfig); @@ -43,6 +44,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { // Enable tsconfig resolveJsonModule option in tsconfig await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.moduleResolution = 'node'; tsconfig.compilerOptions.resolveJsonModule = undefined; return JSON.stringify(tsconfig); @@ -71,6 +73,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { // Enable tsconfig resolveJsonModule option in tsconfig await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); + tsconfig.compilerOptions.moduleResolution = 'node'; tsconfig.compilerOptions.resolveJsonModule = false; return JSON.stringify(tsconfig); diff --git a/packages/angular/build/src/builders/application/tests/options/allowed-common-js-dependencies_spec.ts b/packages/angular/build/src/builders/application/tests/options/allowed-common-js-dependencies_spec.ts index ad29d985f712..bcc361ccdbe1 100644 --- a/packages/angular/build/src/builders/application/tests/options/allowed-common-js-dependencies_spec.ts +++ b/packages/angular/build/src/builders/application/tests/options/allowed-common-js-dependencies_spec.ts @@ -6,9 +6,14 @@ * found in the LICENSE file at https://angular.dev/license */ -import { logging } from '@angular-devkit/core'; import { buildApplication } from '../../index'; -import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; +import { + APPLICATION_BUILDER_INFO, + BASE_OPTIONS, + describeBuilder, + expectLog, + expectNoLog, +} from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "allowedCommonJsDependencies"', () => { @@ -30,22 +35,11 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching( - /Module 'buffer' used by 'src\/app\/app\.component\.ts' is not ESM/, - ), - }), - ); - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(/CommonJS or AMD dependencies/), - }), - ); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching('base64-js'), - }), + expectLog(logs, /Module 'buffer' used by 'src\/app\/app\.component\.ts' is not ESM/); + expectLog(logs, /CommonJS or AMD dependencies/); + expectNoLog( + logs, + 'base64-js', 'Should not warn on transitive CommonJS packages which parent is also CommonJS.', ); }); @@ -70,11 +64,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(/CommonJS or AMD dependencies/), - }), - ); + expectNoLog(logs, /CommonJS or AMD dependencies/); }); it('should not show warning when all dependencies are allowed by wildcard', async () => { @@ -95,11 +85,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(/CommonJS or AMD dependencies/), - }), - ); + expectNoLog(logs, /CommonJS or AMD dependencies/); }); it('should not show warning when depending on zone.js', async () => { @@ -120,11 +106,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(/CommonJS or AMD dependencies/), - }), - ); + expectNoLog(logs, /CommonJS or AMD dependencies/); }); it(`should not show warning when importing non global local data '@angular/common/locale/fr'`, async () => { @@ -142,11 +124,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(/CommonJS or AMD dependencies/), - }), - ); + expectNoLog(logs, /CommonJS or AMD dependencies/); }); it('should not show warning in JIT for templateUrl and styleUrl when using paths', async () => { @@ -178,11 +156,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(/CommonJS or AMD dependencies/), - }), - ); + expectNoLog(logs, /CommonJS or AMD dependencies/); }); it('should not show warning for relative imports', async () => { @@ -198,11 +172,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(/CommonJS or AMD dependencies/), - }), - ); + expectNoLog(logs, /CommonJS or AMD dependencies/); }); }); }); diff --git a/packages/angular/build/src/builders/application/tests/options/bundle-budgets_spec.ts b/packages/angular/build/src/builders/application/tests/options/bundle-budgets_spec.ts index 4614d5a5788e..40757365ce8e 100644 --- a/packages/angular/build/src/builders/application/tests/options/bundle-budgets_spec.ts +++ b/packages/angular/build/src/builders/application/tests/options/bundle-budgets_spec.ts @@ -6,13 +6,14 @@ * found in the LICENSE file at https://angular.dev/license */ -import { logging } from '@angular-devkit/core'; import { buildApplication } from '../../index'; import { Type } from '../../schema'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder, + expectLog, + expectNoLog, lazyModuleFiles, lazyModuleFnImport, } from '../setup'; @@ -31,12 +32,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).not.toContain( - jasmine.objectContaining({ - level: 'warn', - message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), - }), - ); + expectNoLog(logs, BUDGET_NOT_MET_REGEXP); }); it(`should error when size is above 'maximumError' threshold`, async () => { @@ -48,12 +44,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeFalse(); - expect(logs).toContain( - jasmine.objectContaining({ - level: 'error', - message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), - }), - ); + expectLog(logs, BUDGET_NOT_MET_REGEXP); }); it(`should warn when size is above 'maximumWarning' threshold`, async () => { @@ -65,12 +56,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).toContain( - jasmine.objectContaining({ - level: 'warn', - message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), - }), - ); + expectLog(logs, BUDGET_NOT_MET_REGEXP); }); it(`should warn when lazy bundle is above 'maximumWarning' threshold`, async () => { @@ -85,12 +71,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).toContain( - jasmine.objectContaining({ - level: 'warn', - message: jasmine.stringMatching('lazy-module exceeded maximum budget'), - }), - ); + expectLog(logs, 'lazy-module exceeded maximum budget'); }); it(`should not warn when non-injected style is not within the baseline threshold`, async () => { @@ -118,12 +99,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeTrue(); - expect(logs).not.toContain( - jasmine.objectContaining({ - level: 'warn', - message: jasmine.stringMatching('lazy-styles failed to meet minimum budget'), - }), - ); + expectNoLog(logs, 'lazy-styles failed to meet minimum budget'); }); CSS_EXTENSIONS.forEach((ext) => { @@ -154,12 +130,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).toContain( - jasmine.objectContaining({ - level: 'warn', - message: jasmine.stringMatching(new RegExp(`app.component.${ext}`)), - }), - ); + expectLog(logs, new RegExp(`app.component.${ext}`)); }); }); @@ -175,12 +146,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).not.toContain( - jasmine.objectContaining({ - level: 'error', - message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), - }), - ); + expectNoLog(logs, BUDGET_NOT_MET_REGEXP); }); it(`when 'intial' budget`, async () => { @@ -194,12 +160,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).not.toContain( - jasmine.objectContaining({ - level: 'error', - message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), - }), - ); + expectNoLog(logs, BUDGET_NOT_MET_REGEXP); }); it(`when 'all' budget`, async () => { @@ -213,12 +174,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).not.toContain( - jasmine.objectContaining({ - level: 'error', - message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), - }), - ); + expectNoLog(logs, BUDGET_NOT_MET_REGEXP); }); it(`when 'any' budget`, async () => { @@ -232,12 +188,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); - expect(logs).not.toContain( - jasmine.objectContaining({ - level: 'error', - message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), - }), - ); + expectNoLog(logs, BUDGET_NOT_MET_REGEXP); }); }); }); diff --git a/packages/angular/build/src/builders/application/tests/options/external-dependencies_spec.ts b/packages/angular/build/src/builders/application/tests/options/external-dependencies_spec.ts index feb9b6447c3b..deb55e172109 100644 --- a/packages/angular/build/src/builders/application/tests/options/external-dependencies_spec.ts +++ b/packages/angular/build/src/builders/application/tests/options/external-dependencies_spec.ts @@ -24,7 +24,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { .content.not.toMatch(/from ['"]@angular\/common['"]/); }); - it('should only externalize the listed depedencies when option is set', async () => { + it('should only externalize the listed dependencies when option is set', async () => { harness.useTarget('build', { ...BASE_OPTIONS, externalDependencies: ['@angular/core'], @@ -39,7 +39,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { .content.not.toMatch(/from ['"]@angular\/common['"]/); }); - it('should externalize the listed depedencies in Web Workers when option is set', async () => { + it('should externalize the listed dependencies in Web Workers when option is set', async () => { harness.useTarget('build', { ...BASE_OPTIONS, externalDependencies: ['path'], diff --git a/packages/angular/build/src/builders/application/tests/options/i18n-missing-translation_spec.ts b/packages/angular/build/src/builders/application/tests/options/i18n-missing-translation_spec.ts index d29c0a84adbc..90ac8206a1b8 100644 --- a/packages/angular/build/src/builders/application/tests/options/i18n-missing-translation_spec.ts +++ b/packages/angular/build/src/builders/application/tests/options/i18n-missing-translation_spec.ts @@ -7,7 +7,7 @@ */ import { buildApplication } from '../../index'; -import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder, expectNoLog } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "i18nMissingTranslation"', () => { @@ -131,11 +131,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeTrue(); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching('No translation found for'), - }), - ); + expectNoLog(logs, 'No translation found for'); }); it('should not error or warn when i18nMissingTranslation is set to error and all found', async () => { @@ -158,11 +154,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeTrue(); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching('No translation found for'), - }), - ); + expectNoLog(logs, 'No translation found for'); }); it('should not error or warn when i18nMissingTranslation is set to warning and all found', async () => { @@ -185,11 +177,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeTrue(); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching('No translation found for'), - }), - ); + expectNoLog(logs, 'No translation found for'); }); }); }); diff --git a/packages/angular/build/src/builders/application/tests/options/scripts_spec.ts b/packages/angular/build/src/builders/application/tests/options/scripts_spec.ts index 757ff81acbac..dde35f851159 100644 --- a/packages/angular/build/src/builders/application/tests/options/scripts_spec.ts +++ b/packages/angular/build/src/builders/application/tests/options/scripts_spec.ts @@ -7,7 +7,7 @@ */ import { buildApplication } from '../../index'; -import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder, expectLog } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "scripts"', () => { @@ -145,9 +145,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { expect(result?.success).toBe(true); - expect(logs).toContain( - jasmine.objectContaining({ message: jasmine.stringMatching(/scripts\.js.+\d+ bytes/) }), - ); + expectLog(logs, /scripts\.js.+\d+ bytes/); }); }); @@ -412,9 +410,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { expect(result?.success).toBe(true); - expect(logs).toContain( - jasmine.objectContaining({ message: jasmine.stringMatching(/scripts\.js.+\d+ bytes/) }), - ); + expectLog(logs, /scripts\.js.+\d+ bytes/); }); it('shows the output script as a chunk entry with bundleName in the logging output', async () => { @@ -429,9 +425,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { expect(result?.success).toBe(true); - expect(logs).toContain( - jasmine.objectContaining({ message: jasmine.stringMatching(/extra\.js.+\d+ bytes/) }), - ); + expectLog(logs, /extra\.js.+\d+ bytes/); }); }); }); diff --git a/packages/angular/build/src/builders/application/tests/options/style-preprocessor-options-sass_spec.ts b/packages/angular/build/src/builders/application/tests/options/style-preprocessor-options-sass_spec.ts index 33c1d1cc9a4b..a3da36606825 100644 --- a/packages/angular/build/src/builders/application/tests/options/style-preprocessor-options-sass_spec.ts +++ b/packages/angular/build/src/builders/application/tests/options/style-preprocessor-options-sass_spec.ts @@ -7,8 +7,7 @@ */ import { buildApplication } from '../../index'; -import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; -import { logging } from '@angular-devkit/core'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder, expectNoLog } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "stylePreprocessorOptions.sass"', () => { @@ -28,11 +27,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching('darken() is deprecated'), - }), - ); + expectNoLog(logs, 'darken() is deprecated'); }); it('should succeed without `fatalDeprecations` despite using deprecated color functions', async () => { @@ -79,11 +74,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { }); expect(result?.success).toBeFalse(); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching('darken() is deprecated'), - }), - ); + expectNoLog(logs, 'darken() is deprecated'); }); }); }); diff --git a/packages/angular/build/src/builders/application/tests/options/styles_spec.ts b/packages/angular/build/src/builders/application/tests/options/styles_spec.ts index eb8d973ae904..311b0037daa5 100644 --- a/packages/angular/build/src/builders/application/tests/options/styles_spec.ts +++ b/packages/angular/build/src/builders/application/tests/options/styles_spec.ts @@ -7,7 +7,7 @@ */ import { buildApplication } from '../../index'; -import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder, expectLog } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "styles"', () => { @@ -147,9 +147,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { expect(result?.success).toBe(true); - expect(logs).toContain( - jasmine.objectContaining({ message: jasmine.stringMatching(/styles\.css.+\d+ bytes/) }), - ); + expectLog(logs, /styles\.css.+\d+ bytes/); }); }); @@ -440,9 +438,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { expect(result?.success).toBe(true); - expect(logs).toContain( - jasmine.objectContaining({ message: jasmine.stringMatching(/styles\.css.+\d+ bytes/) }), - ); + expectLog(logs, /styles\.css.+\d+ bytes/); }); it('shows the output style as a chunk entry with bundleName in the logging output', async () => { @@ -457,9 +453,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { expect(result?.success).toBe(true); - expect(logs).toContain( - jasmine.objectContaining({ message: jasmine.stringMatching(/extra\.css.+\d+ bytes/) }), - ); + expectLog(logs, /extra\.css.+\d+ bytes/); }); }); }); diff --git a/packages/angular/build/src/builders/application/tests/options/subresource-integrity_spec.ts b/packages/angular/build/src/builders/application/tests/options/subresource-integrity_spec.ts index 4afb87ebaed3..f3ec9476b21f 100644 --- a/packages/angular/build/src/builders/application/tests/options/subresource-integrity_spec.ts +++ b/packages/angular/build/src/builders/application/tests/options/subresource-integrity_spec.ts @@ -6,9 +6,8 @@ * found in the LICENSE file at https://angular.dev/license */ -import { logging } from '@angular-devkit/core'; import { buildApplication } from '../../index'; -import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder, expectNoLog } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "subresourceIntegrity"', () => { @@ -64,11 +63,7 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { harness .expectFile('dist/browser/index.html') .content.toMatch(/integrity="\w+-[A-Za-z0-9/+=]+"/); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(/subresource-integrity/), - }), - ); + expectNoLog(logs, /subresource-integrity/); }); }); }); diff --git a/packages/angular/build/src/builders/dev-server/builder.ts b/packages/angular/build/src/builders/dev-server/builder.ts index 4ea11d5f11e9..d75f999d84fd 100644 --- a/packages/angular/build/src/builders/dev-server/builder.ts +++ b/packages/angular/build/src/builders/dev-server/builder.ts @@ -18,7 +18,7 @@ import { import { normalizeOptions } from './options'; import type { DevServerBuilderOutput } from './output'; import type { Schema as DevServerBuilderOptions } from './schema'; -import { serveWithVite } from './vite-server'; +import { serveWithVite } from './vite'; /** * A Builder that executes a development server based on the provided browser target option. diff --git a/packages/angular/build/src/builders/dev-server/options.ts b/packages/angular/build/src/builders/dev-server/options.ts index 3e0f59319117..b6da278f2936 100644 --- a/packages/angular/build/src/builders/dev-server/options.ts +++ b/packages/angular/build/src/builders/dev-server/options.ts @@ -93,6 +93,7 @@ export async function normalizeOptions( poll, open, verbose, + define, watch, liveReload, hmr, @@ -114,6 +115,7 @@ export async function normalizeOptions( poll, open, verbose, + define, watch, liveReload: !!liveReload, hmr: hmr ?? !!liveReload, diff --git a/packages/angular/build/src/builders/dev-server/schema.json b/packages/angular/build/src/builders/dev-server/schema.json index 41902e43d8d0..023478ff7e52 100644 --- a/packages/angular/build/src/builders/dev-server/schema.json +++ b/packages/angular/build/src/builders/dev-server/schema.json @@ -53,6 +53,13 @@ } ] }, + "define": { + "description": "Defines global identifiers that will be replaced with a specified constant value when found in any JavaScript or TypeScript code including libraries. The value will be used directly. String values must be put in quotes. Identifiers within Angular metadata such as Component Decorators will not be replaced.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, "headers": { "type": "object", "description": "Custom HTTP headers to be added to all responses.", diff --git a/packages/angular/build/src/builders/dev-server/tests/behavior/build-errors_spec.ts b/packages/angular/build/src/builders/dev-server/tests/behavior/build-errors_spec.ts index 3bf4aa5fed6e..aa4763771fdd 100644 --- a/packages/angular/build/src/builders/dev-server/tests/behavior/build-errors_spec.ts +++ b/packages/angular/build/src/builders/dev-server/tests/behavior/build-errors_spec.ts @@ -6,10 +6,9 @@ * found in the LICENSE file at https://angular.dev/license */ -import { logging } from '@angular-devkit/core'; import { executeDevServer } from '../../index'; import { describeServeBuilder } from '../jasmine-helpers'; -import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; +import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO, expectLog, expectNoLog } from '../setup'; describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => { describe('Behavior: "Rebuild Error Detection"', () => { @@ -31,21 +30,13 @@ describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupT async ({ result, logs }) => { expect(result?.success).toBeFalse(); debugger; - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching('Unexpected character "EOF"'), - }), - ); + expectLog(logs, 'Unexpected character "EOF"'); await harness.appendToFile('src/app/app.component.html', '>'); }, ({ result, logs }) => { expect(result?.success).toBeTrue(); - expect(logs).not.toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching('Unexpected character "EOF"'), - }), - ); + expectNoLog(logs, 'Unexpected character "EOF"'); }, ], { outputLogsOnFailure: false }, diff --git a/packages/angular/build/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts b/packages/angular/build/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts index 083773529058..efdd749de258 100644 --- a/packages/angular/build/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts +++ b/packages/angular/build/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts @@ -6,8 +6,6 @@ * found in the LICENSE file at https://angular.dev/license */ -/* eslint-disable import/no-extraneous-dependencies */ -import { tags } from '@angular-devkit/core'; import { createServer } from 'node:http'; import { createProxyServer } from 'http-proxy'; import { AddressInfo } from 'node:net'; @@ -43,58 +41,58 @@ async function createProxy(target: string, secure: boolean, ws = true): Promise< target, secure, ssl: secure && { - key: tags.stripIndents` - -----BEGIN RSA PRIVATE KEY----- - MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDEBRUsUz4rdcMt - CQGLvG3SzUinsmgdgOyTNQNA0eOMyRSrmS8L+F/kSLUnqqu4mzdeqDzo2Xj553jK - dRqMCRFGJuGnQ/VIbW2A+ywgrqILuDyF5i4PL1aQW4yJ7TnXfONKfpswQArlN6DF - gBYJtoJlf8XD1sOeJpsv/O46/ix/wngQ+GwQQ2cfqxQT0fE9SBCY23VNt3SPUJ3k - 9etJMvJ9U9GHSb1CFdNQe7Gyx7xdKf1TazB27ElNZEg2aF99if47uRskYjvvFivy - 7nxGx/ccIwjwNMpk29AsKG++0sn1yTK7tD5Px6aCSVK0BKbdXZS2euJor8hASGBJ - 3GpVGJvdAgMBAAECggEAapYo8TVCdPdP7ckb4hPP0/R0MVu9aW2VNmZ5ImH+zar5 - ZmWhQ20HF2bBupP/VB5yeTIaDLNUKO9Iqy4KBWNY1UCHKyC023FFPgFV+V98FctU - faqwGOmwtEZToRwxe48ZOISndhEc247oCPyg/x8SwIY9z0OUkwaDFBEAqWtUXxM3 - /SPpCT5ilLgxnRgVB8Fj5Z0q7ThnxNVOmVC1OSIakEj46PzmMXn1pCKLOCUmAAOQ - BnrOZuty2b8b2M/GHsktLZwojQQJmArnIBymTXQTVhaGgKSyOv1qvHLp9L1OJf0/ - Xm+/TqT6ztzhzlftcObdfQZZ5JuoEwlvyrsGFlA3MQKBgQDiQC3KYMG8ViJkWrv6 - XNAFEoAjVEKrtirGWJ66YfQ9KSJ7Zttrd1Y1V1OLtq3z4YMH39wdQ8rOD+yR8mWV - 6Tnsxma6yJXAH8uan8iVbxjIZKF1hnvNCxUoxYmWOmTLcEQMzmxvTzAiR+s6R6Uj - 9LgGqppt30nM4wnOhOJU6UxqbwKBgQDdy03KidbPZuycJSy1C9AIt0jlrxDsYm+U - fZrB6mHEZcgoZS5GbLKinQCdGcgERa05BXvJmNbfZtT5a37YEnbjsTImIhDiBP5P - nW36/9a3Vg1svd1KP2206/Bh3gfZbgTsQg4YogXgjf0Uzuvw18btgTtLVpVyeuqz - TU3eeF30cwKBgQCN6lvOmapsDEs+T3uhqx4AUH53qp63PmjOSUAnANJGmsq6ROZV - HmHAy6nn9Qpf85BRHCXhZWiMoIhvc3As/EINNtWxS6hC/q6jqp4SvcD50cVFBroY - /16iWGXZCX+37A+DSOfTWgSDPEFcKRx41UOpStHbITgVgEPieo/NWxlHmQKBgQDX - JOLs2RB6V0ilnpnjdPXzvncD9fHgmwvJap24BPeZX3HtXViqD76oZsu1mNCg9EW3 - zk3pnEyyoDlvSIreZerVq4kN3HWsCVP3Pqr0kz9g0CRtmy8RWr28hjHDfXD3xPUZ - iGnMEz7IOHOKv722/liFAprV1cNaLUmFbDNg3jmlaQKBgQDG5WwngPhOHmjTnSml - amfEz9a4yEhQqpqgVNW5wwoXOf6DbjL2m/maJh01giThj7inMcbpkZlIclxD0Eu6 - Lof+ctCeqSAJvaVPmd+nv8Yp26zsF1yM8ax9xXjrIvv9fSbycNveGTDCsNNTiYoW - QyvMqmN1kGy20SZbQDD/fLfqBQ== - -----END RSA PRIVATE KEY----- + key: ` +-----BEGIN RSA PRIVATE KEY----- +MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDEBRUsUz4rdcMt +CQGLvG3SzUinsmgdgOyTNQNA0eOMyRSrmS8L+F/kSLUnqqu4mzdeqDzo2Xj553jK +dRqMCRFGJuGnQ/VIbW2A+ywgrqILuDyF5i4PL1aQW4yJ7TnXfONKfpswQArlN6DF +gBYJtoJlf8XD1sOeJpsv/O46/ix/wngQ+GwQQ2cfqxQT0fE9SBCY23VNt3SPUJ3k +9etJMvJ9U9GHSb1CFdNQe7Gyx7xdKf1TazB27ElNZEg2aF99if47uRskYjvvFivy +7nxGx/ccIwjwNMpk29AsKG++0sn1yTK7tD5Px6aCSVK0BKbdXZS2euJor8hASGBJ +3GpVGJvdAgMBAAECggEAapYo8TVCdPdP7ckb4hPP0/R0MVu9aW2VNmZ5ImH+zar5 +ZmWhQ20HF2bBupP/VB5yeTIaDLNUKO9Iqy4KBWNY1UCHKyC023FFPgFV+V98FctU +faqwGOmwtEZToRwxe48ZOISndhEc247oCPyg/x8SwIY9z0OUkwaDFBEAqWtUXxM3 +/SPpCT5ilLgxnRgVB8Fj5Z0q7ThnxNVOmVC1OSIakEj46PzmMXn1pCKLOCUmAAOQ +BnrOZuty2b8b2M/GHsktLZwojQQJmArnIBymTXQTVhaGgKSyOv1qvHLp9L1OJf0/ +Xm+/TqT6ztzhzlftcObdfQZZ5JuoEwlvyrsGFlA3MQKBgQDiQC3KYMG8ViJkWrv6 +XNAFEoAjVEKrtirGWJ66YfQ9KSJ7Zttrd1Y1V1OLtq3z4YMH39wdQ8rOD+yR8mWV +6Tnsxma6yJXAH8uan8iVbxjIZKF1hnvNCxUoxYmWOmTLcEQMzmxvTzAiR+s6R6Uj +9LgGqppt30nM4wnOhOJU6UxqbwKBgQDdy03KidbPZuycJSy1C9AIt0jlrxDsYm+U +fZrB6mHEZcgoZS5GbLKinQCdGcgERa05BXvJmNbfZtT5a37YEnbjsTImIhDiBP5P +nW36/9a3Vg1svd1KP2206/Bh3gfZbgTsQg4YogXgjf0Uzuvw18btgTtLVpVyeuqz +TU3eeF30cwKBgQCN6lvOmapsDEs+T3uhqx4AUH53qp63PmjOSUAnANJGmsq6ROZV +HmHAy6nn9Qpf85BRHCXhZWiMoIhvc3As/EINNtWxS6hC/q6jqp4SvcD50cVFBroY +/16iWGXZCX+37A+DSOfTWgSDPEFcKRx41UOpStHbITgVgEPieo/NWxlHmQKBgQDX +JOLs2RB6V0ilnpnjdPXzvncD9fHgmwvJap24BPeZX3HtXViqD76oZsu1mNCg9EW3 +zk3pnEyyoDlvSIreZerVq4kN3HWsCVP3Pqr0kz9g0CRtmy8RWr28hjHDfXD3xPUZ +iGnMEz7IOHOKv722/liFAprV1cNaLUmFbDNg3jmlaQKBgQDG5WwngPhOHmjTnSml +amfEz9a4yEhQqpqgVNW5wwoXOf6DbjL2m/maJh01giThj7inMcbpkZlIclxD0Eu6 +Lof+ctCeqSAJvaVPmd+nv8Yp26zsF1yM8ax9xXjrIvv9fSbycNveGTDCsNNTiYoW +QyvMqmN1kGy20SZbQDD/fLfqBQ== +-----END RSA PRIVATE KEY----- `, - cert: tags.stripIndents` - -----BEGIN CERTIFICATE----- - MIIDXTCCAkWgAwIBAgIJALz8gD/gAt0OMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV - BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX - aWRnaXRzIFB0eSBMdGQwHhcNMTgxMDIzMTgyMTQ5WhcNMTkxMDIzMTgyMTQ5WjBF - MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 - ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB - CgKCAQEAxAUVLFM+K3XDLQkBi7xt0s1Ip7JoHYDskzUDQNHjjMkUq5kvC/hf5Ei1 - J6qruJs3Xqg86Nl4+ed4ynUajAkRRibhp0P1SG1tgPssIK6iC7g8heYuDy9WkFuM - ie0513zjSn6bMEAK5TegxYAWCbaCZX/Fw9bDniabL/zuOv4sf8J4EPhsEENnH6sU - E9HxPUgQmNt1Tbd0j1Cd5PXrSTLyfVPRh0m9QhXTUHuxsse8XSn9U2swduxJTWRI - NmhffYn+O7kbJGI77xYr8u58Rsf3HCMI8DTKZNvQLChvvtLJ9ckyu7Q+T8emgklS - tASm3V2UtnriaK/IQEhgSdxqVRib3QIDAQABo1AwTjAdBgNVHQ4EFgQUDZBhVKdb - 3BRhLIhuuE522Vsul0IwHwYDVR0jBBgwFoAUDZBhVKdb3BRhLIhuuE522Vsul0Iw - DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEABh9WWZwWLgb9/DcTxL72 - 6pI96t4jiF79Q+pPefkaIIi0mE6yodWrTAsBQu9I6bNRaEcCSoiXkP2bqskD/UGg - LwUFgSrDOAA3UjdHw3QU5g2NocduG7mcFwA40TB98sOsxsUyYlzSyWzoiQWwPYwb - hek1djuWkqPXsTjlj54PTPN/SjTFmo4p5Ip6nbRf2nOREl7v0rJpGbJvXiCMYyd+ - Zv+j4mRjCGo8ysMR2HjCUGkYReLAgKyyz3M7i8vevJhKslyOmy6Txn4F0nPVumaU - DDIy4xXPW1STWfsmSYJfYW3wa0wk+pJQ3j2cTzkPQQ8gwpvM3U9DJl43uwb37v6I - 7Q== - -----END CERTIFICATE----- + cert: ` +-----BEGIN CERTIFICATE----- +MIIDXTCCAkWgAwIBAgIJALz8gD/gAt0OMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV +BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX +aWRnaXRzIFB0eSBMdGQwHhcNMTgxMDIzMTgyMTQ5WhcNMTkxMDIzMTgyMTQ5WjBF +MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 +ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEAxAUVLFM+K3XDLQkBi7xt0s1Ip7JoHYDskzUDQNHjjMkUq5kvC/hf5Ei1 +J6qruJs3Xqg86Nl4+ed4ynUajAkRRibhp0P1SG1tgPssIK6iC7g8heYuDy9WkFuM +ie0513zjSn6bMEAK5TegxYAWCbaCZX/Fw9bDniabL/zuOv4sf8J4EPhsEENnH6sU +E9HxPUgQmNt1Tbd0j1Cd5PXrSTLyfVPRh0m9QhXTUHuxsse8XSn9U2swduxJTWRI +NmhffYn+O7kbJGI77xYr8u58Rsf3HCMI8DTKZNvQLChvvtLJ9ckyu7Q+T8emgklS +tASm3V2UtnriaK/IQEhgSdxqVRib3QIDAQABo1AwTjAdBgNVHQ4EFgQUDZBhVKdb +3BRhLIhuuE522Vsul0IwHwYDVR0jBBgwFoAUDZBhVKdb3BRhLIhuuE522Vsul0Iw +DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEABh9WWZwWLgb9/DcTxL72 +6pI96t4jiF79Q+pPefkaIIi0mE6yodWrTAsBQu9I6bNRaEcCSoiXkP2bqskD/UGg +LwUFgSrDOAA3UjdHw3QU5g2NocduG7mcFwA40TB98sOsxsUyYlzSyWzoiQWwPYwb +hek1djuWkqPXsTjlj54PTPN/SjTFmo4p5Ip6nbRf2nOREl7v0rJpGbJvXiCMYyd+ +Zv+j4mRjCGo8ysMR2HjCUGkYReLAgKyyz3M7i8vevJhKslyOmy6Txn4F0nPVumaU +DDIy4xXPW1STWfsmSYJfYW3wa0wk+pJQ3j2cTzkPQQ8gwpvM3U9DJl43uwb37v6I +7Q== +-----END CERTIFICATE----- `, }, }).listen(proxyPort); @@ -107,8 +105,7 @@ async function createProxy(target: string, secure: boolean, ws = true): Promise< async function goToPageAndWaitForWS(page: Page, url: string): Promise { const baseUrl = url.replace(/^http/, 'ws'); - const socksRequest = - baseUrl[baseUrl.length - 1] === '/' ? `${baseUrl}ng-cli-ws` : `${baseUrl}/ng-cli-ws`; + const socksRequest = baseUrl.at(-1) === '/' ? `${baseUrl}ng-cli-ws` : `${baseUrl}/ng-cli-ws`; // Create a Chrome dev tools session so that we can capturing websocket request. // https://github.com/puppeteer/puppeteer/issues/2974 diff --git a/packages/angular/build/src/builders/dev-server/tests/execute-fetch.ts b/packages/angular/build/src/builders/dev-server/tests/execute-fetch.ts index ebbdcf3f1133..75a4e7935ebe 100644 --- a/packages/angular/build/src/builders/dev-server/tests/execute-fetch.ts +++ b/packages/angular/build/src/builders/dev-server/tests/execute-fetch.ts @@ -28,7 +28,7 @@ export async function executeOnceAndFetch( let content = undefined; if (executionResult.result?.success) { let baseUrl = `${executionResult.result.baseUrl}`; - baseUrl = baseUrl[baseUrl.length - 1] === '/' ? baseUrl : `${baseUrl}/`; + baseUrl = baseUrl.at(-1) === '/' ? baseUrl : `${baseUrl}/`; const resolvedUrl = new URL(url, baseUrl); const originalResponse = await fetch(resolvedUrl, options?.request); response = originalResponse.clone(); @@ -68,7 +68,7 @@ export async function executeOnceAndGet( let content = undefined; if (executionResult.result?.success) { let baseUrl = `${executionResult.result.baseUrl}`; - baseUrl = baseUrl[baseUrl.length - 1] === '/' ? baseUrl : `${baseUrl}/`; + baseUrl = baseUrl.at(-1) === '/' ? baseUrl : `${baseUrl}/`; const resolvedUrl = new URL(url, baseUrl); response = await new Promise((resolve) => diff --git a/packages/angular/build/src/builders/dev-server/tests/options/allowed-hosts_spec.ts b/packages/angular/build/src/builders/dev-server/tests/options/allowed-hosts_spec.ts index 8e96c7b4b4b0..775e057bece6 100644 --- a/packages/angular/build/src/builders/dev-server/tests/options/allowed-hosts_spec.ts +++ b/packages/angular/build/src/builders/dev-server/tests/options/allowed-hosts_spec.ts @@ -10,6 +10,7 @@ import { executeDevServer } from '../../index'; import { executeOnceAndGet } from '../execute-fetch'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; +import { text } from 'node:stream/consumers'; const FETCH_HEADERS = Object.freeze({ Host: 'example.com' }); @@ -33,6 +34,7 @@ describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupT expect(result?.success).toBeTrue(); expect(response?.statusCode).toBe(403); + expect(response && (await text(response))).toContain('angular.json'); }); it('does not allow an invalid host when option is an empty array', async () => { @@ -47,6 +49,7 @@ describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupT expect(result?.success).toBeTrue(); expect(response?.statusCode).toBe(403); + expect(response && (await text(response))).toContain('angular.json'); }); it('allows a host when specified in the option', async () => { diff --git a/packages/angular/build/src/builders/dev-server/tests/options/define_spec.ts b/packages/angular/build/src/builders/dev-server/tests/options/define_spec.ts new file mode 100644 index 000000000000..3c6ea08e15b4 --- /dev/null +++ b/packages/angular/build/src/builders/dev-server/tests/options/define_spec.ts @@ -0,0 +1,92 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { executeDevServer } from '../../index'; +import { executeOnceAndFetch } from '../execute-fetch'; +import { describeServeBuilder } from '../jasmine-helpers'; +import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; + +describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => { + describe('option: "define"', () => { + beforeEach(() => { + setupTarget(harness); + + // Application code + harness.writeFile( + 'src/main.ts', + ` + // @ts-ignore + console.log(TEST); + // @ts-ignore + console.log(BUILD); + // @ts-ignore + console.log(SERVE); + `, + ); + }); + + it('should replace global identifiers in the application', async () => { + harness.useTarget('serve', { + ...BASE_OPTIONS, + define: { + TEST: JSON.stringify('test123'), + }, + }); + + const { result, response } = await executeOnceAndFetch(harness, '/main.js'); + + expect(result?.success).toBeTrue(); + const content = await response?.text(); + expect(content).toContain('console.log("test123")'); + }); + + it('should merge "define" option from dev-server and build', async () => { + harness.modifyTarget('build', (options) => { + options.define = { + BUILD: JSON.stringify('build'), + }; + }); + + harness.useTarget('serve', { + ...BASE_OPTIONS, + define: { + SERVE: JSON.stringify('serve'), + }, + }); + + const { result, response } = await executeOnceAndFetch(harness, '/main.js'); + + expect(result?.success).toBeTrue(); + const content = await response?.text(); + expect(content).toContain('console.log("build")'); + expect(content).toContain('console.log("serve")'); + }); + + it('should overwrite "define" option from build with the one from dev-server', async () => { + harness.modifyTarget('build', (options) => { + options.define = { + TEST: JSON.stringify('build'), + }; + }); + + harness.useTarget('serve', { + ...BASE_OPTIONS, + define: { + TEST: JSON.stringify('serve'), + }, + }); + + const { result, response } = await executeOnceAndFetch(harness, '/main.js'); + + expect(result?.success).toBeTrue(); + const content = await response?.text(); + expect(content).toContain('console.log("serve")'); + expect(content).not.toContain('console.log("build")'); + }); + }); +}); diff --git a/packages/angular/build/src/builders/dev-server/vite-server.ts b/packages/angular/build/src/builders/dev-server/vite-server.ts deleted file mode 100644 index 6f68a37691c6..000000000000 --- a/packages/angular/build/src/builders/dev-server/vite-server.ts +++ /dev/null @@ -1,979 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.dev/license - */ - -import type { ɵdestroyAngularServerApp as destroyAngularServerApp } from '@angular/ssr'; -import type { BuilderContext } from '@angular-devkit/architect'; -import type { Plugin } from 'esbuild'; -import assert from 'node:assert'; -import { readFile } from 'node:fs/promises'; -import { builtinModules, isBuiltin } from 'node:module'; -import { join } from 'node:path'; -import type { Connect, InlineConfig, ViteDevServer } from 'vite'; -import type { ComponentStyleRecord } from '../../tools/vite/middlewares'; -import { - ServerSsrMode, - createAngularLocaleDataPlugin, - createAngularMemoryPlugin, - createAngularSetupMiddlewaresPlugin, - createAngularSsrTransformPlugin, - createRemoveIdPrefixPlugin, -} from '../../tools/vite/plugins'; -import { EsbuildLoaderOption, getDepOptimizationConfig } from '../../tools/vite/utils'; -import { loadProxyConfiguration, normalizeSourceMaps } from '../../utils'; -import { useComponentStyleHmr, useComponentTemplateHmr } from '../../utils/environment-options'; -import { loadEsmModule } from '../../utils/load-esm'; -import { Result, ResultFile, ResultKind } from '../application/results'; -import { OutputHashing } from '../application/schema'; -import { - type ApplicationBuilderInternalOptions, - BuildOutputFileType, - type ExternalResultMetadata, - JavaScriptTransformer, - getSupportedBrowsers, - isZonelessApp, - transformSupportedBrowsersToTargets, -} from './internal'; -import type { NormalizedDevServerOptions } from './options'; -import type { DevServerBuilderOutput } from './output'; - -interface OutputFileRecord { - contents: Uint8Array; - size: number; - hash: string; - updated: boolean; - servable: boolean; - type: BuildOutputFileType; -} - -interface OutputAssetRecord { - source: string; - updated: boolean; -} - -interface DevServerExternalResultMetadata extends Omit { - explicitBrowser: string[]; - explicitServer: string[]; -} - -export type BuilderAction = ( - options: ApplicationBuilderInternalOptions, - context: BuilderContext, - plugins?: Plugin[], -) => AsyncIterable; - -/** - * Build options that are also present on the dev server but are only passed - * to the build. - */ -const CONVENIENCE_BUILD_OPTIONS = ['watch', 'poll', 'verbose'] as const; - -// eslint-disable-next-line max-lines-per-function -export async function* serveWithVite( - serverOptions: NormalizedDevServerOptions, - builderName: string, - builderAction: BuilderAction, - context: BuilderContext, - transformers?: { - indexHtml?: (content: string) => Promise; - }, - extensions?: { - middleware?: Connect.NextHandleFunction[]; - buildPlugins?: Plugin[]; - }, -): AsyncIterableIterator { - // Get the browser configuration from the target name. - const rawBrowserOptions = await context.getTargetOptions(serverOptions.buildTarget); - - // Deploy url is not used in the dev-server. - delete rawBrowserOptions.deployUrl; - - // Copy convenience options to build - for (const optionName of CONVENIENCE_BUILD_OPTIONS) { - const optionValue = serverOptions[optionName]; - if (optionValue !== undefined) { - rawBrowserOptions[optionName] = optionValue; - } - } - - // TODO: Adjust architect to not force a JsonObject derived return type - const browserOptions = (await context.validateOptions( - rawBrowserOptions, - builderName, - )) as unknown as ApplicationBuilderInternalOptions; - - if (browserOptions.prerender || (browserOptions.outputMode && browserOptions.server)) { - // Disable prerendering if enabled and force SSR. - // This is so instead of prerendering all the routes for every change, the page is "prerendered" when it is requested. - browserOptions.prerender = undefined; - browserOptions.ssr ||= true; - } - - // Disable auto CSP. - browserOptions.security = { - autoCsp: false, - }; - - // Disable JSON build stats. - // These are not accessible with the dev server and can cause HMR fallbacks. - if (browserOptions.statsJson === true) { - context.logger.warn( - 'Build JSON statistics output (`statsJson` option) has been disabled.' + - ' The development server does not support this option.', - ); - } - browserOptions.statsJson = false; - - // Set all packages as external to support Vite's prebundle caching - browserOptions.externalPackages = serverOptions.prebundle; - - // Disable generating a full manifest with routes. - // This is done during runtime when using the dev-server. - browserOptions.partialSSRBuild = true; - - // The development server currently only supports a single locale when localizing. - // This matches the behavior of the Webpack-based development server but could be expanded in the future. - if ( - browserOptions.localize === true || - (Array.isArray(browserOptions.localize) && browserOptions.localize.length > 1) - ) { - context.logger.warn( - 'Localization (`localize` option) has been disabled. The development server only supports localizing a single locale per build.', - ); - browserOptions.localize = false; - } else if (browserOptions.localize) { - // When localization is enabled with a single locale, force a flat path to maintain behavior with the existing Webpack-based dev server. - browserOptions.forceI18nFlatOutput = true; - } - - const { vendor: thirdPartySourcemaps, scripts: scriptsSourcemaps } = normalizeSourceMaps( - browserOptions.sourceMap ?? false, - ); - - if (scriptsSourcemaps && browserOptions.server) { - // https://nodejs.org/api/process.html#processsetsourcemapsenabledval - process.setSourceMapsEnabled(true); - } - - if ( - serverOptions.hmr && - (browserOptions.outputHashing === OutputHashing.All || - browserOptions.outputHashing === OutputHashing.Bundles) - ) { - serverOptions.hmr = false; - - context.logger.warn( - `Hot Module Replacement (HMR) is disabled because the 'outputHashing' option is set to '${browserOptions.outputHashing}'. ` + - 'HMR is incompatible with this setting.', - ); - } - - const componentsHmrCanBeUsed = - browserOptions.aot && serverOptions.liveReload && serverOptions.hmr; - - // Enable to support link-based component style hot reloading (`NG_HMR_CSTYLES=1` can be used to enable) - browserOptions.externalRuntimeStyles = componentsHmrCanBeUsed && useComponentStyleHmr; - - // Enable to support component template hot replacement (`NG_HMR_TEMPLATE=0` can be used to disable selectively) - // This will also replace file-based/inline styles as code if external runtime styles are not enabled. - browserOptions.templateUpdates = componentsHmrCanBeUsed && useComponentTemplateHmr; - browserOptions.incrementalResults = true; - - // Setup the prebundling transformer that will be shared across Vite prebundling requests - const prebundleTransformer = new JavaScriptTransformer( - // Always enable JIT linking to support applications built with and without AOT. - // In a development environment the additional scope information does not - // have a negative effect unlike production where final output size is relevant. - { sourcemap: true, jit: true, thirdPartySourcemaps }, - 1, - ); - - // The index HTML path will be updated from the build results if provided by the builder - let htmlIndexPath = 'index.html'; - - // dynamically import Vite for ESM compatibility - const { createServer, normalizePath } = await loadEsmModule('vite'); - - let server: ViteDevServer | undefined; - let serverUrl: URL | undefined; - let hadError = false; - const generatedFiles = new Map(); - const assetFiles = new Map(); - const externalMetadata: DevServerExternalResultMetadata = { - implicitBrowser: [], - implicitServer: [], - explicitBrowser: [], - explicitServer: [], - }; - const componentStyles = new Map(); - const templateUpdates = new Map(); - - // Add cleanup logic via a builder teardown. - let deferred: () => void; - context.addTeardown(async () => { - await server?.close(); - await prebundleTransformer.close(); - deferred?.(); - }); - - // TODO: Switch this to an architect schedule call when infrastructure settings are supported - for await (const result of builderAction(browserOptions, context, extensions?.buildPlugins)) { - if (result.kind === ResultKind.Failure) { - if (result.errors.length && server) { - hadError = true; - server.ws.send({ - type: 'error', - err: { - message: result.errors[0].text, - stack: '', - loc: result.errors[0].location ?? undefined, - }, - }); - } - - yield { baseUrl: '', success: false }; - continue; - } - // Clear existing error overlay on successful result - if (hadError && server) { - hadError = false; - // Send an empty update to clear the error overlay - server.ws.send({ - 'type': 'update', - updates: [], - }); - } - - let needClientUpdate = true; - switch (result.kind) { - case ResultKind.Full: - if (result.detail?.['htmlIndexPath']) { - htmlIndexPath = result.detail['htmlIndexPath'] as string; - } - if (serverOptions.servePath === undefined && result.detail?.['htmlBaseHref']) { - const baseHref = result.detail['htmlBaseHref'] as string; - // Remove trailing slash - serverOptions.servePath = - baseHref !== './' && baseHref[baseHref.length - 1] === '/' - ? baseHref.slice(0, -1) - : baseHref; - } - - assetFiles.clear(); - componentStyles.clear(); - generatedFiles.clear(); - - for (const [outputPath, file] of Object.entries(result.files)) { - updateResultRecord( - outputPath, - file, - normalizePath, - htmlIndexPath, - generatedFiles, - assetFiles, - componentStyles, - // The initial build will not yet have a server setup - !server, - ); - } - - // Clear stale template updates on code rebuilds - templateUpdates.clear(); - - break; - case ResultKind.Incremental: - assert(server, 'Builder must provide an initial full build before incremental results.'); - - // Background updates should only update server files/options - needClientUpdate = !result.background; - - for (const removed of result.removed) { - const filePath = '/' + normalizePath(removed.path); - generatedFiles.delete(filePath); - assetFiles.delete(filePath); - } - - for (const modified of result.modified) { - updateResultRecord( - modified, - result.files[modified], - normalizePath, - htmlIndexPath, - generatedFiles, - assetFiles, - componentStyles, - ); - } - - for (const added of result.added) { - updateResultRecord( - added, - result.files[added], - normalizePath, - htmlIndexPath, - generatedFiles, - assetFiles, - componentStyles, - ); - } - - break; - case ResultKind.ComponentUpdate: - assert(serverOptions.hmr, 'Component updates are only supported with HMR enabled.'); - assert( - server, - 'Builder must provide an initial full build before component update results.', - ); - - for (const componentUpdate of result.updates) { - if (componentUpdate.type === 'template') { - templateUpdates.set(componentUpdate.id, componentUpdate.content); - server.ws.send('angular:component-update', { - id: componentUpdate.id, - timestamp: Date.now(), - }); - } - } - - context.logger.info('Component update sent to client(s).'); - continue; - default: - context.logger.warn(`Unknown result kind [${(result as Result).kind}] provided by build.`); - continue; - } - - // To avoid disconnecting the array objects from the option, these arrays need to be mutated instead of replaced. - if (result.detail?.['externalMetadata']) { - const { implicitBrowser, implicitServer, explicit } = result.detail[ - 'externalMetadata' - ] as ExternalResultMetadata; - const implicitServerFiltered = implicitServer.filter( - (m) => !isBuiltin(m) && !isAbsoluteUrl(m), - ); - const implicitBrowserFiltered = implicitBrowser.filter((m) => !isAbsoluteUrl(m)); - - // Empty Arrays to avoid growing unlimited with every re-build. - externalMetadata.explicitBrowser.length = 0; - externalMetadata.explicitServer.length = 0; - externalMetadata.implicitServer.length = 0; - externalMetadata.implicitBrowser.length = 0; - - const externalDeps = browserOptions.externalDependencies ?? []; - externalMetadata.explicitBrowser.push(...explicit, ...externalDeps); - externalMetadata.explicitServer.push(...explicit, ...externalDeps, ...builtinModules); - externalMetadata.implicitServer.push(...implicitServerFiltered); - externalMetadata.implicitBrowser.push(...implicitBrowserFiltered); - - // The below needs to be sorted as Vite uses these options are part of the hashing invalidation algorithm. - // See: https://github.com/vitejs/vite/blob/0873bae0cfe0f0718ad2f5743dd34a17e4ab563d/packages/vite/src/node/optimizer/index.ts#L1203-L1239 - externalMetadata.explicitBrowser.sort(); - externalMetadata.explicitServer.sort(); - externalMetadata.implicitServer.sort(); - externalMetadata.implicitBrowser.sort(); - } - - if (server) { - // Update fs allow list to include any new assets from the build option. - server.config.server.fs.allow = [ - ...new Set([ - ...server.config.server.fs.allow, - ...[...assetFiles.values()].map(({ source }) => source), - ]), - ]; - - const updatedFiles = await invalidateUpdatedFiles( - normalizePath, - generatedFiles, - assetFiles, - server, - ); - - if (needClientUpdate) { - handleUpdate(server, serverOptions, context.logger, componentStyles, updatedFiles); - } - } else { - const projectName = context.target?.project; - if (!projectName) { - throw new Error('The builder requires a target.'); - } - - context.logger.info( - 'NOTE: Raw file sizes do not reflect development server per-request transformations.', - ); - - if (browserOptions.ssr && serverOptions.inspect) { - const { host, port } = serverOptions.inspect as { host?: string; port?: number }; - const { default: inspector } = await import('node:inspector'); - inspector.open(port, host, true); - context.addTeardown(() => inspector.close()); - } - - const { root = '' } = await context.getProjectMetadata(projectName); - const projectRoot = join(context.workspaceRoot, root as string); - const browsers = getSupportedBrowsers(projectRoot, context.logger); - - const target = transformSupportedBrowsersToTargets(browsers); - // Needed for browser-esbuild as polyfills can be a string. - const polyfills = Array.isArray((browserOptions.polyfills ??= [])) - ? browserOptions.polyfills - : [browserOptions.polyfills]; - - let ssrMode: ServerSsrMode = ServerSsrMode.NoSsr; - if ( - browserOptions.outputMode && - typeof browserOptions.ssr === 'object' && - browserOptions.ssr.entry - ) { - ssrMode = ServerSsrMode.ExternalSsrMiddleware; - } else if (browserOptions.ssr) { - ssrMode = ServerSsrMode.InternalSsrMiddleware; - } - - if (browserOptions.progress !== false && ssrMode !== ServerSsrMode.NoSsr) { - // This is a workaround for https://github.com/angular/angular-cli/issues/28336, which is caused by the interaction between `zone.js` and `listr2`. - process.once('SIGINT', () => { - process.kill(process.pid); - }); - } - - // Setup server and start listening - const serverConfiguration = await setupServer( - serverOptions, - generatedFiles, - assetFiles, - browserOptions.preserveSymlinks, - externalMetadata, - ssrMode, - prebundleTransformer, - target, - isZonelessApp(polyfills), - componentStyles, - templateUpdates, - browserOptions.loader as EsbuildLoaderOption | undefined, - { - ...browserOptions.define, - 'ngHmrMode': browserOptions.templateUpdates ? 'true' : 'false', - }, - extensions?.middleware, - transformers?.indexHtml, - thirdPartySourcemaps, - ); - - server = await createServer(serverConfiguration); - await server.listen(); - - // Setup builder context logging for browser clients - server.hot.on('angular:log', (data: { text: string; kind?: string }) => { - if (typeof data?.text !== 'string') { - context.logger.warn('Development server client sent invalid internal log event.'); - } - switch (data.kind) { - case 'error': - context.logger.error(`[CLIENT ERROR]: ${data.text}`); - break; - case 'warning': - context.logger.warn(`[CLIENT WARNING]: ${data.text}`); - break; - default: - context.logger.info(`[CLIENT INFO]: ${data.text}`); - break; - } - }); - - // Setup component HMR invalidation - // Invalidation occurs when the runtime cannot update a component - server.hot.on( - 'angular:invalidate', - (data: { id: string; message?: string; error?: boolean }) => { - if (typeof data?.id !== 'string') { - context.logger.warn( - 'Development server client sent invalid internal invalidate event.', - ); - } - - // Clear invalid template update - templateUpdates.delete(data.id); - - // Some cases are expected unsupported update scenarios but some may be errors. - // If an error occurred, log the error in addition to the invalidation. - if (data.error) { - context.logger.error( - `Component update failed${data.message ? `: ${data.message}` : '.'}` + - '\nPlease consider reporting the error at https://github.com/angular/angular-cli/issues', - ); - } else { - context.logger.warn( - `Component update unsupported${data.message ? `: ${data.message}` : '.'}`, - ); - } - - server?.ws.send({ - type: 'full-reload', - path: '*', - }); - context.logger.info('Page reload sent to client(s).'); - }, - ); - - const urls = server.resolvedUrls; - if (urls && (urls.local.length || urls.network.length)) { - serverUrl = new URL(urls.local[0] ?? urls.network[0]); - } - - // log connection information - server.printUrls(); - - server.bindCLIShortcuts({ - print: true, - customShortcuts: [ - { - key: 'r', - description: 'force reload browser', - action(server) { - componentStyles.forEach((record) => record.used?.clear()); - server.ws.send({ - type: 'full-reload', - path: '*', - }); - }, - }, - ], - }); - } - - // TODO: adjust output typings to reflect both development servers - yield { - success: true, - port: serverUrl?.port, - baseUrl: serverUrl?.href, - } as unknown as DevServerBuilderOutput; - } - - await new Promise((resolve) => (deferred = resolve)); -} - -/** - * Invalidates any updated asset or generated files and resets their `updated` state. - * This function also clears the server application cache when necessary. - * - * @returns A list of files that were updated and invalidated. - */ -async function invalidateUpdatedFiles( - normalizePath: (id: string) => string, - generatedFiles: Map, - assetFiles: Map, - server: ViteDevServer, -): Promise { - const updatedFiles: string[] = []; - - // Invalidate any updated asset - for (const [file, record] of assetFiles) { - if (!record.updated) { - continue; - } - - record.updated = false; - updatedFiles.push(file); - } - - // Invalidate any updated files - let serverApplicationChanged = false; - for (const [file, record] of generatedFiles) { - if (!record.updated) { - continue; - } - - record.updated = false; - updatedFiles.push(file); - serverApplicationChanged ||= record.type === BuildOutputFileType.ServerApplication; - - const updatedModules = server.moduleGraph.getModulesByFile( - normalizePath(join(server.config.root, file)), - ); - updatedModules?.forEach((m) => server.moduleGraph.invalidateModule(m)); - } - - if (serverApplicationChanged) { - // Clear the server app cache and - // trigger module evaluation before reload to initiate dependency optimization. - const { ɵdestroyAngularServerApp } = (await server.ssrLoadModule('/main.server.mjs')) as { - ɵdestroyAngularServerApp: typeof destroyAngularServerApp; - }; - - ɵdestroyAngularServerApp(); - } - - return updatedFiles; -} - -/** - * Handles updates for the client by sending HMR or full page reload commands - * based on the updated files. It also ensures proper tracking of component styles and determines if - * a full reload is needed. - */ -function handleUpdate( - server: ViteDevServer, - serverOptions: NormalizedDevServerOptions, - logger: BuilderContext['logger'], - componentStyles: Map, - updatedFiles: string[], -): void { - if (!updatedFiles.length) { - return; - } - - if (serverOptions.hmr) { - if (updatedFiles.every((f) => f.endsWith('.css'))) { - let requiresReload = false; - const timestamp = Date.now(); - const updates = updatedFiles.flatMap((filePath) => { - // For component styles, an HMR update must be sent for each one with the corresponding - // component identifier search parameter (`ngcomp`). The Vite client code will not keep - // the existing search parameters when it performs an update and each one must be - // specified explicitly. Typically, there is only one each though as specific style files - // are not typically reused across components. - const record = componentStyles.get(filePath); - if (record) { - if (record.reload) { - // Shadow DOM components currently require a full reload. - // Vite's CSS hot replacement does not support shadow root searching. - requiresReload = true; - - return []; - } - - return Array.from(record.used ?? []).map((id) => { - return { - type: 'css-update' as const, - timestamp, - path: `${filePath}?ngcomp` + (typeof id === 'string' ? `=${id}` : ''), - acceptedPath: filePath, - }; - }); - } - - return { - type: 'css-update' as const, - timestamp, - path: filePath, - acceptedPath: filePath, - }; - }); - - if (!requiresReload) { - server.ws.send({ - type: 'update', - updates, - }); - logger.info('Stylesheet update sent to client(s).'); - - return; - } - } - } - - // Send reload command to clients - if (serverOptions.liveReload) { - // Clear used component tracking on full reload - componentStyles.forEach((record) => record.used?.clear()); - - server.ws.send({ - type: 'full-reload', - path: '*', - }); - - logger.info('Page reload sent to client(s).'); - } -} - -function updateResultRecord( - outputPath: string, - file: ResultFile, - normalizePath: (id: string) => string, - htmlIndexPath: string, - generatedFiles: Map, - assetFiles: Map, - componentStyles: Map, - initial = false, -): void { - if (file.origin === 'disk') { - assetFiles.set('/' + normalizePath(outputPath), { - source: normalizePath(file.inputPath), - updated: !initial, - }); - - return; - } - - let filePath; - if (outputPath === htmlIndexPath) { - // Convert custom index output path to standard index path for dev-server usage. - // This mimics the Webpack dev-server behavior. - filePath = '/index.html'; - } else { - filePath = '/' + normalizePath(outputPath); - } - - const servable = - file.type === BuildOutputFileType.Browser || file.type === BuildOutputFileType.Media; - - // Skip analysis of sourcemaps - if (filePath.endsWith('.map')) { - generatedFiles.set(filePath, { - contents: file.contents, - servable, - size: file.contents.byteLength, - hash: file.hash, - type: file.type, - updated: false, - }); - - return; - } - - // New or updated file - generatedFiles.set(filePath, { - contents: file.contents, - size: file.contents.byteLength, - hash: file.hash, - // Consider the files updated except on the initial build result - updated: !initial, - type: file.type, - servable, - }); - - // Record any external component styles - if (filePath.endsWith('.css') && /^\/[a-f0-9]{64}\.css$/.test(filePath)) { - const componentStyle = componentStyles.get(filePath); - if (componentStyle) { - componentStyle.rawContent = file.contents; - } else { - componentStyles.set(filePath, { - rawContent: file.contents, - }); - } - } -} - -// eslint-disable-next-line max-lines-per-function -export async function setupServer( - serverOptions: NormalizedDevServerOptions, - outputFiles: Map, - assets: Map, - preserveSymlinks: boolean | undefined, - externalMetadata: DevServerExternalResultMetadata, - ssrMode: ServerSsrMode, - prebundleTransformer: JavaScriptTransformer, - target: string[], - zoneless: boolean, - componentStyles: Map, - templateUpdates: Map, - prebundleLoaderExtensions: EsbuildLoaderOption | undefined, - define: ApplicationBuilderInternalOptions['define'], - extensionMiddleware?: Connect.NextHandleFunction[], - indexHtmlTransformer?: (content: string) => Promise, - thirdPartySourcemaps = false, -): Promise { - const proxy = await loadProxyConfiguration( - serverOptions.workspaceRoot, - serverOptions.proxyConfig, - ); - - // dynamically import Vite for ESM compatibility - const { normalizePath } = await loadEsmModule('vite'); - - // Path will not exist on disk and only used to provide separate path for Vite requests - const virtualProjectRoot = normalizePath( - join(serverOptions.workspaceRoot, `.angular/vite-root`, serverOptions.buildTarget.project), - ); - - // Files used for SSR warmup. - let ssrFiles: string[] | undefined; - switch (ssrMode) { - case ServerSsrMode.InternalSsrMiddleware: - ssrFiles = ['./main.server.mjs']; - break; - case ServerSsrMode.ExternalSsrMiddleware: - ssrFiles = ['./main.server.mjs', './server.mjs']; - break; - } - - /** - * Required when using `externalDependencies` to prevent Vite load errors. - * - * @note Can be removed if Vite introduces native support for externals. - * @note Vite misresolves browser modules in SSR when accessing URLs with multiple segments - * (e.g., 'foo/bar'), as they are not correctly re-based from the base href. - */ - const preTransformRequests = - externalMetadata.explicitBrowser.length === 0 && ssrMode === ServerSsrMode.NoSsr; - const cacheDir = join(serverOptions.cacheOptions.path, serverOptions.buildTarget.project, 'vite'); - const configuration: InlineConfig = { - configFile: false, - envFile: false, - cacheDir, - root: virtualProjectRoot, - publicDir: false, - esbuild: false, - mode: 'development', - // We use custom as we do not rely on Vite's htmlFallbackMiddleware and indexHtmlMiddleware. - appType: 'custom', - css: { - devSourcemap: true, - }, - // Ensure custom 'file' loader build option entries are handled by Vite in application code that - // reference third-party libraries. Relative usage is handled directly by the build and not Vite. - // Only 'file' loader entries are currently supported directly by Vite. - assetsInclude: - prebundleLoaderExtensions && - Object.entries(prebundleLoaderExtensions) - .filter(([, value]) => value === 'file') - // Create a file extension glob for each key - .map(([key]) => '*' + key), - // Vite will normalize the `base` option by adding a leading slash. - base: serverOptions.servePath, - resolve: { - mainFields: ['es2020', 'browser', 'module', 'main'], - preserveSymlinks, - }, - dev: { - preTransformRequests, - }, - server: { - preTransformRequests, - warmup: { - ssrFiles, - }, - port: serverOptions.port, - strictPort: true, - host: serverOptions.host, - open: serverOptions.open, - allowedHosts: serverOptions.allowedHosts, - headers: serverOptions.headers, - // Disable the websocket if live reload is disabled (false/undefined are the only valid values) - ws: serverOptions.liveReload === false && serverOptions.hmr === false ? false : undefined, - // When server-side rendering (SSR) is enabled togather with SSL and Express is being used, - // we must configure Vite to use HTTP/1.1. - // This is necessary because Express does not support HTTP/2. - // We achieve this by defining an empty proxy. - // See: https://github.com/vitejs/vite/blob/c4b532cc900bf988073583511f57bd581755d5e3/packages/vite/src/node/http.ts#L106 - proxy: - serverOptions.ssl && ssrMode === ServerSsrMode.ExternalSsrMiddleware - ? (proxy ?? {}) - : proxy, - cors: { - // This will add the header `Access-Control-Allow-Origin: http://example.com`, - // where `http://example.com` is the requesting origin. - origin: true, - // Allow preflight requests to be proxied. - preflightContinue: true, - }, - // File watching is handled by the build directly. `null` disables file watching for Vite. - watch: null, - fs: { - // Ensure cache directory, node modules, and all assets are accessible by the client. - // The first two are required for Vite to function in prebundling mode (the default) and to load - // the Vite client-side code for browser reloading. These would be available by default but when - // the `allow` option is explicitly configured, they must be included manually. - allow: [ - cacheDir, - join(serverOptions.workspaceRoot, 'node_modules'), - ...[...assets.values()].map(({ source }) => source), - ], - }, - }, - ssr: { - // Note: `true` and `/.*/` have different sematics. When true, the `external` option is ignored. - noExternal: /.*/, - // Exclude any Node.js built in module and provided dependencies (currently build defined externals) - external: externalMetadata.explicitServer, - optimizeDeps: getDepOptimizationConfig({ - // Only enable with caching since it causes prebundle dependencies to be cached - disabled: serverOptions.prebundle === false, - // Exclude any explicitly defined dependencies (currently build defined externals and node.js built-ins) - exclude: externalMetadata.explicitServer, - // Include all implict dependencies from the external packages internal option - include: externalMetadata.implicitServer, - ssr: true, - prebundleTransformer, - zoneless, - target, - loader: prebundleLoaderExtensions, - thirdPartySourcemaps, - define, - }), - }, - plugins: [ - createAngularLocaleDataPlugin(), - createAngularSetupMiddlewaresPlugin({ - outputFiles, - assets, - indexHtmlTransformer, - extensionMiddleware, - componentStyles, - templateUpdates, - ssrMode, - resetComponentUpdates: () => templateUpdates.clear(), - projectRoot: serverOptions.projectRoot, - }), - createRemoveIdPrefixPlugin(externalMetadata.explicitBrowser), - await createAngularSsrTransformPlugin(serverOptions.workspaceRoot), - await createAngularMemoryPlugin({ - virtualProjectRoot, - outputFiles, - templateUpdates, - external: externalMetadata.explicitBrowser, - disableViteTransport: !serverOptions.liveReload, - }), - ], - // Browser only optimizeDeps. (This does not run for SSR dependencies). - optimizeDeps: getDepOptimizationConfig({ - // Only enable with caching since it causes prebundle dependencies to be cached - disabled: serverOptions.prebundle === false, - // Exclude any explicitly defined dependencies (currently build defined externals) - exclude: externalMetadata.explicitBrowser, - // Include all implict dependencies from the external packages internal option - include: externalMetadata.implicitBrowser, - ssr: false, - prebundleTransformer, - target, - zoneless, - loader: prebundleLoaderExtensions, - thirdPartySourcemaps, - define, - }), - }; - - if (serverOptions.ssl) { - if (serverOptions.sslCert && serverOptions.sslKey) { - configuration.server ??= {}; - // server configuration is defined above - configuration.server.https = { - cert: await readFile(serverOptions.sslCert), - key: await readFile(serverOptions.sslKey), - }; - } else { - const { default: basicSslPlugin } = await import('@vitejs/plugin-basic-ssl'); - configuration.plugins ??= []; - configuration.plugins.push(basicSslPlugin()); - } - } - - return configuration; -} - -/** - * Checks if the given value is an absolute URL. - * - * This function helps in avoiding Vite's prebundling from processing absolute URLs (http://, https://, //) as files. - * - * @param value - The URL or path to check. - * @returns `true` if the value is not an absolute URL; otherwise, `false`. - */ -function isAbsoluteUrl(value: string): boolean { - return /^(?:https?:)?\/\//.test(value); -} diff --git a/packages/angular/build/src/builders/dev-server/vite/hmr.ts b/packages/angular/build/src/builders/dev-server/vite/hmr.ts new file mode 100644 index 000000000000..467962572463 --- /dev/null +++ b/packages/angular/build/src/builders/dev-server/vite/hmr.ts @@ -0,0 +1,153 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { ɵdestroyAngularServerApp as destroyAngularServerApp } from '@angular/ssr'; +import type { BuilderContext } from '@angular-devkit/architect'; +import { join } from 'node:path'; +import type { ViteDevServer } from 'vite'; +import type { ComponentStyleRecord } from '../../../tools/vite/middlewares'; +import { BuildOutputFileType } from '../internal'; +import type { NormalizedDevServerOptions } from '../options'; +import type { OutputAssetRecord, OutputFileRecord } from './utils'; + +/** + * Invalidates any updated asset or generated files and resets their `updated` state. + * This function also clears the server application cache when necessary. + * + * @returns A list of files that were updated and invalidated. + */ +export async function invalidateUpdatedFiles( + normalizePath: (id: string) => string, + generatedFiles: Map, + assetFiles: Map, + server: ViteDevServer, +): Promise { + const updatedFiles: string[] = []; + + // Invalidate any updated asset + for (const [file, record] of assetFiles) { + if (!record.updated) { + continue; + } + + record.updated = false; + updatedFiles.push(file); + } + + // Invalidate any updated files + let serverApplicationChanged = false; + for (const [file, record] of generatedFiles) { + if (!record.updated) { + continue; + } + + record.updated = false; + updatedFiles.push(file); + serverApplicationChanged ||= record.type === BuildOutputFileType.ServerApplication; + + const updatedModules = server.moduleGraph.getModulesByFile( + normalizePath(join(server.config.root, file)), + ); + updatedModules?.forEach((m) => server.moduleGraph.invalidateModule(m)); + } + + if (serverApplicationChanged) { + // Clear the server app cache and trigger module evaluation before reload to initiate dependency optimization. + // The querystring is needed as a workaround for: + // `ɵgetOrCreateAngularServerApp` can be undefined right after an error. + const { ɵdestroyAngularServerApp } = (await server.ssrLoadModule( + `/main.server.mjs?timestamp=${Date.now()}`, + )) as { + ɵdestroyAngularServerApp: typeof destroyAngularServerApp; + }; + + ɵdestroyAngularServerApp(); + } + + return updatedFiles; +} + +/** + * Handles updates for the client by sending HMR or full page reload commands + * based on the updated files. It also ensures proper tracking of component styles and determines if + * a full reload is needed. + */ +export function handleUpdate( + server: ViteDevServer, + serverOptions: NormalizedDevServerOptions, + logger: BuilderContext['logger'], + componentStyles: Map, + updatedFiles: string[], +): void { + if (!updatedFiles.length) { + return; + } + + if (serverOptions.hmr) { + if (updatedFiles.every((f) => f.endsWith('.css'))) { + let requiresReload = false; + const timestamp = Date.now(); + const updates = updatedFiles.flatMap((filePath) => { + // For component styles, an HMR update must be sent for each one with the corresponding + // component identifier search parameter (`ngcomp`). The Vite client code will not keep + // the existing search parameters when it performs an update and each one must be + // specified explicitly. Typically, there is only one each though as specific style files + // are not typically reused across components. + const record = componentStyles.get(filePath); + if (record) { + if (record.reload) { + // Shadow DOM components currently require a full reload. + // Vite's CSS hot replacement does not support shadow root searching. + requiresReload = true; + + return []; + } + + return Array.from(record.used ?? []).map((id) => { + return { + type: 'css-update' as const, + timestamp, + path: `${filePath}?ngcomp` + (typeof id === 'string' ? `=${id}` : ''), + acceptedPath: filePath, + }; + }); + } + + return { + type: 'css-update' as const, + timestamp, + path: filePath, + acceptedPath: filePath, + }; + }); + + if (!requiresReload) { + server.ws.send({ + type: 'update', + updates, + }); + logger.info('Stylesheet update sent to client(s).'); + + return; + } + } + } + + // Send reload command to clients + if (serverOptions.liveReload) { + // Clear used component tracking on full reload + componentStyles.forEach((record) => record.used?.clear()); + + server.ws.send({ + type: 'full-reload', + path: '*', + }); + + logger.info('Page reload sent to client(s).'); + } +} diff --git a/packages/angular/build/src/builders/dev-server/vite/index.ts b/packages/angular/build/src/builders/dev-server/vite/index.ts new file mode 100644 index 000000000000..8129daac1ba1 --- /dev/null +++ b/packages/angular/build/src/builders/dev-server/vite/index.ts @@ -0,0 +1,514 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuilderContext } from '@angular-devkit/architect'; +import type { Plugin } from 'esbuild'; +import assert from 'node:assert'; +import { builtinModules, isBuiltin } from 'node:module'; +import { join } from 'node:path'; +import type { Connect, ViteDevServer } from 'vite'; +import type { ComponentStyleRecord } from '../../../tools/vite/middlewares'; +import { ServerSsrMode } from '../../../tools/vite/plugins'; +import { EsbuildLoaderOption, updateExternalMetadata } from '../../../tools/vite/utils'; +import { normalizeSourceMaps } from '../../../utils'; +import { useComponentStyleHmr, useComponentTemplateHmr } from '../../../utils/environment-options'; +import { Result, ResultKind } from '../../application/results'; +import { OutputHashing } from '../../application/schema'; +import { + type ApplicationBuilderInternalOptions, + type ExternalResultMetadata, + JavaScriptTransformer, + getSupportedBrowsers, + isZonelessApp, + transformSupportedBrowsersToTargets, +} from '../internal'; +import type { NormalizedDevServerOptions } from '../options'; +import type { DevServerBuilderOutput } from '../output'; +import { handleUpdate, invalidateUpdatedFiles } from './hmr'; +import { setupServer } from './server'; +import { + DevServerExternalResultMetadata, + OutputAssetRecord, + OutputFileRecord, + updateResultRecord, +} from './utils'; + +export type BuilderAction = ( + options: ApplicationBuilderInternalOptions, + context: BuilderContext, + plugins?: Plugin[], +) => AsyncIterable; + +/** + * Build options that are also present on the dev server but are only passed + * to the build. + */ +const CONVENIENCE_BUILD_OPTIONS = ['watch', 'poll', 'verbose', 'define'] as const; + +// eslint-disable-next-line max-lines-per-function +export async function* serveWithVite( + serverOptions: NormalizedDevServerOptions, + builderName: string, + builderAction: BuilderAction, + context: BuilderContext, + transformers?: { + indexHtml?: (content: string) => Promise; + }, + extensions?: { + middleware?: Connect.NextHandleFunction[]; + buildPlugins?: Plugin[]; + }, +): AsyncIterableIterator { + // Get the browser configuration from the target name. + const rawBrowserOptions = await context.getTargetOptions(serverOptions.buildTarget); + + // Deploy url is not used in the dev-server. + delete rawBrowserOptions.deployUrl; + + // Copy convenience options to build + for (const optionName of CONVENIENCE_BUILD_OPTIONS) { + const optionValue = serverOptions[optionName]; + if (optionValue !== undefined) { + if (optionName === 'define' && rawBrowserOptions[optionName]) { + // Define has merging behavior within the application + for (const [key, value] of Object.entries(optionValue)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (rawBrowserOptions[optionName] as any)[key] = value; + } + } else { + rawBrowserOptions[optionName] = optionValue; + } + } + } + + // TODO: Adjust architect to not force a JsonObject derived return type + const browserOptions = (await context.validateOptions( + rawBrowserOptions, + builderName, + )) as unknown as ApplicationBuilderInternalOptions; + + if (browserOptions.prerender || (browserOptions.outputMode && browserOptions.server)) { + // Disable prerendering if enabled and force SSR. + // This is so instead of prerendering all the routes for every change, the page is "prerendered" when it is requested. + browserOptions.prerender = undefined; + browserOptions.ssr ||= true; + } + + // Disable auto CSP. + browserOptions.security = { + autoCsp: false, + }; + + // Disable JSON build stats. + // These are not accessible with the dev server and can cause HMR fallbacks. + if (browserOptions.statsJson === true) { + context.logger.warn( + 'Build JSON statistics output (`statsJson` option) has been disabled.' + + ' The development server does not support this option.', + ); + } + browserOptions.statsJson = false; + + // Set all packages as external to support Vite's prebundle caching + browserOptions.externalPackages = serverOptions.prebundle; + + // Disable generating a full manifest with routes. + // This is done during runtime when using the dev-server. + browserOptions.partialSSRBuild = true; + + // The development server currently only supports a single locale when localizing. + // This matches the behavior of the Webpack-based development server but could be expanded in the future. + if ( + browserOptions.localize === true || + (Array.isArray(browserOptions.localize) && browserOptions.localize.length > 1) + ) { + context.logger.warn( + 'Localization (`localize` option) has been disabled. The development server only supports localizing a single locale per build.', + ); + browserOptions.localize = false; + } else if (browserOptions.localize) { + // When localization is enabled with a single locale, force a flat path to maintain behavior with the existing Webpack-based dev server. + browserOptions.forceI18nFlatOutput = true; + } + + const { vendor: thirdPartySourcemaps, scripts: scriptsSourcemaps } = normalizeSourceMaps( + browserOptions.sourceMap ?? false, + ); + + if (scriptsSourcemaps && browserOptions.server) { + // https://nodejs.org/api/process.html#processsetsourcemapsenabledval + process.setSourceMapsEnabled(true); + } + + if ( + serverOptions.hmr && + (browserOptions.outputHashing === OutputHashing.All || + browserOptions.outputHashing === OutputHashing.Bundles) + ) { + serverOptions.hmr = false; + + context.logger.warn( + `Hot Module Replacement (HMR) is disabled because the 'outputHashing' option is set to '${browserOptions.outputHashing}'. ` + + 'HMR is incompatible with this setting.', + ); + } + + const componentsHmrCanBeUsed = + browserOptions.aot && serverOptions.liveReload && serverOptions.hmr; + + // Enable to support link-based component style hot reloading (`NG_HMR_CSTYLES=1` can be used to enable) + browserOptions.externalRuntimeStyles = componentsHmrCanBeUsed && useComponentStyleHmr; + + // Enable to support component template hot replacement (`NG_HMR_TEMPLATE=0` can be used to disable selectively) + // This will also replace file-based/inline styles as code if external runtime styles are not enabled. + browserOptions.templateUpdates = componentsHmrCanBeUsed && useComponentTemplateHmr; + browserOptions.incrementalResults = true; + + // Setup the prebundling transformer that will be shared across Vite prebundling requests + const prebundleTransformer = new JavaScriptTransformer( + // Always enable JIT linking to support applications built with and without AOT. + // In a development environment the additional scope information does not + // have a negative effect unlike production where final output size is relevant. + { sourcemap: true, jit: true, thirdPartySourcemaps }, + 1, + ); + + // The index HTML path will be updated from the build results if provided by the builder + let htmlIndexPath = 'index.html'; + + const { createServer, normalizePath } = await import('vite'); + + let server: ViteDevServer | undefined; + let serverUrl: URL | undefined; + let hadError = false; + const generatedFiles = new Map(); + const assetFiles = new Map(); + const externalMetadata: DevServerExternalResultMetadata = { + implicitBrowser: [], + implicitServer: [], + explicitBrowser: [], + explicitServer: [], + }; + const componentStyles = new Map(); + const templateUpdates = new Map(); + + // Add cleanup logic via a builder teardown. + let deferred: () => void; + context.addTeardown(async () => { + await server?.close(); + await prebundleTransformer.close(); + deferred?.(); + }); + + // TODO: Switch this to an architect schedule call when infrastructure settings are supported + for await (const result of builderAction(browserOptions, context, extensions?.buildPlugins)) { + if (result.kind === ResultKind.Failure) { + if (result.errors.length && server) { + hadError = true; + server.ws.send({ + type: 'error', + err: { + message: result.errors[0].text, + stack: '', + loc: result.errors[0].location ?? undefined, + }, + }); + } + + yield { baseUrl: '', success: false }; + continue; + } + // Clear existing error overlay on successful result + if (hadError && server) { + hadError = false; + // Send an empty update to clear the error overlay + server.ws.send({ + 'type': 'update', + updates: [], + }); + } + + let needClientUpdate = true; + switch (result.kind) { + case ResultKind.Full: + if (result.detail?.['htmlIndexPath']) { + htmlIndexPath = result.detail['htmlIndexPath'] as string; + } + if (serverOptions.servePath === undefined && result.detail?.['htmlBaseHref']) { + const baseHref = result.detail['htmlBaseHref'] as string; + // Remove trailing slash + serverOptions.servePath = + baseHref !== './' && baseHref.at(-1) === '/' ? baseHref.slice(0, -1) : baseHref; + } + + assetFiles.clear(); + componentStyles.clear(); + generatedFiles.clear(); + + for (const [outputPath, file] of Object.entries(result.files)) { + updateResultRecord( + outputPath, + file, + normalizePath, + htmlIndexPath, + generatedFiles, + assetFiles, + componentStyles, + // The initial build will not yet have a server setup + !server, + ); + } + + // Clear stale template updates on code rebuilds + templateUpdates.clear(); + + break; + case ResultKind.Incremental: + assert(server, 'Builder must provide an initial full build before incremental results.'); + + // Background updates should only update server files/options + needClientUpdate = !result.background; + + for (const removed of result.removed) { + const filePath = '/' + normalizePath(removed.path); + generatedFiles.delete(filePath); + assetFiles.delete(filePath); + } + + for (const modified of result.modified) { + updateResultRecord( + modified, + result.files[modified], + normalizePath, + htmlIndexPath, + generatedFiles, + assetFiles, + componentStyles, + ); + } + + for (const added of result.added) { + updateResultRecord( + added, + result.files[added], + normalizePath, + htmlIndexPath, + generatedFiles, + assetFiles, + componentStyles, + ); + } + + break; + case ResultKind.ComponentUpdate: + assert(serverOptions.hmr, 'Component updates are only supported with HMR enabled.'); + assert( + server, + 'Builder must provide an initial full build before component update results.', + ); + + for (const componentUpdate of result.updates) { + if (componentUpdate.type === 'template') { + templateUpdates.set(componentUpdate.id, componentUpdate.content); + server.ws.send('angular:component-update', { + id: componentUpdate.id, + timestamp: Date.now(), + }); + } + } + + context.logger.info('Component update sent to client(s).'); + continue; + default: + context.logger.warn(`Unknown result kind [${(result as Result).kind}] provided by build.`); + continue; + } + + // To avoid disconnecting the array objects from the option, these arrays need to be mutated instead of replaced. + updateExternalMetadata(result, externalMetadata, browserOptions.externalDependencies); + + if (server) { + // Update fs allow list to include any new assets from the build option. + server.config.server.fs.allow = [ + ...new Set([ + ...server.config.server.fs.allow, + ...[...assetFiles.values()].map(({ source }) => source), + ]), + ]; + + const updatedFiles = await invalidateUpdatedFiles( + normalizePath, + generatedFiles, + assetFiles, + server, + ); + + if (needClientUpdate) { + handleUpdate(server, serverOptions, context.logger, componentStyles, updatedFiles); + } + } else { + const projectName = context.target?.project; + if (!projectName) { + throw new Error('The builder requires a target.'); + } + + context.logger.info( + 'NOTE: Raw file sizes do not reflect development server per-request transformations.', + ); + + if (browserOptions.ssr && serverOptions.inspect) { + const { host, port } = serverOptions.inspect as { host?: string; port?: number }; + const { default: inspector } = await import('node:inspector'); + inspector.open(port, host, true); + context.addTeardown(() => inspector.close()); + } + + const { root = '' } = await context.getProjectMetadata(projectName); + const projectRoot = join(context.workspaceRoot, root as string); + const browsers = getSupportedBrowsers(projectRoot, context.logger); + + const target = transformSupportedBrowsersToTargets(browsers); + // Needed for browser-esbuild as polyfills can be a string. + const polyfills = Array.isArray((browserOptions.polyfills ??= [])) + ? browserOptions.polyfills + : [browserOptions.polyfills]; + + let ssrMode: ServerSsrMode = ServerSsrMode.NoSsr; + if ( + browserOptions.outputMode && + typeof browserOptions.ssr === 'object' && + browserOptions.ssr.entry + ) { + ssrMode = ServerSsrMode.ExternalSsrMiddleware; + } else if (browserOptions.ssr) { + ssrMode = ServerSsrMode.InternalSsrMiddleware; + } + + if (browserOptions.progress !== false && ssrMode !== ServerSsrMode.NoSsr) { + // This is a workaround for https://github.com/angular/angular-cli/issues/28336, which is caused by the interaction between `zone.js` and `listr2`. + process.once('SIGINT', () => { + process.kill(process.pid); + }); + } + + // Setup server and start listening + const serverConfiguration = await setupServer( + serverOptions, + generatedFiles, + assetFiles, + browserOptions.preserveSymlinks, + externalMetadata, + ssrMode, + prebundleTransformer, + target, + isZonelessApp(polyfills), + componentStyles, + templateUpdates, + browserOptions.loader as EsbuildLoaderOption | undefined, + { + ...browserOptions.define, + 'ngJitMode': browserOptions.aot ? 'false' : 'true', + 'ngHmrMode': browserOptions.templateUpdates ? 'true' : 'false', + }, + extensions?.middleware, + transformers?.indexHtml, + thirdPartySourcemaps, + ); + + server = await createServer(serverConfiguration); + await server.listen(); + + // Setup builder context logging for browser clients + server.hot.on('angular:log', (data: { text: string; kind?: string }) => { + if (typeof data?.text !== 'string') { + context.logger.warn('Development server client sent invalid internal log event.'); + } + switch (data.kind) { + case 'error': + context.logger.error(`[CLIENT ERROR]: ${data.text}`); + break; + case 'warning': + context.logger.warn(`[CLIENT WARNING]: ${data.text}`); + break; + default: + context.logger.info(`[CLIENT INFO]: ${data.text}`); + break; + } + }); + + // Setup component HMR invalidation + // Invalidation occurs when the runtime cannot update a component + server.hot.on( + 'angular:invalidate', + (data: { id: string; message?: string; error?: boolean }) => { + if (typeof data?.id !== 'string') { + context.logger.warn( + 'Development server client sent invalid internal invalidate event.', + ); + } + + // Clear invalid template update + templateUpdates.delete(data.id); + + // Some cases are expected unsupported update scenarios but some may be errors. + // If an error occurred, log the error in addition to the invalidation. + if (data.error) { + context.logger.error( + `Component update failed${data.message ? `: ${data.message}` : '.'}` + + '\nPlease consider reporting the error at https://github.com/angular/angular-cli/issues', + ); + } else { + context.logger.warn( + `Component update unsupported${data.message ? `: ${data.message}` : '.'}`, + ); + } + + server?.ws.send({ + type: 'full-reload', + path: '*', + }); + context.logger.info('Page reload sent to client(s).'); + }, + ); + + const urls = server.resolvedUrls; + if (urls && (urls.local.length || urls.network.length)) { + serverUrl = new URL(urls.local[0] ?? urls.network[0]); + } + + // log connection information + server.printUrls(); + + server.bindCLIShortcuts({ + print: true, + customShortcuts: [ + { + key: 'r', + description: 'force reload browser', + action(server) { + componentStyles.forEach((record) => record.used?.clear()); + server.ws.send({ + type: 'full-reload', + path: '*', + }); + }, + }, + ], + }); + } + + // TODO: adjust output typings to reflect both development servers + yield { + success: true, + port: serverUrl?.port, + baseUrl: serverUrl?.href, + } as unknown as DevServerBuilderOutput; + } + + await new Promise((resolve) => (deferred = resolve)); +} diff --git a/packages/angular/build/src/builders/dev-server/vite/server.ts b/packages/angular/build/src/builders/dev-server/vite/server.ts new file mode 100644 index 000000000000..73f58ad5c348 --- /dev/null +++ b/packages/angular/build/src/builders/dev-server/vite/server.ts @@ -0,0 +1,271 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import type { Connect, InlineConfig, SSROptions, ServerOptions } from 'vite'; +import type { ComponentStyleRecord } from '../../../tools/vite/middlewares'; +import { + ServerSsrMode, + createAngularMemoryPlugin, + createAngularServerSideSSLPlugin, + createAngularSetupMiddlewaresPlugin, + createAngularSsrTransformPlugin, + createRemoveIdPrefixPlugin, +} from '../../../tools/vite/plugins'; +import { EsbuildLoaderOption, getDepOptimizationConfig } from '../../../tools/vite/utils'; +import { loadProxyConfiguration } from '../../../utils'; +import { type ApplicationBuilderInternalOptions, JavaScriptTransformer } from '../internal'; +import type { NormalizedDevServerOptions } from '../options'; +import { DevServerExternalResultMetadata, OutputAssetRecord, OutputFileRecord } from './utils'; + +async function createServerConfig( + serverOptions: NormalizedDevServerOptions, + assets: Map, + ssrMode: ServerSsrMode, + preTransformRequests: boolean, + cacheDir: string, +): Promise { + const proxy = await loadProxyConfiguration( + serverOptions.workspaceRoot, + serverOptions.proxyConfig, + ); + + // Files used for SSR warmup. + let ssrFiles: string[] | undefined; + switch (ssrMode) { + case ServerSsrMode.InternalSsrMiddleware: + ssrFiles = ['./main.server.mjs']; + break; + case ServerSsrMode.ExternalSsrMiddleware: + ssrFiles = ['./main.server.mjs', './server.mjs']; + break; + } + + const server: ServerOptions = { + preTransformRequests, + warmup: { + ssrFiles, + }, + port: serverOptions.port, + strictPort: true, + host: serverOptions.host, + open: serverOptions.open, + allowedHosts: serverOptions.allowedHosts, + headers: serverOptions.headers, + // Disable the websocket if live reload is disabled (false/undefined are the only valid values) + ws: serverOptions.liveReload === false && serverOptions.hmr === false ? false : undefined, + proxy, + cors: { + // This will add the header `Access-Control-Allow-Origin: http://example.com`, + // where `http://example.com` is the requesting origin. + origin: true, + // Allow preflight requests to be proxied. + preflightContinue: true, + }, + // File watching is handled by the build directly. `null` disables file watching for Vite. + watch: null, + fs: { + // Ensure cache directory, node modules, and all assets are accessible by the client. + // The first two are required for Vite to function in prebundling mode (the default) and to load + // the Vite client-side code for browser reloading. These would be available by default but when + // the `allow` option is explicitly configured, they must be included manually. + allow: [ + cacheDir, + join(serverOptions.workspaceRoot, 'node_modules'), + ...[...assets.values()].map(({ source }) => source), + ], + }, + }; + + if (serverOptions.ssl) { + if (serverOptions.sslCert && serverOptions.sslKey) { + server.https = { + cert: await readFile(serverOptions.sslCert), + key: await readFile(serverOptions.sslKey), + }; + } + } + + return server; +} + +function createSsrConfig( + externalMetadata: DevServerExternalResultMetadata, + serverOptions: NormalizedDevServerOptions, + prebundleTransformer: JavaScriptTransformer, + zoneless: boolean, + target: string[], + prebundleLoaderExtensions: EsbuildLoaderOption | undefined, + thirdPartySourcemaps: boolean, + define: ApplicationBuilderInternalOptions['define'], +): SSROptions { + return { + // Note: `true` and `/.*/` have different sematics. When true, the `external` option is ignored. + noExternal: /.*/, + // Exclude any Node.js built in module and provided dependencies (currently build defined externals) + external: externalMetadata.explicitServer, + optimizeDeps: getDepOptimizationConfig({ + // Only enable with caching since it causes prebundle dependencies to be cached + disabled: serverOptions.prebundle === false, + // Exclude any explicitly defined dependencies (currently build defined externals and node.js built-ins) + exclude: externalMetadata.explicitServer, + // Include all implict dependencies from the external packages internal option + include: externalMetadata.implicitServer, + ssr: true, + prebundleTransformer, + zoneless, + target, + loader: prebundleLoaderExtensions, + thirdPartySourcemaps, + define, + }), + }; +} + +export async function setupServer( + serverOptions: NormalizedDevServerOptions, + outputFiles: Map, + assets: Map, + preserveSymlinks: boolean | undefined, + externalMetadata: DevServerExternalResultMetadata, + ssrMode: ServerSsrMode, + prebundleTransformer: JavaScriptTransformer, + target: string[], + zoneless: boolean, + componentStyles: Map, + templateUpdates: Map, + prebundleLoaderExtensions: EsbuildLoaderOption | undefined, + define: ApplicationBuilderInternalOptions['define'], + extensionMiddleware?: Connect.NextHandleFunction[], + indexHtmlTransformer?: (content: string) => Promise, + thirdPartySourcemaps = false, +): Promise { + const { normalizePath } = await import('vite'); + + // Path will not exist on disk and only used to provide separate path for Vite requests + const virtualProjectRoot = normalizePath( + join(serverOptions.workspaceRoot, `.angular/vite-root`, serverOptions.buildTarget.project), + ); + + /** + * Required when using `externalDependencies` to prevent Vite load errors. + * + * @note Can be removed if Vite introduces native support for externals. + * @note Vite misresolves browser modules in SSR when accessing URLs with multiple segments + * (e.g., 'foo/bar'), as they are not correctly re-based from the base href. + */ + const preTransformRequests = + externalMetadata.explicitBrowser.length === 0 && ssrMode === ServerSsrMode.NoSsr; + const cacheDir = join(serverOptions.cacheOptions.path, serverOptions.buildTarget.project, 'vite'); + + const configuration: InlineConfig = { + configFile: false, + envFile: false, + cacheDir, + root: virtualProjectRoot, + publicDir: false, + esbuild: false, + mode: 'development', + // We use custom as we do not rely on Vite's htmlFallbackMiddleware and indexHtmlMiddleware. + appType: 'custom', + css: { + devSourcemap: true, + }, + // Ensure custom 'file' loader build option entries are handled by Vite in application code that + // reference third-party libraries. Relative usage is handled directly by the build and not Vite. + // Only 'file' loader entries are currently supported directly by Vite. + assetsInclude: + prebundleLoaderExtensions && + Object.entries(prebundleLoaderExtensions) + .filter(([, value]) => value === 'file') + // Create a file extension glob for each key + .map(([key]) => '*' + key), + // Vite will normalize the `base` option by adding a leading slash. + base: serverOptions.servePath, + resolve: { + mainFields: ['es2020', 'browser', 'module', 'main'], + preserveSymlinks, + }, + dev: { + preTransformRequests, + }, + server: await createServerConfig( + serverOptions, + assets, + ssrMode, + preTransformRequests, + cacheDir, + ), + ssr: + ssrMode === ServerSsrMode.NoSsr + ? undefined + : createSsrConfig( + externalMetadata, + serverOptions, + prebundleTransformer, + zoneless, + target, + prebundleLoaderExtensions, + thirdPartySourcemaps, + define, + ), + plugins: [ + createAngularSetupMiddlewaresPlugin({ + outputFiles, + assets, + indexHtmlTransformer, + extensionMiddleware, + componentStyles, + templateUpdates, + ssrMode, + resetComponentUpdates: () => templateUpdates.clear(), + projectRoot: serverOptions.projectRoot, + }), + createRemoveIdPrefixPlugin(externalMetadata.explicitBrowser), + await createAngularSsrTransformPlugin(serverOptions.workspaceRoot), + await createAngularMemoryPlugin({ + virtualProjectRoot, + outputFiles, + templateUpdates, + external: externalMetadata.explicitBrowser, + disableViteTransport: !serverOptions.liveReload, + }), + ], + // Browser only optimizeDeps. (This does not run for SSR dependencies). + optimizeDeps: getDepOptimizationConfig({ + // Only enable with caching since it causes prebundle dependencies to be cached + disabled: serverOptions.prebundle === false, + // Exclude any explicitly defined dependencies (currently build defined externals) + exclude: externalMetadata.explicitBrowser, + // Include all implict dependencies from the external packages internal option + include: externalMetadata.implicitBrowser, + ssr: false, + prebundleTransformer, + target, + zoneless, + loader: prebundleLoaderExtensions, + thirdPartySourcemaps, + define, + }), + }; + + if (serverOptions.ssl) { + configuration.plugins ??= []; + if (!serverOptions.sslCert || !serverOptions.sslKey) { + const { default: basicSslPlugin } = await import('@vitejs/plugin-basic-ssl'); + configuration.plugins.push(basicSslPlugin()); + } + + if (ssrMode !== ServerSsrMode.NoSsr) { + configuration.plugins?.push(createAngularServerSideSSLPlugin()); + } + } + + return configuration; +} diff --git a/packages/angular/build/src/builders/dev-server/vite/utils.ts b/packages/angular/build/src/builders/dev-server/vite/utils.ts new file mode 100644 index 000000000000..e1e6b4f96847 --- /dev/null +++ b/packages/angular/build/src/builders/dev-server/vite/utils.ts @@ -0,0 +1,111 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { ComponentStyleRecord } from '../../../tools/vite/middlewares'; +import type { ResultFile } from '../../application/results'; +import { BuildOutputFileType, type ExternalResultMetadata } from '../internal'; + +export interface OutputFileRecord { + contents: Uint8Array; + size: number; + hash: string; + updated: boolean; + servable: boolean; + type: BuildOutputFileType; +} + +export interface OutputAssetRecord { + source: string; + updated: boolean; +} + +export interface DevServerExternalResultMetadata extends Omit { + explicitBrowser: string[]; + explicitServer: string[]; +} + +export function updateResultRecord( + outputPath: string, + file: ResultFile, + normalizePath: (id: string) => string, + htmlIndexPath: string, + generatedFiles: Map, + assetFiles: Map, + componentStyles: Map, + initial = false, +): void { + if (file.origin === 'disk') { + assetFiles.set('/' + normalizePath(outputPath), { + source: normalizePath(file.inputPath), + updated: !initial, + }); + + return; + } + + let filePath; + if (outputPath === htmlIndexPath) { + // Convert custom index output path to standard index path for dev-server usage. + // This mimics the Webpack dev-server behavior. + filePath = '/index.html'; + } else { + filePath = '/' + normalizePath(outputPath); + } + + const servable = + file.type === BuildOutputFileType.Browser || file.type === BuildOutputFileType.Media; + + // Skip analysis of sourcemaps + if (filePath.endsWith('.map')) { + generatedFiles.set(filePath, { + contents: file.contents, + servable, + size: file.contents.byteLength, + hash: file.hash, + type: file.type, + updated: false, + }); + + return; + } + + // New or updated file + generatedFiles.set(filePath, { + contents: file.contents, + size: file.contents.byteLength, + hash: file.hash, + // Consider the files updated except on the initial build result + updated: !initial, + type: file.type, + servable, + }); + + // Record any external component styles + if (filePath.endsWith('.css') && /^\/[a-f0-9]{64}\.css$/.test(filePath)) { + const componentStyle = componentStyles.get(filePath); + if (componentStyle) { + componentStyle.rawContent = file.contents; + } else { + componentStyles.set(filePath, { + rawContent: file.contents, + }); + } + } +} + +/** + * Checks if the given value is an absolute URL. + * + * This function helps in avoiding Vite's prebundling from processing absolute URLs (http://, https://, //) as files. + * + * @param value - The URL or path to check. + * @returns `true` if the value is not an absolute URL; otherwise, `false`. + */ +export function isAbsoluteUrl(value: string): boolean { + return /^(?:https?:)?\/\//.test(value); +} diff --git a/packages/angular/build/src/builders/extract-i18n/builder.ts b/packages/angular/build/src/builders/extract-i18n/builder.ts index 15b0156f749b..f74d1d219712 100644 --- a/packages/angular/build/src/builders/extract-i18n/builder.ts +++ b/packages/angular/build/src/builders/extract-i18n/builder.ts @@ -10,7 +10,6 @@ import type { Diagnostics } from '@angular/localize/tools'; import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; import fs from 'node:fs'; import path from 'node:path'; -import { loadEsmModule } from '../../utils/load-esm'; import { assertCompatibleAngularVersion } from '../../utils/version'; import type { ApplicationBuilderExtensions } from '../application/options'; import { normalizeOptions } from './options'; @@ -51,8 +50,7 @@ export async function execute( // The package is a peer dependency and might not be present let localizeToolsModule; try { - localizeToolsModule = - await loadEsmModule('@angular/localize/tools'); + localizeToolsModule = await import('@angular/localize/tools'); } catch { return { success: false, diff --git a/packages/angular/build/src/builders/karma/application_builder.ts b/packages/angular/build/src/builders/karma/application_builder.ts index ae238b7239cf..34e94b1b7645 100644 --- a/packages/angular/build/src/builders/karma/application_builder.ts +++ b/packages/angular/build/src/builders/karma/application_builder.ts @@ -9,28 +9,32 @@ import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; import type { Config, ConfigOptions, FilePattern, InlinePluginDef, Server } from 'karma'; import { randomUUID } from 'node:crypto'; +import { rmSync } from 'node:fs'; import * as fs from 'node:fs/promises'; -import type { IncomingMessage, ServerResponse } from 'node:http'; -import { createRequire } from 'node:module'; import path from 'node:path'; -import { ReadableStreamController } from 'node:stream/web'; -import { globSync } from 'tinyglobby'; -import { BuildOutputFileType } from '../../tools/esbuild/bundler-context'; -import { emitFilesToDisk } from '../../tools/esbuild/utils'; +import { ReadableStream } from 'node:stream/web'; import { createVirtualModulePlugin } from '../../tools/esbuild/virtual-module-plugin'; -import { getProjectRootPaths } from '../../utils/project-metadata'; +import { writeTestFiles } from '../../utils/test-files'; import { buildApplicationInternal } from '../application/index'; import { ApplicationBuilderInternalOptions } from '../application/options'; -import { Result, ResultFile, ResultKind } from '../application/results'; +import { Result, ResultKind } from '../application/results'; import { OutputHashing } from '../application/schema'; -import { findTests, getTestEntrypoints } from './find-tests'; +import { AngularAssetsMiddleware } from './assets-middleware'; +import { createInstrumentationFilter, getInstrumentationExcludedPaths } from './coverage'; +import { getBaseKarmaOptions } from './karma-config'; import { NormalizedKarmaBuilderOptions, normalizeOptions } from './options'; +import { AngularPolyfillsPlugin } from './polyfills-plugin'; +import { injectKarmaReporter } from './progress-reporter'; import { Schema as KarmaBuilderOptions } from './schema'; +import { + collectEntrypoints, + first, + getProjectSourceRoot, + hasChunkOrWorkerFiles, + normalizePolyfills, +} from './utils'; import type { KarmaBuilderTransformsOptions } from './index'; -const localResolve = createRequire(__filename).resolve; -const isWindows = process.platform === 'win32'; - interface BuildOptions extends ApplicationBuilderInternalOptions { // We know that it's always a string since we set it. outputPath: string; @@ -43,239 +47,6 @@ class ApplicationBuildError extends Error { } } -interface ServeFileFunction { - ( - filepath: string, - rangeHeader: string | string[] | undefined, - response: ServerResponse, - transform?: (c: string | Uint8Array) => string | Uint8Array, - content?: string | Uint8Array, - doNotCache?: boolean, - ): void; -} - -interface LatestBuildFiles { - files: Record; -} - -const LATEST_BUILD_FILES_TOKEN = 'angularLatestBuildFiles'; - -class AngularAssetsMiddleware { - static readonly $inject = ['serveFile', LATEST_BUILD_FILES_TOKEN]; - - static readonly NAME = 'angular-test-assets'; - - constructor( - private readonly serveFile: ServeFileFunction, - private readonly latestBuildFiles: LatestBuildFiles, - ) {} - - handle(req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => unknown) { - const url = new URL(`http://${req.headers['host']}${req.url}`); - // Remove the leading slash from the URL path and convert to platform specific. - // The latest build files will use the platform path separator. - let pathname = url.pathname.slice(1); - if (isWindows) { - pathname = pathname.replaceAll(path.posix.sep, path.win32.sep); - } - - const file = this.latestBuildFiles.files[pathname]; - if (!file) { - next(); - - return; - } - - // Implementation of serverFile can be found here: - // https://github.com/karma-runner/karma/blob/84f85e7016efc2266fa6b3465f494a3fa151c85c/lib/middleware/common.js#L10 - switch (file.origin) { - case 'disk': - this.serveFile(file.inputPath, undefined, res, undefined, undefined, /* doNotCache */ true); - break; - case 'memory': - // Include pathname to help with Content-Type headers. - this.serveFile( - `/unused/${url.pathname}`, - undefined, - res, - undefined, - file.contents, - /* doNotCache */ false, - ); - break; - } - } - - static createPlugin(initialFiles: LatestBuildFiles): InlinePluginDef { - return { - [LATEST_BUILD_FILES_TOKEN]: ['value', { files: { ...initialFiles.files } }], - - [`middleware:${AngularAssetsMiddleware.NAME}`]: [ - 'factory', - Object.assign((...args: ConstructorParameters) => { - const inst = new AngularAssetsMiddleware(...args); - - return inst.handle.bind(inst); - }, AngularAssetsMiddleware), - ], - }; - } -} - -class AngularPolyfillsPlugin { - static readonly $inject = ['config.files']; - - static readonly NAME = 'angular-polyfills'; - - static createPlugin( - polyfillsFile: FilePattern, - jasmineCleanupFiles: FilePattern, - scriptsFiles: FilePattern[], - ): InlinePluginDef { - return { - // This has to be a "reporter" because reporters run _after_ frameworks - // and karma-jasmine-html-reporter injects additional scripts that may - // depend on Jasmine but aren't modules - which means that they would run - // _before_ all module code (including jasmine). - [`reporter:${AngularPolyfillsPlugin.NAME}`]: [ - 'factory', - Object.assign((files: (string | FilePattern)[]) => { - // The correct order is zone.js -> jasmine -> zone.js/testing. - // Jasmine has to see the patched version of the global `setTimeout` - // function so it doesn't cache the unpatched version. And /testing - // needs to see the global `jasmine` object so it can patch it. - const polyfillsIndex = 0; - files.splice(polyfillsIndex, 0, polyfillsFile); - - // Insert just before test_main.js. - const zoneTestingIndex = files.findIndex((f) => { - if (typeof f === 'string') { - return false; - } - - return f.pattern.endsWith('/test_main.js'); - }); - if (zoneTestingIndex === -1) { - throw new Error('Could not find test entrypoint file.'); - } - files.splice(zoneTestingIndex, 0, jasmineCleanupFiles); - - // We need to ensure that all files are served as modules, otherwise - // the order in the files list gets really confusing: Karma doesn't - // set defer on scripts, so all scripts with type=js will run first, - // even if type=module files appeared earlier in `files`. - for (const f of files) { - if (typeof f === 'string') { - throw new Error(`Unexpected string-based file: "${f}"`); - } - if (f.included === false) { - // Don't worry about files that aren't included on the initial - // page load. `type` won't affect them. - continue; - } - if (f.pattern.endsWith('.js') && 'js' === (f.type ?? 'js')) { - f.type = 'module'; - } - } - - // Add "scripts" option files as classic scripts - files.unshift(...scriptsFiles); - - // Add browser sourcemap support as a classic script - files.unshift({ - pattern: localResolve('source-map-support/browser-source-map-support.js'), - included: true, - watched: false, - }); - }, AngularPolyfillsPlugin), - ], - }; - } -} - -function injectKarmaReporter( - buildOptions: BuildOptions, - buildIterator: AsyncIterator, - karmaConfig: Config & ConfigOptions, - controller: ReadableStreamController, -) { - const reporterName = 'angular-progress-notifier'; - - interface RunCompleteInfo { - exitCode: number; - } - - interface KarmaEmitter { - refreshFiles(): void; - } - - class ProgressNotifierReporter { - static $inject = ['emitter', LATEST_BUILD_FILES_TOKEN]; - - constructor( - private readonly emitter: KarmaEmitter, - private readonly latestBuildFiles: LatestBuildFiles, - ) { - this.startWatchingBuild(); - } - - private startWatchingBuild() { - void (async () => { - // This is effectively "for await of but skip what's already consumed". - let isDone = false; // to mark the loop condition as "not constant". - while (!isDone) { - const { done, value: buildOutput } = await buildIterator.next(); - if (done) { - isDone = true; - break; - } - - if (buildOutput.kind === ResultKind.Failure) { - controller.enqueue({ success: false, message: 'Build failed' }); - } else if ( - buildOutput.kind === ResultKind.Incremental || - buildOutput.kind === ResultKind.Full - ) { - if (buildOutput.kind === ResultKind.Full) { - this.latestBuildFiles.files = buildOutput.files; - } else { - this.latestBuildFiles.files = { - ...this.latestBuildFiles.files, - ...buildOutput.files, - }; - } - await writeTestFiles(buildOutput.files, buildOptions.outputPath); - this.emitter.refreshFiles(); - } - } - })(); - } - - onRunComplete = function (_browsers: unknown, results: RunCompleteInfo) { - if (results.exitCode === 0) { - controller.enqueue({ success: true }); - } else { - controller.enqueue({ success: false }); - } - }; - } - - karmaConfig.reporters ??= []; - karmaConfig.reporters.push(reporterName); - - karmaConfig.plugins ??= []; - karmaConfig.plugins.push({ - [`reporter:${reporterName}`]: [ - 'factory', - Object.assign( - (...args: ConstructorParameters) => - new ProgressNotifierReporter(...args), - ProgressNotifierReporter, - ), - ], - }); -} - export function execute( options: KarmaBuilderOptions, context: BuilderContext, @@ -324,54 +95,6 @@ export function execute( }); } -async function getProjectSourceRoot(context: BuilderContext): Promise { - // We have already validated that the project name is set before calling this function. - const projectName = context.target?.project; - if (!projectName) { - return context.workspaceRoot; - } - - const projectMetadata = await context.getProjectMetadata(projectName); - const { projectSourceRoot } = getProjectRootPaths(context.workspaceRoot, projectMetadata); - - return projectSourceRoot; -} - -function normalizePolyfills( - polyfills: string[] = [], -): [polyfills: string[], jasmineCleanup: string[]] { - const jasmineGlobalEntryPoint = localResolve('./polyfills/jasmine_global.js'); - const jasmineGlobalCleanupEntrypoint = localResolve('./polyfills/jasmine_global_cleanup.js'); - const sourcemapEntrypoint = localResolve('./polyfills/init_sourcemaps.js'); - - const zoneTestingEntryPoint = 'zone.js/testing'; - const polyfillsExludingZoneTesting = polyfills.filter((p) => p !== zoneTestingEntryPoint); - - return [ - polyfillsExludingZoneTesting.concat([jasmineGlobalEntryPoint, sourcemapEntrypoint]), - polyfillsExludingZoneTesting.length === polyfills.length - ? [jasmineGlobalCleanupEntrypoint] - : [jasmineGlobalCleanupEntrypoint, zoneTestingEntryPoint], - ]; -} - -async function collectEntrypoints( - options: NormalizedKarmaBuilderOptions, - context: BuilderContext, - projectSourceRoot: string, -): Promise> { - // Glob for files to test. - const testFiles = await findTests( - options.include, - options.exclude, - context.workspaceRoot, - projectSourceRoot, - ); - - return getTestEntrypoints(testFiles, { projectSourceRoot, workspaceRoot: context.workspaceRoot }); -} - -// eslint-disable-next-line max-lines-per-function async function initializeApplication( options: NormalizedKarmaBuilderOptions, context: BuilderContext, @@ -380,14 +103,48 @@ async function initializeApplication( ): Promise< [typeof import('karma'), Config & ConfigOptions, BuildOptions, AsyncIterator | null] > { - const outputPath = path.join(context.workspaceRoot, 'dist/test-out', randomUUID()); + const karma = await import('karma'); const projectSourceRoot = await getProjectSourceRoot(context); - const [karma, entryPoints] = await Promise.all([ - import('karma'), - collectEntrypoints(options, context, projectSourceRoot), - fs.rm(outputPath, { recursive: true, force: true }), - ]); + // Setup temporary output path and ensure it is empty + const outputPath = path.join(context.workspaceRoot, 'dist/test-out', randomUUID()); + await fs.rm(outputPath, { recursive: true, force: true }); + // Setup exit cleanup for temporary directory + const handleProcessExit = () => rmSync(outputPath, { recursive: true, force: true }); + process.once('exit', handleProcessExit); + process.once('SIGINT', handleProcessExit); + process.once('uncaughtException', handleProcessExit); + + const { buildOptions, mainName } = await setupBuildOptions( + options, + context, + projectSourceRoot, + outputPath, + ); + + const [buildOutput, buildIterator] = await runEsbuild(buildOptions, context, projectSourceRoot); + + const karmaConfig = await configureKarma( + karma, + context, + karmaOptions, + options, + buildOptions, + buildOutput, + mainName, + transforms, + ); + + return [karma, karmaConfig, buildOptions, buildIterator]; +} + +async function setupBuildOptions( + options: NormalizedKarmaBuilderOptions, + context: BuilderContext, + projectSourceRoot: string, + outputPath: string, +): Promise<{ buildOptions: BuildOptions; mainName: string }> { + const entryPoints = await collectEntrypoints(options, context, projectSourceRoot); const mainName = 'test_main'; if (options.main) { @@ -433,17 +190,29 @@ async function initializeApplication( externalDependencies: options.externalDependencies, }; + return { buildOptions, mainName }; +} + +async function runEsbuild( + buildOptions: BuildOptions, + context: BuilderContext, + projectSourceRoot: string, +): Promise<[Result & { kind: ResultKind.Full }, AsyncIterator | null]> { + const usesZoneJS = buildOptions.polyfills?.includes('zone.js'); const virtualTestBedInit = createVirtualModulePlugin({ namespace: 'angular:test-bed-init', loadContent: async () => { const contents: string[] = [ // Initialize the Angular testing environment + `import { NgModule${usesZoneJS ? ', provideZoneChangeDetection' : ''} } from '@angular/core';`, `import { getTestBed } from '@angular/core/testing';`, `import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';`, - `getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting(), {`, + `@NgModule({ providers: [${usesZoneJS ? 'provideZoneChangeDetection(), ' : ''}], })`, + `export class TestModule {}`, + `getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {`, ` errorOnUnknownElements: true,`, ` errorOnUnknownProperties: true,`, - '});', + `});`, ]; return { @@ -470,6 +239,21 @@ async function initializeApplication( // Write test files await writeTestFiles(buildOutput.files, buildOptions.outputPath); + return [buildOutput, buildIterator]; +} + +async function configureKarma( + karma: typeof import('karma'), + context: BuilderContext, + karmaOptions: ConfigOptions, + options: NormalizedKarmaBuilderOptions, + buildOptions: BuildOptions, + buildOutput: Result & { kind: ResultKind.Full }, + mainName: string, + transforms?: KarmaBuilderTransformsOptions, +): Promise { + const outputPath = buildOptions.outputPath; + // We need to add this to the beginning *after* the testing framework has // prepended its files. The output path is required for each since they are // added later in the test process via a plugin. @@ -629,160 +413,5 @@ async function initializeApplication( parsedKarmaConfig.reporters = (parsedKarmaConfig.reporters ?? []).concat(['coverage']); } - return [karma, parsedKarmaConfig, buildOptions, buildIterator]; -} - -function hasChunkOrWorkerFiles(files: Record): boolean { - return Object.keys(files).some((filename) => { - return /(?:^|\/)(?:worker|chunk)[^/]+\.js$/.test(filename); - }); -} - -export async function writeTestFiles(files: Record, testDir: string) { - const directoryExists = new Set(); - // Writes the test related output files to disk and ensures the containing directories are present - await emitFilesToDisk(Object.entries(files), async ([filePath, file]) => { - if (file.type !== BuildOutputFileType.Browser && file.type !== BuildOutputFileType.Media) { - return; - } - - const fullFilePath = path.join(testDir, filePath); - - // Ensure output subdirectories exist - const fileBasePath = path.dirname(fullFilePath); - if (fileBasePath && !directoryExists.has(fileBasePath)) { - await fs.mkdir(fileBasePath, { recursive: true }); - directoryExists.add(fileBasePath); - } - - if (file.origin === 'memory') { - // Write file contents - await fs.writeFile(fullFilePath, file.contents); - } else { - // Copy file contents - await fs.copyFile(file.inputPath, fullFilePath, fs.constants.COPYFILE_FICLONE); - } - }); -} - -/** Returns the first item yielded by the given generator and cancels the execution. */ -async function first( - generator: AsyncIterable, - { cancel }: { cancel: boolean }, -): Promise<[T, AsyncIterator | null]> { - if (!cancel) { - const iterator: AsyncIterator = generator[Symbol.asyncIterator](); - const firstValue = await iterator.next(); - if (firstValue.done) { - throw new Error('Expected generator to emit at least once.'); - } - - return [firstValue.value, iterator]; - } - - for await (const value of generator) { - return [value, null]; - } - - throw new Error('Expected generator to emit at least once.'); -} - -function createInstrumentationFilter(includedBasePath: string, excludedPaths: Set) { - return (request: string): boolean => { - return ( - !excludedPaths.has(request) && - !/\.(e2e|spec)\.tsx?$|[\\/]node_modules[\\/]/.test(request) && - request.startsWith(includedBasePath) - ); - }; -} - -function getInstrumentationExcludedPaths(root: string, excludedPaths: string[]): Set { - const excluded = new Set(); - - for (const excludeGlob of excludedPaths) { - const excludePath = excludeGlob[0] === '/' ? excludeGlob.slice(1) : excludeGlob; - globSync(excludePath, { cwd: root }).forEach((p) => excluded.add(path.join(root, p))); - } - - return excluded; -} -function getBaseKarmaOptions( - options: NormalizedKarmaBuilderOptions, - context: BuilderContext, -): ConfigOptions { - // Determine project name from builder context target - const projectName = context.target?.project; - if (!projectName) { - throw new Error(`The 'karma' builder requires a target to be specified.`); - } - - const karmaOptions: ConfigOptions = options.karmaConfig - ? {} - : getBuiltInKarmaConfig(context.workspaceRoot, projectName); - - const singleRun = !options.watch; - karmaOptions.singleRun = singleRun; - - // Workaround https://github.com/angular/angular-cli/issues/28271, by clearing context by default - // for single run executions. Not clearing context for multi-run (watched) builds allows the - // Jasmine Spec Runner to be visible in the browser after test execution. - karmaOptions.client ??= {}; - karmaOptions.client.clearContext ??= singleRun; - - // Convert browsers from a string to an array - if (options.browsers) { - karmaOptions.browsers = options.browsers; - } - - if (options.reporters) { - karmaOptions.reporters = options.reporters; - } - - return karmaOptions; -} - -function getBuiltInKarmaConfig( - workspaceRoot: string, - projectName: string, -): ConfigOptions & Record { - let coverageFolderName = projectName.charAt(0) === '@' ? projectName.slice(1) : projectName; - coverageFolderName = coverageFolderName.toLowerCase(); - - const workspaceRootRequire = createRequire(workspaceRoot + '/'); - - // Any changes to the config here need to be synced to: packages/schematics/angular/config/files/karma.conf.js.template - return { - basePath: '', - frameworks: ['jasmine'], - plugins: [ - 'karma-jasmine', - 'karma-chrome-launcher', - 'karma-jasmine-html-reporter', - 'karma-coverage', - ].map((p) => workspaceRootRequire(p)), - jasmineHtmlReporter: { - suppressAll: true, // removes the duplicated traces - }, - coverageReporter: { - dir: path.join(workspaceRoot, 'coverage', coverageFolderName), - subdir: '.', - reporters: [{ type: 'html' }, { type: 'text-summary' }], - }, - reporters: ['progress', 'kjhtml'], - browsers: ['Chrome'], - customLaunchers: { - // Chrome configured to run in a bazel sandbox. - // Disable the use of the gpu and `/dev/shm` because it causes Chrome to - // crash on some environments. - // See: - // https://github.com/puppeteer/puppeteer/blob/v1.0.0/docs/troubleshooting.md#tips - // https://stackoverflow.com/questions/50642308/webdriverexception-unknown-error-devtoolsactiveport-file-doesnt-exist-while-t - ChromeHeadlessNoSandbox: { - base: 'ChromeHeadless', - flags: ['--no-sandbox', '--headless', '--disable-gpu', '--disable-dev-shm-usage'], - }, - }, - restartOnFileChange: true, - }; + return parsedKarmaConfig; } diff --git a/packages/angular/build/src/builders/karma/assets-middleware.ts b/packages/angular/build/src/builders/karma/assets-middleware.ts new file mode 100644 index 000000000000..fd6ce489e583 --- /dev/null +++ b/packages/angular/build/src/builders/karma/assets-middleware.ts @@ -0,0 +1,93 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { InlinePluginDef } from 'karma'; +import type { IncomingMessage, ServerResponse } from 'node:http'; +import path from 'node:path'; +import type { ResultFile } from '../application/results'; + +const isWindows = process.platform === 'win32'; + +interface ServeFileFunction { + ( + filepath: string, + rangeHeader: string | string[] | undefined, + response: ServerResponse, + transform?: (c: string | Uint8Array) => string | Uint8Array, + content?: string | Uint8Array, + doNotCache?: boolean, + ): void; +} + +export interface LatestBuildFiles { + files: Record; +} + +const LATEST_BUILD_FILES_TOKEN = 'angularLatestBuildFiles'; + +export class AngularAssetsMiddleware { + static readonly $inject = ['serveFile', LATEST_BUILD_FILES_TOKEN]; + + static readonly NAME = 'angular-test-assets'; + + constructor( + private readonly serveFile: ServeFileFunction, + private readonly latestBuildFiles: LatestBuildFiles, + ) {} + + handle(req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => unknown): void { + const url = new URL(`http://${req.headers['host'] ?? ''}${req.url ?? ''}`); + // Remove the leading slash from the URL path and convert to platform specific. + // The latest build files will use the platform path separator. + let pathname = url.pathname.slice(1); + if (isWindows) { + pathname = pathname.replaceAll(path.posix.sep, path.win32.sep); + } + + const file = this.latestBuildFiles.files[pathname]; + if (!file) { + next(); + + return; + } + + // Implementation of serverFile can be found here: + // https://github.com/karma-runner/karma/blob/84f85e7016efc2266fa6b3465f494a3fa151c85c/lib/middleware/common.js#L10 + switch (file.origin) { + case 'disk': + this.serveFile(file.inputPath, undefined, res, undefined, undefined, /* doNotCache */ true); + break; + case 'memory': + // Include pathname to help with Content-Type headers. + this.serveFile( + `/unused/${url.pathname}`, + undefined, + res, + undefined, + file.contents, + /* doNotCache */ false, + ); + break; + } + } + + static createPlugin(initialFiles: LatestBuildFiles): InlinePluginDef { + return { + [LATEST_BUILD_FILES_TOKEN]: ['value', { files: { ...initialFiles.files } }], + + [`middleware:${AngularAssetsMiddleware.NAME}`]: [ + 'factory', + Object.assign((...args: ConstructorParameters) => { + const inst = new AngularAssetsMiddleware(...args); + + return inst.handle.bind(inst); + }, AngularAssetsMiddleware), + ], + }; + } +} diff --git a/packages/angular/build/src/builders/karma/coverage.ts b/packages/angular/build/src/builders/karma/coverage.ts new file mode 100644 index 000000000000..7a19f57fbebf --- /dev/null +++ b/packages/angular/build/src/builders/karma/coverage.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import path from 'node:path'; +import { globSync } from 'tinyglobby'; + +export function createInstrumentationFilter(includedBasePath: string, excludedPaths: Set) { + return (request: string): boolean => { + return ( + !excludedPaths.has(request) && + !/\.(e2e|spec)\.tsx?$|[\\/]node_modules[\\/]|[\\/]\.angular[\\/]/.test(request) && + request.startsWith(includedBasePath) + ); + }; +} + +export function getInstrumentationExcludedPaths( + root: string, + excludedPaths: string[], +): Set { + const excluded = new Set(); + + for (const excludeGlob of excludedPaths) { + const excludePath = excludeGlob[0] === '/' ? excludeGlob.slice(1) : excludeGlob; + globSync(excludePath, { cwd: root }).forEach((p) => excluded.add(path.join(root, p))); + } + + return excluded; +} diff --git a/packages/angular/build/src/builders/karma/find-tests.ts b/packages/angular/build/src/builders/karma/find-tests.ts index 67ae410c6125..00468146df5f 100644 --- a/packages/angular/build/src/builders/karma/find-tests.ts +++ b/packages/angular/build/src/builders/karma/find-tests.ts @@ -6,150 +6,27 @@ * found in the LICENSE file at https://angular.dev/license */ -import { PathLike, constants, promises as fs } from 'node:fs'; -import { basename, dirname, extname, join, relative } from 'node:path'; -import { glob, isDynamicPattern } from 'tinyglobby'; -import { toPosixPath } from '../../utils/path'; +import { findTests as findTestsBase } from '../unit-test/test-discovery'; -/* Go through all patterns and find unique list of files */ -export async function findTests( - include: string[], - exclude: string[], - workspaceRoot: string, - projectSourceRoot: string, -): Promise { - const matchingTestsPromises = include.map((pattern) => - findMatchingTests(pattern, exclude, workspaceRoot, projectSourceRoot), - ); - const files = await Promise.all(matchingTestsPromises); - - // Unique file names - return [...new Set(files.flat())]; -} - -interface TestEntrypointsOptions { - projectSourceRoot: string; - workspaceRoot: string; -} - -/** Generate unique bundle names for a set of test files. */ -export function getTestEntrypoints( - testFiles: string[], - { projectSourceRoot, workspaceRoot }: TestEntrypointsOptions, -): Map { - const seen = new Set(); - - return new Map( - Array.from(testFiles, (testFile) => { - const relativePath = removeRoots(testFile, [projectSourceRoot, workspaceRoot]) - // Strip leading dots and path separators. - .replace(/^[./\\]+/, '') - // Replace any path separators with dashes. - .replace(/[/\\]/g, '-'); - const baseName = `spec-${basename(relativePath, extname(relativePath))}`; - let uniqueName = baseName; - let suffix = 2; - while (seen.has(uniqueName)) { - uniqueName = `${baseName}-${suffix}`.replace(/([^\w](?:spec|test))-([\d]+)$/, '-$2$1'); - ++suffix; - } - seen.add(uniqueName); - - return [uniqueName, testFile]; - }), - ); -} - -const removeLeadingSlash = (pattern: string): string => { - if (pattern.charAt(0) === '/') { - return pattern.substring(1); - } - - return pattern; -}; +// This file is a compatibility layer that re-exports the test discovery logic from its new location. +// This is necessary to avoid breaking the Karma builder, which still depends on this file. +export { getTestEntrypoints } from '../unit-test/test-discovery'; -const removeRelativeRoot = (path: string, root: string): string => { - if (path.startsWith(root)) { - return path.substring(root.length); - } - - return path; +const removeLeadingSlash = (path: string): string => { + return path.startsWith('/') ? path.substring(1) : path; }; -function removeRoots(path: string, roots: string[]): string { - for (const root of roots) { - if (path.startsWith(root)) { - return path.substring(root.length); - } - } - - return basename(path); -} - -async function findMatchingTests( - pattern: string, - ignore: string[], +export async function findTests( + include: string[], + exclude: string[], workspaceRoot: string, projectSourceRoot: string, ): Promise { - // normalize pattern, glob lib only accepts forward slashes - let normalizedPattern = toPosixPath(pattern); - normalizedPattern = removeLeadingSlash(normalizedPattern); - - const relativeProjectRoot = toPosixPath(relative(workspaceRoot, projectSourceRoot) + '/'); - - // remove relativeProjectRoot to support relative paths from root - // such paths are easy to get when running scripts via IDEs - normalizedPattern = removeRelativeRoot(normalizedPattern, relativeProjectRoot); - - // special logic when pattern does not look like a glob - if (!isDynamicPattern(normalizedPattern)) { - if (await isDirectory(join(projectSourceRoot, normalizedPattern))) { - normalizedPattern = `${normalizedPattern}/**/*.spec.@(ts|tsx)`; - } else { - // see if matching spec file exists - const fileExt = extname(normalizedPattern); - // Replace extension to `.spec.ext`. Example: `src/app/app.component.ts`-> `src/app/app.component.spec.ts` - const potentialSpec = join( - projectSourceRoot, - dirname(normalizedPattern), - `${basename(normalizedPattern, fileExt)}.spec${fileExt}`, - ); - - if (await exists(potentialSpec)) { - return [potentialSpec]; - } - } - } - - // normalize the patterns in the ignore list - const normalizedIgnorePatternList = ignore.map((pattern: string) => - removeRelativeRoot(removeLeadingSlash(toPosixPath(pattern)), relativeProjectRoot), + // Karma has legacy support for workspace "root-relative" file paths + return findTestsBase( + include.map(removeLeadingSlash), + exclude.map(removeLeadingSlash), + workspaceRoot, + projectSourceRoot, ); - - return glob(normalizedPattern, { - cwd: projectSourceRoot, - absolute: true, - ignore: ['**/node_modules/**', ...normalizedIgnorePatternList], - }); -} - -async function isDirectory(path: PathLike): Promise { - try { - const stats = await fs.stat(path); - - return stats.isDirectory(); - } catch { - return false; - } -} - -async function exists(path: PathLike): Promise { - try { - await fs.access(path, constants.F_OK); - - return true; - } catch { - return false; - } } diff --git a/packages/angular/build/src/builders/karma/find-tests_spec.ts b/packages/angular/build/src/builders/karma/find-tests_spec.ts index 8264539ae9dd..88c97c8575fe 100644 --- a/packages/angular/build/src/builders/karma/find-tests_spec.ts +++ b/packages/angular/build/src/builders/karma/find-tests_spec.ts @@ -62,6 +62,36 @@ describe('getTestEntrypoints', () => { ]), ); }); + + describe('with removeTestExtension enabled', () => { + function getEntrypoints(workspaceRelative: string[], sourceRootRelative: string[] = []) { + return getTestEntrypoints( + [ + ...workspaceRelative.map((p) => joinWithSeparator(options.workspaceRoot, p)), + ...sourceRootRelative.map((p) => joinWithSeparator(options.projectSourceRoot, p)), + ], + { ...options, removeTestExtension: true }, + ); + } + + it('removes .spec extension', () => { + expect(getEntrypoints(['a/b.spec.js'], ['c/d.spec.js'])).toEqual( + new Map([ + ['spec-a-b', joinWithSeparator(options.workspaceRoot, 'a/b.spec.js')], + ['spec-c-d', joinWithSeparator(options.projectSourceRoot, 'c/d.spec.js')], + ]), + ); + }); + + it('removes .test extension', () => { + expect(getEntrypoints(['a/b.test.js'], ['c/d.test.js'])).toEqual( + new Map([ + ['spec-a-b', joinWithSeparator(options.workspaceRoot, 'a/b.test.js')], + ['spec-c-d', joinWithSeparator(options.projectSourceRoot, 'c/d.test.js')], + ]), + ); + }); + }); }); } }); diff --git a/packages/angular/build/src/builders/karma/karma-config.ts b/packages/angular/build/src/builders/karma/karma-config.ts new file mode 100644 index 000000000000..08e39887bcb1 --- /dev/null +++ b/packages/angular/build/src/builders/karma/karma-config.ts @@ -0,0 +1,93 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuilderContext } from '@angular-devkit/architect'; +import type { ConfigOptions } from 'karma'; +import { createRequire } from 'node:module'; +import path from 'node:path'; +import type { NormalizedKarmaBuilderOptions } from './options'; + +export function getBaseKarmaOptions( + options: NormalizedKarmaBuilderOptions, + context: BuilderContext, +): ConfigOptions { + // Determine project name from builder context target + const projectName = context.target?.project; + if (!projectName) { + throw new Error(`The 'karma' builder requires a target to be specified.`); + } + + const karmaOptions: ConfigOptions = options.karmaConfig + ? {} + : getBuiltInKarmaConfig(context.workspaceRoot, projectName); + + const singleRun = !options.watch; + karmaOptions.singleRun = singleRun; + + // Workaround https://github.com/angular/angular-cli/issues/28271, by clearing context by default + // for single run executions. Not clearing context for multi-run (watched) builds allows the + // Jasmine Spec Runner to be visible in the browser after test execution. + karmaOptions.client ??= {}; + karmaOptions.client.clearContext ??= singleRun; + + // Convert browsers from a string to an array + if (options.browsers) { + karmaOptions.browsers = options.browsers; + } + + if (options.reporters) { + karmaOptions.reporters = options.reporters; + } + + return karmaOptions; +} + +function getBuiltInKarmaConfig( + workspaceRoot: string, + projectName: string, +): ConfigOptions & Record { + let coverageFolderName = projectName.charAt(0) === '@' ? projectName.slice(1) : projectName; + coverageFolderName = coverageFolderName.toLowerCase(); + + const workspaceRootRequire = createRequire(workspaceRoot + '/'); + + // Any changes to the config here need to be synced to: packages/schematics/angular/config/files/karma.conf.js.template + return { + basePath: '', + frameworks: ['jasmine'], + plugins: [ + 'karma-jasmine', + 'karma-chrome-launcher', + 'karma-jasmine-html-reporter', + 'karma-coverage', + ].map((p) => workspaceRootRequire(p)), + jasmineHtmlReporter: { + suppressAll: true, // removes the duplicated traces + }, + coverageReporter: { + dir: path.join(workspaceRoot, 'coverage', coverageFolderName), + subdir: '.', + reporters: [{ type: 'html' }, { type: 'text-summary' }], + }, + reporters: ['progress', 'kjhtml'], + browsers: ['Chrome'], + customLaunchers: { + // Chrome configured to run in a bazel sandbox. + // Disable the use of the gpu and `/dev/shm` because it causes Chrome to + // crash on some environments. + // See: + // https://github.com/puppeteer/puppeteer/blob/v1.0.0/docs/troubleshooting.md#tips + // https://stackoverflow.com/questions/50642308/webdriverexception-unknown-error-devtoolsactiveport-file-doesnt-exist-while-t + ChromeHeadlessNoSandbox: { + base: 'ChromeHeadless', + flags: ['--no-sandbox', '--headless', '--disable-gpu', '--disable-dev-shm-usage'], + }, + }, + restartOnFileChange: true, + }; +} diff --git a/packages/angular/build/src/builders/karma/polyfills-plugin.ts b/packages/angular/build/src/builders/karma/polyfills-plugin.ts new file mode 100644 index 000000000000..5cf1022766ec --- /dev/null +++ b/packages/angular/build/src/builders/karma/polyfills-plugin.ts @@ -0,0 +1,86 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { FilePattern, InlinePluginDef } from 'karma'; +import { createRequire } from 'node:module'; + +const localResolve = createRequire(__filename).resolve; + +export class AngularPolyfillsPlugin { + static readonly $inject = ['config.files']; + + static readonly NAME = 'angular-polyfills'; + + static createPlugin( + polyfillsFile: FilePattern, + jasmineCleanupFiles: FilePattern, + scriptsFiles: FilePattern[], + ): InlinePluginDef { + return { + // This has to be a "reporter" because reporters run _after_ frameworks + // and karma-jasmine-html-reporter injects additional scripts that may + // depend on Jasmine but aren't modules - which means that they would run + // _before_ all module code (including jasmine). + [`reporter:${AngularPolyfillsPlugin.NAME}`]: [ + 'factory', + Object.assign((files: (string | FilePattern)[]) => { + // The correct order is zone.js -> jasmine -> zone.js/testing. + // Jasmine has to see the patched version of the global `setTimeout` + // function so it doesn't cache the unpatched version. And /testing + // needs to see the global `jasmine` object so it can patch it. + const polyfillsIndex = 0; + files.splice(polyfillsIndex, 0, polyfillsFile); + + // Insert just before test_main.js. + const zoneTestingIndex = files.findIndex((f) => { + if (typeof f === 'string') { + return false; + } + + return f.pattern.endsWith('/test_main.js'); + }); + if (zoneTestingIndex === -1) { + throw new Error('Could not find test entrypoint file.'); + } + files.splice(zoneTestingIndex, 0, jasmineCleanupFiles); + + // We need to ensure that all files are served as modules, otherwise + // the order in the files list gets really confusing: Karma doesn't + // set defer on scripts, so all scripts with type=js will run first, + // even if type=module files appeared earlier in `files`. + for (const f of files) { + if (typeof f === 'string') { + throw new Error(`Unexpected string-based file: "${f}"`); + } + if (f.included === false) { + // Don't worry about files that aren't included on the initial + // page load. `type` won't affect them. + continue; + } + if (f.pattern.endsWith('.js') && 'js' === (f.type ?? 'js')) { + f.type = 'module'; + } + } + + // Add "scripts" option files as classic scripts + files.unshift(...scriptsFiles); + + // Add browser sourcemap support as a classic script + files.unshift({ + pattern: localResolve('source-map-support/browser-source-map-support.js'), + included: true, + watched: false, + }); + + // Karma needs a return value for a factory and Karma's multi-reporter expects an `adapters` array + return { adapters: [] }; + }, AngularPolyfillsPlugin), + ], + }; + } +} diff --git a/packages/angular/build/src/builders/karma/progress-reporter.ts b/packages/angular/build/src/builders/karma/progress-reporter.ts new file mode 100644 index 000000000000..908f1c856e6d --- /dev/null +++ b/packages/angular/build/src/builders/karma/progress-reporter.ts @@ -0,0 +1,108 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuilderOutput } from '@angular-devkit/architect'; +import type { Config, ConfigOptions } from 'karma'; +import type { ReadableStreamController } from 'node:stream/web'; +import { writeTestFiles } from '../../utils/test-files'; +import type { ApplicationBuilderInternalOptions } from '../application/options'; +import type { Result } from '../application/results'; +import { ResultKind } from '../application/results'; +import type { LatestBuildFiles } from './assets-middleware'; + +const LATEST_BUILD_FILES_TOKEN = 'angularLatestBuildFiles'; + +interface BuildOptions extends ApplicationBuilderInternalOptions { + // We know that it's always a string since we set it. + outputPath: string; +} + +export function injectKarmaReporter( + buildOptions: BuildOptions, + buildIterator: AsyncIterator, + karmaConfig: Config & ConfigOptions, + controller: ReadableStreamController, +): void { + const reporterName = 'angular-progress-notifier'; + + interface RunCompleteInfo { + exitCode: number; + } + + interface KarmaEmitter { + refreshFiles(): void; + } + + class ProgressNotifierReporter { + static $inject = ['emitter', LATEST_BUILD_FILES_TOKEN]; + // Needed for the karma reporter interface, see https://github.com/angular/angular-cli/issues/31629 + adapters = []; + + constructor( + private readonly emitter: KarmaEmitter, + private readonly latestBuildFiles: LatestBuildFiles, + ) { + this.startWatchingBuild(); + } + + private startWatchingBuild() { + void (async () => { + // This is effectively "for await of but skip what's already consumed". + let isDone = false; // to mark the loop condition as "not constant". + while (!isDone) { + const { done, value: buildOutput } = await buildIterator.next(); + if (done) { + isDone = true; + break; + } + + if (buildOutput.kind === ResultKind.Failure) { + controller.enqueue({ success: false, message: 'Build failed' }); + } else if ( + buildOutput.kind === ResultKind.Incremental || + buildOutput.kind === ResultKind.Full + ) { + if (buildOutput.kind === ResultKind.Full) { + this.latestBuildFiles.files = buildOutput.files; + } else { + this.latestBuildFiles.files = { + ...this.latestBuildFiles.files, + ...buildOutput.files, + }; + } + await writeTestFiles(buildOutput.files, buildOptions.outputPath); + this.emitter.refreshFiles(); + } + } + })(); + } + + onRunComplete = function (_browsers: unknown, results: RunCompleteInfo): void { + if (results.exitCode === 0) { + controller.enqueue({ success: true }); + } else { + controller.enqueue({ success: false }); + } + }; + } + + karmaConfig.reporters ??= []; + karmaConfig.reporters.push(reporterName); + + karmaConfig.plugins ??= []; + karmaConfig.plugins.push({ + [`reporter:${reporterName}`]: [ + 'factory', + Object.assign( + (...args: ConstructorParameters) => + new ProgressNotifierReporter(...args), + ProgressNotifierReporter, + ), + ], + }); +} diff --git a/packages/angular/build/src/builders/karma/tests/behavior/code-coverage_spec.ts b/packages/angular/build/src/builders/karma/tests/behavior/code-coverage_spec.ts index 835f48724dbe..9882af429b76 100644 --- a/packages/angular/build/src/builders/karma/tests/behavior/code-coverage_spec.ts +++ b/packages/angular/build/src/builders/karma/tests/behavior/code-coverage_spec.ts @@ -7,7 +7,6 @@ */ import { setTimeout } from 'node:timers/promises'; -import { tags } from '@angular-devkit/core'; import { last, tap } from 'rxjs'; import { execute } from '../../index'; import { BASE_OPTIONS, KARMA_BUILDER_INFO, describeKarmaBuilder } from '../setup'; @@ -96,12 +95,12 @@ describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { await harness.modifyFile('src/app/app.component.ts', (content) => { return content.replace( `title = 'app'`, - tags.stripIndents` - title = 'app'; + ` +title = 'app'; - async foo() { - return 'foo'; - } +async foo() { + return 'foo'; +} `, ); }); diff --git a/packages/angular/build/src/builders/karma/tests/behavior/fake-async_spec.ts b/packages/angular/build/src/builders/karma/tests/behavior/fake-async_spec.ts index 355ddda8ed43..16da8daf2f55 100644 --- a/packages/angular/build/src/builders/karma/tests/behavior/fake-async_spec.ts +++ b/packages/angular/build/src/builders/karma/tests/behavior/fake-async_spec.ts @@ -35,12 +35,14 @@ describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { } }`, './src/app/app.component.spec.ts': ` + import { provideZoneChangeDetection } from '@angular/core'; import { TestBed, fakeAsync, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(() => TestBed.configureTestingModule({ + providers: [provideZoneChangeDetection()], declarations: [AppComponent] })); diff --git a/packages/angular/build/src/builders/karma/tests/behavior/module-cjs_spec.ts b/packages/angular/build/src/builders/karma/tests/behavior/module-cjs_spec.ts index d5c1c7b3d134..646ee6b605ee 100644 --- a/packages/angular/build/src/builders/karma/tests/behavior/module-cjs_spec.ts +++ b/packages/angular/build/src/builders/karma/tests/behavior/module-cjs_spec.ts @@ -22,6 +22,7 @@ describeKarmaBuilder(execute, KARMA_BUILDER_INFO, (harness, setupTarget) => { await harness.modifyFile('src/tsconfig.spec.json', (content) => { const tsConfig = JSON.parse(content); + tsConfig.compilerOptions.moduleResolution = 'bundler'; tsConfig.compilerOptions.module = 'commonjs'; return JSON.stringify(tsConfig); diff --git a/packages/angular/build/src/builders/karma/utils.ts b/packages/angular/build/src/builders/karma/utils.ts new file mode 100644 index 000000000000..6ce8e33ed9aa --- /dev/null +++ b/packages/angular/build/src/builders/karma/utils.ts @@ -0,0 +1,91 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuilderContext } from '@angular-devkit/architect'; +import { createRequire } from 'node:module'; +import { BuildOutputFileType } from '../../tools/esbuild/bundler-context'; +import { getProjectRootPaths } from '../../utils/project-metadata'; +import { findTests, getTestEntrypoints } from './find-tests'; +import type { NormalizedKarmaBuilderOptions } from './options'; + +const localResolve = createRequire(__filename).resolve; + +export async function getProjectSourceRoot(context: BuilderContext): Promise { + // We have already validated that the project name is set before calling this function. + const projectName = context.target?.project; + if (!projectName) { + return context.workspaceRoot; + } + + const projectMetadata = await context.getProjectMetadata(projectName); + const { projectSourceRoot } = getProjectRootPaths(context.workspaceRoot, projectMetadata); + + return projectSourceRoot; +} + +export function normalizePolyfills( + polyfills: string[] = [], +): [polyfills: string[], jasmineCleanup: string[]] { + const jasmineGlobalEntryPoint = localResolve('./polyfills/jasmine_global.js'); + const jasmineGlobalCleanupEntrypoint = localResolve('./polyfills/jasmine_global_cleanup.js'); + const sourcemapEntrypoint = localResolve('./polyfills/init_sourcemaps.js'); + + const zoneTestingEntryPoint = 'zone.js/testing'; + const polyfillsExludingZoneTesting = polyfills.filter((p) => p !== zoneTestingEntryPoint); + + return [ + polyfillsExludingZoneTesting.concat([jasmineGlobalEntryPoint, sourcemapEntrypoint]), + polyfillsExludingZoneTesting.length === polyfills.length + ? [jasmineGlobalCleanupEntrypoint] + : [jasmineGlobalCleanupEntrypoint, zoneTestingEntryPoint], + ]; +} + +export async function collectEntrypoints( + options: NormalizedKarmaBuilderOptions, + context: BuilderContext, + projectSourceRoot: string, +): Promise> { + // Glob for files to test. + const testFiles = await findTests( + options.include, + options.exclude, + context.workspaceRoot, + projectSourceRoot, + ); + + return getTestEntrypoints(testFiles, { projectSourceRoot, workspaceRoot: context.workspaceRoot }); +} + +export function hasChunkOrWorkerFiles(files: Record): boolean { + return Object.keys(files).some((filename) => { + return /(?:^|\/)(?:worker|chunk)[^/]+\.js$/.test(filename); + }); +} + +/** Returns the first item yielded by the given generator and cancels the execution. */ +export async function first( + generator: AsyncIterable, + { cancel }: { cancel: boolean }, +): Promise<[T, AsyncIterator | null]> { + if (!cancel) { + const iterator: AsyncIterator = generator[Symbol.asyncIterator](); + const firstValue = await iterator.next(); + if (firstValue.done) { + throw new Error('Expected generator to emit at least once.'); + } + + return [firstValue.value, iterator]; + } + + for await (const value of generator) { + return [value, null]; + } + + throw new Error('Expected generator to emit at least once.'); +} diff --git a/packages/angular/build/src/builders/unit-test/builder.ts b/packages/angular/build/src/builders/unit-test/builder.ts index dde40f449742..6f2edd0281d7 100644 --- a/packages/angular/build/src/builders/unit-test/builder.ts +++ b/packages/angular/build/src/builders/unit-test/builder.ts @@ -6,423 +6,383 @@ * found in the LICENSE file at https://angular.dev/license */ -import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; +import { + type BuilderContext, + type BuilderOutput, + targetStringFromTarget, +} from '@angular-devkit/architect'; import assert from 'node:assert'; -import { randomUUID } from 'node:crypto'; -import { createRequire } from 'node:module'; +import { readFile, rm } from 'node:fs/promises'; import path from 'node:path'; import { createVirtualModulePlugin } from '../../tools/esbuild/virtual-module-plugin'; import { assertIsError } from '../../utils/error'; -import { loadEsmModule } from '../../utils/load-esm'; -import { toPosixPath } from '../../utils/path'; +import { writeTestFiles } from '../../utils/test-files'; import { buildApplicationInternal } from '../application'; import type { ApplicationBuilderExtensions, ApplicationBuilderInternalOptions, } from '../application/options'; import { ResultKind } from '../application/results'; -import { OutputHashing } from '../application/schema'; -import { writeTestFiles } from '../karma/application_builder'; -import { findTests, getTestEntrypoints } from '../karma/find-tests'; -import { useKarmaBuilder } from './karma-bridge'; -import { - NormalizedUnitTestBuilderOptions, - injectTestingPolyfills, - normalizeOptions, -} from './options'; +import { normalizeOptions } from './options'; +import type { TestRunner } from './runners/api'; +import { MissingDependenciesError } from './runners/dependency-checker'; import type { Schema as UnitTestBuilderOptions } from './schema'; +import { findTests } from './test-discovery'; export type { UnitTestBuilderOptions }; -type VitestCoverageOption = Exclude; +async function loadTestRunner(runnerName: string): Promise { + // Harden against directory traversal + if (!/^[a-zA-Z0-9-]+$/.test(runnerName)) { + throw new Error( + `Invalid runner name "${runnerName}". Runner names can only contain alphanumeric characters and hyphens.`, + ); + } + + let runnerModule; + try { + runnerModule = await import(`./runners/${runnerName}/index`); + } catch (e) { + assertIsError(e); + if (e.code === 'ERR_MODULE_NOT_FOUND') { + throw new Error(`Unknown test runner "${runnerName}".`); + } + throw new Error( + `Failed to load the '${runnerName}' test runner. The package may be corrupted or improperly installed.\n` + + `Error: ${e.message}`, + ); + } + + const runner = runnerModule.default; + if ( + !runner || + typeof runner.getBuildOptions !== 'function' || + typeof runner.createExecutor !== 'function' + ) { + throw new Error( + `The loaded test runner '${runnerName}' does not appear to be a valid TestRunner implementation.`, + ); + } + + return runner; +} + +function prepareBuildExtensions( + virtualFiles: Record | undefined, + projectSourceRoot: string, + extensions?: ApplicationBuilderExtensions, +): ApplicationBuilderExtensions | undefined { + if (!virtualFiles) { + return extensions; + } + + extensions ??= {}; + extensions.codePlugins ??= []; + for (const [namespace, contents] of Object.entries(virtualFiles)) { + extensions.codePlugins.push( + createVirtualModulePlugin({ + namespace, + loadContent: () => { + return { + contents, + loader: 'js', + resolveDir: projectSourceRoot, + }; + }, + }), + ); + } + + return extensions; +} + +async function* runBuildAndTest( + executor: import('./runners/api').TestExecutor, + applicationBuildOptions: ApplicationBuilderInternalOptions, + context: BuilderContext, + dumpDirectory: string | undefined, + extensions: ApplicationBuilderExtensions | undefined, +): AsyncIterable { + let consecutiveErrorCount = 0; + for await (const buildResult of buildApplicationInternal( + applicationBuildOptions, + context, + extensions, + )) { + if (buildResult.kind === ResultKind.Failure) { + yield { success: false }; + continue; + } else if ( + buildResult.kind !== ResultKind.Full && + buildResult.kind !== ResultKind.Incremental + ) { + assert.fail( + 'A full and/or incremental build result is required from the application builder.', + ); + } + + assert(buildResult.files, 'Builder did not provide result files.'); + + if (dumpDirectory) { + if (buildResult.kind === ResultKind.Full) { + // Full build, so clean the directory + await rm(dumpDirectory, { recursive: true, force: true }); + } else { + // Incremental build, so delete removed files + for (const file of buildResult.removed) { + await rm(path.join(dumpDirectory, file.path), { force: true }); + } + } + await writeTestFiles(buildResult.files, dumpDirectory); + context.logger.info(`Build output files successfully dumped to '${dumpDirectory}'.`); + } + + // Pass the build artifacts to the executor + try { + yield* executor.execute(buildResult); + + // Successful execution resets the failure counter + consecutiveErrorCount = 0; + } catch (e) { + assertIsError(e); + context.logger.error(`An exception occurred during test execution:\n${e.stack ?? e.message}`); + if (e instanceof AggregateError) { + e.errors.forEach((inner) => { + assertIsError(inner); + context.logger.error(inner.stack ?? inner.message); + }); + } + + yield { success: false }; + consecutiveErrorCount++; + } + + if (consecutiveErrorCount >= 3) { + context.logger.error( + 'Test runner process has failed multiple times in a row. Please fix the configuration and restart the process.', + ); + + return; + } + } +} /** * @experimental Direct usage of this function is considered experimental. */ -// eslint-disable-next-line max-lines-per-function export async function* execute( options: UnitTestBuilderOptions, context: BuilderContext, - extensions: ApplicationBuilderExtensions = {}, + extensions?: ApplicationBuilderExtensions, ): AsyncIterable { // Determine project name from builder context target const projectName = context.target?.project; if (!projectName) { - context.logger.error( - `The "${context.builder.builderName}" builder requires a target to be specified.`, - ); + context.logger.error(`The builder requires a target to be specified.`); return; } - context.logger.warn( - `NOTE: The "${context.builder.builderName}" builder is currently EXPERIMENTAL and not ready for production use.`, - ); - - const normalizedOptions = await normalizeOptions(context, projectName, options); - const { projectSourceRoot, workspaceRoot, runnerName } = normalizedOptions; - - // Translate options and use karma builder directly if specified - if (runnerName === 'karma') { - const karmaBridge = await useKarmaBuilder(context, normalizedOptions); - yield* karmaBridge; + // Initialize the test runner and normalize options + let runner; + let normalizedOptions; + try { + normalizedOptions = await normalizeOptions(context, projectName, options); + runner = await loadTestRunner(normalizedOptions.runnerName); + await runner.validateDependencies?.(normalizedOptions); + } catch (e) { + assertIsError(e); + if (e instanceof MissingDependenciesError) { + context.logger.error(e.message); + } else { + context.logger.error( + `An exception occurred during initialization of the test runner:\n${e.stack ?? e.message}`, + ); + } + yield { success: false }; return; } - if (runnerName !== 'vitest') { - context.logger.error('Unknown test runner: ' + runnerName); - - return; - } + if (normalizedOptions.listTests) { + const testFiles = await findTests( + normalizedOptions.include, + normalizedOptions.exclude ?? [], + normalizedOptions.workspaceRoot, + normalizedOptions.projectSourceRoot, + ); - // Find test files - const testFiles = await findTests( - normalizedOptions.include, - normalizedOptions.exclude, - workspaceRoot, - projectSourceRoot, - ); + context.logger.info('Discovered test files:'); + for (const file of testFiles) { + context.logger.info(` ${path.relative(normalizedOptions.workspaceRoot, file)}`); + } - if (testFiles.length === 0) { - context.logger.error('No tests found.'); + yield { success: true }; - return { success: false }; + return; } - const entryPoints = getTestEntrypoints(testFiles, { projectSourceRoot, workspaceRoot }); - entryPoints.set('init-testbed', 'angular:test-bed-init'); - - let vitestNodeModule; - try { - vitestNodeModule = await loadEsmModule('vitest/node'); - } catch (error: unknown) { - assertIsError(error); - if (error.code !== 'ERR_MODULE_NOT_FOUND') { - throw error; + if (runner.isStandalone) { + try { + await using executor = await runner.createExecutor(context, normalizedOptions, undefined); + yield* executor.execute({ + kind: ResultKind.Full, + files: {}, + }); + } catch (e) { + assertIsError(e); + context.logger.error( + `An exception occurred during standalone test execution:\n${e.stack ?? e.message}`, + ); + yield { success: false }; } - context.logger.error( - 'The `vitest` package was not found. Please install the package and rerun the test command.', - ); - return; } - const { startVitest } = vitestNodeModule; - - // Setup test file build options based on application build target options - const buildTargetOptions = (await context.validateOptions( - await context.getTargetOptions(normalizedOptions.buildTarget), - await context.getBuilderNameForTarget(normalizedOptions.buildTarget), - )) as unknown as ApplicationBuilderInternalOptions; - - buildTargetOptions.polyfills = injectTestingPolyfills(buildTargetOptions.polyfills); - - const outputPath = toPosixPath(path.join(context.workspaceRoot, generateOutputPath())); - const buildOptions: ApplicationBuilderInternalOptions = { - ...buildTargetOptions, - watch: normalizedOptions.watch, - incrementalResults: normalizedOptions.watch, - outputPath, - index: false, - browser: undefined, - server: undefined, - outputMode: undefined, - localize: false, - budgets: [], - serviceWorker: false, - appShell: false, - ssr: false, - prerender: false, - sourceMap: { scripts: true, vendor: false, styles: false }, - outputHashing: OutputHashing.None, - optimization: false, - tsConfig: normalizedOptions.tsConfig, - entryPoints, - externalDependencies: [ - 'vitest', - '@vitest/browser/context', - ...(buildTargetOptions.externalDependencies ?? []), - ], - }; - extensions ??= {}; - extensions.codePlugins ??= []; - const virtualTestBedInit = createVirtualModulePlugin({ - namespace: 'angular:test-bed-init', - loadContent: async () => { - const contents: string[] = [ - // Initialize the Angular testing environment - `import { NgModule } from '@angular/core';`, - `import { getTestBed, ɵgetCleanupHook as getCleanupHook } from '@angular/core/testing';`, - `import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';`, - '', - normalizedOptions.providersFile - ? `import providers from './${toPosixPath( - path - .relative(projectSourceRoot, normalizedOptions.providersFile) - .replace(/.[mc]?ts$/, ''), - )}'` - : 'const providers = [];', - '', - // Same as https://github.com/angular/angular/blob/05a03d3f975771bb59c7eefd37c01fa127ee2229/packages/core/testing/src/test_hooks.ts#L21-L29 - `beforeEach(getCleanupHook(false));`, - `afterEach(getCleanupHook(true));`, - '', - `@NgModule({`, - ` providers,`, - `})`, - `export class TestModule {}`, - '', - `getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {`, - ` errorOnUnknownElements: true,`, - ` errorOnUnknownProperties: true,`, - '});', - ]; - - return { - contents: contents.join('\n'), - loader: 'js', - resolveDir: projectSourceRoot, - }; - }, - }); - extensions.codePlugins.unshift(virtualTestBedInit); - - let instance: import('vitest/node').Vitest | undefined; - - // Setup vitest browser options if configured - const { browser, errors } = setupBrowserConfiguration( - normalizedOptions.browsers, - normalizedOptions.debug, - projectSourceRoot, - ); - if (errors?.length) { - errors.forEach((error) => context.logger.error(error)); - - return { success: false }; - } - - // Add setup file entries for TestBed initialization and project polyfills - const setupFiles = ['init-testbed.js', ...normalizedOptions.setupFiles]; - if (buildTargetOptions?.polyfills?.length) { - // Placed first as polyfills may be required by the Testbed initialization - // or other project provided setup files (e.g., zone.js, ECMAScript polyfills). - setupFiles.unshift('polyfills.js'); - } - const debugOptions = normalizedOptions.debug - ? { - inspectBrk: true, - isolate: false, - fileParallelism: false, - } - : {}; + // Get base build options from the buildTarget + let buildTargetOptions: ApplicationBuilderInternalOptions; try { - for await (const result of buildApplicationInternal(buildOptions, context, extensions)) { - if (result.kind === ResultKind.Failure) { - continue; - } else if (result.kind !== ResultKind.Full && result.kind !== ResultKind.Incremental) { - assert.fail( - 'A full and/or incremental build result is required from the application builder.', - ); - } - assert(result.files, 'Builder did not provide result files.'); - - await writeTestFiles(result.files, outputPath); - - instance ??= await startVitest( - 'test', - undefined /* cliFilters */, - { - // Disable configuration file resolution/loading - config: false, - root: workspaceRoot, - project: ['base', projectName], - name: 'base', - include: [], - reporters: normalizedOptions.reporters ?? ['default'], - watch: normalizedOptions.watch, - coverage: generateCoverageOption( - normalizedOptions.codeCoverage, - workspaceRoot, - outputPath, - ), - ...debugOptions, - }, - { - plugins: [ - { - name: 'angular:project-init', - async configureVitest(context) { - // Create a subproject that can be configured with plugins for browser mode. - // Plugins defined directly in the vite overrides will not be present in the - // browser specific Vite instance. - const [project] = await context.injectTestProjects({ - test: { - name: projectName, - root: outputPath, - globals: true, - setupFiles, - // Use `jsdom` if no browsers are explicitly configured. - // `node` is effectively no "environment" and the default. - environment: browser ? 'node' : 'jsdom', - browser, - }, - plugins: [ - { - name: 'angular:html-index', - transformIndexHtml() { - // Add all global stylesheets - return ( - Object.entries(result.files) - // TODO: Expand this to all configured global stylesheets - .filter(([file]) => file === 'styles.css') - .map(([styleUrl]) => ({ - tag: 'link', - attrs: { - 'href': styleUrl, - 'rel': 'stylesheet', - }, - injectTo: 'head', - })) - ); - }, - }, - ], - }); - - // Adjust coverage excludes to not include the otherwise automatically inserted included unit tests. - // Vite does this as a convenience but is problematic for the bundling strategy employed by the - // builder's test setup. To workaround this, the excludes are adjusted here to only automaticallyAdd commentMore actions - // exclude the TypeScript source test files. - project.config.coverage.exclude = [ - ...(normalizedOptions.codeCoverage?.exclude ?? []), - '**/*.{test,spec}.?(c|m)ts', - ]; - }, - }, - ], - }, + const builderName = await context.getBuilderNameForTarget(normalizedOptions.buildTarget); + if (builderName === '@angular/build:application') { + buildTargetOptions = (await context.validateOptions( + await context.getTargetOptions(normalizedOptions.buildTarget), + builderName, + )) as unknown as ApplicationBuilderInternalOptions; + } else if (builderName === '@angular/build:ng-packagr') { + const ngPackagrOptions = await context.validateOptions( + await context.getTargetOptions(normalizedOptions.buildTarget), + builderName, ); - // Check if all the tests pass to calculate the result - const testModules = instance.state.getTestModules(); + buildTargetOptions = await transformNgPackagrOptions( + context, + ngPackagrOptions, + normalizedOptions.projectRoot, + ); + } else { + context.logger.warn( + `The 'buildTarget' is configured to use '${builderName}', which is not supported. ` + + `The 'unit-test' builder is designed to work with '@angular/build:application' or '@angular/build:ng-packagr'. ` + + 'Unexpected behavior or build failures may occur.', + ); - yield { success: testModules.every((testModule) => testModule.ok()) }; + buildTargetOptions = (await context.validateOptions( + await context.getTargetOptions(normalizedOptions.buildTarget), + builderName, + )) as unknown as ApplicationBuilderInternalOptions; } - } finally { - if (normalizedOptions.watch) { - // Vitest will automatically close if not using watch mode - await instance?.close(); - } - } -} - -function findBrowserProvider( - projectResolver: NodeJS.RequireResolve, -): import('vitest/node').BrowserBuiltinProvider | undefined { - // One of these must be installed in the project to use browser testing - const vitestBuiltinProviders = ['playwright', 'webdriverio'] as const; - - for (const providerName of vitestBuiltinProviders) { - try { - projectResolver(providerName); + } catch (e) { + assertIsError(e); + context.logger.error( + `Could not load build target options for "${targetStringFromTarget( + normalizedOptions.buildTarget, + )}".\n` + + `Please check your 'angular.json' configuration.\n` + + `Error: ${e.message}`, + ); + yield { success: false }; - return providerName; - } catch {} + return; } -} -function normalizeBrowserName(browserName: string): string { - // Normalize browser names to match Vitest's expectations for headless but also supports karma's names - // e.g., 'ChromeHeadless' -> 'chrome', 'FirefoxHeadless' - // and 'Chrome' -> 'chrome', 'Firefox' -> 'firefox'. - const normalized = browserName.toLowerCase(); - - return normalized.replace(/headless$/, ''); -} + // Get runner-specific build options + let runnerBuildOptions; + let virtualFiles; + let testEntryPointMappings; + try { + ({ + buildOptions: runnerBuildOptions, + virtualFiles, + testEntryPointMappings, + } = await runner.getBuildOptions(normalizedOptions, buildTargetOptions)); + } catch (e) { + assertIsError(e); + context.logger.error( + `An exception occurred while getting runner-specific build options:\n${e.stack ?? e.message}`, + ); + yield { success: false }; -function setupBrowserConfiguration( - browsers: string[] | undefined, - debug: boolean, - projectSourceRoot: string, -): { browser?: import('vitest/node').BrowserConfigOptions; errors?: string[] } { - if (browsers === undefined) { - return {}; + return; } - const projectResolver = createRequire(projectSourceRoot + '/').resolve; - let errors: string[] | undefined; - try { - projectResolver('@vitest/browser'); - } catch { - errors ??= []; - errors.push( - 'The "browsers" option requires the "@vitest/browser" package to be installed within the project.' + - ' Please install this package and rerun the test command.', + await using executor = await runner.createExecutor( + context, + normalizedOptions, + testEntryPointMappings, ); - } - const provider = findBrowserProvider(projectResolver); - if (!provider) { - errors ??= []; - errors.push( - 'The "browsers" option requires either "playwright" or "webdriverio" to be installed within the project.' + - ' Please install one of these packages and rerun the test command.', + const finalExtensions = prepareBuildExtensions( + virtualFiles, + normalizedOptions.projectSourceRoot, + extensions, ); - } - // Vitest current requires the playwright browser provider to use the inspect-brk option used by "debug" - if (debug && provider !== 'playwright') { - errors ??= []; - errors.push( - 'Debugging browser mode tests currently requires the use of "playwright".' + - ' Please install this package and rerun the test command.', + // Prepare and run the application build + const applicationBuildOptions = { + ...buildTargetOptions, + ...runnerBuildOptions, + watch: normalizedOptions.watch, + progress: normalizedOptions.buildProgress ?? buildTargetOptions.progress, + ...(normalizedOptions.tsConfig ? { tsConfig: normalizedOptions.tsConfig } : {}), + } satisfies ApplicationBuilderInternalOptions; + + const dumpDirectory = normalizedOptions.dumpVirtualFiles + ? path.join(normalizedOptions.cacheOptions.path, 'unit-test', 'output-files') + : undefined; + + yield* runBuildAndTest( + executor, + applicationBuildOptions, + context, + dumpDirectory, + finalExtensions, ); + } catch (e) { + assertIsError(e); + context.logger.error( + `An exception occurred while creating the test executor:\n${e.stack ?? e.message}`, + ); + yield { success: false }; } - - if (errors) { - return { errors }; - } - - const browser = { - enabled: true, - provider, - headless: browsers.some((name) => name.toLowerCase().includes('headless')), - - instances: browsers.map((browserName) => ({ - browser: normalizeBrowserName(browserName), - })), - }; - - return { browser }; } -function generateOutputPath(): string { - const datePrefix = new Date().toISOString().replaceAll(/[-:.]/g, ''); - const uuidSuffix = randomUUID().slice(0, 8); +async function transformNgPackagrOptions( + context: BuilderContext, + options: Record, + projectRoot: string, +): Promise { + const projectPath = options['project']; + + let ngPackagePath: string; + if (projectPath) { + if (typeof projectPath !== 'string') { + throw new Error('ng-packagr builder options "project" property must be a string.'); + } + ngPackagePath = path.join(context.workspaceRoot, projectPath); + } else { + ngPackagePath = path.join(projectRoot, 'ng-package.json'); + } - return path.join('dist', 'test-out', `${datePrefix}-${uuidSuffix}`); -} -function generateCoverageOption( - codeCoverage: NormalizedUnitTestBuilderOptions['codeCoverage'], - workspaceRoot: string, - outputPath: string, -): VitestCoverageOption { - if (!codeCoverage) { - return { - enabled: false, - }; + let ngPackageJson; + try { + ngPackageJson = JSON.parse(await readFile(ngPackagePath, 'utf-8')); + } catch (e) { + assertIsError(e); + throw new Error(`Could not read ng-package.json at ${ngPackagePath}: ${e.message}`); } + const lib = ngPackageJson['lib'] || {}; + const styleIncludePaths = lib['styleIncludePaths'] || []; + const assets = ngPackageJson['assets'] || []; + const inlineStyleLanguage = ngPackageJson['inlineStyleLanguage']; + return { - enabled: true, - excludeAfterRemap: true, - include: [`${toPosixPath(path.relative(workspaceRoot, outputPath))}/**`], - // Special handling for `reporter` due to an undefined value causing upstream failures - ...(codeCoverage.reporters - ? ({ reporter: codeCoverage.reporters } satisfies VitestCoverageOption) - : {}), - }; + stylePreprocessorOptions: styleIncludePaths.length + ? { includePaths: styleIncludePaths } + : undefined, + assets: assets.length ? assets : undefined, + inlineStyleLanguage: typeof inlineStyleLanguage === 'string' ? inlineStyleLanguage : undefined, + } as ApplicationBuilderInternalOptions; } diff --git a/packages/angular/build/src/builders/unit-test/karma-bridge.ts b/packages/angular/build/src/builders/unit-test/karma-bridge.ts deleted file mode 100644 index 7bfe9a1ebe94..000000000000 --- a/packages/angular/build/src/builders/unit-test/karma-bridge.ts +++ /dev/null @@ -1,67 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.dev/license - */ - -import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; -import type { ApplicationBuilderInternalOptions } from '../application/options'; -import type { KarmaBuilderOptions } from '../karma'; -import { type NormalizedUnitTestBuilderOptions, injectTestingPolyfills } from './options'; - -export async function useKarmaBuilder( - context: BuilderContext, - unitTestOptions: NormalizedUnitTestBuilderOptions, -): Promise> { - if (unitTestOptions.debug) { - context.logger.warn( - 'The "karma" test runner does not support the "debug" option. The option will be ignored.', - ); - } - - if (unitTestOptions.setupFiles.length) { - context.logger.warn( - 'The "karma" test runner does not support the "setupFiles" option. The option will be ignored.', - ); - } - - const buildTargetOptions = (await context.validateOptions( - await context.getTargetOptions(unitTestOptions.buildTarget), - await context.getBuilderNameForTarget(unitTestOptions.buildTarget), - )) as unknown as ApplicationBuilderInternalOptions; - - buildTargetOptions.polyfills = injectTestingPolyfills(buildTargetOptions.polyfills); - - const options: KarmaBuilderOptions = { - tsConfig: unitTestOptions.tsConfig, - polyfills: buildTargetOptions.polyfills, - assets: buildTargetOptions.assets, - scripts: buildTargetOptions.scripts, - styles: buildTargetOptions.styles, - inlineStyleLanguage: buildTargetOptions.inlineStyleLanguage, - stylePreprocessorOptions: buildTargetOptions.stylePreprocessorOptions, - externalDependencies: buildTargetOptions.externalDependencies, - loader: buildTargetOptions.loader, - define: buildTargetOptions.define, - include: unitTestOptions.include, - exclude: unitTestOptions.exclude, - sourceMap: buildTargetOptions.sourceMap, - progress: buildTargetOptions.progress, - watch: unitTestOptions.watch, - poll: buildTargetOptions.poll, - preserveSymlinks: buildTargetOptions.preserveSymlinks, - browsers: unitTestOptions.browsers?.join(','), - codeCoverage: !!unitTestOptions.codeCoverage, - codeCoverageExclude: unitTestOptions.codeCoverage?.exclude, - fileReplacements: buildTargetOptions.fileReplacements, - reporters: unitTestOptions.reporters, - webWorkerTsConfig: buildTargetOptions.webWorkerTsConfig, - aot: buildTargetOptions.aot, - }; - - const { execute } = await import('../karma'); - - return execute(options, context); -} diff --git a/packages/angular/build/src/builders/unit-test/options.ts b/packages/angular/build/src/builders/unit-test/options.ts index c1d4b8a308a1..7f8f8db182fe 100644 --- a/packages/angular/build/src/builders/unit-test/options.ts +++ b/packages/angular/build/src/builders/unit-test/options.ts @@ -7,14 +7,35 @@ */ import { type BuilderContext, targetFromTargetString } from '@angular-devkit/architect'; +import { constants, promises as fs } from 'node:fs'; import path from 'node:path'; import { normalizeCacheOptions } from '../../utils/normalize-cache'; import { getProjectRootPaths } from '../../utils/project-metadata'; import { isTTY } from '../../utils/tty'; -import type { Schema as UnitTestBuilderOptions } from './schema'; +import { Runner, type Schema as UnitTestBuilderOptions } from './schema'; export type NormalizedUnitTestBuilderOptions = Awaited>; +async function exists(path: string): Promise { + try { + await fs.access(path, constants.F_OK); + + return true; + } catch { + return false; + } +} + +function normalizeReporterOption( + reporters: unknown[] | undefined, +): [string, Record][] | undefined { + return reporters?.map((entry) => + typeof entry === 'string' + ? ([entry, {}] as [string, Record]) + : (entry as [string, Record]), + ); +} + export async function normalizeOptions( context: BuilderContext, projectName: string, @@ -33,7 +54,35 @@ export async function normalizeOptions( const buildTargetSpecifier = options.buildTarget ?? `::development`; const buildTarget = targetFromTargetString(buildTargetSpecifier, projectName, 'build'); - const { tsConfig, runner, reporters, browsers } = options; + const { runner, browsers, progress, filter, browserViewport, ui, runnerConfig } = options; + + if (ui && runner !== Runner.Vitest) { + throw new Error('The "ui" option is only available for the "vitest" runner.'); + } + + const [width, height] = browserViewport?.split('x').map(Number) ?? []; + + let tsConfig = options.tsConfig; + if (tsConfig) { + const fullTsConfigPath = path.join(workspaceRoot, tsConfig); + if (!(await exists(fullTsConfigPath))) { + throw new Error(`The specified tsConfig file '${tsConfig}' does not exist.`); + } + } else { + const tsconfigSpecPath = path.join(projectRoot, 'tsconfig.spec.json'); + if (await exists(tsconfigSpecPath)) { + // The application builder expects a path relative to the workspace root. + tsConfig = path.relative(workspaceRoot, tsconfigSpecPath); + } + } + + let watch = options.watch ?? isTTY(); + if (options.ui && options.watch === false) { + context.logger.warn( + `The '--ui' option requires watch mode. The '--no-watch' flag will be ignored.`, + ); + watch = true; + } return { // Project/workspace information @@ -44,27 +93,45 @@ export async function normalizeOptions( // Target/configuration specified options buildTarget, include: options.include ?? ['**/*.spec.ts'], - exclude: options.exclude ?? [], - runnerName: runner, - codeCoverage: options.codeCoverage - ? { - exclude: options.codeCoverageExclude, - reporters: options.codeCoverageReporters?.map((entry) => - typeof entry === 'string' - ? ([entry, {}] as [string, Record]) - : (entry as [string, Record]), - ), - } - : undefined, + exclude: options.exclude, + filter, + runnerName: runner ?? Runner.Vitest, + coverage: { + enabled: options.coverage, + exclude: options.coverageExclude, + include: options.coverageInclude, + reporters: normalizeReporterOption(options.coverageReporters), + thresholds: options.coverageThresholds, + // The schema generation tool doesn't support tuple types for items, but the schema validation + // does ensure that the array has exactly two numbers. + watermarks: options.coverageWatermarks as { + statements?: [number, number]; + branches?: [number, number]; + functions?: [number, number]; + lines?: [number, number]; + }, + }, tsConfig, - reporters, + buildProgress: progress, + reporters: normalizeReporterOption(options.reporters), + outputFile: options.outputFile, browsers, - watch: options.watch ?? isTTY(), + browserViewport: width && height ? { width, height } : undefined, + watch, debug: options.debug ?? false, + ui: process.env['CI'] ? false : ui, providersFile: options.providersFile && path.join(workspaceRoot, options.providersFile), setupFiles: options.setupFiles ? options.setupFiles.map((setupFile) => path.join(workspaceRoot, setupFile)) : [], + dumpVirtualFiles: options.dumpVirtualFiles, + listTests: options.listTests, + runnerConfig: + typeof runnerConfig === 'string' + ? runnerConfig.length === 0 + ? true + : path.resolve(workspaceRoot, runnerConfig) + : runnerConfig, }; } diff --git a/packages/angular/build/src/builders/unit-test/runners/api.ts b/packages/angular/build/src/builders/unit-test/runners/api.ts new file mode 100644 index 000000000000..43f65ef68adc --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/api.ts @@ -0,0 +1,82 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; +import type { ApplicationBuilderInternalOptions } from '../../application/options'; +import type { FullResult, IncrementalResult } from '../../application/results'; +import type { NormalizedUnitTestBuilderOptions } from '../options'; + +/** + * Represents the options for a test runner. + */ +export interface RunnerOptions { + /** + * Partial options for the application builder. + * These will be merged with the options from the build target. + */ + buildOptions: Partial; + + /** + * A record of virtual files to be added to the build. + * The key is the file path and the value is the file content. + */ + virtualFiles?: Record; + + /** + * A map of test entry points to their corresponding test files. + * This is used to avoid re-discovering the test files in the executor. + */ + testEntryPointMappings?: Map; +} + +/** + * Represents a stateful test execution session. + * An instance of this is created for each `ng test` command. + */ +export interface TestExecutor { + /** + * Executes tests using the artifacts from a specific build. + * This method can be called multiple times in watch mode. + * + * @param buildResult The output from the application builder. + * @returns An async iterable builder output stream. + */ + execute(buildResult: FullResult | IncrementalResult): AsyncIterable; + + [Symbol.asyncDispose](): Promise; +} + +/** + * Represents the metadata and hooks for a specific test runner. + */ +export interface TestRunner { + readonly name: string; + readonly isStandalone?: boolean; + + validateDependencies?(options: NormalizedUnitTestBuilderOptions): void | Promise; + + getBuildOptions( + options: NormalizedUnitTestBuilderOptions, + baseBuildOptions: Partial, + ): RunnerOptions | Promise; + + /** + * Creates a stateful executor for a test session. + * This is called once at the start of the `ng test` command. + * + * @param context The Architect builder context. + * @param options The normalized unit test options. + * @param testEntryPointMappings A map of test entry points to their corresponding test files. + * @returns A TestExecutor instance that will handle the test runs. + */ + createExecutor( + context: BuilderContext, + options: NormalizedUnitTestBuilderOptions, + testEntryPointMappings: Map | undefined, + ): Promise; +} diff --git a/packages/angular/build/src/builders/unit-test/runners/dependency-checker.ts b/packages/angular/build/src/builders/unit-test/runners/dependency-checker.ts new file mode 100644 index 000000000000..3072bb038464 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/dependency-checker.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { createRequire } from 'node:module'; + +/** + * A custom error class to represent missing dependency errors. + * This is used to avoid printing a stack trace for this expected error. + */ +export class MissingDependenciesError extends Error { + constructor(message: string) { + super(message); + this.name = 'MissingDependenciesError'; + } +} + +type Resolver = (packageName: string) => string; + +export class DependencyChecker { + private readonly resolver: Resolver; + private readonly missingDependencies = new Set(); + + constructor(projectSourceRoot: string) { + this.resolver = createRequire(projectSourceRoot + '/').resolve; + } + + /** + * Checks if a package is installed. + * @param packageName The name of the package to check. + * @returns True if the package is found, false otherwise. + */ + private isInstalled(packageName: string): boolean { + try { + this.resolver(packageName); + + return true; + } catch { + return false; + } + } + + /** + * Verifies that a package is installed and adds it to a list of missing + * dependencies if it is not. + * @param packageName The name of the package to check. + */ + check(packageName: string): void { + if (!this.isInstalled(packageName)) { + this.missingDependencies.add(packageName); + } + } + + /** + * Verifies that at least one of a list of packages is installed. If none are + * installed, a custom error message is added to the list of errors. + * @param packageNames An array of package names to check. + * @param customErrorMessage The error message to use if none of the packages are found. + */ + checkAny(packageNames: string[], customErrorMessage: string): void { + if (packageNames.every((name) => !this.isInstalled(name))) { + // This is a custom error, so we add it directly. + // Using a Set avoids duplicate custom messages. + this.missingDependencies.add(customErrorMessage); + } + } + + /** + * Throws a `MissingDependenciesError` if any dependencies were found to be missing. + * The error message is a formatted list of all missing packages. + */ + report(): void { + if (this.missingDependencies.size === 0) { + return; + } + + let message = 'The following packages are required but were not found:\n'; + for (const name of this.missingDependencies) { + message += ` - ${name}\n`; + } + message += 'Please install the missing packages and rerun the test command.'; + + throw new MissingDependenciesError(message); + } +} diff --git a/packages/angular/build/src/builders/unit-test/runners/karma/executor.ts b/packages/angular/build/src/builders/unit-test/runners/karma/executor.ts new file mode 100644 index 000000000000..0cee5e11cd6f --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/karma/executor.ts @@ -0,0 +1,154 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import type { ApplicationBuilderInternalOptions } from '../../../application/options'; +import type { KarmaBuilderOptions, KarmaBuilderTransformsOptions } from '../../../karma'; +import { type NormalizedUnitTestBuilderOptions, injectTestingPolyfills } from '../../options'; +import type { TestExecutor } from '../api'; + +export class KarmaExecutor implements TestExecutor { + constructor( + private context: BuilderContext, + private options: NormalizedUnitTestBuilderOptions, + ) {} + + async *execute(): AsyncIterable { + const { context, options: unitTestOptions } = this; + + if (unitTestOptions.browserViewport) { + context.logger.warn( + 'The "karma" test runner does not support the "browserViewport" option. The option will be ignored.', + ); + } + + if (unitTestOptions.debug) { + context.logger.warn( + 'The "karma" test runner does not support the "debug" option. The option will be ignored.', + ); + } + + if (unitTestOptions.setupFiles.length) { + context.logger.warn( + 'The "karma" test runner does not support the "setupFiles" option. The option will be ignored.', + ); + } + + if (unitTestOptions.coverage?.include) { + context.logger.warn( + 'The "karma" test runner does not support the "coverageInclude" option. The option will be ignored.', + ); + } + + const buildTargetOptions = (await context.validateOptions( + await context.getTargetOptions(unitTestOptions.buildTarget), + await context.getBuilderNameForTarget(unitTestOptions.buildTarget), + )) as unknown as ApplicationBuilderInternalOptions; + + let karmaConfig: string | undefined; + if (typeof unitTestOptions.runnerConfig === 'string') { + karmaConfig = unitTestOptions.runnerConfig; + context.logger.info(`Using Karma configuration file: ${karmaConfig}`); + } else if (unitTestOptions.runnerConfig) { + const potentialPath = path.join(unitTestOptions.projectRoot, 'karma.conf.js'); + try { + await fs.access(potentialPath); + karmaConfig = potentialPath; + context.logger.info(`Using Karma configuration file: ${karmaConfig}`); + } catch { + context.logger.info('No Karma configuration file found. Using default configuration.'); + } + } + + const karmaOptions: KarmaBuilderOptions = { + karmaConfig, + tsConfig: unitTestOptions.tsConfig ?? buildTargetOptions.tsConfig, + polyfills: injectTestingPolyfills(buildTargetOptions.polyfills), + assets: buildTargetOptions.assets, + scripts: buildTargetOptions.scripts, + styles: buildTargetOptions.styles, + inlineStyleLanguage: buildTargetOptions.inlineStyleLanguage, + stylePreprocessorOptions: buildTargetOptions.stylePreprocessorOptions, + externalDependencies: buildTargetOptions.externalDependencies, + loader: buildTargetOptions.loader, + define: buildTargetOptions.define, + include: unitTestOptions.include, + exclude: unitTestOptions.exclude, + sourceMap: buildTargetOptions.sourceMap, + progress: unitTestOptions.buildProgress ?? buildTargetOptions.progress, + watch: unitTestOptions.watch, + poll: buildTargetOptions.poll, + preserveSymlinks: buildTargetOptions.preserveSymlinks, + browsers: unitTestOptions.browsers?.join(','), + codeCoverage: unitTestOptions.coverage.enabled, + codeCoverageExclude: unitTestOptions.coverage.exclude, + fileReplacements: buildTargetOptions.fileReplacements, + reporters: unitTestOptions.reporters?.map((reporter) => { + // Karma only supports string reporters. + if (Object.keys(reporter[1]).length > 0) { + context.logger.warn( + `The "karma" test runner does not support options for the "${reporter[0]}" reporter. The options will be ignored.`, + ); + } + + return reporter[0]; + }), + webWorkerTsConfig: buildTargetOptions.webWorkerTsConfig, + aot: buildTargetOptions.aot, + }; + + const transformOptions = { + karmaOptions: (options) => { + if (unitTestOptions.filter) { + let filter = unitTestOptions.filter; + if (filter[0] === '/' && filter.at(-1) === '/') { + this.context.logger.warn( + 'The `--filter` option is always a regular expression.' + + 'Leading and trailing `/` are not required and will be ignored.', + ); + } else { + filter = `/${filter}/`; + } + + options.client ??= {}; + options.client.args ??= []; + options.client.args.push('--grep', filter); + } + + // Add coverage options + if (unitTestOptions.coverage.enabled) { + const { thresholds, watermarks } = unitTestOptions.coverage; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const coverageReporter = ((options as any).coverageReporter ??= {}); + + if (thresholds) { + coverageReporter.check = thresholds.perFile + ? { each: thresholds } + : { global: thresholds }; + } + + if (watermarks) { + coverageReporter.watermarks = watermarks; + } + } + + return options; + }, + } satisfies KarmaBuilderTransformsOptions; + + const { execute } = await import('../../../karma'); + + yield* execute(karmaOptions, context, transformOptions); + } + + async [Symbol.asyncDispose](): Promise { + // The Karma builder handles its own teardown + } +} diff --git a/packages/angular/build/src/builders/unit-test/runners/karma/index.ts b/packages/angular/build/src/builders/unit-test/runners/karma/index.ts new file mode 100644 index 000000000000..36eadb255c47 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/karma/index.ts @@ -0,0 +1,51 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { TestRunner } from '../api'; +import { DependencyChecker } from '../dependency-checker'; +import { KarmaExecutor } from './executor'; + +/** + * A declarative definition of the Karma test runner. + */ +const KarmaTestRunner: TestRunner = { + name: 'karma', + isStandalone: true, + + validateDependencies(options) { + const checker = new DependencyChecker(options.projectSourceRoot); + checker.check('karma'); + checker.check('karma-jasmine'); + + // Check for browser launchers + if (options.browsers?.length) { + for (const browser of options.browsers) { + const launcherName = `karma-${browser.toLowerCase().split('headless')[0]}-launcher`; + checker.check(launcherName); + } + } + + if (options.coverage) { + checker.check('karma-coverage'); + } + + checker.report(); + }, + + getBuildOptions() { + return { + buildOptions: {}, + }; + }, + + async createExecutor(context, options) { + return new KarmaExecutor(context, options); + }, +}; + +export default KarmaTestRunner; diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/browser-provider.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/browser-provider.ts new file mode 100644 index 000000000000..3aeeb7afe474 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/browser-provider.ts @@ -0,0 +1,147 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { createRequire } from 'node:module'; +import type { BrowserBuiltinProvider, BrowserConfigOptions } from 'vitest/node'; +import { assertIsError } from '../../../../utils/error'; + +export interface BrowserConfiguration { + browser?: BrowserConfigOptions; + errors?: string[]; +} + +function findBrowserProvider( + projectResolver: NodeJS.RequireResolve, +): BrowserBuiltinProvider | undefined { + const requiresPreview = !!process.versions.webcontainer; + + // One of these must be installed in the project to use browser testing + const vitestBuiltinProviders = requiresPreview + ? (['preview'] as const) + : (['playwright', 'webdriverio', 'preview'] as const); + + for (const providerName of vitestBuiltinProviders) { + try { + projectResolver(`@vitest/browser-${providerName}`); + + return providerName; + } catch {} + } + + return undefined; +} + +function normalizeBrowserName(browserName: string): { browser: string; headless: boolean } { + // Normalize browser names to match Vitest's expectations for headless but also supports karma's names + // e.g., 'ChromeHeadless' -> 'chrome', 'FirefoxHeadless' -> 'firefox' + // and 'Chrome' -> 'chrome', 'Firefox' -> 'firefox'. + const normalized = browserName.toLowerCase(); + const headless = normalized.endsWith('headless'); + + return { + browser: headless ? normalized.slice(0, -8) : normalized, + headless: headless, + }; +} + +export async function setupBrowserConfiguration( + browsers: string[] | undefined, + debug: boolean, + projectSourceRoot: string, + viewport: { width: number; height: number } | undefined, +): Promise { + if (browsers === undefined) { + return {}; + } + + const projectResolver = createRequire(projectSourceRoot + '/').resolve; + let errors: string[] | undefined; + + const providerName = findBrowserProvider(projectResolver); + if (!providerName) { + errors ??= []; + errors.push( + 'The "browsers" option requires either "playwright" or "webdriverio" to be installed within the project.' + + ' Please install one of these packages and rerun the test command.', + ); + } + + let provider: import('vitest/node').BrowserProviderOption | undefined; + if (providerName) { + const providerPackage = `@vitest/browser-${providerName}`; + try { + const providerModule = await import(projectResolver(providerPackage)); + + // Validate that the imported module has the expected structure + const providerFactory = providerModule[providerName]; + if (typeof providerFactory === 'function') { + if ( + providerName === 'playwright' && + process.env['CHROME_BIN']?.includes('rules_browsers') + ) { + // Use the Chrome binary from the 'rules_browsers' toolchain (via CHROME_BIN) + // for Playwright when available to ensure hermetic testing, preventing reliance + // on locally installed or NPM-managed browser versions. + provider = providerFactory({ + launchOptions: { + executablePath: process.env.CHROME_BIN, + }, + }); + } else { + provider = providerFactory(); + } + } else { + errors ??= []; + errors.push( + `The "${providerPackage}" package does not have a valid browser provider export.`, + ); + } + } catch (e) { + assertIsError(e); + errors ??= []; + // Check for a module not found error to provide a more specific message + if (e.code === 'ERR_MODULE_NOT_FOUND') { + errors.push( + `The "browsers" option with "${providerName}" requires the "${providerPackage}" package.` + + ' Please install this package and rerun the test command.', + ); + } else { + // Handle other potential errors during import + errors.push( + `An error occurred while loading the "${providerPackage}" browser provider:\n ${e.message}`, + ); + } + } + } + + if (errors) { + return { errors }; + } + + const isCI = !!process.env['CI']; + const instances = browsers.map(normalizeBrowserName); + if (providerName === 'preview') { + instances.forEach((instance) => { + instance.headless = false; + }); + } else if (isCI) { + instances.forEach((instance) => { + instance.headless = true; + }); + } + + const browser = { + enabled: true, + provider, + ui: !isCI && instances.some((instance) => !instance.headless), + viewport, + instances, + } satisfies BrowserConfigOptions; + + return { browser }; +} diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/browser-provider_spec.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/browser-provider_spec.ts new file mode 100644 index 000000000000..2162ffa6ed5e --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/browser-provider_spec.ts @@ -0,0 +1,163 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { setupBrowserConfiguration } from './browser-provider'; + +describe('setupBrowserConfiguration', () => { + let workspaceRoot: string; + + beforeEach(async () => { + // Create a temporary workspace root + workspaceRoot = await mkdtemp(join(tmpdir(), 'angular-cli-test-')); + await writeFile(join(workspaceRoot, 'package.json'), '{}'); + + // Create a mock @vitest/browser-playwright package + const playwrightPkgPath = join(workspaceRoot, 'node_modules/@vitest/browser-playwright'); + await mkdir(playwrightPkgPath, { recursive: true }); + await writeFile( + join(playwrightPkgPath, 'package.json'), + JSON.stringify({ name: '@vitest/browser-playwright', main: 'index.js' }), + ); + await writeFile( + join(playwrightPkgPath, 'index.js'), + 'module.exports = { playwright: () => ({ name: "playwright" }) };', + ); + }); + + afterEach(async () => { + await rm(workspaceRoot, { recursive: true, force: true }); + }); + + it('should configure headless mode for specific browsers based on name', async () => { + const { browser } = await setupBrowserConfiguration( + ['ChromeHeadless', 'Firefox'], + false, + workspaceRoot, + undefined, + ); + + expect(browser?.enabled).toBeTrue(); + expect(browser?.instances).toEqual([ + { browser: 'chrome', headless: true }, + { browser: 'firefox', headless: false }, + ]); + }); + + it('should force headless mode in CI environment', async () => { + const originalCI = process.env['CI']; + process.env['CI'] = 'true'; + + try { + const { browser } = await setupBrowserConfiguration( + ['Chrome', 'FirefoxHeadless'], + false, + workspaceRoot, + undefined, + ); + + expect(browser?.instances).toEqual([ + { browser: 'chrome', headless: true }, + { browser: 'firefox', headless: true }, + ]); + } finally { + if (originalCI === undefined) { + delete process.env['CI']; + } else { + process.env['CI'] = originalCI; + } + } + }); + + it('should set ui property based on headless instances (local)', async () => { + // Local run (not CI) + const originalCI = process.env['CI']; + delete process.env['CI']; + + try { + // Case 1: All headless -> UI false + let result = await setupBrowserConfiguration( + ['ChromeHeadless'], + false, + workspaceRoot, + undefined, + ); + expect(result.browser?.ui).toBeFalse(); + + // Case 2: Mixed -> UI true + result = await setupBrowserConfiguration( + ['ChromeHeadless', 'Firefox'], + false, + workspaceRoot, + undefined, + ); + expect(result.browser?.ui).toBeTrue(); + } finally { + if (originalCI !== undefined) { + process.env['CI'] = originalCI; + } + } + }); + + it('should disable UI in CI even if headed browsers are requested', async () => { + const originalCI = process.env['CI']; + process.env['CI'] = 'true'; + + try { + const { browser } = await setupBrowserConfiguration( + ['Chrome'], + false, + workspaceRoot, + undefined, + ); + + expect(browser?.ui).toBeFalse(); + // And verify instances are forced to headless + expect(browser?.instances?.[0].headless).toBeTrue(); + } finally { + if (originalCI === undefined) { + delete process.env['CI']; + } else { + process.env['CI'] = originalCI; + } + } + }); + + it('should support Preview provider forcing headless false', async () => { + // Create mock preview package + const previewPkgPath = join(workspaceRoot, 'node_modules/@vitest/browser-preview'); + await mkdir(previewPkgPath, { recursive: true }); + await writeFile( + join(previewPkgPath, 'package.json'), + JSON.stringify({ name: '@vitest/browser-preview', main: 'index.js' }), + ); + await writeFile( + join(previewPkgPath, 'index.js'), + 'module.exports = { preview: () => ({ name: "preview" }) };', + ); + + // Remove playwright mock for this test to force usage of preview + await rm(join(workspaceRoot, 'node_modules/@vitest/browser-playwright'), { + recursive: true, + force: true, + }); + + const { browser } = await setupBrowserConfiguration( + ['ChromeHeadless'], + false, + workspaceRoot, + undefined, + ); + + expect(browser?.provider).toBeDefined(); + // Preview forces headless false + expect(browser?.instances?.[0].headless).toBeFalse(); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts new file mode 100644 index 000000000000..7129ea4fff54 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts @@ -0,0 +1,149 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import path from 'node:path'; +import { toPosixPath } from '../../../../utils/path'; +import type { ApplicationBuilderInternalOptions } from '../../../application/options'; +import { OutputHashing } from '../../../application/schema'; +import { NormalizedUnitTestBuilderOptions, injectTestingPolyfills } from '../../options'; +import { findTests, getTestEntrypoints } from '../../test-discovery'; +import { RunnerOptions } from '../api'; + +function createTestBedInitVirtualFile( + providersFile: string | undefined, + projectSourceRoot: string, + teardown: boolean, + polyfills: string[] = [], +): string { + const usesZoneJS = polyfills.includes('zone.js'); + let providersImport = 'const providers = [];'; + if (providersFile) { + const relativePath = path.relative(projectSourceRoot, providersFile); + const { dir, name } = path.parse(relativePath); + const importPath = toPosixPath(path.join(dir, name)); + providersImport = `import providers from './${importPath}';`; + } + + return ` + // Initialize the Angular testing environment + import { NgModule${usesZoneJS ? ', provideZoneChangeDetection' : ''} } from '@angular/core'; + import { getTestBed, ɵgetCleanupHook as getCleanupHook } from '@angular/core/testing'; + import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing'; + import { afterEach, beforeEach } from 'vitest'; + ${providersImport} + + // The beforeEach and afterEach hooks are registered outside the globalThis guard. + // This ensures that the hooks are always applied, even in non-isolated browser environments. + // Same as https://github.com/angular/angular/blob/05a03d3f975771bb59c7eefd37c01fa127ee2229/packages/core/testing/srcs/test_hooks.ts#L21-L29 + beforeEach(getCleanupHook(false)); + afterEach(getCleanupHook(true)); + + const ANGULAR_TESTBED_SETUP = Symbol.for('@angular/cli/testbed-setup'); + if (!globalThis[ANGULAR_TESTBED_SETUP]) { + globalThis[ANGULAR_TESTBED_SETUP] = true; + + // The Angular TestBed needs to be initialized before any tests are run. + // In a non-isolated environment, this setup file can be executed multiple times. + // The guard condition above ensures that the setup is only performed once. + + @NgModule({ + providers: [${usesZoneJS ? 'provideZoneChangeDetection(), ' : ''}...providers], + }) + class TestModule {} + + getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), { + errorOnUnknownElements: true, + errorOnUnknownProperties: true, + ${teardown === false ? 'teardown: { destroyAfterEach: false },' : ''} + }); + } + `; +} + +function adjustOutputHashing(hashing?: OutputHashing): OutputHashing { + switch (hashing) { + case OutputHashing.All: + case OutputHashing.Media: + // Ensure media is continued to be hashed to avoid overwriting of output media files + return OutputHashing.Media; + default: + return OutputHashing.None; + } +} + +export async function getVitestBuildOptions( + options: NormalizedUnitTestBuilderOptions, + baseBuildOptions: Partial, +): Promise { + const { workspaceRoot, projectSourceRoot, include, exclude = [], watch, providersFile } = options; + + // Find test files + const testFiles = await findTests(include, exclude, workspaceRoot, projectSourceRoot); + if (testFiles.length === 0) { + throw new Error( + 'No tests found matching the following patterns:\n' + + `- Included: ${include.join(', ')}\n` + + (exclude.length ? `- Excluded: ${exclude.join(', ')}\n` : '') + + `\nPlease check the 'test' target configuration in your project's 'angular.json' file.`, + ); + } + + const entryPoints = getTestEntrypoints(testFiles, { + projectSourceRoot, + workspaceRoot, + removeTestExtension: true, + }); + entryPoints.set('init-testbed', 'angular:test-bed-init'); + + // The 'vitest' package is always external for testing purposes + const externalDependencies = ['vitest']; + if (baseBuildOptions.externalDependencies) { + externalDependencies.push(...baseBuildOptions.externalDependencies); + } + + const buildOptions: Partial = { + ...baseBuildOptions, + watch, + incrementalResults: watch, + index: false, + browser: undefined, + server: undefined, + outputMode: undefined, + localize: false, + budgets: [], + serviceWorker: false, + appShell: false, + ssr: false, + prerender: false, + sourceMap: { scripts: true, vendor: false, styles: false }, + outputHashing: adjustOutputHashing(baseBuildOptions.outputHashing), + optimization: false, + entryPoints, + // Enable support for vitest browser prebundling. Excludes can be controlled with a runnerConfig + // and the `optimizeDeps.exclude` option. + externalPackages: true, + externalDependencies, + }; + + buildOptions.polyfills = injectTestingPolyfills(buildOptions.polyfills); + + const testBedInitContents = createTestBedInitVirtualFile( + providersFile, + projectSourceRoot, + !options.debug, + buildOptions.polyfills, + ); + + return { + buildOptions, + virtualFiles: { + 'angular:test-bed-init': testBedInitContents, + }, + testEntryPointMappings: entryPoints, + }; +} diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/configuration.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/configuration.ts new file mode 100644 index 000000000000..6df583350e07 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/configuration.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * @fileoverview + * This file contains utility functions for finding the Vitest base configuration file. + */ + +import { readdir } from 'node:fs/promises'; +import path from 'node:path'; + +/** + * A list of potential Vitest configuration filenames. + * The order of the files is important as the first one found will be used. + */ +const POTENTIAL_CONFIGS = [ + 'vitest-base.config.ts', + 'vitest-base.config.mts', + 'vitest-base.config.cts', + 'vitest-base.config.js', + 'vitest-base.config.mjs', + 'vitest-base.config.cjs', +]; + +/** + * Finds the Vitest configuration file in the given search directories. + * + * @param searchDirs An array of directories to search for the configuration file. + * @returns The path to the configuration file, or `false` if no file is found. + * Returning `false` is used to disable Vitest's default configuration file search. + */ +export async function findVitestBaseConfig(searchDirs: string[]): Promise { + const uniqueDirs = new Set(searchDirs); + for (const dir of uniqueDirs) { + try { + const entries = await readdir(dir, { withFileTypes: true }); + const files = new Set(entries.filter((e) => e.isFile()).map((e) => e.name)); + + for (const potential of POTENTIAL_CONFIGS) { + if (files.has(potential)) { + return path.join(dir, potential); + } + } + } catch { + // Ignore directories that cannot be read + } + } + + return false; +} diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/executor.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/executor.ts new file mode 100644 index 000000000000..ed754d9f9c30 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/executor.ts @@ -0,0 +1,269 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; +import assert from 'node:assert'; +import path from 'node:path'; +import type { Vitest } from 'vitest/node'; +import { + DevServerExternalResultMetadata, + updateExternalMetadata, +} from '../../../../tools/vite/utils'; +import { assertIsError } from '../../../../utils/error'; +import { + type FullResult, + type IncrementalResult, + type ResultFile, + ResultKind, +} from '../../../application/results'; +import { NormalizedUnitTestBuilderOptions } from '../../options'; +import type { TestExecutor } from '../api'; +import { setupBrowserConfiguration } from './browser-provider'; +import { findVitestBaseConfig } from './configuration'; +import { createVitestConfigPlugin, createVitestPlugins } from './plugins'; + +export class VitestExecutor implements TestExecutor { + private vitest: Vitest | undefined; + private normalizePath: ((id: string) => string) | undefined; + private readonly projectName: string; + private readonly options: NormalizedUnitTestBuilderOptions; + private readonly logger: BuilderContext['logger']; + private readonly buildResultFiles = new Map(); + private readonly externalMetadata: DevServerExternalResultMetadata = { + implicitBrowser: [], + implicitServer: [], + explicitBrowser: [], + explicitServer: [], + }; + + // This is a reverse map of the entry points created in `build-options.ts`. + // It is used by the in-memory provider plugin to map the requested test file + // path back to its bundled output path. + // Example: `Map<'/path/to/src/app.spec.ts', 'spec-src-app-spec'>` + private readonly testFileToEntryPoint = new Map(); + private readonly entryPointToTestFile = new Map(); + + constructor( + projectName: string, + options: NormalizedUnitTestBuilderOptions, + testEntryPointMappings: Map | undefined, + logger: BuilderContext['logger'], + ) { + this.projectName = projectName; + this.options = options; + this.logger = logger; + + if (testEntryPointMappings) { + for (const [entryPoint, testFile] of testEntryPointMappings) { + this.testFileToEntryPoint.set(testFile, entryPoint); + this.entryPointToTestFile.set(entryPoint + '.js', testFile); + } + } + } + + async *execute(buildResult: FullResult | IncrementalResult): AsyncIterable { + this.normalizePath ??= (await import('vite')).normalizePath; + + if (buildResult.kind === ResultKind.Full) { + this.buildResultFiles.clear(); + for (const [path, file] of Object.entries(buildResult.files)) { + this.buildResultFiles.set(this.normalizePath(path), file); + } + } else { + for (const file of buildResult.removed) { + this.buildResultFiles.delete(this.normalizePath(file.path)); + } + for (const [path, file] of Object.entries(buildResult.files)) { + this.buildResultFiles.set(this.normalizePath(path), file); + } + } + + updateExternalMetadata(buildResult, this.externalMetadata, undefined, true); + + // Initialize Vitest if not already present. + this.vitest ??= await this.initializeVitest(); + const vitest = this.vitest; + + let testResults; + if (buildResult.kind === ResultKind.Incremental) { + // To rerun tests, Vitest needs the original test file paths, not the output paths. + const modifiedSourceFiles = new Set(); + for (const modifiedFile of [...buildResult.modified, ...buildResult.added]) { + // The `modified` files in the build result are the output paths. + // We need to find the original source file path to pass to Vitest. + const source = this.entryPointToTestFile.get(modifiedFile); + if (source) { + modifiedSourceFiles.add(source); + } + vitest.invalidateFile( + this.normalizePath(path.join(this.options.workspaceRoot, modifiedFile)), + ); + } + + const specsToRerun = []; + for (const file of modifiedSourceFiles) { + vitest.invalidateFile(file); + const specs = vitest.getModuleSpecifications(file); + if (specs) { + specsToRerun.push(...specs); + } + } + + if (specsToRerun.length > 0) { + testResults = await vitest.rerunTestSpecifications(specsToRerun); + } + } + + // Check if all the tests pass to calculate the result + const testModules = testResults?.testModules ?? this.vitest.state.getTestModules(); + + yield { success: testModules.every((testModule) => testModule.ok()) }; + } + + async [Symbol.asyncDispose](): Promise { + await this.vitest?.close(); + } + + private prepareSetupFiles(): string[] { + const { setupFiles } = this.options; + // Add setup file entries for TestBed initialization and project polyfills + const testSetupFiles = ['init-testbed.js', ...setupFiles]; + + // TODO: Provide additional result metadata to avoid needing to extract based on filename + if (this.buildResultFiles.has('polyfills.js')) { + testSetupFiles.unshift('polyfills.js'); + } + + return testSetupFiles; + } + + private async initializeVitest(): Promise { + const { + coverage, + reporters, + outputFile, + workspaceRoot, + browsers, + debug, + watch, + browserViewport, + ui, + projectRoot, + runnerConfig, + projectSourceRoot, + cacheOptions, + } = this.options; + const projectName = this.projectName; + + let vitestNodeModule; + try { + vitestNodeModule = await import('vitest/node'); + } catch (error: unknown) { + assertIsError(error); + if (error.code !== 'ERR_MODULE_NOT_FOUND') { + throw error; + } + throw new Error( + 'The `vitest` package was not found. Please install the package and rerun the test command.', + ); + } + const { startVitest } = vitestNodeModule; + + // Setup vitest browser options if configured + const browserOptions = await setupBrowserConfiguration( + browsers, + debug, + projectSourceRoot, + browserViewport, + ); + if (browserOptions.errors?.length) { + throw new Error(browserOptions.errors.join('\n')); + } + + assert( + this.buildResultFiles.size > 0, + 'buildResult must be available before initializing vitest', + ); + + const testSetupFiles = this.prepareSetupFiles(); + const projectPlugins = createVitestPlugins({ + workspaceRoot, + projectSourceRoot, + projectName, + buildResultFiles: this.buildResultFiles, + testFileToEntryPoint: this.testFileToEntryPoint, + }); + + const debugOptions = debug + ? { + inspectBrk: true, + isolate: false, + fileParallelism: false, + } + : {}; + + const externalConfigPath = + runnerConfig === true + ? await findVitestBaseConfig([projectRoot, workspaceRoot]) + : runnerConfig; + + let project = projectName; + if (debug && browserOptions.browser?.instances) { + if (browserOptions.browser.instances.length > 1) { + this.logger.warn( + 'Multiple browsers are configured, but only the first browser will be used for debugging.', + ); + } + + // When running browser tests, Vitest appends the browser name to the project identifier. + // The project name must match this augmented name to ensure the correct project is targeted. + project = `${projectName} (${browserOptions.browser.instances[0].browser})`; + } + + return startVitest( + 'test', + undefined, + { + config: externalConfigPath, + root: workspaceRoot, + project, + outputFile, + cache: cacheOptions.enabled ? undefined : false, + testNamePattern: this.options.filter, + watch, + ...(typeof ui === 'boolean' ? { ui } : {}), + ...debugOptions, + }, + { + // Note `.vitest` is auto appended to the path. + cacheDir: cacheOptions.path, + server: { + // Disable the actual file watcher. The boolean watch option above should still + // be enabled as it controls other internal behavior related to rerunning tests. + watch: null, + }, + plugins: [ + await createVitestConfigPlugin({ + browser: browserOptions.browser, + coverage, + projectName, + projectSourceRoot, + optimizeDepsInclude: this.externalMetadata.implicitBrowser, + reporters, + setupFiles: testSetupFiles, + projectPlugins, + include: [...this.testFileToEntryPoint.keys()].filter( + // Filter internal entries + (entry) => !entry.startsWith('angular:'), + ), + }), + ], + }, + ); + } +} diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/index.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/index.ts new file mode 100644 index 000000000000..081d635c1a2b --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/index.ts @@ -0,0 +1,74 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import type { TestRunner } from '../api'; +import { DependencyChecker } from '../dependency-checker'; +import { getVitestBuildOptions } from './build-options'; +import { VitestExecutor } from './executor'; + +/** + * A declarative definition of the Vitest test runner. + */ +const VitestTestRunner: TestRunner = { + name: 'vitest', + + validateDependencies(options) { + const checker = new DependencyChecker(options.projectSourceRoot); + checker.check('vitest'); + + if (options.browsers?.length) { + if (process.versions.webcontainer) { + checker.check('@vitest/browser-preview'); + } else { + checker.checkAny( + ['@vitest/browser-playwright', '@vitest/browser-webdriverio', '@vitest/browser-preview'], + 'The "browsers" option requires either ' + + '"@vitest/browser-playwright", "@vitest/browser-webdriverio", or "@vitest/browser-preview" to be installed.', + ); + } + } else { + // DOM emulation is used when no browsers are specified + checker.checkAny( + ['jsdom', 'happy-dom'], + 'A DOM environment is required for non-browser tests. Please install either "jsdom" or "happy-dom".', + ); + } + + if (options.coverage.enabled) { + checker.check('@vitest/coverage-v8'); + } + + checker.report(); + }, + + getBuildOptions(options, baseBuildOptions) { + return getVitestBuildOptions(options, baseBuildOptions); + }, + + async createExecutor(context, options, testEntryPointMappings) { + const projectName = context.target?.project; + assert(projectName, 'The builder requires a target.'); + + if (!!process.versions.webcontainer && options.browsers?.length) { + context.logger.info( + `Webcontainer environment detected. Using '@vitest/browser-preview' for browser-based tests.`, + ); + } + + if (typeof options.runnerConfig === 'string') { + context.logger.info(`Using Vitest configuration file: ${options.runnerConfig}`); + } else if (options.runnerConfig) { + context.logger.info('Automatically searching for and using Vitest configuration file.'); + } + + return new VitestExecutor(projectName, options, testEntryPointMappings, context.logger); + }, +}; + +export default VitestTestRunner; diff --git a/packages/angular/build/src/builders/unit-test/runners/vitest/plugins.ts b/packages/angular/build/src/builders/unit-test/runners/vitest/plugins.ts new file mode 100644 index 000000000000..4bd6666250e7 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/runners/vitest/plugins.ts @@ -0,0 +1,390 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import assert from 'node:assert'; +import { readFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { platform } from 'node:os'; +import path from 'node:path'; +import type { + BrowserConfigOptions, + InlineConfig, + UserWorkspaceConfig, + VitestPlugin, +} from 'vitest/node'; +import { createBuildAssetsMiddleware } from '../../../../tools/vite/middlewares/assets-middleware'; +import { toPosixPath } from '../../../../utils/path'; +import type { ResultFile } from '../../../application/results'; +import type { NormalizedUnitTestBuilderOptions } from '../../options'; + +type VitestPlugins = Awaited>; + +interface PluginOptions { + workspaceRoot: string; + projectSourceRoot: string; + projectName: string; + buildResultFiles: ReadonlyMap; + testFileToEntryPoint: ReadonlyMap; +} + +type VitestCoverageOption = Exclude; + +interface VitestConfigPluginOptions { + browser: BrowserConfigOptions | undefined; + coverage: NormalizedUnitTestBuilderOptions['coverage']; + projectName: string; + projectSourceRoot: string; + reporters?: string[] | [string, object][]; + setupFiles: string[]; + projectPlugins: Exclude; + include: string[]; + optimizeDepsInclude: string[]; +} + +async function findTestEnvironment( + projectResolver: NodeJS.RequireResolve, +): Promise<'jsdom' | 'happy-dom'> { + try { + projectResolver('happy-dom'); + + return 'happy-dom'; + } catch { + // happy-dom is not installed, fallback to jsdom + return 'jsdom'; + } +} + +export async function createVitestConfigPlugin( + options: VitestConfigPluginOptions, +): Promise { + const { + include, + browser, + projectName, + reporters, + setupFiles, + projectPlugins, + projectSourceRoot, + } = options; + + const { mergeConfig } = await import('vitest/config'); + + return { + name: 'angular:vitest-configuration', + async config(config) { + const testConfig = config.test; + + if (testConfig?.projects?.length) { + this.warn( + 'The "test.projects" option in the Vitest configuration file is not supported. ' + + 'The Angular CLI Test system will construct its own project configuration.', + ); + delete testConfig.projects; + } + + if (testConfig?.include) { + this.warn( + 'The "test.include" option in the Vitest configuration file is not supported. ' + + 'The Angular CLI Test system will manage test file discovery.', + ); + delete testConfig.include; + } + + // Merge user-defined plugins from the Vitest config with the CLI's internal plugins. + if (config.plugins) { + const userPlugins = config.plugins.filter( + (plugin) => + // Only inspect objects with a `name` property as these would be the internal injected plugins + !plugin || + typeof plugin !== 'object' || + !('name' in plugin) || + (!plugin.name.startsWith('angular:') && !plugin.name.startsWith('vitest')), + ); + + if (userPlugins.length > 0) { + projectPlugins.push(...userPlugins); + } + delete config.plugins; + } + + // Add browser source map support + if (browser || testConfig?.browser?.enabled) { + projectPlugins.unshift(createSourcemapSupportPlugin()); + setupFiles.unshift('virtual:source-map-support'); + } + + const projectResolver = createRequire(projectSourceRoot + '/').resolve; + + const projectDefaults: UserWorkspaceConfig = { + test: { + setupFiles, + globals: true, + // Default to `false` to align with the Karma/Jasmine experience. + isolate: false, + sequence: { setupFiles: 'list' }, + }, + optimizeDeps: { + noDiscovery: true, + include: options.optimizeDepsInclude, + }, + resolve: { + mainFields: ['es2020', 'module', 'main'], + conditions: ['es2015', 'es2020', 'module', ...(browser ? ['browser'] : [])], + }, + }; + + const { optimizeDeps, resolve } = config; + const projectOverrides: UserWorkspaceConfig = { + test: { + name: projectName, + include, + // CLI provider browser options override, if present + ...(browser ? { browser } : {}), + // If the user has not specified an environment, use a smart default. + ...(!testConfig?.environment + ? { environment: await findTestEnvironment(projectResolver) } + : {}), + }, + plugins: projectPlugins, + optimizeDeps, + resolve, + }; + + const projectBase = mergeConfig(projectDefaults, testConfig ? { test: testConfig } : {}); + const projectConfig = mergeConfig(projectBase, projectOverrides); + + return { + test: { + coverage: await generateCoverageOption( + options.coverage, + testConfig?.coverage, + projectName, + ), + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ...(reporters ? ({ reporters } as any) : {}), + projects: [projectConfig], + }, + }; + }, + }; +} + +async function loadResultFile(file: ResultFile): Promise { + if (file.origin === 'memory') { + return new TextDecoder('utf-8').decode(file.contents); + } + + return readFile(file.inputPath, 'utf-8'); +} + +export function createVitestPlugins(pluginOptions: PluginOptions): VitestPlugins { + const { workspaceRoot, buildResultFiles, testFileToEntryPoint } = pluginOptions; + const isWindows = platform() === 'win32'; + + return [ + { + name: 'angular:test-in-memory-provider', + enforce: 'pre', + resolveId: (id, importer) => { + // Fast path for test entry points. + if (testFileToEntryPoint.has(id)) { + return id; + } + + // Workaround for Vitest in Windows when a fully qualified absolute path is provided with + // a superfluous leading slash. This can currently occur with the `@vitest/coverage-v8` provider + // when it uses `removeStartsWith(url, FILE_PROTOCOL)` to convert a file URL resulting in + // `/D:/tmp_dir/...` instead of `D:/tmp_dir/...`. + if (id[0] === '/' && isWindows) { + const slicedId = id.slice(1); + if (path.isAbsolute(slicedId)) { + return slicedId; + } + } + + if (importer && (id[0] === '.' || id[0] === '/')) { + let fullPath; + if (testFileToEntryPoint.has(importer)) { + fullPath = toPosixPath(path.join(workspaceRoot, id)); + } else { + fullPath = toPosixPath(path.join(path.dirname(importer), id)); + } + + const relativePath = path.relative(workspaceRoot, fullPath); + if (buildResultFiles.has(toPosixPath(relativePath))) { + return fullPath; + } + } + + // Determine the base directory for resolution. + let baseDir: string; + if (importer) { + // If the importer is a test entry point, resolve relative to the workspace root. + // Otherwise, resolve relative to the importer's directory. + baseDir = testFileToEntryPoint.has(importer) ? workspaceRoot : path.dirname(importer); + } else { + // If there's no importer, assume the id is relative to the workspace root. + baseDir = workspaceRoot; + } + + // Construct the full, absolute path and normalize it to POSIX format. + const fullPath = toPosixPath(path.join(baseDir, id)); + + if (testFileToEntryPoint.has(fullPath)) { + return fullPath; + } + + // Check if the resolved path corresponds to a known build artifact. + const relativePath = path.relative(workspaceRoot, fullPath); + if (buildResultFiles.has(toPosixPath(relativePath))) { + return fullPath; + } + + // If the module cannot be resolved from the build artifacts, let other plugins handle it. + return undefined; + }, + load: async (id) => { + assert(buildResultFiles.size > 0, 'buildResult must be available for in-memory loading.'); + + // Attempt to load as a source test file. + const entryPoint = testFileToEntryPoint.get(id); + let outputPath; + if (entryPoint) { + outputPath = entryPoint + '.js'; + + // To support coverage exclusion of the actual test file, the virtual + // test entry point only references the built and bundled intermediate file. + return { + code: `import "./${outputPath}";`, + }; + } else { + // Attempt to load as a built artifact. + const relativePath = path.relative(workspaceRoot, id); + outputPath = toPosixPath(relativePath); + } + + const outputFile = buildResultFiles.get(outputPath); + if (outputFile) { + const code = await loadResultFile(outputFile); + const sourceMapPath = outputPath + '.map'; + const sourceMapFile = buildResultFiles.get(sourceMapPath); + const sourceMapText = sourceMapFile ? await loadResultFile(sourceMapFile) : undefined; + + // Vitest will include files in the coverage report if the sourcemap contains no sources. + // For builder-internal generated code chunks, which are typically helper functions, + // a virtual source is added to the sourcemap to prevent them from being incorrectly + // included in the final coverage report. + const map = sourceMapText ? JSON.parse(sourceMapText) : undefined; + if (map) { + if (!map.sources?.length && !map.sourcesContent?.length && !map.mappings) { + map.sources = ['virtual:builder']; + } + } + + return { + code, + map, + }; + } + }, + configureServer: (server) => { + server.middlewares.use(createBuildAssetsMiddleware(server.config.base, buildResultFiles)); + }, + }, + { + name: 'angular:html-index', + transformIndexHtml: () => { + // Add all global stylesheets + if (buildResultFiles.has('styles.css')) { + return [ + { + tag: 'link', + attrs: { href: 'styles.css', rel: 'stylesheet' }, + injectTo: 'head', + }, + ]; + } + + return []; + }, + }, + ]; +} + +function createSourcemapSupportPlugin(): VitestPlugins[0] { + return { + name: 'angular:source-map-support', + enforce: 'pre', + resolveId(source) { + if (source.includes('virtual:source-map-support')) { + return '\0source-map-support'; + } + }, + async load(id) { + if (id !== '\0source-map-support') { + return; + } + + const packageResolve = createRequire(__filename).resolve; + const supportPath = packageResolve('source-map-support/browser-source-map-support.js'); + + const content = await readFile(supportPath, 'utf-8'); + + // The `source-map-support` library currently relies on `this` being defined in the global scope. + // However, when running in an ESM environment, `this` is undefined. + // To workaround this, we patch the library to use `globalThis` instead of `this`. + return ( + content.replaceAll(/this\.(define|sourceMapSupport|base64js)/g, 'globalThis.$1') + + '\n;globalThis.sourceMapSupport.install();' + ); + }, + }; +} + +async function generateCoverageOption( + optionsCoverage: NormalizedUnitTestBuilderOptions['coverage'], + configCoverage: VitestCoverageOption | undefined, + projectName: string, +): Promise { + let defaultExcludes: string[] = []; + if (optionsCoverage.exclude) { + try { + const vitestConfig = await import('vitest/config'); + defaultExcludes = vitestConfig.coverageConfigDefaults.exclude; + } catch {} + } + + return { + excludeAfterRemap: true, + reportsDirectory: + configCoverage?.reportsDirectory ?? toPosixPath(path.join('coverage', projectName)), + ...(optionsCoverage.enabled !== undefined ? { enabled: optionsCoverage.enabled } : {}), + // Vitest performs a pre-check and a post-check for sourcemaps. + // The pre-check uses the bundled files, so specific bundled entry points and chunks need to be included. + // The post-check uses the original source files, so the user's include is used. + ...(optionsCoverage.include + ? { include: ['spec-*.js', 'chunk-*.js', ...optionsCoverage.include] } + : {}), + thresholds: optionsCoverage.thresholds, + watermarks: optionsCoverage.watermarks, + // Special handling for `exclude`/`reporters` due to an undefined value causing upstream failures + ...(optionsCoverage.exclude + ? { + exclude: [ + // Augment the default exclude https://vitest.dev/config/#coverage-exclude + // with the user defined exclusions + ...optionsCoverage.exclude, + ...defaultExcludes, + ], + } + : {}), + ...(optionsCoverage.reporters + ? ({ reporter: optionsCoverage.reporters } satisfies VitestCoverageOption) + : {}), + }; +} diff --git a/packages/angular/build/src/builders/unit-test/schema.json b/packages/angular/build/src/builders/unit-test/schema.json index 8628bb9725e9..2a3cf27719e8 100644 --- a/packages/angular/build/src/builders/unit-test/schema.json +++ b/packages/angular/build/src/builders/unit-test/schema.json @@ -6,71 +6,104 @@ "properties": { "buildTarget": { "type": "string", - "description": "A build builder target to serve in the format of `project:target[:configuration]`. You can also pass in more than one configuration name as a comma-separated list. Example: `project:target:production,staging`.", + "description": "Specifies the build target to use for the unit test build in the format `project:target[:configuration]`. This defaults to the `build` target of the current project with the `development` configuration. You can also pass a comma-separated list of configurations. Example: `project:target:production,staging`.", "pattern": "^[^:\\s]*:[^:\\s]*(:[^\\s]+)?$" }, "tsConfig": { "type": "string", - "description": "The name of the TypeScript configuration file." + "description": "The path to the TypeScript configuration file, relative to the workspace root. Defaults to `tsconfig.spec.json` in the project root if it exists. If not specified and the default does not exist, the `tsConfig` from the specified `buildTarget` will be used." }, "runner": { "type": "string", - "description": "The name of the test runner to use for test execution.", + "description": "Specifies the test runner to use for test execution.", + "default": "vitest", "enum": ["karma", "vitest"] }, + "runnerConfig": { + "type": ["string", "boolean"], + "description": "Specifies the configuration file for the selected test runner. If a string is provided, it will be used as the path to the configuration file. If `true`, the builder will search for a default configuration file (e.g., `vitest.config.ts` or `karma.conf.js`). If `false`, no external configuration file will be used.\\nFor Vitest, this enables advanced options and the use of custom plugins. Please note that while the file is loaded, the Angular team does not provide direct support for its specific contents or any third-party plugins used within it.", + "default": false + }, "browsers": { - "description": "A list of browsers to use for test execution. If undefined, jsdom on Node.js will be used instead of a browser. For Vitest and Karma, browser names ending with 'Headless' (e.g., 'ChromeHeadless') will enable headless mode for that browser.", + "description": "Specifies the browsers to use for test execution. When not specified, tests are run in a Node.js environment using jsdom. For both Vitest and Karma, browser names ending with 'Headless' (e.g., 'ChromeHeadless') will enable headless mode.", "type": "array", "items": { "type": "string" }, "minItems": 1 }, + "browserViewport": { + "description": "Specifies the browser viewport dimensions for browser-based tests in the format `widthxheight`.", + "type": "string", + "pattern": "^\\d+x\\d+$" + }, "include": { "type": "array", "items": { "type": "string" }, - "default": ["**/*.spec.ts"], - "description": "Globs of files to include, relative to project root. \nThere are 2 special cases:\n - when a path to directory is provided, all spec files ending \".spec.@(ts|tsx)\" will be included\n - when a path to a file is provided, and a matching spec file exists it will be included instead." + "default": ["**/*.spec.ts", "**/*.test.ts"], + "description": "Specifies glob patterns of files to include for testing, relative to the project root. This option also has special handling for directory paths (includes all test files within) and file paths (includes the corresponding test file if one exists)." }, "exclude": { "type": "array", "items": { "type": "string" }, - "default": [], - "description": "Globs of files to exclude, relative to the project root." + "description": "Specifies glob patterns of files to exclude from testing, relative to the project root." + }, + "filter": { + "type": "string", + "description": "Specifies a regular expression pattern to match against test suite and test names. Only tests with a name matching the pattern will be executed. For example, `^App` will run only tests in suites beginning with 'App'." }, "watch": { "type": "boolean", - "description": "Re-run tests when source files change. Defaults to `true` in TTY environments and `false` otherwise." + "description": "Enables watch mode, which re-runs tests when source files change. Defaults to `true` in TTY environments and `false` otherwise." }, "debug": { "type": "boolean", - "description": "Initialize the test runner to support using the Node Inspector for test debugging.", + "description": "Enables debugging mode for tests, allowing the use of the Node Inspector.", "default": false }, - "codeCoverage": { + "ui": { "type": "boolean", - "description": "Output a code coverage report.", + "description": "Enables the Vitest UI for interactive test execution. This option is only available for the Vitest runner." + }, + "coverage": { + "type": "boolean", + "description": "Enables coverage reporting for tests.", "default": false }, - "codeCoverageExclude": { + "coverageInclude": { "type": "array", - "description": "Globs to exclude from code coverage.", + "description": "Specifies glob patterns of files to include in the coverage report.", "items": { "type": "string" - }, - "default": [] + } + }, + "coverageExclude": { + "type": "array", + "description": "Specifies glob patterns of files to exclude from the coverage report.", + "items": { + "type": "string" + } }, - "codeCoverageReporters": { + "coverageReporters": { "type": "array", - "description": "Reporters to use for code coverage results.", + "description": "Specifies the reporters to use for coverage results. Each reporter can be a string representing its name, or a tuple containing the name and an options object. Built-in reporters include 'html', 'lcov', 'lcovonly', 'text', 'text-summary', 'cobertura', 'json', and 'json-summary'.", "items": { "oneOf": [ { - "$ref": "#/definitions/coverage-reporters" + "enum": [ + "html", + "lcov", + "lcovonly", + "text", + "text-summary", + "cobertura", + "json", + "json-summary" + ] }, { "type": "array", @@ -78,7 +111,16 @@ "maxItems": 2, "items": [ { - "$ref": "#/definitions/coverage-reporters" + "enum": [ + "html", + "lcov", + "lcovonly", + "text", + "text-summary", + "cobertura", + "json", + "json-summary" + ] }, { "type": "object" @@ -88,16 +130,122 @@ ] } }, + "coverageThresholds": { + "type": "object", + "description": "Specifies minimum coverage thresholds that must be met. If thresholds are not met, the builder will exit with an error.", + "properties": { + "perFile": { + "type": "boolean", + "description": "When true, thresholds are enforced for each file individually." + }, + "statements": { + "type": "number", + "description": "Minimum percentage of statements covered." + }, + "branches": { + "type": "number", + "description": "Minimum percentage of branches covered." + }, + "functions": { + "type": "number", + "description": "Minimum percentage of functions covered." + }, + "lines": { + "type": "number", + "description": "Minimum percentage of lines covered." + } + }, + "additionalProperties": false + }, + "coverageWatermarks": { + "type": "object", + "description": "Specifies coverage watermarks for the HTML reporter. These determine the color coding for high, medium, and low coverage.", + "properties": { + "statements": { + "type": "array", + "description": "The high and low watermarks for statements coverage. `[low, high]`", + "items": { "type": "number" }, + "minItems": 2, + "maxItems": 2 + }, + "branches": { + "type": "array", + "description": "The high and low watermarks for branches coverage. `[low, high]`", + "items": { "type": "number" }, + "minItems": 2, + "maxItems": 2 + }, + "functions": { + "type": "array", + "description": "The high and low watermarks for functions coverage. `[low, high]`", + "items": { "type": "number" }, + "minItems": 2, + "maxItems": 2 + }, + "lines": { + "type": "array", + "description": "The high and low watermarks for lines coverage. `[low, high]`", + "items": { "type": "number" }, + "minItems": 2, + "maxItems": 2 + } + }, + "additionalProperties": false + }, "reporters": { "type": "array", - "description": "Test runner reporters to use. Directly passed to the test runner.", + "description": "Specifies the reporters to use during test execution. Each reporter can be a string representing its name, or a tuple containing the name and an options object. Built-in reporters include 'default', 'verbose', 'dots', 'json', 'junit', 'tap', 'tap-flat', and 'html'. You can also provide a path to a custom reporter.", "items": { - "type": "string" + "oneOf": [ + { + "anyOf": [ + { + "type": "string" + }, + { + "enum": ["default", "verbose", "dots", "json", "junit", "tap", "tap-flat", "html"] + } + ] + }, + { + "type": "array", + "minItems": 1, + "maxItems": 2, + "items": [ + { + "anyOf": [ + { + "type": "string" + }, + { + "enum": [ + "default", + "verbose", + "dots", + "json", + "junit", + "tap", + "tap-flat", + "html" + ] + } + ] + }, + { + "type": "object" + } + ] + } + ] } }, + "outputFile": { + "type": "string", + "description": "Specifies a file path for the test report, applying only to the first reporter. To configure output files for multiple reporters, use the tuple format `['reporter-name', { outputFile: '...' }]` within the `reporters` option. When not provided, output is written to the console." + }, "providersFile": { "type": "string", - "description": "TypeScript file that exports an array of Angular providers to use during test execution. The array must be a default export.", + "description": "Specifies the path to a TypeScript file that provides an array of Angular providers for the test environment. The file must contain a default export of the provider array.", "minLength": 1 }, "setupFiles": { @@ -105,23 +253,24 @@ "items": { "type": "string" }, - "description": "A list of global setup and configuration files that are included before the test files. The application's polyfills are always included before these files. The Angular Testbed is also initialized prior to the execution of these files." + "description": "A list of paths to global setup files that are executed before the test files. The application's polyfills and the Angular TestBed are always initialized before these files." + }, + "progress": { + "type": "boolean", + "description": "Shows build progress information in the console. Defaults to the `progress` setting of the specified `buildTarget`." + }, + "listTests": { + "type": "boolean", + "description": "Lists all discovered test files and exits the process without building or executing the tests.", + "default": false + }, + "dumpVirtualFiles": { + "type": "boolean", + "description": "Dumps build output files to the `.angular/cache` directory for debugging purposes.", + "default": false, + "visible": false } }, "additionalProperties": false, - "required": ["buildTarget", "tsConfig", "runner"], - "definitions": { - "coverage-reporters": { - "enum": [ - "html", - "lcov", - "lcovonly", - "text", - "text-summary", - "cobertura", - "json", - "json-summary" - ] - } - } + "required": [] } diff --git a/packages/angular/build/src/builders/unit-test/test-discovery.ts b/packages/angular/build/src/builders/unit-test/test-discovery.ts new file mode 100644 index 000000000000..64e9718e48ac --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/test-discovery.ts @@ -0,0 +1,321 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { createHash } from 'node:crypto'; +import { type PathLike, constants, promises as fs } from 'node:fs'; +import os from 'node:os'; +import { basename, dirname, extname, isAbsolute, join, relative } from 'node:path'; +import { glob, isDynamicPattern } from 'tinyglobby'; +import { toPosixPath } from '../../utils/path'; + +/** + * An array of file infix notations that identify a file as a test file. + * For example, `.spec` in `app.component.spec.ts`. + */ +const TEST_FILE_INFIXES = ['.spec', '.test']; + +/** Maximum length for a generated test entrypoint name. */ +const MAX_FILENAME_LENGTH = 128; + +/** + * Finds all test files in the project. This function implements a special handling + * for static paths (non-globs) to improve developer experience. For example, if a + * user provides a path to a component, this function will find the corresponding + * test file. If a user provides a path to a directory, it will find all test + * files within that directory. + * + * @param include Glob patterns of files to include. + * @param exclude Glob patterns of files to exclude. + * @param workspaceRoot The absolute path to the workspace root. + * @param projectSourceRoot The absolute path to the project's source root. + * @returns A unique set of absolute paths to all test files. + */ +export async function findTests( + include: string[], + exclude: string[], + workspaceRoot: string, + projectSourceRoot: string, +): Promise { + const resolvedTestFiles = new Set(); + const dynamicPatterns: string[] = []; + + const projectRootPrefix = toPosixPath(relative(workspaceRoot, projectSourceRoot) + '/'); + const normalizedExcludes = exclude.map((p) => normalizePattern(p, projectRootPrefix)); + + // 1. Separate static and dynamic patterns + for (const pattern of include) { + const normalized = normalizePattern(pattern, projectRootPrefix); + if (isDynamicPattern(pattern)) { + dynamicPatterns.push(normalized); + } else { + const { resolved, unresolved } = await resolveStaticPattern(normalized, projectSourceRoot); + resolved.forEach((file) => resolvedTestFiles.add(file)); + unresolved.forEach((p) => dynamicPatterns.push(p)); + } + } + + // 2. Execute a single glob for all dynamic patterns + if (dynamicPatterns.length > 0) { + const globMatches = await glob(dynamicPatterns, { + cwd: projectSourceRoot, + absolute: true, + expandDirectories: false, + ignore: ['**/node_modules/**', ...normalizedExcludes], + }); + + for (const match of globMatches) { + resolvedTestFiles.add(toPosixPath(match)); + } + } + + // 3. Combine and de-duplicate results + return [...resolvedTestFiles]; +} + +interface TestEntrypointsOptions { + projectSourceRoot: string; + workspaceRoot: string; + removeTestExtension?: boolean; +} + +/** + * Generates unique, dash-delimited bundle names for a set of test files. + * This is used to create distinct output files for each test. + * + * @param testFiles An array of absolute paths to test files. + * @param options Configuration options for generating entry points. + * @returns A map where keys are the generated unique bundle names and values are the original file paths. + */ +export function getTestEntrypoints( + testFiles: string[], + { projectSourceRoot, workspaceRoot, removeTestExtension }: TestEntrypointsOptions, +): Map { + const seen = new Set(); + const roots = [projectSourceRoot, workspaceRoot]; + + return new Map( + Array.from(testFiles, (testFile) => { + const fileName = generateNameFromPath(testFile, roots, !!removeTestExtension); + const baseName = `spec-${fileName}`; + let uniqueName = baseName; + let suffix = 2; + while (seen.has(uniqueName)) { + uniqueName = `${baseName}-${suffix}`.replace(/([^\w](?:spec|test))-([\d]+)$/, '-$2$1'); + ++suffix; + } + seen.add(uniqueName); + + return [uniqueName, testFile]; + }), + ); +} + +/** + * Generates a unique, dash-delimited name from a file path. This is used to + * create a consistent and readable bundle name for a given test file. + * + * @param testFile The absolute path to the test file. + * @param roots An array of root paths to remove from the beginning of the test file path. + * @param removeTestExtension Whether to remove the test file infix and extension from the result. + * @returns A dash-cased name derived from the relative path of the test file. + */ +export function generateNameFromPath( + testFile: string, + roots: string[], + removeTestExtension: boolean, +): string { + const relativePath = removeRoots(testFile, roots.map(toPosixPath)); + + let startIndex = 0; + // Skip leading dots and slashes + while (startIndex < relativePath.length && /^[./\\]$/.test(relativePath[startIndex])) { + startIndex++; + } + + let endIndex = relativePath.length; + if (removeTestExtension) { + const infixes = TEST_FILE_INFIXES.map((p) => p.substring(1)).join('|'); + const match = relativePath.match(new RegExp(`\\.(${infixes})\\.[^.]+$`)); + + if (match?.index) { + endIndex = match.index; + } + } else { + const extIndex = relativePath.lastIndexOf('.'); + if (extIndex > startIndex) { + endIndex = extIndex; + } + } + + // Build the final string in a single pass + let result = ''; + for (let i = startIndex; i < endIndex; i++) { + const char = relativePath[i]; + result += char === '/' || char === '\\' ? '-' : char; + } + + return truncateName(result, relativePath); +} + +/** + * Truncates a generated name if it exceeds the maximum allowed filename length. + * If truncation occurs, the name will be shortened by replacing a middle segment + * with an 8-character SHA256 hash of the original full path to maintain uniqueness. + * + * @param name The generated name to potentially truncate. + * @param originalPath The original full path from which the name was derived. Used for hashing. + * @returns The original name if within limits, or a truncated name with a hash. + */ +function truncateName(name: string, originalPath: string): string { + if (name.length <= MAX_FILENAME_LENGTH) { + return name; + } + + const hash = createHash('sha256').update(originalPath).digest('hex').substring(0, 8); + const availableLength = MAX_FILENAME_LENGTH - hash.length - 2; // 2 for '-' separators + const prefixLength = Math.floor(availableLength / 2); + const suffixLength = availableLength - prefixLength; + + return `${name.substring(0, prefixLength)}-${hash}-${name.substring(name.length - suffixLength)}`; +} + +/** + * Whether the current operating system's filesystem is case-insensitive. + */ +const isCaseInsensitiveFilesystem = os.platform() === 'win32' || os.platform() === 'darwin'; + +/** + * Removes a prefix from the beginning of a string, with conditional case-insensitivity + * based on the operating system's filesystem characteristics. + * + * @param text The string to remove the prefix from. + * @param prefix The prefix to remove. + * @returns The string with the prefix removed, or the original string if the prefix was not found. + */ +function removePrefix(text: string, prefix: string): string { + if (isCaseInsensitiveFilesystem) { + if (text.toLowerCase().startsWith(prefix.toLowerCase())) { + return text.substring(prefix.length); + } + } else { + if (text.startsWith(prefix)) { + return text.substring(prefix.length); + } + } + + return text; +} + +/** + * Removes potential root paths from a file path, returning a relative path. + * If no root path matches, it returns the file's basename. + * + * @param path The file path to process. + * @param roots An array of root paths to attempt to remove. + * @returns A relative path. + */ +function removeRoots(path: string, roots: string[]): string { + for (const root of roots) { + const result = removePrefix(path, root); + // If the prefix was removed, the result will be a different string. + if (result !== path) { + return result; + } + } + + return basename(path); +} + +/** + * Normalizes a glob pattern by converting it to a POSIX path, removing leading + * slashes, and making it relative to the project source root. + * + * @param pattern The glob pattern to normalize. + * @param projectRootPrefix The POSIX-formatted prefix of the project's source root relative to the workspace root. + * @returns A normalized glob pattern. + */ +function normalizePattern(pattern: string, projectRootPrefix: string): string { + const posixPattern = toPosixPath(pattern); + + // Do not modify absolute paths. The globber will handle them correctly. + if (isAbsolute(posixPattern)) { + return posixPattern; + } + + // For relative paths, ensure they are correctly relative to the project source root. + // This involves removing the project root prefix if the user provided a workspace-relative path. + const normalizedRelative = removePrefix(posixPattern, projectRootPrefix); + + return normalizedRelative; +} + +/** + * Resolves a static (non-glob) path. + * + * If the path is a directory, it returns a glob pattern to find all test files + * within that directory. + * + * If the path is a file, it attempts to find a corresponding test file by + * checking for files with the same name and a test infix (e.g., `.spec.ts`). + * + * If no corresponding test file is found, the original path is returned as an + * unresolved pattern. + * + * @param pattern The static path pattern. + * @param projectSourceRoot The absolute path to the project's source root. + * @returns A promise that resolves to an object containing resolved spec files and unresolved patterns. + */ +async function resolveStaticPattern( + pattern: string, + projectSourceRoot: string, +): Promise<{ resolved: string[]; unresolved: string[] }> { + const fullPath = isAbsolute(pattern) ? pattern : join(projectSourceRoot, pattern); + if (await isDirectory(fullPath)) { + const infixes = TEST_FILE_INFIXES.map((p) => p.substring(1)).join('|'); + + return { resolved: [], unresolved: [`${pattern}/**/*.@(${infixes}).@(ts|tsx)`] }; + } + + const fileExt = extname(fullPath); + const baseName = basename(fullPath, fileExt); + + for (const infix of TEST_FILE_INFIXES) { + const potentialSpec = join(dirname(fullPath), `${baseName}${infix}${fileExt}`); + if (await exists(potentialSpec)) { + return { resolved: [toPosixPath(potentialSpec)], unresolved: [] }; + } + } + + if (await exists(fullPath)) { + return { resolved: [toPosixPath(fullPath)], unresolved: [] }; + } + + return { resolved: [], unresolved: [toPosixPath(pattern)] }; +} + +/** Checks if a path exists and is a directory. */ +async function isDirectory(path: PathLike): Promise { + try { + const stats = await fs.stat(path); + + return stats.isDirectory(); + } catch { + return false; + } +} + +/** Checks if a path exists on the file system. */ +async function exists(path: PathLike): Promise { + try { + await fs.access(path, constants.F_OK); + + return true; + } catch { + return false; + } +} diff --git a/packages/angular/build/src/builders/unit-test/test-discovery_spec.ts b/packages/angular/build/src/builders/unit-test/test-discovery_spec.ts new file mode 100644 index 000000000000..617839868d50 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/test-discovery_spec.ts @@ -0,0 +1,91 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { generateNameFromPath } from './test-discovery'; + +describe('generateNameFromPath', () => { + const roots = ['/project/src/', '/project/']; + + it('should generate a dash-cased name from a simple path', () => { + const testFile = '/project/src/app/components/my-component.spec.ts'; + const result = generateNameFromPath(testFile, roots, true); + expect(result).toBe('app-components-my-component'); + }); + + it('should handle Windows-style paths', () => { + const testFile = 'C:\\project\\src\\app\\components\\my-component.spec.ts'; + const result = generateNameFromPath(testFile, ['C:\\project\\src\\'], true); + expect(result).toBe('app-components-my-component'); + }); + + it('should remove test extensions when removeTestExtension is true', () => { + const testFile = '/project/src/app/utils/helpers.test.ts'; + const result = generateNameFromPath(testFile, roots, true); + expect(result).toBe('app-utils-helpers'); + }); + + it('should not remove test extensions when removeTestExtension is false', () => { + const testFile = '/project/src/app/utils/helpers.test.ts'; + const result = generateNameFromPath(testFile, roots, false); + expect(result).toBe('app-utils-helpers.test'); + }); + + it('should handle paths with leading dots and slashes', () => { + const testFile = '/project/src/./app/services/api.service.spec.ts'; + const result = generateNameFromPath(testFile, roots, true); + expect(result).toBe('app-services-api.service'); + }); + + it('should return the basename if no root matches', () => { + const testFile = '/unrelated/path/to/some/file.spec.ts'; + const result = generateNameFromPath(testFile, roots, true); + expect(result).toBe('file'); + }); + + it('should truncate a long file name', () => { + const longPath = + 'a/very/long/path/that/definitely/exceeds/the/maximum/allowed/length/for/a/filename/in/order/to/trigger/the/truncation/logic/in/the/function.spec.ts'; // eslint-disable-line max-len + const testFile = `/project/src/${longPath}`; + const result = generateNameFromPath(testFile, roots, true); + + expect(result.length).toBeLessThanOrEqual(128); + expect(result).toBe( + 'a-very-long-path-that-definitely-exceeds-the-maximum-allowe-9cf40291-me-in-order-to-trigger-the-truncation-logic-in-the-function', + ); // eslint-disable-line max-len + }); + + it('should generate different hashes for different paths with similar truncated names', () => { + const longPath1 = + 'a/very/long/path/that/definitely/exceeds/the/maximum/allowed/length/for/a/filename/in/order/to/trigger/the/truncation/logic/variant-a.spec.ts'; // eslint-disable-line max-len + const longPath2 = + 'a/very/long/path/that/definitely/exceeds/the/maximum/allowed/length/for/a/filename/in/order/to/trigger/the/truncation/logic/variant-b.spec.ts'; // eslint-disable-line max-len + + const testFile1 = `/project/src/${longPath1}`; + const testFile2 = `/project/src/${longPath2}`; + + const result1 = generateNameFromPath(testFile1, roots, true); + const result2 = generateNameFromPath(testFile2, roots, true); + + expect(result1).not.toBe(result2); + // The hash is always 8 characters long and is surrounded by hyphens. + const hashRegex = /-[a-f0-9]{8}-/; + const hash1 = result1.match(hashRegex)?.[0]; + const hash2 = result2.match(hashRegex)?.[0]; + + expect(hash1).toBeDefined(); + expect(hash2).toBeDefined(); + expect(hash1).not.toBe(hash2); + }); + + it('should not truncate a filename that is exactly the max length', () => { + const name = 'a'.repeat(128); + const testFile = `/project/src/${name}.spec.ts`; + const result = generateNameFromPath(testFile, roots, true); + expect(result).toBe(name); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/behavior/runner-config-vitest_spec.ts b/packages/angular/build/src/builders/unit-test/tests/behavior/runner-config-vitest_spec.ts new file mode 100644 index 000000000000..603c69f533ea --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/behavior/runner-config-vitest_spec.ts @@ -0,0 +1,403 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +const VITEST_CONFIG_CONTENT = ` +import { defineConfig } from 'vitest/config'; +export default defineConfig({ + test: { + reporters: [['junit', { outputFile: './vitest-results.xml' }]], + }, +}); +`; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Behavior: "runnerConfig with Vitest runner"', () => { + beforeEach(() => { + setupApplicationTarget(harness); + }); + + it('should use custom reporters defined in runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.ts', + }); + + harness.writeFile('vitest.config.ts', VITEST_CONFIG_CONTENT); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toExist(); + }); + + it('should use custom reportsDirectory defined in runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.ts', + coverage: true, + }); + + harness.writeFile( + 'vitest.config.ts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + coverage: { + reportsDirectory: './custom-coverage-reports', + }, + }, + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('custom-coverage-reports/coverage-final.json').toExist(); + }); + + it('should use default reportsDirectory when not defined in runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + runnerConfig: 'vitest.config.ts', + }); + + harness.writeFile( + 'vitest.config.ts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + coverage: {}, + }, + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('coverage/test/coverage-final.json').toExist(); + }); + + it('should exclude test files based on runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.ts', + }); + + harness.writeFile( + 'vitest.config.ts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + exclude: ['src/app/app.component.spec.ts'], + reporters: ['default', ['json', { outputFile: 'vitest-results.json' }]], + }, + }); + `, + ); + + // Create a second test file that should be executed + harness.writeFile( + 'src/app/app-second.spec.ts', + ` + import { TestBed } from '@angular/core/testing'; + import { AppComponent } from './app.component'; + + describe('AppComponent', () => { + beforeEach(() => TestBed.configureTestingModule({ + declarations: [AppComponent], + })); + + it('should create the app', () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.componentInstance; + expect(app).toBeTruthy(); + }); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + const results = JSON.parse(harness.readFile('vitest-results.json')); + expect(results.numPassedTests).toBe(1); + }); + + it('should allow overriding globals to false via runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.ts', + }); + + harness.writeFile( + 'vitest.config.ts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + globals: false, + }, + }); + `, + ); + + // This test will fail if globals are enabled, because `test` will not be defined. + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { expect } from 'vitest'; + test('should pass', () => { + expect(true).toBe(true); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + }); + + it('should initialize environment even when globals are disabled in runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.ts', + }); + + harness.writeFile( + 'vitest.config.ts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + globals: false, + }, + }); + `, + ); + + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { test, expect } from 'vitest'; + test('should pass', () => { + expect(true).toBe(true); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should fail when a DOM-dependent test is run in a node environment', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.ts', + }); + + harness.writeFile( + 'vitest.config.ts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + environment: 'node', + }, + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); + }); + + it('should warn and ignore "test.projects" option from runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.ts', + }); + + harness.writeFile( + 'vitest.config.ts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + projects: ['./foo.config.ts'], + }, + }); + `, + ); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // TODO: Re-enable once Vite logs are remapped through build system + // expect(logs).toContain( + // jasmine.objectContaining({ + // level: 'warn', + // message: jasmine.stringMatching( + // 'The "test.projects" option in the Vitest configuration file is not supported.', + // ), + // }), + // ); + }); + + it('should warn and ignore "test.include" option from runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.ts', + }); + + harness.writeFile( + 'vitest.config.ts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + include: ['src/app/non-existent.spec.ts'], + }, + }); + `, + ); + + const { result, logs } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + // TODO: Re-enable once Vite logs are remapped through build system + // expect(logs).toContain( + // jasmine.objectContaining({ + // level: 'warn', + // message: jasmine.stringMatching( + // 'The "test.include" option in the Vitest configuration file is not supported.', + // ), + // }), + // ); + }); + + it(`should append "test.setupFiles" (string) from runnerConfig to the CLI's setup`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.ts', + }); + + harness.writeFile( + 'vitest.config.ts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + setupFiles: './src/app/custom-setup.ts', + }, + }); + `, + ); + + harness.writeFile('src/app/custom-setup.ts', `(globalThis as any).customSetupLoaded = true;`); + + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { test, expect } from 'vitest'; + test('should have custom setup loaded', () => { + expect((globalThis as any).customSetupLoaded).toBe(true); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it(`should append "test.setupFiles" (array) from runnerConfig to the CLI's setup`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.ts', + }); + + harness.writeFile( + 'vitest.config.ts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + setupFiles: ['./src/app/custom-setup-1.ts', './src/app/custom-setup-2.ts'], + }, + }); + `, + ); + + harness.writeFile('src/app/custom-setup-1.ts', `(globalThis as any).customSetup1 = true;`); + harness.writeFile('src/app/custom-setup-2.ts', `(globalThis as any).customSetup2 = true;`); + + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { test, expect } from 'vitest'; + test('should have custom setups loaded', () => { + expect((globalThis as any).customSetup1).toBe(true); + expect((globalThis as any).customSetup2).toBe(true); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it('should merge and apply custom Vite plugins from runnerConfig file', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'vitest.config.ts', + }); + + harness.writeFile( + 'vitest.config.ts', + ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + plugins: [ + { + name: 'my-custom-transform-plugin', + transform(code, id) { + if (code.includes('__PLACEHOLDER__')) { + return code.replace('__PLACEHOLDER__', 'transformed by custom plugin'); + } + }, + }, + ], + }); + `, + ); + + harness.writeFile( + 'src/app/app.component.spec.ts', + ` + import { test, expect } from 'vitest'; + test('should have been transformed by custom plugin', () => { + const placeholder = '__PLACEHOLDER__'; + expect(placeholder).toBe('transformed by custom plugin'); + }); + `, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/behavior/watch_rebuild_spec.ts b/packages/angular/build/src/builders/unit-test/tests/behavior/watch_rebuild_spec.ts new file mode 100644 index 000000000000..6ff753c7eac7 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/behavior/watch_rebuild_spec.ts @@ -0,0 +1,68 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Watch Mode Behavior', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it('should run tests when a compilation error is fixed and a test failure is introduced simultaneously', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + watch: true, + }); + + await harness.executeWithCases([ + // 1. Initial success + ({ result }) => { + expect(result?.success).toBeTrue(); + + // 2. Introduce compilation error + harness.writeFiles({ + 'src/app/app.component.spec.ts': ` + import { describe, expect, test } from 'vitest' + describe('AppComponent', () => { + test('should create the app', () => { + expect(true).toBe(true); // Syntax error incoming + const x: string = 1; // Type error + }); + });`, + }); + }, + // 3. Expect compilation error + ({ result }) => { + expect(result?.success).toBeFalse(); + + // 4. Fix compilation error BUT introduce test failure + harness.writeFiles({ + 'src/app/app.component.spec.ts': ` + import { describe, expect, test } from 'vitest' + describe('AppComponent', () => { + test('should create the app', () => { + expect(true).toBe(false); // Logic failure + }); + });`, + }); + }, + // 5. Expect test failure (NOT success, which would happen if the test was skipped) + ({ result }) => { + expect(result?.success).toBeFalse(); + }, + ]); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/browsers_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/browsers_spec.ts index 1acc1ee2924a..afb7aee20d22 100644 --- a/packages/angular/build/src/builders/unit-test/tests/options/browsers_spec.ts +++ b/packages/angular/build/src/builders/unit-test/tests/options/browsers_spec.ts @@ -12,63 +12,36 @@ import { describeBuilder, UNIT_TEST_BUILDER_INFO, setupApplicationTarget, + expectLog, } from '../setup'; describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { - xdescribe('Option: "browsers"', () => { + describe('Option: "browsers"', () => { beforeEach(async () => { setupApplicationTarget(harness); }); - it('should use jsdom when browsers is not provided', async () => { + it('should use DOM emulation when browsers is not provided', async () => { harness.useTarget('test', { ...BASE_OPTIONS, browsers: undefined, }); - const { result, logs } = await harness.executeOnce(); + const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); - expect(logs).toContain( - jasmine.objectContaining({ message: 'Using jsdom in Node.js for test execution.' }), - ); - }); - - it('should fail when browsers is empty', async () => { - harness.useTarget('test', { - ...BASE_OPTIONS, - browsers: [], - }); - - await expectAsync(harness.executeOnce()).toBeRejectedWithError( - /must NOT have fewer than 1 items/, - ); }); - it('should launch a browser when provided', async () => { + it('should fail when a browser is requested but no provider is installed', async () => { harness.useTarget('test', { ...BASE_OPTIONS, browsers: ['chrome'], }); const { result, logs } = await harness.executeOnce(); - expect(result?.success).toBeTrue(); - expect(logs).toContain( - jasmine.objectContaining({ message: jasmine.stringMatching(/Starting browser "chrome"/) }), - ); - }); - - it('should launch a browser in headless mode when specified', async () => { - harness.useTarget('test', { - ...BASE_OPTIONS, - browsers: ['chromeheadless'], - }); - - const { result, logs } = await harness.executeOnce(); - expect(result?.success).toBeTrue(); - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(/Starting browser "chrome" in headless mode/), - }), + expect(result?.success).toBeFalse(); + expectLog( + logs, + `The "browsers" option requires either "@vitest/browser-playwright", "@vitest/browser-webdriverio", or "@vitest/browser-preview" to be installed`, ); }); }); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-exclude_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-exclude_spec.ts index 99a730504bbc..b92e709d2f12 100644 --- a/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-exclude_spec.ts +++ b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-exclude_spec.ts @@ -15,7 +15,7 @@ import { } from '../setup'; describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { - xdescribe('Option: "codeCoverageExclude"', () => { + describe('Option: "coverageExclude"', () => { beforeEach(async () => { setupApplicationTarget(harness); await harness.writeFiles({ @@ -26,26 +26,28 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { it('should not exclude any files from coverage when not provided', async () => { harness.useTarget('test', { ...BASE_OPTIONS, - codeCoverage: true, + coverage: true, + coverageInclude: ['**/*.ts'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); - const summary = harness.readFile('coverage/coverage-summary.json'); - expect(summary).toContain('"src/app/error.ts"'); + const summary = harness.readFile('coverage/test/coverage-final.json'); + expect(summary).toContain('src/app/error.ts"'); }); it('should exclude files from coverage that match the glob pattern', async () => { harness.useTarget('test', { ...BASE_OPTIONS, - codeCoverage: true, - codeCoverageExclude: ['**/error.ts'], + coverage: true, + coverageInclude: ['**/*.ts'], + coverageExclude: ['**/error.ts'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); - const summary = harness.readFile('coverage/coverage-summary.json'); - expect(summary).not.toContain('"src/app/error.ts"'); + const summary = harness.readFile('coverage/test/coverage-final.json'); + expect(summary).not.toContain('src/app/error.ts"'); }); }); }); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-include_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-include_spec.ts new file mode 100644 index 000000000000..6cdbc8bfa23b --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-include_spec.ts @@ -0,0 +1,82 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "coverageInclude"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + await harness.writeFiles({ + 'src/app/included.ts': `export const a = 1;`, + 'src/app/included.spec.ts': ` + import { a } from './included'; + describe('included', () => { + it('should work', () => { + expect(a).toBe(1); + }); + }); + `, + 'src/app/excluded.ts': `export const b = 2;`, + }); + }); + + it('should only include and report coverage for files that match the glob pattern', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + coverageInclude: ['**/included.ts'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + + const summary = JSON.parse(harness.readFile('coverage/test/coverage-final.json')); + const summaryKeys = Object.keys(summary); + + const includedKey = summaryKeys.find((key) => key.endsWith('src/app/included.ts')); + const excludedKey = summaryKeys.find((key) => key.endsWith('src/app/excluded.ts')); + + // Check that the included file is in the report and the excluded one is not. + expect(includedKey).toBeDefined(); + expect(excludedKey).toBeUndefined(); + + // Check that the coverage data for the included file is valid. + const includedCoverage = summary[includedKey!]; + // The file has one statement, and it should have been executed once. + expect(includedCoverage.s['0']).toBe(1); + }); + + it('should only include referenced files when no include pattern is provided', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + // coverageInclude is not provided, so only referenced files should be included. + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + const summary = JSON.parse(harness.readFile('coverage/test/coverage-final.json')); + const summaryKeys = Object.keys(summary); + + const includedKey = summaryKeys.find((key) => key.endsWith('src/app/included.ts')); + const excludedKey = summaryKeys.find((key) => key.endsWith('src/app/excluded.ts')); + + // The included file is referenced by its spec and should be in the report. + expect(includedKey).toBeDefined(); + // The excluded file is not referenced and should NOT be in the report. + expect(excludedKey).toBeUndefined(); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-reporters_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-reporters_spec.ts index 4d0515d43cf3..edebb9e28167 100644 --- a/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-reporters_spec.ts +++ b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage-reporters_spec.ts @@ -15,7 +15,7 @@ import { } from '../setup'; describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { - xdescribe('Option: "codeCoverageReporters"', () => { + describe('Option: "coverageReporters"', () => { beforeEach(async () => { setupApplicationTarget(harness); }); @@ -23,26 +23,26 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { it('should generate a json summary report when specified', async () => { harness.useTarget('test', { ...BASE_OPTIONS, - codeCoverage: true, - codeCoverageReporters: ['json-summary'] as any, + coverage: true, + coverageReporters: ['json-summary'] as any, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); - expect(harness.hasFile('coverage/coverage-summary.json')).toBeTrue(); + expect(harness.hasFile('coverage/test/coverage-summary.json')).toBeTrue(); }); it('should generate multiple reports when specified', async () => { harness.useTarget('test', { ...BASE_OPTIONS, - codeCoverage: true, - codeCoverageReporters: ['json-summary', 'lcov'] as any, + coverage: true, + coverageReporters: ['json-summary', 'lcov'] as any, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); - expect(harness.hasFile('coverage/coverage-summary.json')).toBeTrue(); - expect(harness.hasFile('coverage/lcov.info')).toBeTrue(); + expect(harness.hasFile('coverage/test/coverage-summary.json')).toBeTrue(); + expect(harness.hasFile('coverage/test/lcov.info')).toBeTrue(); }); }); }); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/code-coverage_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage_spec.ts index 0264a58b58e9..f8a8acb60591 100644 --- a/packages/angular/build/src/builders/unit-test/tests/options/code-coverage_spec.ts +++ b/packages/angular/build/src/builders/unit-test/tests/options/code-coverage_spec.ts @@ -15,31 +15,43 @@ import { } from '../setup'; describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { - xdescribe('Option: "codeCoverage"', () => { + describe('Option: "coverage"', () => { beforeEach(async () => { setupApplicationTarget(harness); }); - it('should not generate a code coverage report when codeCoverage is false', async () => { + it('should not generate a code coverage report when coverage is false', async () => { harness.useTarget('test', { ...BASE_OPTIONS, - codeCoverage: false, + coverage: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); - expect(harness.hasFile('coverage/index.html')).toBeFalse(); + harness.expectFile('coverage/test/index.html').toNotExist(); }); - it('should generate a code coverage report when codeCoverage is true', async () => { + it('should generate a code coverage report when coverage is true', async () => { harness.useTarget('test', { ...BASE_OPTIONS, - codeCoverage: true, + coverage: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); - expect(harness.hasFile('coverage/index.html')).toBeTrue(); + harness.expectFile('coverage/test/index.html').toExist(); + }); + + it('should generate a code coverage report when coverage is true', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + coverage: true, + coverageReporters: ['json'] as any, + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('coverage/test/coverage-final.json').content.toContain('app.component.ts'); }); }); }); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/debug_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/debug_spec.ts index 965d08ce3079..9028ee0eb5fd 100644 --- a/packages/angular/build/src/builders/unit-test/tests/options/debug_spec.ts +++ b/packages/angular/build/src/builders/unit-test/tests/options/debug_spec.ts @@ -12,6 +12,8 @@ import { describeBuilder, UNIT_TEST_BUILDER_INFO, setupApplicationTarget, + expectLog, + expectNoLog, } from '../setup'; describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { @@ -28,9 +30,7 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeTrue(); - expect(logs).not.toContain( - jasmine.objectContaining({ message: jasmine.stringMatching(/Node.js inspector/) }), - ); + expectNoLog(logs, /Node.js inspector/); }); it('should enter debug mode when debug is true', async () => { @@ -41,11 +41,7 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeTrue(); - expect(logs).toContain( - jasmine.objectContaining({ - message: jasmine.stringMatching(/Node.js inspector is active/), - }), - ); + expectLog(logs, /Node.js inspector is active/); }); }); }); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/exclude_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/exclude_spec.ts index 036adf8be63f..2c21f7680716 100644 --- a/packages/angular/build/src/builders/unit-test/tests/options/exclude_spec.ts +++ b/packages/angular/build/src/builders/unit-test/tests/options/exclude_spec.ts @@ -15,7 +15,7 @@ import { } from '../setup'; describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { - xdescribe('Option: "exclude"', () => { + describe('Option: "exclude"', () => { beforeEach(async () => { setupApplicationTarget(harness); }); @@ -59,15 +59,5 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); - - it(`should exclude spec that matches the 'exclude' pattern prefixed with a slash`, async () => { - harness.useTarget('test', { - ...BASE_OPTIONS, - exclude: ['/src/app/error.spec.ts'], - }); - - const { result } = await harness.executeOnce(); - expect(result?.success).toBeTrue(); - }); }); }); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/filter_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/filter_spec.ts new file mode 100644 index 000000000000..abcfe5976f94 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/filter_spec.ts @@ -0,0 +1,62 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../builder'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "filter"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + + await harness.writeFiles({ + 'src/app/pass.spec.ts': ` + describe('Passing Suite', () => { + it('should pass', () => { + expect(true).toBe(true); + }); + }); + `, + 'src/app/fail.spec.ts': ` + describe('Failing Suite', () => { + it('should fail', () => { + expect(true).toBe(false); + }); + }); + `, + }); + }); + + it('should only run tests that match the filter regex', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + // This filter should only match the 'should pass' test + filter: 'pass$', + }); + + const { result } = await harness.executeOnce(); + // The overall result should be success because the failing test was filtered out. + expect(result?.success).toBe(true); + }); + + it('should run all tests when no filter is provided', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + // The overall result should be failure because the failing test was included. + expect(result?.success).toBe(false); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/include_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/include_spec.ts index be759449d8bc..f1cdd4a14f0b 100644 --- a/packages/angular/build/src/builders/unit-test/tests/options/include_spec.ts +++ b/packages/angular/build/src/builders/unit-test/tests/options/include_spec.ts @@ -15,7 +15,7 @@ import { } from '../setup'; describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { - xdescribe('Option: "include"', () => { + describe('Option: "include"', () => { beforeEach(async () => { setupApplicationTarget(harness); }); @@ -35,18 +35,10 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { test: 'relative path from workspace to spec', input: ['src/app/app.component.spec.ts'], }, - { - test: 'relative path from workspace to file', - input: ['src/app/app.component.ts'], - }, { test: 'relative path from project root to spec', input: ['app/services/test.service.spec.ts'], }, - { - test: 'relative path from project root to file', - input: ['app/services/test.service.ts'], - }, { test: 'relative path from workspace to directory', input: ['src/app/services'], @@ -59,10 +51,6 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { test: 'glob with spec suffix', input: ['**/*.pipe.spec.ts', '**/*.pipe.spec.ts', '**/*test.service.spec.ts'], }, - { - test: 'glob with forward slash and spec suffix', - input: ['/**/*test.service.spec.ts'], - }, ].forEach((options, index) => { it(`should work with ${options.test} (${index})`, async () => { await harness.writeFiles({ diff --git a/packages/angular/build/src/builders/unit-test/tests/options/list-tests_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/list-tests_spec.ts new file mode 100644 index 000000000000..ade399d1936f --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/list-tests_spec.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "listTests"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + + await harness.writeFiles({ + 'src/app/app.component.spec.ts': + 'describe("AppComponent", () => { it("should...", () => {}); });', + 'src/app/other.spec.ts': 'describe("Other", () => { it("should...", () => {}); });', + 'src/app/ignored.ts': 'export const a = 1;', + }); + }); + + it('should list all discovered tests and exit when true', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + listTests: true, + }); + + const { result, logs } = await harness.executeOnce(); + + // Should succeed and exit without running tests + expect(result?.success).toBe(true); + + // Should log the discovered test files + expect(logs).toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/Discovered test files:/) }), + ); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(/.*app\.component\.spec\.ts/), + }), + ); + expect(logs).toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/.*other\.spec\.ts/) }), + ); + expect(logs).not.toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/.*ignore\.ts/) }), + ); + + // Should NOT log output from the test runner (since it shouldn't run) + expect(logs).not.toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(/Application bundle generation complete/), + }), + ); + }); + + it('should not list tests and should run them as normal when false', async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + listTests: false, + }); + + const { result, logs } = await harness.executeOnce(); + + // Should succeed because the tests pass + expect(result?.success).toBe(true); + + // Should NOT log the discovered test files + expect(logs).not.toContain( + jasmine.objectContaining({ message: jasmine.stringMatching(/Discovered test files:/) }), + ); + + // Should log output from the test runner + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching(/Application bundle generation complete/), + }), + ); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/providers-file_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/providers-file_spec.ts index d5b64923d70f..d69f6480c54d 100644 --- a/packages/angular/build/src/builders/unit-test/tests/options/providers-file_spec.ts +++ b/packages/angular/build/src/builders/unit-test/tests/options/providers-file_spec.ts @@ -15,7 +15,7 @@ import { } from '../setup'; describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { - xdescribe('Option: "providersFile"', () => { + describe('Option: "providersFile"', () => { beforeEach(async () => { setupApplicationTarget(harness); }); @@ -26,10 +26,12 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { providersFile: 'src/my.providers.ts', }); - const { result, error } = await harness.executeOnce({ outputLogsOnFailure: false }); - expect(result).toBeUndefined(); - expect(error?.message).toMatch( - `The specified providers file "src/my.providers.ts" does not exist.`, + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBeFalse(); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('Could not resolve "./my.providers"'), + }), ); }); @@ -42,6 +44,14 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { `, }); + await harness.modifyFile('src/tsconfig.spec.json', (content) => { + const tsConfig = JSON.parse(content); + tsConfig.files ??= []; + tsConfig.files.push('my.providers.ts'); + + return JSON.stringify(tsConfig); + }); + harness.useTarget('test', { ...BASE_OPTIONS, providersFile: 'src/my.providers.ts', diff --git a/packages/angular/build/src/builders/unit-test/tests/options/reporter_and_output_file_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/reporter_and_output_file_spec.ts new file mode 100644 index 000000000000..31fc1a7bfe95 --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/reporter_and_output_file_spec.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Options: "reporter" and "outputFile"', () => { + beforeEach(async () => { + setupApplicationTarget(harness); + }); + + it(`should output a JSON report`, async () => { + await harness.removeFile('src/app/app.component.spec.ts'); + await harness.writeFiles({ + 'src/app/services/test.service.spec.ts': ` + describe('TestService', () => { + it('should succeed', () => { + expect(true).toBe(true); + }); + });`, + }); + + harness.useTarget('test', { + ...BASE_OPTIONS, + reporters: ['json'], + outputFile: 'test-report.json', + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + const reportContent = await harness.readFile('test-report.json'); + expect(reportContent).toContain('TestService'); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/reporters_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/reporters_spec.ts index 657d688fb6dc..89ac5804e37e 100644 --- a/packages/angular/build/src/builders/unit-test/tests/options/reporters_spec.ts +++ b/packages/angular/build/src/builders/unit-test/tests/options/reporters_spec.ts @@ -15,34 +15,66 @@ import { } from '../setup'; describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { - xdescribe('Option: "reporters"', () => { - beforeEach(async () => { + describe('Option: "reporters"', () => { + beforeEach(() => { setupApplicationTarget(harness); }); - it('should use the default reporter when none is specified', async () => { + it(`should support a single reporter`, async () => { harness.useTarget('test', { ...BASE_OPTIONS, + reporters: ['json'], }); - const { result, logs } = await harness.executeOnce(); + const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); - expect(logs).toContain( - jasmine.objectContaining({ message: jasmine.stringMatching(/DefaultReporter/) }), - ); }); - it('should use a custom reporter when specified', async () => { + it(`should support multiple reporters`, async () => { harness.useTarget('test', { ...BASE_OPTIONS, - reporters: ['json'], + reporters: ['json', 'verbose'], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + }); + + it(`should support a single reporter with options`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + reporters: [['json', { outputFile: 'a.json' }]], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('a.json').toExist(); + }); + + it(`should support multiple reporters with options`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + reporters: [ + ['json', { outputFile: 'a.json' }], + ['junit', { outputFile: 'a.xml' }], + ], + }); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + harness.expectFile('a.json').toExist(); + harness.expectFile('a.xml').toExist(); + }); + + it(`should support multiple reporters with and without options`, async () => { + harness.useTarget('test', { + ...BASE_OPTIONS, + reporters: [['json', { outputFile: 'a.json' }], 'verbose', 'default'], }); - const { result, logs } = await harness.executeOnce(); + const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); - expect(logs).toContain( - jasmine.objectContaining({ message: jasmine.stringMatching(/JsonReporter/) }), - ); + harness.expectFile('a.json').toExist(); }); }); }); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/runner-config_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/runner-config_spec.ts new file mode 100644 index 000000000000..b061b88e990c --- /dev/null +++ b/packages/angular/build/src/builders/unit-test/tests/options/runner-config_spec.ts @@ -0,0 +1,129 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { execute } from '../../index'; +import { + BASE_OPTIONS, + describeBuilder, + UNIT_TEST_BUILDER_INFO, + setupApplicationTarget, +} from '../setup'; + +const VITEST_CONFIG_CONTENT = ` +import { defineConfig } from 'vitest/config'; +export default defineConfig({ + test: { + reporters: [['junit', { outputFile: './vitest-results.xml' }]], + }, +}); +`; + +describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { + describe('Option: "runnerConfig"', () => { + beforeEach(() => { + setupApplicationTarget(harness); + }); + + describe('Vitest Runner', () => { + it('should use a specified config file path', async () => { + harness.writeFile('custom-vitest.config.ts', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: 'custom-vitest.config.ts', + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toExist(); + }); + + it('should search for a config file when `true`', async () => { + harness.writeFile('vitest-base.config.ts', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toExist(); + }); + + it('should ignore config file when `false`', async () => { + harness.writeFile('vitest-base.config.ts', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: false, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toNotExist(); + }); + + it('should ignore config file by default', async () => { + harness.writeFile('vitest-base.config.ts', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toNotExist(); + }); + + it('should find and use a `vitest-base.config.mts` in the project root', async () => { + harness.writeFile('vitest-base.config.mts', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toExist(); + }); + + it('should find and use a `vitest-base.config.js` in the workspace root', async () => { + // This file should be ignored because the new logic looks for `vitest-base.config.*`. + harness.writeFile('vitest.config.ts', VITEST_CONFIG_CONTENT); + // The workspace root is the directory containing the project root in the test harness. + harness.writeFile('vitest-base.config.js', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toExist(); + }); + + it('should fallback to in-memory config when no base config is found', async () => { + // This file should be ignored because the new logic looks for `vitest-base.config.*` + // and when `runnerConfig` is true, it should not fall back to the default search. + harness.writeFile('vitest.config.ts', VITEST_CONFIG_CONTENT); + harness.useTarget('test', { + ...BASE_OPTIONS, + runnerConfig: true, + }); + + const { result } = await harness.executeOnce(); + + expect(result?.success).toBeTrue(); + harness.expectFile('vitest-results.xml').toNotExist(); + }); + }); + }); +}); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/setup-files_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/setup-files_spec.ts index 8a461be4fd1f..5f888ed7ff64 100644 --- a/packages/angular/build/src/builders/unit-test/tests/options/setup-files_spec.ts +++ b/packages/angular/build/src/builders/unit-test/tests/options/setup-files_spec.ts @@ -12,6 +12,7 @@ import { describeBuilder, UNIT_TEST_BUILDER_INFO, setupApplicationTarget, + expectLog, } from '../setup'; describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { @@ -50,7 +51,7 @@ describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeTrue(); - expect(logs).toContain(jasmine.objectContaining({ message: 'Hello from setup.ts' })); + expectLog(logs, 'Hello from setup.ts'); }); }); }); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/tsconfig_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/tsconfig_spec.ts index 85723f71c4bf..101f07c1d12e 100644 --- a/packages/angular/build/src/builders/unit-test/tests/options/tsconfig_spec.ts +++ b/packages/angular/build/src/builders/unit-test/tests/options/tsconfig_spec.ts @@ -12,43 +12,48 @@ import { describeBuilder, UNIT_TEST_BUILDER_INFO, setupApplicationTarget, + expectLog, } from '../setup'; describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { - xdescribe('Option: "tsConfig"', () => { + describe('Option: "tsConfig"', () => { beforeEach(async () => { setupApplicationTarget(harness); }); - it('should fail when tsConfig is not provided', async () => { + it('should use "tsconfig.spec.json" by default when it exists', async () => { const { tsConfig, ...rest } = BASE_OPTIONS; - harness.useTarget('test', rest as any); + harness.useTarget('test', rest); - await expectAsync(harness.executeOnce()).toBeRejectedWithError(/"tsConfig" is required/); + // Create tsconfig.spec.json + await harness.writeFile( + 'tsconfig.spec.json', + `{ "extends": "./tsconfig.json", "compilerOptions": { "types": ["jasmine"] }, "include": ["src/**/*.ts"] }`, + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBeTrue(); + // TODO: Add expectation that the file was used. }); - it('should fail when tsConfig is empty', async () => { - harness.useTarget('test', { - ...BASE_OPTIONS, - tsConfig: '', - }); + it('should use build target tsConfig when "tsconfig.spec.json" does not exist', async () => { + const { tsConfig, ...rest } = BASE_OPTIONS; + harness.useTarget('test', rest); - await expectAsync(harness.executeOnce()).toBeRejectedWithError( - /must NOT have fewer than 1 characters/, - ); + // The build target tsconfig is not setup to build the tests and should fail + const { result } = await harness.executeOnce(); + expect(result?.success).toBeFalse(); }); - it('should fail when tsConfig does not exist', async () => { + it('should fail when user specified tsConfig does not exist', async () => { harness.useTarget('test', { ...BASE_OPTIONS, - tsConfig: 'src/tsconfig.spec.json', + tsConfig: 'random/tsconfig.spec.json', }); - const { result, error } = await harness.executeOnce({ outputLogsOnFailure: false }); - expect(result).toBeUndefined(); - expect(error?.message).toMatch( - `The specified tsConfig file "src/tsconfig.spec.json" does not exist.`, - ); + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBeFalse(); + expectLog(logs, `The specified tsConfig file 'random/tsconfig.spec.json' does not exist.`); }); }); }); diff --git a/packages/angular/build/src/builders/unit-test/tests/options/watch_spec.ts b/packages/angular/build/src/builders/unit-test/tests/options/watch_spec.ts index 98434f302d57..d1840beb4a96 100644 --- a/packages/angular/build/src/builders/unit-test/tests/options/watch_spec.ts +++ b/packages/angular/build/src/builders/unit-test/tests/options/watch_spec.ts @@ -15,7 +15,7 @@ import { } from '../setup'; describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => { - xdescribe('Option: "watch"', () => { + describe('Option: "watch"', () => { beforeEach(async () => { setupApplicationTarget(harness); }); diff --git a/packages/angular/build/src/builders/unit-test/tests/setup.ts b/packages/angular/build/src/builders/unit-test/tests/setup.ts index 80e0426ec3e4..e6770e115789 100644 --- a/packages/angular/build/src/builders/unit-test/tests/setup.ts +++ b/packages/angular/build/src/builders/unit-test/tests/setup.ts @@ -11,10 +11,10 @@ import { readFileSync } from 'node:fs'; import path from 'node:path'; import { BuilderHarness } from '../../../../../../../modules/testing/builder/src'; import { - ApplicationBuilderOptions as AppilicationSchema, + ApplicationBuilderOptions as ApplicationSchema, buildApplication, } from '../../../builders/application'; -import { Schema } from '../schema'; +import { Runner, Schema } from '../schema'; // TODO: Consider using package.json imports field instead of relative path // after the switch to rules_js. @@ -33,7 +33,7 @@ export const APPLICATION_BUILDER_INFO = Object.freeze({ * Contains all required application builder fields. * Also disables progress reporting to minimize logging output. */ -export const APPLICATION_BASE_OPTIONS = Object.freeze({ +export const APPLICATION_BASE_OPTIONS = Object.freeze({ index: 'src/index.html', browser: 'src/main.ts', outputPath: 'dist', @@ -61,7 +61,7 @@ export const UNIT_TEST_BUILDER_INFO = Object.freeze({ export const BASE_OPTIONS = Object.freeze({ buildTarget: 'test:build', tsConfig: 'src/tsconfig.spec.json', - runner: 'vitest' as any, + runner: Runner.Vitest, }); /** @@ -84,7 +84,7 @@ let applicationSchema: json.schema.JsonSchema | undefined; */ export function setupApplicationTarget( harness: BuilderHarness, - extraOptions?: Partial, + extraOptions?: Partial, ): void { applicationSchema ??= JSON.parse( readFileSync(APPLICATION_BUILDER_INFO.schemaPath, 'utf8'), @@ -95,6 +95,7 @@ export function setupApplicationTarget( buildApplication, { ...APPLICATION_BASE_OPTIONS, + polyfills: ['zone.js', '@angular/localize/init'], ...extraOptions, }, { diff --git a/packages/angular/build/src/private.ts b/packages/angular/build/src/private.ts index e572ac02b216..4791a94a42d3 100644 --- a/packages/angular/build/src/private.ts +++ b/packages/angular/build/src/private.ts @@ -25,7 +25,7 @@ import { BundleStylesheetOptions } from './tools/esbuild/stylesheets/bundle-opti export { buildApplicationInternal } from './builders/application'; export type { ApplicationBuilderInternalOptions } from './builders/application/options'; export { type Result, type ResultFile, ResultKind } from './builders/application/results'; -export { serveWithVite } from './builders/dev-server/vite-server'; +export { serveWithVite } from './builders/dev-server/vite'; // Tools export * from './tools/babel/plugins'; @@ -35,6 +35,7 @@ export { transformSupportedBrowsersToTargets } from './tools/esbuild/utils'; export { SassWorkerImplementation } from './tools/sass/sass-service'; export { SourceFileCache } from './tools/esbuild/angular/source-file-cache'; +export { Cache } from './tools/esbuild/cache'; export { createJitResourceTransformer } from './tools/angular/transformers/jit-resource-transformer'; export { JavaScriptTransformer } from './tools/esbuild/javascript-transformer'; @@ -58,7 +59,9 @@ export function createCompilerPlugin( ); } +export type { CompilerPluginOptions, BundleStylesheetOptions }; export type { AngularCompilation } from './tools/angular/compilation'; +export { DiagnosticModes } from './tools/angular/compilation'; export { createAngularCompilation }; export { ComponentStylesheetBundler } from './tools/esbuild/angular/component-stylesheets'; diff --git a/packages/angular/build/src/tools/angular/angular-host.ts b/packages/angular/build/src/tools/angular/angular-host.ts index 38c096f67674..e98ebf49f3eb 100644 --- a/packages/angular/build/src/tools/angular/angular-host.ts +++ b/packages/angular/build/src/tools/angular/angular-host.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.dev/license */ -import type ng from '@angular/compiler-cli'; +import type * as ng from '@angular/compiler-cli'; import assert from 'node:assert'; import { createHash } from 'node:crypto'; import nodePath from 'node:path'; diff --git a/packages/angular/build/src/tools/angular/compilation/angular-compilation.ts b/packages/angular/build/src/tools/angular/compilation/angular-compilation.ts index bea3c65e1b8a..00a17ccc453e 100644 --- a/packages/angular/build/src/tools/angular/compilation/angular-compilation.ts +++ b/packages/angular/build/src/tools/angular/compilation/angular-compilation.ts @@ -6,10 +6,9 @@ * found in the LICENSE file at https://angular.dev/license */ -import type ng from '@angular/compiler-cli'; +import type * as ng from '@angular/compiler-cli'; import type { PartialMessage } from 'esbuild'; import type ts from 'typescript'; -import { loadEsmModule } from '../../../utils/load-esm'; import { convertTypeScriptDiagnostic } from '../../esbuild/angular/diagnostics'; import { profileAsync, profileSync } from '../../esbuild/profiling'; import type { AngularHostOptions } from '../angular-host'; @@ -33,10 +32,7 @@ export abstract class AngularCompilation { static #typescriptModule?: typeof ts; static async loadCompilerCli(): Promise { - // This uses a wrapped dynamic import to load `@angular/compiler-cli` which is ESM. - // Once TypeScript provides support for retaining dynamic imports this workaround can be dropped. - AngularCompilation.#angularCompilerCliModule ??= - await loadEsmModule('@angular/compiler-cli'); + AngularCompilation.#angularCompilerCliModule ??= await import('@angular/compiler-cli'); return AngularCompilation.#angularCompilerCliModule; } @@ -80,6 +76,7 @@ export abstract class AngularCompilation { referencedFiles: readonly string[]; externalStylesheets?: ReadonlyMap; templateUpdates?: ReadonlyMap; + componentResourcesDependencies?: ReadonlyMap; }>; abstract emitAffectedFiles(): Iterable | Promise>; diff --git a/packages/angular/build/src/tools/angular/compilation/aot-compilation.ts b/packages/angular/build/src/tools/angular/compilation/aot-compilation.ts index a340d602577e..06a3f6e8c8d6 100644 --- a/packages/angular/build/src/tools/angular/compilation/aot-compilation.ts +++ b/packages/angular/build/src/tools/angular/compilation/aot-compilation.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.dev/license */ -import type ng from '@angular/compiler-cli'; +import type * as ng from '@angular/compiler-cli'; import assert from 'node:assert'; import { relative } from 'node:path'; import ts from 'typescript'; @@ -62,6 +62,7 @@ export class AotCompilation extends AngularCompilation { referencedFiles: readonly string[]; externalStylesheets?: ReadonlyMap; templateUpdates?: ReadonlyMap; + componentResourcesDependencies?: ReadonlyMap; }> { // Dynamically load the Angular compiler CLI package const { NgtscProgram, OptimizeFor } = await AngularCompilation.loadCompilerCli(); @@ -175,13 +176,15 @@ export class AotCompilation extends AngularCompilation { findAffectedFiles(typeScriptProgram, angularCompiler, usingBuildInfo), ); + const componentResourcesDependencies = new Map(); + // Get all files referenced in the TypeScript/Angular program including component resources const referencedFiles = typeScriptProgram .getSourceFiles() .filter((sourceFile) => !angularCompiler.ignoreForEmit.has(sourceFile)) .flatMap((sourceFile) => { const resourceDependencies = angularCompiler.getResourceDependencies(sourceFile); - + componentResourcesDependencies.set(sourceFile.fileName, resourceDependencies); // Also invalidate Angular diagnostics for a source file if component resources are modified if (this.#state && hostOptions.modifiedFiles?.size) { for (const resourceDependency of resourceDependencies) { @@ -212,6 +215,7 @@ export class AotCompilation extends AngularCompilation { referencedFiles, externalStylesheets: hostOptions.externalStylesheets, templateUpdates, + componentResourcesDependencies, }; } diff --git a/packages/angular/build/src/tools/angular/compilation/hmr-candidates.ts b/packages/angular/build/src/tools/angular/compilation/hmr-candidates.ts index e10b935907c0..cba0b18e7414 100644 --- a/packages/angular/build/src/tools/angular/compilation/hmr-candidates.ts +++ b/packages/angular/build/src/tools/angular/compilation/hmr-candidates.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.dev/license */ -import type ng from '@angular/compiler-cli'; +import type * as ng from '@angular/compiler-cli'; import assert from 'node:assert'; import ts from 'typescript'; diff --git a/packages/angular/build/src/tools/angular/compilation/jit-compilation.ts b/packages/angular/build/src/tools/angular/compilation/jit-compilation.ts index a811cb50ec0a..4c529df0db08 100644 --- a/packages/angular/build/src/tools/angular/compilation/jit-compilation.ts +++ b/packages/angular/build/src/tools/angular/compilation/jit-compilation.ts @@ -6,10 +6,9 @@ * found in the LICENSE file at https://angular.dev/license */ -import type ng from '@angular/compiler-cli'; +import type * as ng from '@angular/compiler-cli'; import assert from 'node:assert'; import ts from 'typescript'; -import { loadEsmModule } from '../../../utils/load-esm'; import { profileSync } from '../../esbuild/profiling'; import { AngularHostOptions, createAngularCompilerHost } from '../angular-host'; import { createJitResourceTransformer } from '../transformers/jit-resource-transformer'; @@ -44,9 +43,9 @@ export class JitCompilation extends AngularCompilation { referencedFiles: readonly string[]; }> { // Dynamically load the Angular compiler CLI package - const { constructorParametersDownlevelTransform } = await loadEsmModule< - typeof import('@angular/compiler-cli/private/tooling') - >('@angular/compiler-cli/private/tooling'); + const { constructorParametersDownlevelTransform } = await import( + '@angular/compiler-cli/private/tooling' + ); // Load the compiler configuration and transform as needed const { diff --git a/packages/angular/build/src/tools/angular/compilation/noop-compilation.ts b/packages/angular/build/src/tools/angular/compilation/noop-compilation.ts index a683271b287f..e2c597b4d315 100644 --- a/packages/angular/build/src/tools/angular/compilation/noop-compilation.ts +++ b/packages/angular/build/src/tools/angular/compilation/noop-compilation.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.dev/license */ -import type ng from '@angular/compiler-cli'; +import type * as ng from '@angular/compiler-cli'; import type ts from 'typescript'; import { AngularHostOptions } from '../angular-host'; import { AngularCompilation } from './angular-compilation'; diff --git a/packages/angular/build/src/tools/angular/compilation/parallel-worker.ts b/packages/angular/build/src/tools/angular/compilation/parallel-worker.ts index d67fbb9bd06c..b6eccf20e3db 100644 --- a/packages/angular/build/src/tools/angular/compilation/parallel-worker.ts +++ b/packages/angular/build/src/tools/angular/compilation/parallel-worker.ts @@ -45,58 +45,63 @@ export async function initialize(request: InitRequest) { } }); - const { compilerOptions, referencedFiles, externalStylesheets, templateUpdates } = - await compilation.initialize( - request.tsconfig, - { - fileReplacements: request.fileReplacements, - sourceFileCache, - modifiedFiles: sourceFileCache.modifiedFiles, - transformStylesheet(data, containingFile, stylesheetFile, order, className) { - const requestId = randomUUID(); - const resultPromise = new Promise((resolve, reject) => - stylesheetRequests.set(requestId, [resolve, reject]), - ); - - request.stylesheetPort.postMessage({ - requestId, - data, - containingFile, - stylesheetFile, - order, - className, - }); - - return resultPromise; - }, - processWebWorker(workerFile, containingFile) { - Atomics.store(request.webWorkerSignal, 0, 0); - request.webWorkerPort.postMessage({ workerFile, containingFile }); - - Atomics.wait(request.webWorkerSignal, 0, 0); - const result = receiveMessageOnPort(request.webWorkerPort)?.message; - - if (result?.error) { - throw result.error; - } - - return result?.workerCodeFile ?? workerFile; - }, + const { + compilerOptions, + referencedFiles, + externalStylesheets, + templateUpdates, + componentResourcesDependencies, + } = await compilation.initialize( + request.tsconfig, + { + fileReplacements: request.fileReplacements, + sourceFileCache, + modifiedFiles: sourceFileCache.modifiedFiles, + transformStylesheet(data, containingFile, stylesheetFile, order, className) { + const requestId = randomUUID(); + const resultPromise = new Promise((resolve, reject) => + stylesheetRequests.set(requestId, [resolve, reject]), + ); + + request.stylesheetPort.postMessage({ + requestId, + data, + containingFile, + stylesheetFile, + order, + className, + }); + + return resultPromise; }, - (compilerOptions) => { - Atomics.store(request.optionsSignal, 0, 0); - request.optionsPort.postMessage(compilerOptions); + processWebWorker(workerFile, containingFile) { + Atomics.store(request.webWorkerSignal, 0, 0); + request.webWorkerPort.postMessage({ workerFile, containingFile }); - Atomics.wait(request.optionsSignal, 0, 0); - const result = receiveMessageOnPort(request.optionsPort)?.message; + Atomics.wait(request.webWorkerSignal, 0, 0); + const result = receiveMessageOnPort(request.webWorkerPort)?.message; if (result?.error) { throw result.error; } - return result?.transformedOptions ?? compilerOptions; + return result?.workerCodeFile ?? workerFile; }, - ); + }, + (compilerOptions) => { + Atomics.store(request.optionsSignal, 0, 0); + request.optionsPort.postMessage(compilerOptions); + + Atomics.wait(request.optionsSignal, 0, 0); + const result = receiveMessageOnPort(request.optionsPort)?.message; + + if (result?.error) { + throw result.error; + } + + return result?.transformedOptions ?? compilerOptions; + }, + ); return { externalStylesheets, @@ -109,6 +114,7 @@ export async function initialize(request: InitRequest) { sourceMap: compilerOptions.sourceMap, inlineSourceMap: compilerOptions.inlineSourceMap, }, + componentResourcesDependencies, }; } diff --git a/packages/angular/build/src/tools/angular/transformers/jit-bootstrap-transformer.ts b/packages/angular/build/src/tools/angular/transformers/jit-bootstrap-transformer.ts index 89b96244b765..d1d0a76df85d 100644 --- a/packages/angular/build/src/tools/angular/transformers/jit-bootstrap-transformer.ts +++ b/packages/angular/build/src/tools/angular/transformers/jit-bootstrap-transformer.ts @@ -32,7 +32,7 @@ export function replaceBootstrap( bootstrapImport = nodeFactory.createImportDeclaration( undefined, nodeFactory.createImportClause( - false, + undefined, undefined, nodeFactory.createNamespaceImport(bootstrapNamespace), ), diff --git a/packages/angular/build/src/tools/angular/transformers/jit-resource-transformer.ts b/packages/angular/build/src/tools/angular/transformers/jit-resource-transformer.ts index 3d7878378537..2a064ba63cb5 100644 --- a/packages/angular/build/src/tools/angular/transformers/jit-resource-transformer.ts +++ b/packages/angular/build/src/tools/angular/transformers/jit-resource-transformer.ts @@ -254,7 +254,7 @@ function createResourceImport( resourceImportDeclarations.push( nodeFactory.createImportDeclaration( undefined, - nodeFactory.createImportClause(false, importName, undefined), + nodeFactory.createImportClause(undefined, importName, undefined), urlLiteral, ), ); diff --git a/packages/angular/build/src/tools/babel/plugins/pure-toplevel-functions.ts b/packages/angular/build/src/tools/babel/plugins/pure-toplevel-functions.ts index ce47977a74e3..5aec104a38d2 100644 --- a/packages/angular/build/src/tools/babel/plugins/pure-toplevel-functions.ts +++ b/packages/angular/build/src/tools/babel/plugins/pure-toplevel-functions.ts @@ -6,12 +6,17 @@ * found in the LICENSE file at https://angular.dev/license */ -import type { PluginObj } from '@babel/core'; +import type { NodePath, PluginObj, PluginPass, types } from '@babel/core'; import annotateAsPure from '@babel/helper-annotate-as-pure'; import * as tslib from 'tslib'; /** - * A cached set of TypeScript helper function names used by the helper name matcher utility function. + * A set of constructor names that are considered to be side-effect free. + */ +const sideEffectFreeConstructors = new Set(['InjectionToken']); + +/** + * A set of TypeScript helper function names used by the helper name matcher utility function. */ const tslibHelpers = new Set(Object.keys(tslib).filter((h) => h.startsWith('__'))); @@ -44,15 +49,23 @@ function isBabelHelperName(name: string): boolean { return babelHelpers.has(name); } +interface ExtendedPluginPass extends PluginPass { + opts: { topLevelSafeMode?: boolean }; +} + /** * A babel plugin factory function for adding the PURE annotation to top-level new and call expressions. - * * @returns A babel plugin object instance. */ export default function (): PluginObj { return { visitor: { - CallExpression(path) { + CallExpression(path: NodePath, state: ExtendedPluginPass) { + const { topLevelSafeMode = false } = state.opts; + if (topLevelSafeMode) { + return; + } + // If the expression has a function parent, it is not top-level if (path.getFunctionParent()) { return; @@ -65,6 +78,7 @@ export default function (): PluginObj { ) { return; } + // Do not annotate TypeScript helpers emitted by the TypeScript compiler or Babel helpers. // They are intended to cause side effects. if ( @@ -76,9 +90,22 @@ export default function (): PluginObj { annotateAsPure(path); }, - NewExpression(path) { + NewExpression(path: NodePath, state: ExtendedPluginPass) { // If the expression has a function parent, it is not top-level - if (!path.getFunctionParent()) { + if (path.getFunctionParent()) { + return; + } + + const { topLevelSafeMode = false } = state.opts; + + if (!topLevelSafeMode) { + annotateAsPure(path); + + return; + } + + const callee = path.get('callee'); + if (callee.isIdentifier() && sideEffectFreeConstructors.has(callee.node.name)) { annotateAsPure(path); } }, diff --git a/packages/angular/build/src/tools/babel/plugins/pure-toplevel-functions_spec.ts b/packages/angular/build/src/tools/babel/plugins/pure-toplevel-functions_spec.ts index 891f794f43d5..0966a67d068a 100644 --- a/packages/angular/build/src/tools/babel/plugins/pure-toplevel-functions_spec.ts +++ b/packages/angular/build/src/tools/babel/plugins/pure-toplevel-functions_spec.ts @@ -7,23 +7,24 @@ */ import { transformSync } from '@babel/core'; -// eslint-disable-next-line import/no-extraneous-dependencies import { format } from 'prettier'; import pureTopLevelPlugin from './pure-toplevel-functions'; function testCase({ input, expected, + options, }: { input: string; expected: string; + options?: { topLevelSafeMode: boolean }; }): jasmine.ImplementationCallback { return async () => { const result = transformSync(input, { configFile: false, babelrc: false, compact: true, - plugins: [pureTopLevelPlugin], + plugins: [[pureTopLevelPlugin, options]], }); if (!result?.code) { fail('Expected babel to return a transform result.'); @@ -152,4 +153,33 @@ describe('pure-toplevel-functions Babel plugin', () => { }; `), ); + + describe('topLevelSafeMode: true', () => { + it( + 'annotates top-level `new InjectionToken` expressions', + testCase({ + input: `const result = new InjectionToken('abc');`, + expected: `const result = /*#__PURE__*/ new InjectionToken('abc');`, + options: { topLevelSafeMode: true }, + }), + ); + + it( + 'does not annotate other top-level `new` expressions', + testCase({ + input: 'const result = new SomeClass();', + expected: 'const result = new SomeClass();', + options: { topLevelSafeMode: true }, + }), + ); + + it( + 'does not annotate top-level function calls', + testCase({ + input: 'const result = someCall();', + expected: 'const result = someCall();', + options: { topLevelSafeMode: true }, + }), + ); + }); }); diff --git a/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts b/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts index f56e6c6c3119..af4dcaea01fb 100644 --- a/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts +++ b/packages/angular/build/src/tools/esbuild/angular/compiler-plugin.ts @@ -13,11 +13,13 @@ import type { OnStartResult, OutputFile, PartialMessage, + PartialNote, Plugin, PluginBuild, } from 'esbuild'; import assert from 'node:assert'; import { createHash } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; import * as path from 'node:path'; import { maxWorkers, useTypeChecking } from '../../../utils/environment-options'; import { AngularHostOptions } from '../../angular/angular-host'; @@ -29,6 +31,7 @@ import { SharedTSCompilationState, getSharedCompilationState } from './compilati import { ComponentStylesheetBundler } from './component-stylesheets'; import { FileReferenceTracker } from './file-reference-tracker'; import { setupJitPluginCallbacks } from './jit-plugin-callbacks'; +import { rewriteForBazel } from './rewrite-bazel-paths'; import { SourceFileCache } from './source-file-cache'; export interface CompilerPluginOptions { @@ -70,11 +73,11 @@ export function createCompilerPlugin( // Initialize a worker pool for JavaScript transformations. // Webcontainers currently do not support this persistent cache store. - let cacheStore: import('../lmdb-cache-store').LmbdCacheStore | undefined; + let cacheStore: import('../lmdb-cache-store').LmdbCacheStore | undefined; if (pluginOptions.sourceFileCache?.persistentCachePath && !process.versions.webcontainer) { try { - const { LmbdCacheStore } = await import('../lmdb-cache-store'); - cacheStore = new LmbdCacheStore( + const { LmdbCacheStore } = await import('../lmdb-cache-store'); + cacheStore = new LmdbCacheStore( path.join(pluginOptions.sourceFileCache.persistentCachePath, 'angular-compiler.db'), ); } catch (e) { @@ -411,8 +414,8 @@ export function createCompilerPlugin( }); build.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (args) => { - const request = path.normalize( - pluginOptions.fileReplacements?.[path.normalize(args.path)] ?? args.path, + const request = rewriteForBazel( + path.normalize(pluginOptions.fileReplacements?.[path.normalize(args.path)] ?? args.path), ); const isJS = /\.[cm]?js$/.test(request); @@ -440,11 +443,23 @@ export function createCompilerPlugin( return undefined; } + const diangosticRoot = build.initialOptions.absWorkingDir ?? ''; + + // Evaluate whether the file requires the Angular compiler transpilation. + // If not, issue a warning but allow bundler to process the file (no type-checking). + const directContents = await readFile(request, 'utf-8'); + if (!requiresAngularCompiler(directContents)) { + return { + warnings: [createMissingFileDiagnostic(request, args.path, diangosticRoot, false)], + contents, + loader: 'ts', + resolveDir: path.dirname(request), + }; + } + // Otherwise return an error return { - errors: [ - createMissingFileError(request, args.path, build.initialOptions.absWorkingDir ?? ''), - ], + errors: [createMissingFileDiagnostic(request, args.path, diangosticRoot, true)], }; } else if (typeof contents === 'string' && (useTypeScriptTranspilation || isJS)) { // A string indicates untransformed output from the TS/NG compiler. @@ -478,13 +493,14 @@ export function createCompilerPlugin( return { contents, loader, + resolveDir: path.dirname(request), }; }); build.onLoad( { filter: /\.[cm]?js$/ }, createCachedLoad(pluginOptions.loadResultCache, async (args) => { - let request = args.path; + let request = rewriteForBazel(args.path); if (pluginOptions.fileReplacements) { const replacement = pluginOptions.fileReplacements[path.normalize(args.path)]; if (replacement) { @@ -505,6 +521,7 @@ export function createCompilerPlugin( return { contents, loader: 'js', + resolveDir: path.dirname(request), watchFiles: request !== args.path ? [request] : undefined, }; }, @@ -574,6 +591,7 @@ export function createCompilerPlugin( build.onDispose(() => { sharedTSCompilationState?.dispose(); void compilation.close?.(); + void javascriptTransformer.close(); void cacheStore?.close(); }); @@ -759,23 +777,46 @@ function bundleWebWorker( } } -function createMissingFileError(request: string, original: string, root: string): PartialMessage { +function createMissingFileDiagnostic( + request: string, + original: string, + root: string, + angular: boolean, +): PartialMessage { const relativeRequest = path.relative(root, request); - const error = { - text: `File '${relativeRequest}' is missing from the TypeScript compilation.`, - notes: [ - { - text: `Ensure the file is part of the TypeScript program via the 'files' or 'include' property.`, - }, - ], - }; + const notes: PartialNote[] = []; + + if (angular) { + notes.push({ + text: + `Files containing Angular metadata ('@Component'/'@Directive'/etc.) must be part of the TypeScript compilation.` + + ` You can ensure the file is part of the TypeScript program via the 'files' or 'include' property.`, + }); + } else { + notes.push({ + text: + `The file will be bundled and included in the output but will not be type-checked at build time.` + + ` To remove this message you can add the file to the TypeScript program via the 'files' or 'include' property.`, + }); + } const relativeOriginal = path.relative(root, original); if (relativeRequest !== relativeOriginal) { - error.notes.push({ + notes.push({ text: `File is requested from a file replacement of '${relativeOriginal}'.`, }); } - return error; + const diagnostic = { + text: `File '${relativeRequest}' not found in TypeScript compilation.`, + notes, + }; + + return diagnostic; +} + +const POTENTIAL_METADATA_REGEX = /@angular\/core|@Component|@Directive|@Injectable|@Pipe|@NgModule/; + +function requiresAngularCompiler(contents: string): boolean { + return POTENTIAL_METADATA_REGEX.test(contents); } diff --git a/packages/angular/build/src/tools/esbuild/angular/rewrite-bazel-paths.ts b/packages/angular/build/src/tools/esbuild/angular/rewrite-bazel-paths.ts new file mode 100644 index 000000000000..8a6fb6aa82a4 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/angular/rewrite-bazel-paths.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { join, relative } from 'node:path'; + +const bazelBinDirectory = process.env['BAZEL_BINDIR']; +const bazelExecRoot = process.env['JS_BINARY__EXECROOT']; + +export function rewriteForBazel(path: string): string { + if (!bazelBinDirectory || !bazelExecRoot) { + return path; + } + + const fromExecRoot = relative(bazelExecRoot, path); + if (!fromExecRoot.startsWith('..')) { + return path; + } + + const fromBinDirectory = relative(bazelBinDirectory, path); + if (fromBinDirectory.startsWith('..')) { + return path; + } + + return join(bazelExecRoot, fromBinDirectory); +} diff --git a/packages/angular/build/src/tools/esbuild/application-code-bundle.ts b/packages/angular/build/src/tools/esbuild/application-code-bundle.ts index b17029f6c5e1..635faca8c82e 100644 --- a/packages/angular/build/src/tools/esbuild/application-code-bundle.ts +++ b/packages/angular/build/src/tools/esbuild/application-code-bundle.ts @@ -654,7 +654,7 @@ function getEsBuildCommonPolyfillsOptions( tryToResolvePolyfillsAsRelative: boolean, loadResultCache: LoadResultCache | undefined, ): BuildOptions | undefined { - const { jit, workspaceRoot, i18nOptions } = options; + const { jit, workspaceRoot, i18nOptions, externalPackages } = options; const buildOptions = getEsBuildCommonOptions(options); buildOptions.splitting = false; @@ -671,8 +671,10 @@ function getEsBuildCommonPolyfillsOptions( // Locale data should go first so that project provided polyfill code can augment if needed. let needLocaleDataPlugin = false; if (i18nOptions.shouldInline) { - // Remove localize polyfill as this is not needed for build time i18n. - polyfills = polyfills.filter((path) => !path.startsWith('@angular/localize')); + if (!externalPackages) { + // Remove localize polyfill when i18n inline transformation have been applied to all the packages. + polyfills = polyfills.filter((path) => !path.startsWith('@angular/localize')); + } // Add locale data for all active locales // TODO: Inject each individually within the inlining process itself @@ -686,7 +688,7 @@ function getEsBuildCommonPolyfillsOptions( needLocaleDataPlugin = true; } if (needLocaleDataPlugin) { - buildOptions.plugins.push(createAngularLocaleDataPlugin()); + buildOptions.plugins.unshift(createAngularLocaleDataPlugin()); } if (polyfills.length === 0) { diff --git a/packages/angular/build/src/tools/esbuild/i18n-inliner-worker.ts b/packages/angular/build/src/tools/esbuild/i18n-inliner-worker.ts index 9caa2ca5da45..74550e83e5de 100644 --- a/packages/angular/build/src/tools/esbuild/i18n-inliner-worker.ts +++ b/packages/angular/build/src/tools/esbuild/i18n-inliner-worker.ts @@ -11,7 +11,6 @@ import { PluginObj, parseSync, transformFromAstAsync, types } from '@babel/core' import assert from 'node:assert'; import { workerData } from 'node:worker_threads'; import { assertIsError } from '../../utils/error'; -import { loadEsmModule } from '../../utils/load-esm'; /** * The options passed to the inliner for each file request @@ -131,7 +130,7 @@ async function loadLocalizeTools(): Promise { // Load ESM `@angular/localize/tools` using the TypeScript dynamic import workaround. // Once TypeScript provides support for keeping the dynamic import this workaround can be // changed to a direct dynamic import. - localizeToolsModule ??= await loadEsmModule('@angular/localize/tools'); + localizeToolsModule ??= await import('@angular/localize/tools'); return localizeToolsModule; } diff --git a/packages/angular/build/src/tools/esbuild/i18n-inliner.ts b/packages/angular/build/src/tools/esbuild/i18n-inliner.ts index 365fbb300953..fcb439b84c5c 100644 --- a/packages/angular/build/src/tools/esbuild/i18n-inliner.ts +++ b/packages/angular/build/src/tools/esbuild/i18n-inliner.ts @@ -11,7 +11,7 @@ import { createHash } from 'node:crypto'; import { extname, join } from 'node:path'; import { WorkerPool } from '../../utils/worker-pool'; import { BuildOutputFile, BuildOutputFileType } from './bundler-context'; -import type { LmbdCacheStore } from './lmdb-cache-store'; +import type { LmdbCacheStore } from './lmdb-cache-store'; import { createOutputFile } from './utils'; /** @@ -39,7 +39,7 @@ export interface I18nInlinerOptions { export class I18nInliner { #cacheInitFailed = false; #workerPool: WorkerPool; - #cache: LmbdCacheStore | undefined; + #cache: LmdbCacheStore | undefined; readonly #localizeFiles: ReadonlyMap; readonly #unmodifiedFiles: Array; @@ -274,9 +274,9 @@ export class I18nInliner { // Initialize a persistent cache for i18n transformations. try { - const { LmbdCacheStore } = await import('./lmdb-cache-store'); + const { LmdbCacheStore } = await import('./lmdb-cache-store'); - this.#cache = new LmbdCacheStore(join(persistentCachePath, 'angular-i18n.db')); + this.#cache = new LmdbCacheStore(join(persistentCachePath, 'angular-i18n.db')); } catch { this.#cacheInitFailed = true; diff --git a/packages/angular/build/src/tools/esbuild/i18n-locale-plugin.ts b/packages/angular/build/src/tools/esbuild/i18n-locale-plugin.ts index 30f4540dc3a8..ae94b62ca16d 100644 --- a/packages/angular/build/src/tools/esbuild/i18n-locale-plugin.ts +++ b/packages/angular/build/src/tools/esbuild/i18n-locale-plugin.ts @@ -6,7 +6,8 @@ * found in the LICENSE file at https://angular.dev/license */ -import type { Plugin } from 'esbuild'; +import type { Plugin, ResolveResult } from 'esbuild'; +import { createRequire } from 'node:module'; /** * The internal namespace used by generated locale import statements and Angular locale data plugin. @@ -27,17 +28,6 @@ export function createAngularLocaleDataPlugin(): Plugin { return { name: 'angular-locale-data', setup(build): void { - // If packages are configured to be external then leave the original angular locale import path. - // This happens when using the development server with caching enabled to allow Vite prebundling to work. - // There currently is no option on the esbuild resolve function to resolve while disabling the option. To - // workaround the inability to resolve the full locale location here, the Vite dev server prebundling also - // contains a plugin to allow the locales to be correctly resolved when prebundling. - // NOTE: If esbuild eventually allows controlling the external package options in a build.resolve call, this - // workaround can be removed. - if (build.initialOptions.packages === 'external') { - return; - } - build.onResolve({ filter: /^angular:locale\/data:/ }, async ({ path }) => { // Extract the locale from the path const rawLocaleTag = path.split(':', 3)[2]; @@ -60,6 +50,7 @@ export function createAngularLocaleDataPlugin(): Plugin { } let exact = true; + let localeRequire: NodeJS.Require | undefined; while (partialLocaleTag) { // Angular embeds the `en`/`en-US` locale into the framework and it does not need to be included again here. // The onLoad hook below for the locale data namespace has an `empty` loader that will prevent inclusion. @@ -73,11 +64,39 @@ export function createAngularLocaleDataPlugin(): Plugin { // Attempt to resolve the locale tag data within the Angular base module location const potentialPath = `${LOCALE_DATA_BASE_MODULE}/${partialLocaleTag}`; - const result = await build.resolve(potentialPath, { - kind: 'import-statement', - resolveDir: build.initialOptions.absWorkingDir, - }); - if (result.path) { + + // If packages are configured to be external then leave the original angular locale import path. + // This happens when using the development server with caching enabled to allow Vite prebundling to work. + // There currently is no option on the esbuild resolve function to resolve while disabling the option. + // NOTE: If esbuild eventually allows controlling the external package options in a build.resolve call, this + // workaround can be removed. + let result: ResolveResult | undefined; + const { packages, absWorkingDir } = build.initialOptions; + if (packages === 'external' && absWorkingDir) { + localeRequire ??= createRequire(absWorkingDir + '/'); + + try { + localeRequire.resolve(potentialPath); + + result = { + errors: [], + warnings: [], + external: true, + sideEffects: true, + namespace: '', + suffix: '', + pluginData: undefined, + path: potentialPath, + }; + } catch {} + } else { + result = await build.resolve(potentialPath, { + kind: 'import-statement', + resolveDir: absWorkingDir, + }); + } + + if (result?.path) { if (exact) { return result; } else { diff --git a/packages/angular/build/src/tools/esbuild/javascript-transformer-worker.ts b/packages/angular/build/src/tools/esbuild/javascript-transformer-worker.ts index 8fa551b38ba2..7d86009b773f 100644 --- a/packages/angular/build/src/tools/esbuild/javascript-transformer-worker.ts +++ b/packages/angular/build/src/tools/esbuild/javascript-transformer-worker.ts @@ -10,7 +10,6 @@ import { type PluginItem, transformAsync } from '@babel/core'; import fs from 'node:fs'; import path from 'node:path'; import Piscina from 'piscina'; -import { loadEsmModule } from '../../utils/load-esm'; interface JavaScriptTransformRequest { filename: string; @@ -78,21 +77,19 @@ async function transformWithBabel( } if (options.advancedOptimizations) { - const sideEffectFree = options.sideEffects === false; - const safeAngularPackage = - sideEffectFree && /[\\/]node_modules[\\/]@angular[\\/]/.test(filename); - const { adjustStaticMembers, adjustTypeScriptEnums, elideAngularMetadata, markTopLevelPure } = await import('../babel/plugins'); - if (safeAngularPackage) { - plugins.push(markTopLevelPure); - } + const sideEffectFree = options.sideEffects === false; + const safeAngularPackage = + sideEffectFree && /[\\/]node_modules[\\/]@angular[\\/]/.test(filename); - plugins.push(elideAngularMetadata, adjustTypeScriptEnums, [ - adjustStaticMembers, - { wrapDecorators: sideEffectFree }, - ]); + plugins.push( + [markTopLevelPure, { topLevelSafeMode: !safeAngularPackage }], + elideAngularMetadata, + adjustTypeScriptEnums, + [adjustStaticMembers, { wrapDecorators: sideEffectFree }], + ); } // If no additional transformations are needed, return the data directly @@ -135,11 +132,8 @@ async function requiresLinking(path: string, source: string): Promise { } async function createLinkerPlugin(options: Omit) { - linkerPluginCreator ??= ( - await loadEsmModule( - '@angular/compiler-cli/linker/babel', - ) - ).createEs2015LinkerPlugin; + linkerPluginCreator ??= (await import('@angular/compiler-cli/linker/babel')) + .createEs2015LinkerPlugin; const linkerPlugin = linkerPluginCreator({ linkerJitMode: options.jit, diff --git a/packages/angular/build/src/tools/esbuild/javascript-transformer.ts b/packages/angular/build/src/tools/esbuild/javascript-transformer.ts index b27b8a087b46..b728a0f599e2 100644 --- a/packages/angular/build/src/tools/esbuild/javascript-transformer.ts +++ b/packages/angular/build/src/tools/esbuild/javascript-transformer.ts @@ -125,7 +125,7 @@ export class JavaScriptTransformer { { // The below is disable as with Yarn PNP this causes build failures with the below message // `Unable to deserialize cloned data`. - transferList: process.versions.pnp ? undefined : [data.buffer as ArrayBuffer], + transferList: process.versions.pnp ? undefined : [data.buffer], }, )) as Uint8Array; diff --git a/packages/angular/build/src/tools/esbuild/lmdb-cache-store.ts b/packages/angular/build/src/tools/esbuild/lmdb-cache-store.ts index 7d03cb597738..dba108285342 100644 --- a/packages/angular/build/src/tools/esbuild/lmdb-cache-store.ts +++ b/packages/angular/build/src/tools/esbuild/lmdb-cache-store.ts @@ -9,7 +9,7 @@ import { RootDatabase, open } from 'lmdb'; import { Cache, CacheStore } from './cache'; -export class LmbdCacheStore implements CacheStore { +export class LmdbCacheStore implements CacheStore { readonly #cacheFileUrl; #db: RootDatabase | undefined; diff --git a/packages/angular/build/src/tools/esbuild/stylesheets/bundle-options.ts b/packages/angular/build/src/tools/esbuild/stylesheets/bundle-options.ts index 9bbcb7c5ecb8..7fa20dde64ae 100644 --- a/packages/angular/build/src/tools/esbuild/stylesheets/bundle-options.ts +++ b/packages/angular/build/src/tools/esbuild/stylesheets/bundle-options.ts @@ -31,7 +31,7 @@ export interface BundleStylesheetOptions { externalDependencies?: string[]; target: string[]; tailwindConfiguration?: { file: string; package: string }; - postcssConfiguration?: PostcssConfiguration; + postcssConfiguration?: { config: PostcssConfiguration; configPath: string }; publicPath?: string; cacheOptions: NormalizedCachedOptions; } diff --git a/packages/angular/build/src/tools/esbuild/stylesheets/less-language.ts b/packages/angular/build/src/tools/esbuild/stylesheets/less-language.ts index 1f6d8f2b7c26..68cacd576b10 100644 --- a/packages/angular/build/src/tools/esbuild/stylesheets/less-language.ts +++ b/packages/angular/build/src/tools/esbuild/stylesheets/less-language.ts @@ -32,13 +32,7 @@ export const LessStylesheetLanguage = Object.freeze({ componentFilter: /^less;/, fileFilter: /\.less$/, process(data, file, _, options, build) { - return compileString( - data, - file, - options, - build.resolve.bind(build), - /* unsafeInlineJavaScript */ false, - ); + return compileString(data, file, options, build.resolve.bind(build)); }, }); @@ -47,7 +41,6 @@ async function compileString( filename: string, options: StylesheetPluginOptions, resolver: PluginBuild['resolve'], - unsafeInlineJavaScript: boolean, ): Promise { try { lessPreprocessor ??= (await import('less')).default; @@ -118,7 +111,6 @@ async function compileString( paths: options.includePaths, plugins: [resolverPlugin], rewriteUrls: 'all', - javascriptEnabled: unsafeInlineJavaScript, sourceMap: options.sourcemap ? { sourceMapFileInline: true, @@ -136,35 +128,6 @@ async function compileString( if (isLessException(error)) { const location = convertExceptionLocation(error); - // Retry with a warning for less files requiring the deprecated inline JavaScript option - if (error.message.includes('Inline JavaScript is not enabled.')) { - const withJsResult = await compileString( - data, - filename, - options, - resolver, - /* unsafeInlineJavaScript */ true, - ); - withJsResult.warnings = [ - { - text: 'Deprecated inline execution of JavaScript has been enabled ("javascriptEnabled")', - location, - notes: [ - { - location: null, - text: 'JavaScript found within less stylesheets may be executed at build time. [https://lesscss.org/usage/#less-options]', - }, - { - location: null, - text: 'Support for "javascriptEnabled" may be removed from the Angular CLI starting with Angular v19.', - }, - ], - }, - ]; - - return withJsResult; - } - return { errors: [ { diff --git a/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-plugin-factory.ts b/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-plugin-factory.ts index f618bbf6cc39..78925f35835e 100644 --- a/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-plugin-factory.ts +++ b/packages/angular/build/src/tools/esbuild/stylesheets/stylesheet-plugin-factory.ts @@ -9,7 +9,8 @@ import type { OnLoadResult, Plugin, PluginBuild } from 'esbuild'; import assert from 'node:assert'; import { readFile } from 'node:fs/promises'; -import { extname } from 'node:path'; +import { createRequire } from 'node:module'; +import { dirname, extname } from 'node:path'; import type { Options } from 'sass'; import { glob } from 'tinyglobby'; import { assertIsError } from '../../../utils/error'; @@ -69,7 +70,7 @@ export interface StylesheetPluginOptions { * initialized and used for every stylesheet. This overrides the tailwind integration * and any tailwind usage must be manually configured in the custom postcss usage. */ - postcssConfiguration?: PostcssConfiguration; + postcssConfiguration?: { config: PostcssConfiguration; configPath: string }; /** * Optional Options for configuring Sass behavior. @@ -215,14 +216,18 @@ export class StylesheetPluginFactory { const { options } = this; if (options.postcssConfiguration) { - const postCssInstanceKey = JSON.stringify(options.postcssConfiguration); + const { config, configPath } = options.postcssConfiguration; + const postCssInstanceKey = JSON.stringify(config); let postcssProcessor = postcssProcessors.get(postCssInstanceKey)?.deref(); if (!postcssProcessor) { postcss ??= (await import('postcss')).default; postcssProcessor = postcss(); - for (const [pluginName, pluginOptions] of options.postcssConfiguration.plugins) { - const { default: plugin } = await import(pluginName); + + const postCssPluginRequire = createRequire(dirname(configPath) + '/'); + for (const [pluginName, pluginOptions] of config.plugins) { + const pluginMod = postCssPluginRequire(pluginName); + const plugin = pluginMod.__esModule ? pluginMod['default'] : pluginMod; if (typeof plugin !== 'function' || plugin.postcss !== true) { throw new Error(`Attempted to load invalid Postcss plugin: "${pluginName}"`); } diff --git a/packages/angular/build/src/tools/vite/middlewares/assets-middleware.ts b/packages/angular/build/src/tools/vite/middlewares/assets-middleware.ts index a9fe69ffca15..f0a137f578f8 100644 --- a/packages/angular/build/src/tools/vite/middlewares/assets-middleware.ts +++ b/packages/angular/build/src/tools/vite/middlewares/assets-middleware.ts @@ -12,6 +12,7 @@ import { readFileSync } from 'node:fs'; import type { ServerResponse } from 'node:http'; import { extname } from 'node:path'; import type { Connect, ViteDevServer } from 'vite'; +import { ResultFile } from '../../../builders/application/results'; import { AngularMemoryOutputFiles, AngularOutputAssets, pathnameWithoutBasePath } from '../utils'; export interface ComponentStyleRecord { @@ -39,7 +40,7 @@ export function createAngularAssetsMiddleware( // The base of the URL is unused but required to parse the URL. const pathname = pathnameWithoutBasePath(req.url, server.config.base); const extension = extname(pathname); - const pathnameHasTrailingSlash = pathname[pathname.length - 1] === '/'; + const pathnameHasTrailingSlash = pathname.at(-1) === '/'; // Rewrite all build assets to a vite raw fs URL const asset = assets.get(pathname); @@ -214,3 +215,45 @@ function checkAndHandleEtag( return false; } + +export function createBuildAssetsMiddleware( + basePath: string, + buildResultFiles: ReadonlyMap, + readHandler: (path: string) => Buffer = readFileSync, +): Connect.NextHandleFunction { + return function buildAssetsMiddleware(req, res, next) { + if (req.url === undefined || res.writableEnded) { + return; + } + + // Parse the incoming request. + // The base of the URL is unused but required to parse the URL. + const pathname = pathnameWithoutBasePath(req.url, basePath); + const extension = extname(pathname); + if (extension && !/\.[mc]?[jt]s(?:\.map)?$/.test(extension)) { + const outputFile = buildResultFiles.get(pathname.slice(1)); + if (outputFile) { + const contents = + outputFile.origin === 'memory' ? outputFile.contents : readHandler(outputFile.inputPath); + + const etag = `W/${createHash('sha256').update(contents).digest('hex')}`; + if (checkAndHandleEtag(req, res, etag)) { + return; + } + + const mimeType = lookupMimeType(extension); + if (mimeType) { + res.setHeader('Content-Type', mimeType); + } + + res.setHeader('ETag', etag); + res.setHeader('Cache-Control', 'no-cache'); + res.end(contents); + + return; + } + } + + next(); + }; +} diff --git a/packages/angular/build/src/tools/vite/middlewares/base-middleware.ts b/packages/angular/build/src/tools/vite/middlewares/base-middleware.ts new file mode 100644 index 000000000000..00198e03061a --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/base-middleware.ts @@ -0,0 +1,56 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { IncomingMessage, ServerResponse } from 'node:http'; +import type { Connect } from 'vite'; +import { addLeadingSlash } from '../../../utils/url'; + +/** + * Patches the Vite base middleware to correctly handle the Angular application's base href. + * This is necessary because Vite's default base middleware might not align with Angular's + * expected path handling when using SSR, especially when a base href is configured. + * + * @param middlewares The Connect server instance containing the middleware stack. + * @param base The base URL path to be handled by the middleware. + */ +export function patchBaseMiddleware(middlewares: Connect.Server, base: string): void { + const entry = middlewares.stack.find( + ({ handle }) => typeof handle === 'function' && handle.name.startsWith('viteBaseMiddleware'), + ); + + if (typeof entry?.handle !== 'function') { + return; + } + + entry.handle = function angularBaseMiddleware( + req: IncomingMessage, + res: ServerResponse, + next: (err?: unknown) => void, + ) { + const url = req.url || '/'; + if (url.startsWith(base)) { + // Rewrite the URL to remove the base prefix before passing it to the next middleware. + // If the URL is exactly the base, it becomes '/'. + // Otherwise, we slice off the base and ensure there's a leading slash. + // See: https://github.com/vitejs/vite/blob/e81c183f8c8ccaf7774ef0d0ee125bf63dbf30b4/packages/vite/src/node/server/middlewares/base.ts#L12 + req.url = url === base ? '/' : addLeadingSlash(url.slice(base.length - 1)); + + return next(); + } + + const { pathname, hash, search } = new URL(url, 'http://localhost'); + if (pathname === '/' || pathname === '/index.html') { + res.writeHead(302, { Location: `${base}${search}${hash}` }); + res.end(); + + return; + } + + next(); + }; +} diff --git a/packages/angular/build/src/tools/vite/middlewares/host-check-middleware.ts b/packages/angular/build/src/tools/vite/middlewares/host-check-middleware.ts new file mode 100644 index 000000000000..8561354812b3 --- /dev/null +++ b/packages/angular/build/src/tools/vite/middlewares/host-check-middleware.ts @@ -0,0 +1,76 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { IncomingMessage, ServerResponse } from 'node:http'; +import type { Connect } from 'vite'; + +export function patchHostValidationMiddleware(middlewares: Connect.Server): void { + const entry = middlewares.stack.find( + ({ handle }) => + typeof handle === 'function' && handle.name.startsWith('hostValidationMiddleware'), + ); + + if (typeof entry?.handle !== 'function') { + return; + } + + const originalHandle = entry.handle as Connect.NextHandleFunction; + + entry.handle = function angularHostValidationMiddleware( + req: IncomingMessage, + res: ServerResponse, + next: (err?: unknown) => void, + ) { + originalHandle( + req, + { + writeHead: (code) => { + res.writeHead(code, { 'content-type': 'text/html' }); + }, + end: () => { + const hostname = req.headers.host?.toLowerCase().split(':')[0] ?? ''; + res.end(html403(hostname)); + }, + } as ServerResponse, + next, + ); + }; +} + +function html403(hostname: string): string { + return ` + + + + + Blocked request + + + +
+

Blocked request. This host ("${hostname}") is not allowed.

+

To allow this host, add it to allowedHosts under the serve target in angular.json.

+
{
+  "serve": {
+    "options": {
+      "allowedHosts": ["${hostname}"]
+    }
+  }
+}
+
+ + `; +} diff --git a/packages/angular/build/src/tools/vite/middlewares/index.ts b/packages/angular/build/src/tools/vite/middlewares/index.ts index ef2db01f3aaf..807e739eed59 100644 --- a/packages/angular/build/src/tools/vite/middlewares/index.ts +++ b/packages/angular/build/src/tools/vite/middlewares/index.ts @@ -16,3 +16,5 @@ export { export { createAngularHeadersMiddleware } from './headers-middleware'; export { createAngularComponentMiddleware } from './component-middleware'; export { createChromeDevtoolsMiddleware } from './chrome-devtools-middleware'; +export { patchHostValidationMiddleware } from './host-check-middleware'; +export { patchBaseMiddleware } from './base-middleware'; diff --git a/packages/angular/build/src/tools/vite/middlewares/ssr-middleware.ts b/packages/angular/build/src/tools/vite/middlewares/ssr-middleware.ts index 387a94a2ba53..4b0a8d8390f1 100644 --- a/packages/angular/build/src/tools/vite/middlewares/ssr-middleware.ts +++ b/packages/angular/build/src/tools/vite/middlewares/ssr-middleware.ts @@ -12,7 +12,6 @@ import type { } from '@angular/ssr'; import type { ServerResponse } from 'node:http'; import type { Connect, ViteDevServer } from 'vite'; -import { loadEsmModule } from '../../../utils/load-esm'; import { isSsrNodeRequestHandler, isSsrRequestHandler, @@ -36,20 +35,15 @@ export function createAngularSsrInternalMiddleware( (async () => { // Load the compiler because `@angular/ssr/node` depends on `@angular/` packages, // which must be processed by the runtime linker, even if they are not used. - await loadEsmModule('@angular/compiler'); - const { writeResponseToNodeResponse, createWebRequestFromNodeRequest } = - await loadEsmModule('@angular/ssr/node'); + await import('@angular/compiler'); + const { writeResponseToNodeResponse, createWebRequestFromNodeRequest } = (await import( + '@angular/ssr/node' as string + )) as typeof import('@angular/ssr/node', { with: { 'resolution-mode': 'import' } }); const { ɵgetOrCreateAngularServerApp } = (await server.ssrLoadModule('/main.server.mjs')) as { ɵgetOrCreateAngularServerApp: typeof getOrCreateAngularServerApp; }; - // `ɵgetOrCreateAngularServerApp` can be undefined right after an error. - // See: https://github.com/angular/angular-cli/issues/29907 - if (!ɵgetOrCreateAngularServerApp) { - return next(); - } - const angularServerApp = ɵgetOrCreateAngularServerApp({ allowStaticRouteRender: true, }); @@ -90,10 +84,11 @@ export async function createAngularSsrExternalMiddleware( // Load the compiler because `@angular/ssr/node` depends on `@angular/` packages, // which must be processed by the runtime linker, even if they are not used. - await loadEsmModule('@angular/compiler'); + await import('@angular/compiler'); - const { createWebRequestFromNodeRequest, writeResponseToNodeResponse } = - await loadEsmModule('@angular/ssr/node'); + const { createWebRequestFromNodeRequest, writeResponseToNodeResponse } = (await import( + '@angular/ssr/node' as string + )) as typeof import('@angular/ssr/node', { with: { 'resolution-mode': 'import' } }); return function angularSsrExternalMiddleware( req: Connect.IncomingMessage, diff --git a/packages/angular/build/src/tools/vite/plugins/angular-memory-plugin.ts b/packages/angular/build/src/tools/vite/plugins/angular-memory-plugin.ts index 5fc178b60386..be00e3437f27 100644 --- a/packages/angular/build/src/tools/vite/plugins/angular-memory-plugin.ts +++ b/packages/angular/build/src/tools/vite/plugins/angular-memory-plugin.ts @@ -11,7 +11,6 @@ import { readFile } from 'node:fs/promises'; import { dirname, join, relative } from 'node:path'; import { fileURLToPath } from 'node:url'; import type { Plugin } from 'vite'; -import { loadEsmModule } from '../../../utils/load-esm'; import { AngularMemoryOutputFiles } from '../utils'; interface AngularMemoryPluginOptions { @@ -30,7 +29,7 @@ export async function createAngularMemoryPlugin( options: AngularMemoryPluginOptions, ): Promise { const { virtualProjectRoot, outputFiles, external } = options; - const { normalizePath } = await loadEsmModule('vite'); + const { normalizePath } = await import('vite'); return { name: 'vite:angular-memory', diff --git a/packages/angular/build/src/tools/vite/plugins/i18n-locale-plugin.ts b/packages/angular/build/src/tools/vite/plugins/i18n-locale-plugin.ts deleted file mode 100644 index 5cf3762245a5..000000000000 --- a/packages/angular/build/src/tools/vite/plugins/i18n-locale-plugin.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.dev/license - */ - -import type { Plugin } from 'vite'; - -/** - * The base module location used to search for locale specific data. - */ -const LOCALE_DATA_BASE_MODULE = '@angular/common/locales/global'; - -/** - * Creates a Vite plugin that resolves Angular locale data files from `@angular/common`. - * - * @returns A Vite plugin. - */ -export function createAngularLocaleDataPlugin(): Plugin { - return { - name: 'angular-locale-data', - enforce: 'pre', - async resolveId(source) { - if (!source.startsWith('angular:locale/data:')) { - return; - } - - // Extract the locale from the path - const originalLocale = source.split(':', 3)[2]; - - // Remove any private subtags since these will never match - let partialLocale = originalLocale.replace(/-x(-[a-zA-Z0-9]{1,8})+$/, ''); - - let exact = true; - while (partialLocale) { - const potentialPath = `${LOCALE_DATA_BASE_MODULE}/${partialLocale}`; - - const result = await this.resolve(potentialPath); - if (result) { - if (!exact) { - this.warn( - `Locale data for '${originalLocale}' cannot be found. Using locale data for '${partialLocale}'.`, - ); - } - - return result; - } - - // Remove the last subtag and try again with a less specific locale - const parts = partialLocale.split('-'); - partialLocale = parts.slice(0, -1).join('-'); - exact = false; - // The locales "en" and "en-US" are considered exact to retain existing behavior - if (originalLocale === 'en-US' && partialLocale === 'en') { - exact = true; - } - } - - return null; - }, - }; -} diff --git a/packages/angular/build/src/tools/vite/plugins/index.ts b/packages/angular/build/src/tools/vite/plugins/index.ts index 50a6ab6aa7c9..6c4cdd4496e4 100644 --- a/packages/angular/build/src/tools/vite/plugins/index.ts +++ b/packages/angular/build/src/tools/vite/plugins/index.ts @@ -7,7 +7,7 @@ */ export { createAngularMemoryPlugin } from './angular-memory-plugin'; -export { createAngularLocaleDataPlugin } from './i18n-locale-plugin'; export { createRemoveIdPrefixPlugin } from './id-prefix-plugin'; export { createAngularSetupMiddlewaresPlugin, ServerSsrMode } from './setup-middlewares-plugin'; export { createAngularSsrTransformPlugin } from './ssr-transform-plugin'; +export { createAngularServerSideSSLPlugin } from './ssr-ssl-plugin'; diff --git a/packages/angular/build/src/tools/vite/plugins/setup-middlewares-plugin.ts b/packages/angular/build/src/tools/vite/plugins/setup-middlewares-plugin.ts index 21ddaa350ac1..5d20d5c705ac 100644 --- a/packages/angular/build/src/tools/vite/plugins/setup-middlewares-plugin.ts +++ b/packages/angular/build/src/tools/vite/plugins/setup-middlewares-plugin.ts @@ -7,7 +7,6 @@ */ import type { Connect, Plugin } from 'vite'; -import { loadEsmModule } from '../../../utils/load-esm'; import { ComponentStyleRecord, angularHtmlFallbackMiddleware, @@ -18,6 +17,8 @@ import { createAngularSsrExternalMiddleware, createAngularSsrInternalMiddleware, createChromeDevtoolsMiddleware, + patchBaseMiddleware, + patchHostValidationMiddleware, } from '../middlewares'; import { AngularMemoryOutputFiles, AngularOutputAssets } from '../utils'; @@ -61,8 +62,7 @@ interface AngularSetupMiddlewaresPluginOptions { async function createEncapsulateStyle(): Promise< (style: Uint8Array, componentId: string) => string > { - const { encapsulateStyle } = - await loadEsmModule('@angular/compiler'); + const { encapsulateStyle } = await import('@angular/compiler'); const decoder = new TextDecoder('utf-8'); return (style, componentId) => { @@ -88,10 +88,12 @@ export function createAngularSetupMiddlewaresPlugin( resetComponentUpdates, } = options; + const middlewares = server.middlewares; + // Headers, assets and resources get handled first - server.middlewares.use(createAngularHeadersMiddleware(server)); - server.middlewares.use(createAngularComponentMiddleware(server, templateUpdates)); - server.middlewares.use( + middlewares.use(createAngularHeadersMiddleware(server)); + middlewares.use(createAngularComponentMiddleware(server, templateUpdates)); + middlewares.use( createAngularAssetsMiddleware( server, assets, @@ -101,30 +103,29 @@ export function createAngularSetupMiddlewaresPlugin( ), ); - server.middlewares.use( - createChromeDevtoolsMiddleware(server.config.cacheDir, options.projectRoot), - ); + middlewares.use(createChromeDevtoolsMiddleware(server.config.cacheDir, options.projectRoot)); - extensionMiddleware?.forEach((middleware) => server.middlewares.use(middleware)); + extensionMiddleware?.forEach((middleware) => middlewares.use(middleware)); // Returning a function, installs middleware after the main transform middleware but // before the built-in HTML middleware // eslint-disable-next-line @typescript-eslint/no-misused-promises return async () => { + patchHostValidationMiddleware(server.middlewares); + if (ssrMode === ServerSsrMode.ExternalSsrMiddleware) { - server.middlewares.use( - await createAngularSsrExternalMiddleware(server, indexHtmlTransformer), - ); + patchBaseMiddleware(server.middlewares, server.config.base); + middlewares.use(await createAngularSsrExternalMiddleware(server, indexHtmlTransformer)); return; } if (ssrMode === ServerSsrMode.InternalSsrMiddleware) { - server.middlewares.use(createAngularSsrInternalMiddleware(server, indexHtmlTransformer)); + middlewares.use(createAngularSsrInternalMiddleware(server, indexHtmlTransformer)); } - server.middlewares.use(angularHtmlFallbackMiddleware); - server.middlewares.use( + middlewares.use(angularHtmlFallbackMiddleware); + middlewares.use( createAngularIndexHtmlMiddleware( server, outputFiles, diff --git a/packages/angular/build/src/tools/vite/plugins/ssr-ssl-plugin.ts b/packages/angular/build/src/tools/vite/plugins/ssr-ssl-plugin.ts new file mode 100644 index 000000000000..80ddf56e739a --- /dev/null +++ b/packages/angular/build/src/tools/vite/plugins/ssr-ssl-plugin.ts @@ -0,0 +1,72 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { readFile } from 'node:fs/promises'; +import { getCACertificates, rootCertificates, setDefaultCACertificates } from 'node:tls'; +import type { Plugin } from 'vite'; + +export function createAngularServerSideSSLPlugin(): Plugin { + return { + name: 'angular-ssr-ssl-plugin', + apply: 'serve', + async configureServer({ config, httpServer }) { + const { + ssr, + server: { https }, + } = config; + + if (!ssr || !https?.cert) { + return; + } + + if (httpServer && 'ALPNProtocols' in httpServer) { + // Force Vite to use HTTP/1.1 when SSR and SSL are enabled. + // This is required because the Express server used for SSR does not support HTTP/2. + // See: https://github.com/vitejs/vite/blob/46d3077f2b63771cc50230bc907c48f5773c00fb/packages/vite/src/node/http.ts#L126 + + // We directly set the `ALPNProtocols` on the HTTP server to override the default behavior. + // Passing `ALPNProtocols` in the TLS options would cause Node.js to automatically include `h2`. + // Additionally, using `ALPNCallback` is not an option as it is mutually exclusive with `ALPNProtocols`. + // See: https://github.com/nodejs/node/blob/b8b4350ed3b73d225eb9e628d69151df56eaf298/lib/internal/http2/core.js#L3351 + httpServer.ALPNProtocols = ['http/1.1']; + } + + const { cert } = https; + const additionalCerts = Array.isArray(cert) ? cert : [cert]; + + // TODO(alanagius): Remove the `if` check once we only support Node.js 22.18.0+ and 24.5.0+. + if (getCACertificates && setDefaultCACertificates) { + const currentCerts = getCACertificates('default'); + setDefaultCACertificates([...currentCerts, ...additionalCerts]); + + return; + } + + // TODO(alanagius): Remove the below and `undici` dependency once we only support Node.js 22.18.0+ and 24.5.0+. + const { getGlobalDispatcher, setGlobalDispatcher, Agent } = await import('undici'); + const originalDispatcher = getGlobalDispatcher(); + const ca = [...rootCertificates, ...additionalCerts]; + const extraNodeCerts = process.env['NODE_EXTRA_CA_CERTS']; + if (extraNodeCerts) { + ca.push(await readFile(extraNodeCerts)); + } + + setGlobalDispatcher( + new Agent({ + connect: { + ca, + }, + }), + ); + + httpServer?.on('close', () => { + setGlobalDispatcher(originalDispatcher); + }); + }, + }; +} diff --git a/packages/angular/build/src/tools/vite/plugins/ssr-transform-plugin.ts b/packages/angular/build/src/tools/vite/plugins/ssr-transform-plugin.ts index 0ac7b92d442d..90d183acde02 100644 --- a/packages/angular/build/src/tools/vite/plugins/ssr-transform-plugin.ts +++ b/packages/angular/build/src/tools/vite/plugins/ssr-transform-plugin.ts @@ -8,10 +8,9 @@ import remapping, { SourceMapInput } from '@ampproject/remapping'; import type { Plugin } from 'vite'; -import { loadEsmModule } from '../../../utils/load-esm'; export async function createAngularSsrTransformPlugin(workspaceRoot: string): Promise { - const { normalizePath } = await loadEsmModule('vite'); + const { normalizePath } = await import('vite'); return { name: 'vite:angular-ssr-transform', diff --git a/packages/angular/build/src/tools/vite/utils.ts b/packages/angular/build/src/tools/vite/utils.ts index 2322eb210bec..2f7cfba84306 100644 --- a/packages/angular/build/src/tools/vite/utils.ts +++ b/packages/angular/build/src/tools/vite/utils.ts @@ -7,8 +7,10 @@ */ import { lookup as lookupMimeType } from 'mrmime'; +import { builtinModules, isBuiltin } from 'node:module'; import { extname } from 'node:path'; import type { DepOptimizationConfig } from 'vite'; +import type { ExternalResultMetadata } from '../esbuild/bundler-execution-result'; import { JavaScriptTransformer } from '../esbuild/javascript-transformer'; import { getFeatureSupport } from '../esbuild/utils'; @@ -109,3 +111,61 @@ export function getDepOptimizationConfig({ }, }; } + +export interface DevServerExternalResultMetadata { + implicitBrowser: string[]; + implicitServer: string[]; + explicitBrowser: string[]; + explicitServer: string[]; +} + +export function isAbsoluteUrl(url: string): boolean { + try { + new URL(url); + + return true; + } catch { + return false; + } +} + +export function updateExternalMetadata( + result: { detail?: { externalMetadata?: ExternalResultMetadata } }, + externalMetadata: DevServerExternalResultMetadata, + externalDependencies: string[] | undefined, + explicitPackagesOnly: boolean = false, +): void { + if (!result.detail?.['externalMetadata']) { + return; + } + + const { implicitBrowser, implicitServer, explicit } = result.detail['externalMetadata']; + const implicitServerFiltered = implicitServer.filter((m) => !isBuiltin(m) && !isAbsoluteUrl(m)); + const implicitBrowserFiltered = implicitBrowser.filter((m) => !isAbsoluteUrl(m)); + const explicitBrowserFiltered = explicitPackagesOnly + ? explicit.filter((m) => !isAbsoluteUrl(m)) + : explicit; + + // Empty Arrays to avoid growing unlimited with every re-build. + externalMetadata.explicitBrowser.length = 0; + externalMetadata.explicitServer.length = 0; + externalMetadata.implicitServer.length = 0; + externalMetadata.implicitBrowser.length = 0; + + const externalDeps = externalDependencies ?? []; + externalMetadata.explicitBrowser.push(...explicitBrowserFiltered, ...externalDeps); + externalMetadata.explicitServer.push( + ...explicitBrowserFiltered, + ...externalDeps, + ...builtinModules, + ); + externalMetadata.implicitServer.push(...implicitServerFiltered); + externalMetadata.implicitBrowser.push(...implicitBrowserFiltered); + + // The below needs to be sorted as Vite uses these options as part of the hashing invalidation algorithm. + // See: https://github.com/vitejs/vite/blob/0873bae0cfe0f0718ad2f5743dd34a17e4ab563d/packages/vite/src/node/optimizer/index.ts#L1203-L1239 + externalMetadata.explicitBrowser.sort(); + externalMetadata.explicitServer.sort(); + externalMetadata.implicitServer.sort(); + externalMetadata.implicitBrowser.sort(); +} diff --git a/packages/angular/build/src/typings.d.ts b/packages/angular/build/src/typings.d.ts deleted file mode 100644 index 6296581de448..000000000000 --- a/packages/angular/build/src/typings.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.dev/license - */ - -// The `bundled_beasties` causes issues with module mappings in Bazel, -// leading to unexpected behavior with esbuild. Specifically, the problem occurs -// when esbuild resolves to a different module or version than expected, due to -// how Bazel handles module mappings. -// -// This change aims to resolve esbuild types correctly and maintain consistency -// in the Bazel build process. - -declare module 'esbuild' { - export * from 'esbuild-wasm'; -} - -/** - * Augment the Node.js module builtin types to support the v22.8+ compile cache functions - */ -declare module 'node:module' { - function getCompileCacheDir(): string | undefined; -} diff --git a/packages/angular/build/src/utils/check-port.ts b/packages/angular/build/src/utils/check-port.ts index 58e5a0a0f854..d7c04f0b9f72 100644 --- a/packages/angular/build/src/utils/check-port.ts +++ b/packages/angular/build/src/utils/check-port.ts @@ -32,7 +32,7 @@ export async function checkPort(port: number, host: string): Promise { return; } - if (!isTTY) { + if (!isTTY()) { reject(createInUseError(port)); return; diff --git a/packages/angular/build/src/utils/environment-options.ts b/packages/angular/build/src/utils/environment-options.ts index ea06fea2d09f..80f71d56c119 100644 --- a/packages/angular/build/src/utils/environment-options.ts +++ b/packages/angular/build/src/utils/environment-options.ts @@ -8,22 +8,48 @@ import { availableParallelism } from 'node:os'; -function isDisabled(variable: string): boolean { - return variable === '0' || variable.toLowerCase() === 'false'; -} +/** A set of strings that are considered "truthy" when parsing environment variables. */ +const TRUTHY_VALUES = new Set(['1', 'true']); -function isEnabled(variable: string): boolean { - return variable === '1' || variable.toLowerCase() === 'true'; -} +/** A set of strings that are considered "falsy" when parsing environment variables. */ +const FALSY_VALUES = new Set(['0', 'false']); +/** + * Checks if an environment variable is present and has a non-empty value. + * @param variable The environment variable to check. + * @returns `true` if the variable is a non-empty string. + */ function isPresent(variable: string | undefined): variable is string { return typeof variable === 'string' && variable !== ''; } +/** + * Parses an environment variable into a boolean or undefined. + * @returns `true` if the variable is truthy ('1', 'true'). + * @returns `false` if the variable is falsy ('0', 'false'). + * @returns `undefined` if the variable is not present or has an unknown value. + */ +function parseTristate(variable: string | undefined): boolean | undefined { + if (!isPresent(variable)) { + return undefined; + } + + const value = variable.toLowerCase(); + if (TRUTHY_VALUES.has(value)) { + return true; + } + if (FALSY_VALUES.has(value)) { + return false; + } + + // TODO: Consider whether a warning is useful in this case of a malformed value + return undefined; +} + // Optimization and mangling const debugOptimizeVariable = process.env['NG_BUILD_DEBUG_OPTIMIZE']; const debugOptimize = (() => { - if (!isPresent(debugOptimizeVariable) || isDisabled(debugOptimizeVariable)) { + if (!isPresent(debugOptimizeVariable) || parseTristate(debugOptimizeVariable) === false) { return { mangle: true, minify: true, @@ -37,7 +63,7 @@ const debugOptimize = (() => { beautify: true, }; - if (isEnabled(debugOptimizeVariable)) { + if (parseTristate(debugOptimizeVariable) === true) { return debugValue; } @@ -58,12 +84,22 @@ const debugOptimize = (() => { return debugValue; })(); -const mangleVariable = process.env['NG_BUILD_MANGLE']; -export const allowMangle = isPresent(mangleVariable) - ? !isDisabled(mangleVariable) - : debugOptimize.mangle; +/** + * Allows disabling of code mangling when the `NG_BUILD_MANGLE` environment variable is set to `0` or `false`. + * This is useful for debugging build output. + */ +export const allowMangle = parseTristate(process.env['NG_BUILD_MANGLE']) ?? debugOptimize.mangle; +/** + * Allows beautification of build output when the `NG_BUILD_DEBUG_OPTIMIZE` environment variable is enabled. + * This is useful for debugging build output. + */ export const shouldBeautify = debugOptimize.beautify; + +/** + * Allows disabling of code minification when the `NG_BUILD_DEBUG_OPTIMIZE` environment variable is enabled. + * This is useful for debugging build output. + */ export const allowMinify = debugOptimize.minify; /** @@ -76,39 +112,64 @@ export const allowMinify = debugOptimize.minify; * */ const maxWorkersVariable = process.env['NG_BUILD_MAX_WORKERS']; + +/** + * The maximum number of workers to use for parallel processing. + * This can be controlled by the `NG_BUILD_MAX_WORKERS` environment variable. + */ export const maxWorkers = isPresent(maxWorkersVariable) ? +maxWorkersVariable : Math.min(4, Math.max(availableParallelism() - 1, 1)); -const parallelTsVariable = process.env['NG_BUILD_PARALLEL_TS']; -export const useParallelTs = !isPresent(parallelTsVariable) || !isDisabled(parallelTsVariable); +/** + * When `NG_BUILD_PARALLEL_TS` is set to `0` or `false`, parallel TypeScript compilation is disabled. + */ +export const useParallelTs = parseTristate(process.env['NG_BUILD_PARALLEL_TS']) !== false; -const debugPerfVariable = process.env['NG_BUILD_DEBUG_PERF']; -export const debugPerformance = isPresent(debugPerfVariable) && isEnabled(debugPerfVariable); +/** + * When `NG_BUILD_DEBUG_PERF` is enabled, performance debugging information is printed. + */ +export const debugPerformance = parseTristate(process.env['NG_BUILD_DEBUG_PERF']) === true; -const watchRootVariable = process.env['NG_BUILD_WATCH_ROOT']; -export const shouldWatchRoot = isPresent(watchRootVariable) && isEnabled(watchRootVariable); +/** + * When `NG_BUILD_WATCH_ROOT` is enabled, the build will watch the root directory for changes. + */ +export const shouldWatchRoot = parseTristate(process.env['NG_BUILD_WATCH_ROOT']) === true; -const typeCheckingVariable = process.env['NG_BUILD_TYPE_CHECK']; -export const useTypeChecking = - !isPresent(typeCheckingVariable) || !isDisabled(typeCheckingVariable); +/** + * When `NG_BUILD_TYPE_CHECK` is set to `0` or `false`, type checking is disabled. + */ +export const useTypeChecking = parseTristate(process.env['NG_BUILD_TYPE_CHECK']) !== false; -const buildLogsJsonVariable = process.env['NG_BUILD_LOGS_JSON']; -export const useJSONBuildLogs = - isPresent(buildLogsJsonVariable) && isEnabled(buildLogsJsonVariable); +/** + * When `NG_BUILD_LOGS_JSON` is enabled, build logs will be output in JSON format. + */ +export const useJSONBuildLogs = parseTristate(process.env['NG_BUILD_LOGS_JSON']) === true; -const optimizeChunksVariable = process.env['NG_BUILD_OPTIMIZE_CHUNKS']; -export const shouldOptimizeChunks = - isPresent(optimizeChunksVariable) && isEnabled(optimizeChunksVariable); +/** + * When `NG_BUILD_OPTIMIZE_CHUNKS` is enabled, the build will optimize chunks. + */ +export const shouldOptimizeChunks = parseTristate(process.env['NG_BUILD_OPTIMIZE_CHUNKS']) === true; + +/** + * When `NG_HMR_CSTYLES` is enabled, component styles will be hot-reloaded. + */ +export const useComponentStyleHmr = parseTristate(process.env['NG_HMR_CSTYLES']) === true; -const hmrComponentStylesVariable = process.env['NG_HMR_CSTYLES']; -export const useComponentStyleHmr = - isPresent(hmrComponentStylesVariable) && isEnabled(hmrComponentStylesVariable); +/** + * When `NG_HMR_TEMPLATES` is set to `0` or `false`, component templates will not be hot-reloaded. + */ +export const useComponentTemplateHmr = parseTristate(process.env['NG_HMR_TEMPLATES']) !== false; + +/** + * When `NG_BUILD_PARTIAL_SSR` is enabled, a partial server-side rendering build will be performed. + */ +export const usePartialSsrBuild = parseTristate(process.env['NG_BUILD_PARTIAL_SSR']) === true; -const hmrComponentTemplateVariable = process.env['NG_HMR_TEMPLATES']; -export const useComponentTemplateHmr = - !isPresent(hmrComponentTemplateVariable) || !isDisabled(hmrComponentTemplateVariable); +const bazelBinDirectory = process.env['BAZEL_BINDIR']; +const bazelExecRoot = process.env['JS_BINARY__EXECROOT']; -const partialSsrBuildVariable = process.env['NG_BUILD_PARTIAL_SSR']; -export const usePartialSsrBuild = - isPresent(partialSsrBuildVariable) && isEnabled(partialSsrBuildVariable); +export const bazelEsbuildPluginPath = + bazelBinDirectory && bazelExecRoot + ? process.env['NG_INTERNAL_ESBUILD_PLUGINS_DO_NOT_USE'] + : undefined; diff --git a/packages/angular/build/src/utils/index-file/augment-index-html.ts b/packages/angular/build/src/utils/index-file/augment-index-html.ts index 7a30770fa450..21ba39b39cc4 100644 --- a/packages/angular/build/src/utils/index-file/augment-index-html.ts +++ b/packages/angular/build/src/utils/index-file/augment-index-html.ts @@ -8,7 +8,6 @@ import { createHash } from 'node:crypto'; import { extname } from 'node:path'; -import { loadEsmModule } from '../load-esm'; import { htmlRewritingStream } from './html-rewriting-stream'; import { VALID_SELF_CLOSING_TAGS } from './valid-self-closing-tags'; @@ -352,12 +351,7 @@ async function getLanguageDirection( async function getLanguageDirectionFromLocales(locale: string): Promise { try { - const localeData = ( - await loadEsmModule( - `@angular/common/locales/${locale}`, - ) - ).default; - + const localeData = (await import(`@angular/common/locales/${locale}`)).default; const dir = localeData[localeData.length - 2]; return isString(dir) ? dir : undefined; diff --git a/packages/angular/build/src/utils/index-file/augment-index-html_spec.ts b/packages/angular/build/src/utils/index-file/augment-index-html_spec.ts index 7ea16ab6121b..55adf8d88f0b 100644 --- a/packages/angular/build/src/utils/index-file/augment-index-html_spec.ts +++ b/packages/angular/build/src/utils/index-file/augment-index-html_spec.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.dev/license */ -import { tags } from '@angular-devkit/core'; import { AugmentIndexHtmlOptions, augmentIndexHtml } from './augment-index-html'; describe('augment-index-html', () => { @@ -25,7 +24,7 @@ describe('augment-index-html', () => { }; const oneLineHtml = (html: TemplateStringsArray) => - tags.stripIndents`${html}`.replace(/(>\s+)/g, '>'); + `${html}`.replace(/(>\s+)/g, '>').replace(/\s+ { const { content } = await augmentIndexHtml({ diff --git a/packages/angular/build/src/utils/index-file/html-rewriting-stream.ts b/packages/angular/build/src/utils/index-file/html-rewriting-stream.ts index dbeeadcb2fc1..baf494be033c 100644 --- a/packages/angular/build/src/utils/index-file/html-rewriting-stream.ts +++ b/packages/angular/build/src/utils/index-file/html-rewriting-stream.ts @@ -9,7 +9,6 @@ import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import type { RewritingStream } from 'parse5-html-rewriting-stream'; -import { loadEsmModule } from '../load-esm'; // Export helper types for the rewriter export type StartTag = Parameters[0]; @@ -20,9 +19,7 @@ export async function htmlRewritingStream(content: string): Promise<{ rewriter: RewritingStream; transformedContent: () => Promise; }> { - const { RewritingStream } = await loadEsmModule( - 'parse5-html-rewriting-stream', - ); + const { RewritingStream } = await import('parse5-html-rewriting-stream'); const rewriter = new RewritingStream(); return { diff --git a/packages/angular/build/src/utils/load-proxy-config.ts b/packages/angular/build/src/utils/load-proxy-config.ts index e590ee9efc6c..cf4cb9e3c03e 100644 --- a/packages/angular/build/src/utils/load-proxy-config.ts +++ b/packages/angular/build/src/utils/load-proxy-config.ts @@ -49,33 +49,20 @@ export async function loadProxyConfiguration( break; } - case '.mjs': - // Load the ESM configuration file using the TypeScript dynamic import workaround. - // Once TypeScript provides support for keeping the dynamic import this workaround can be - // changed to a direct dynamic import. - proxyConfiguration = await loadEsmModule<{ default: unknown }>(pathToFileURL(proxyPath)); - break; - case '.cjs': - proxyConfiguration = require(proxyPath); - break; - default: - // The file could be either CommonJS or ESM. - // CommonJS is tried first then ESM if loading fails. + default: { try { - proxyConfiguration = require(proxyPath); - break; + proxyConfiguration = await import(proxyPath); } catch (e) { assertIsError(e); - if (e.code === 'ERR_REQUIRE_ESM' || e.code === 'ERR_REQUIRE_ASYNC_MODULE') { - // Load the ESM configuration file using the TypeScript dynamic import workaround. - // Once TypeScript provides support for keeping the dynamic import this workaround can be - // changed to a direct dynamic import. - proxyConfiguration = await loadEsmModule<{ default: unknown }>(pathToFileURL(proxyPath)); - break; + if (e.code !== 'ERR_REQUIRE_ASYNC_MODULE') { + throw e; } - throw e; + proxyConfiguration = await loadEsmModule<{ default: unknown }>(pathToFileURL(proxyPath)); } + + break; + } } if ('default' in proxyConfiguration) { diff --git a/packages/angular/build/src/utils/load-translations.ts b/packages/angular/build/src/utils/load-translations.ts index eeac280cbf9b..e202273dc73d 100644 --- a/packages/angular/build/src/utils/load-translations.ts +++ b/packages/angular/build/src/utils/load-translations.ts @@ -9,7 +9,6 @@ import type { Diagnostics } from '@angular/localize/tools'; import { createHash } from 'node:crypto'; import * as fs from 'node:fs'; -import { loadEsmModule } from './load-esm'; export type TranslationLoader = (path: string) => { translations: Record; @@ -62,7 +61,7 @@ async function importParsers() { Xliff1TranslationParser, Xliff2TranslationParser, XtbTranslationParser, - } = await loadEsmModule('@angular/localize/tools'); + } = await import('@angular/localize/tools'); const diagnostics = new Diagnostics(); const parsers = { diff --git a/packages/angular/build/src/utils/postcss-configuration.ts b/packages/angular/build/src/utils/postcss-configuration.ts index 1861f9f2b1db..6f3f1f3671f9 100644 --- a/packages/angular/build/src/utils/postcss-configuration.ts +++ b/packages/angular/build/src/utils/postcss-configuration.ts @@ -71,9 +71,13 @@ async function readPostcssConfiguration( return config; } -export async function loadPostcssConfiguration( - searchDirectories: SearchDirectory[], -): Promise { +export async function loadPostcssConfiguration(searchDirectories: SearchDirectory[]): Promise< + | { + configPath: string; + config: PostcssConfiguration; + } + | undefined +> { const configPath = findFile(searchDirectories, postcssConfigurationFiles); if (!configPath) { return undefined; @@ -101,7 +105,7 @@ export async function loadPostcssConfiguration( } } - return config; + return { config, configPath }; } // Normalize plugin object map form @@ -119,5 +123,5 @@ export async function loadPostcssConfiguration( config.plugins.push([name, options]); } - return config; + return { config, configPath }; } diff --git a/packages/angular/build/src/utils/project-metadata.ts b/packages/angular/build/src/utils/project-metadata.ts index bc997652fef1..31912d5e9905 100644 --- a/packages/angular/build/src/utils/project-metadata.ts +++ b/packages/angular/build/src/utils/project-metadata.ts @@ -15,7 +15,7 @@ import { join } from 'node:path'; * @returns A normalized path string. */ export function normalizeDirectoryPath(path: string): string { - const last = path[path.length - 1]; + const last = path.at(-1); if (last === '/' || last === '\\') { return path.slice(0, -1); } diff --git a/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/loader-hooks.ts b/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/loader-hooks.ts index 9e1a657366a0..1d0d9df32d30 100644 --- a/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/loader-hooks.ts +++ b/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/loader-hooks.ts @@ -8,9 +8,9 @@ import assert from 'node:assert'; import { randomUUID } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; import { join } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import { JavaScriptTransformer } from '../../../tools/esbuild/javascript-transformer'; /** * @note For some unknown reason, setting `globalThis.ngServerMode = true` does not work when using ESM loader hooks. @@ -32,14 +32,6 @@ export interface ESMInMemoryFileLoaderWorkerData { let memoryVirtualRootUrl: string; let outputFiles: Record; -const javascriptTransformer = new JavaScriptTransformer( - // Always enable JIT linking to support applications built with and without AOT. - // In a development environment the additional scope information does not - // have a negative effect unlike production where final output size is relevant. - { sourcemap: true, jit: true }, - 1, -); - export function initialize(data: ESMInMemoryFileLoaderWorkerData) { // This path does not actually exist but is used to overlay the in memory files with the // actual filesystem for resolution purposes. @@ -137,7 +129,7 @@ export async function load(url: string, context: { format?: string | null }, nex // need linking are ESM only. if (format === 'module' && isFileProtocol(url)) { const filePath = fileURLToPath(url); - let source = await javascriptTransformer.transformFile(filePath); + let source = await readFile(filePath); if (filePath.includes('@angular/')) { // Prepend 'var ngServerMode=true;' to the source. @@ -158,11 +150,3 @@ export async function load(url: string, context: { format?: string | null }, nex function isFileProtocol(url: string): boolean { return url.startsWith('file://'); } - -function handleProcessExit(): void { - void javascriptTransformer.close(); -} - -process.once('exit', handleProcessExit); -process.once('SIGINT', handleProcessExit); -process.once('uncaughtException', handleProcessExit); diff --git a/packages/angular/build/src/utils/server-rendering/launch-server.ts b/packages/angular/build/src/utils/server-rendering/launch-server.ts index cfb15b0d979b..95b2784c6f63 100644 --- a/packages/angular/build/src/utils/server-rendering/launch-server.ts +++ b/packages/angular/build/src/utils/server-rendering/launch-server.ts @@ -8,7 +8,6 @@ import assert from 'node:assert'; import { createServer } from 'node:http'; -import { loadEsmModule } from '../load-esm'; import { loadEsmModuleFromMemory } from './load-esm-from-memory'; import { isSsrNodeRequestHandler, isSsrRequestHandler } from './utils'; @@ -21,8 +20,9 @@ export const DEFAULT_URL = new URL('http://ng-localhost/'); */ export async function launchServer(): Promise { const { reqHandler } = await loadEsmModuleFromMemory('./server.mjs'); - const { createWebRequestFromNodeRequest, writeResponseToNodeResponse } = - await loadEsmModule('@angular/ssr/node'); + const { createWebRequestFromNodeRequest, writeResponseToNodeResponse } = (await import( + '@angular/ssr/node' as string + )) as typeof import('@angular/ssr/node', { with: { 'resolution-mode': 'import' } }); if (!isSsrNodeRequestHandler(reqHandler) && !isSsrRequestHandler(reqHandler)) { return DEFAULT_URL; diff --git a/packages/angular/build/src/utils/server-rendering/load-esm-from-memory.ts b/packages/angular/build/src/utils/server-rendering/load-esm-from-memory.ts index 1d19a07e61de..87ca9928a86f 100644 --- a/packages/angular/build/src/utils/server-rendering/load-esm-from-memory.ts +++ b/packages/angular/build/src/utils/server-rendering/load-esm-from-memory.ts @@ -7,6 +7,7 @@ */ import type { ApplicationRef, Type } from '@angular/core'; +import type { BootstrapContext } from '@angular/platform-browser'; import type { ɵextractRoutesAndCreateRouteTree, ɵgetOrCreateAngularServerApp } from '@angular/ssr'; import { assertIsError } from '../error'; import { loadEsmModule } from '../load-esm'; @@ -15,7 +16,7 @@ import { loadEsmModule } from '../load-esm'; * Represents the exports available from the main server bundle. */ interface MainServerBundleExports { - default: (() => Promise) | Type; + default: ((context: BootstrapContext) => Promise) | Type; ɵextractRoutesAndCreateRouteTree: typeof ɵextractRoutesAndCreateRouteTree; ɵgetOrCreateAngularServerApp: typeof ɵgetOrCreateAngularServerApp; } diff --git a/packages/angular/build/src/utils/server-rendering/manifest.ts b/packages/angular/build/src/utils/server-rendering/manifest.ts index 2dfad0ff2dfb..b01bff38b58f 100644 --- a/packages/angular/build/src/utils/server-rendering/manifest.ts +++ b/packages/angular/build/src/utils/server-rendering/manifest.ts @@ -77,7 +77,7 @@ export function generateAngularServerAppEngineManifest( // Remove trailing slash but retain leading slash. let basePath = baseHref || '/'; - if (basePath.length > 1 && basePath[basePath.length - 1] === '/') { + if (basePath.length > 1 && basePath.at(-1) === '/') { basePath = basePath.slice(0, -1); } diff --git a/packages/angular/build/src/utils/server-rendering/prerender.ts b/packages/angular/build/src/utils/server-rendering/prerender.ts index e087262a7f0c..f33f851f10c4 100644 --- a/packages/angular/build/src/utils/server-rendering/prerender.ts +++ b/packages/angular/build/src/utils/server-rendering/prerender.ts @@ -14,7 +14,7 @@ import { BuildOutputFile, BuildOutputFileType } from '../../tools/esbuild/bundle import { BuildOutputAsset } from '../../tools/esbuild/bundler-execution-result'; import { assertIsError } from '../error'; import { toPosixPath } from '../path'; -import { urlJoin } from '../url'; +import { addLeadingSlash, addTrailingSlash, joinUrlParts, stripLeadingSlash } from '../url'; import { WorkerPool } from '../worker-pool'; import { IMPORT_EXEC_ARGV } from './esm-in-memory-loader/utils'; import { SERVER_APP_MANIFEST_FILENAME } from './manifest'; @@ -26,6 +26,7 @@ import { WritableSerializableRouteTreeNode, } from './models'; import type { RenderWorkerData } from './render-worker'; +import { generateRedirectStaticPage } from './utils'; type PrerenderOptions = NormalizedApplicationBuildOptions['prerenderOptions']; type AppShellOptions = NormalizedApplicationBuildOptions['appShellOptions']; @@ -239,7 +240,7 @@ async function renderPages( ? addLeadingSlash(route.slice(baseHrefPathnameWithLeadingSlash.length)) : route; - const outPath = posix.join(removeLeadingSlash(routeWithoutBaseHref), 'index.html'); + const outPath = stripLeadingSlash(posix.join(routeWithoutBaseHref, 'index.html')); if (typeof redirectTo === 'string') { output[outPath] = { content: generateRedirectStaticPage(redirectTo), appShellRoute: false }; @@ -297,7 +298,7 @@ async function getAllRoutes( let appShellRoute: string | undefined; if (appShellOptions) { - appShellRoute = urlJoin(baseHref, appShellOptions.route); + appShellRoute = joinUrlParts(baseHref, appShellOptions.route); routes.push({ renderMode: RouteRenderMode.Prerender, @@ -310,7 +311,7 @@ async function getAllRoutes( for (const route of routesFromFile) { routes.push({ renderMode: RouteRenderMode.Prerender, - route: urlJoin(baseHref, route.trim()), + route: joinUrlParts(baseHref, route.trim()), }); } } @@ -368,40 +369,3 @@ async function getAllRoutes( void renderWorker.destroy(); } } - -function addLeadingSlash(value: string): string { - return value[0] === '/' ? value : '/' + value; -} - -function addTrailingSlash(url: string): string { - return url[url.length - 1] === '/' ? url : `${url}/`; -} - -function removeLeadingSlash(value: string): string { - return value[0] === '/' ? value.slice(1) : value; -} - -/** - * Generates a static HTML page with a meta refresh tag to redirect the user to a specified URL. - * - * This function creates a simple HTML page that performs a redirect using a meta tag. - * It includes a fallback link in case the meta-refresh doesn't work. - * - * @param url - The URL to which the page should redirect. - * @returns The HTML content of the static redirect page. - */ -function generateRedirectStaticPage(url: string): string { - return ` - - - - - Redirecting - - - -
Redirecting to ${url}
- - -`.trim(); -} diff --git a/packages/angular/build/src/utils/server-rendering/render-worker.ts b/packages/angular/build/src/utils/server-rendering/render-worker.ts index 92fad35df32a..7ded0550b826 100644 --- a/packages/angular/build/src/utils/server-rendering/render-worker.ts +++ b/packages/angular/build/src/utils/server-rendering/render-worker.ts @@ -12,6 +12,7 @@ import type { ESMInMemoryFileLoaderWorkerData } from './esm-in-memory-loader/loa import { patchFetchToLoadInMemoryAssets } from './fetch-patch'; import { DEFAULT_URL, launchServer } from './launch-server'; import { loadEsmModuleFromMemory } from './load-esm-from-memory'; +import { generateRedirectStaticPage } from './utils'; export interface RenderWorkerData extends ESMInMemoryFileLoaderWorkerData { assetFiles: Record; @@ -48,10 +49,20 @@ async function renderPage({ url }: RenderOptions): Promise { new Request(new URL(url, serverURL), { signal: AbortSignal.timeout(30_000) }), ); - return response ? response.text() : null; + if (!response) { + return null; + } + + const location = response.headers.get('Location'); + + return location ? generateRedirectStaticPage(location) : response.text(); } async function initialize() { + // Load the compiler because `@angular/ssr/node` depends on `@angular/` packages, + // which must be processed by the runtime linker, even if they are not used. + await import('@angular/compiler'); + if (outputMode !== undefined && hasSsrEntry) { serverURL = await launchServer(); } diff --git a/packages/angular/build/src/utils/server-rendering/routes-extractor-worker.ts b/packages/angular/build/src/utils/server-rendering/routes-extractor-worker.ts index 1487db07e811..423a71e83ba5 100644 --- a/packages/angular/build/src/utils/server-rendering/routes-extractor-worker.ts +++ b/packages/angular/build/src/utils/server-rendering/routes-extractor-worker.ts @@ -28,6 +28,10 @@ const { outputMode, hasSsrEntry } = workerData as { /** Renders an application based on a provided options. */ async function extractRoutes(): Promise { + // Load the compiler because `@angular/ssr/node` depends on `@angular/` packages, + // which must be processed by the runtime linker, even if they are not used. + await import('@angular/compiler'); + const serverURL = outputMode !== undefined && hasSsrEntry ? await launchServer() : DEFAULT_URL; patchFetchToLoadInMemoryAssets(serverURL); diff --git a/packages/angular/build/src/utils/server-rendering/utils.ts b/packages/angular/build/src/utils/server-rendering/utils.ts index 83c90187178b..c740d4de06c4 100644 --- a/packages/angular/build/src/utils/server-rendering/utils.ts +++ b/packages/angular/build/src/utils/server-rendering/utils.ts @@ -7,7 +7,7 @@ */ import type { createRequestHandler } from '@angular/ssr'; -import type { createNodeRequestHandler } from '@angular/ssr/node'; +import type { createNodeRequestHandler } from '@angular/ssr/node' with { 'resolution-mode': 'import' }; export function isSsrNodeRequestHandler( value: unknown, @@ -19,3 +19,28 @@ export function isSsrRequestHandler( ): value is ReturnType { return typeof value === 'function' && '__ng_request_handler__' in value; } + +/** + * Generates a static HTML page with a meta refresh tag to redirect the user to a specified URL. + * + * This function creates a simple HTML page that performs a redirect using a meta tag. + * It includes a fallback link in case the meta-refresh doesn't work. + * + * @param url - The URL to which the page should redirect. + * @returns The HTML content of the static redirect page. + */ +export function generateRedirectStaticPage(url: string): string { + return ` + + + + + Redirecting + + + +
Redirecting to ${url}
+ + +`.trim(); +} diff --git a/packages/angular/build/src/utils/service-worker.ts b/packages/angular/build/src/utils/service-worker.ts index c6f95f99a595..1535684f635c 100644 --- a/packages/angular/build/src/utils/service-worker.ts +++ b/packages/angular/build/src/utils/service-worker.ts @@ -6,14 +6,16 @@ * found in the LICENSE file at https://angular.dev/license */ -import type { Config, Filesystem } from '@angular/service-worker/config'; +import type { + Config, + Filesystem, +} from '@angular/service-worker/config' with { 'resolution-mode': 'import' }; import * as crypto from 'node:crypto'; -import { existsSync, constants as fsConstants, promises as fsPromises } from 'node:fs'; +import { existsSync, promises as fsPromises } from 'node:fs'; import * as path from 'node:path'; import { BuildOutputFile, BuildOutputFileType } from '../tools/esbuild/bundler-context'; import { BuildOutputAsset } from '../tools/esbuild/bundler-execution-result'; import { assertIsError } from './error'; -import { loadEsmModule } from './load-esm'; import { toPosixPath } from './path'; class CliFilesystem implements Filesystem { @@ -216,17 +218,14 @@ export async function augmentAppWithServiceWorkerCore( serviceWorkerFilesystem: Filesystem, baseHref: string, ): Promise<{ manifest: string; assetFiles: { source: string; destination: string }[] }> { - // Load ESM `@angular/service-worker/config` using the TypeScript dynamic import workaround. - // Once TypeScript provides support for keeping the dynamic import this workaround can be - // changed to a direct dynamic import. - const GeneratorConstructor = ( - await loadEsmModule( - '@angular/service-worker/config', - ) - ).Generator; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const { Generator } = (await import('@angular/service-worker/config' as any)) as typeof import( + '@angular/service-worker/config', + { with: { 'resolution-mode': 'import' } } + ); // Generate the manifest - const generator = new GeneratorConstructor(serviceWorkerFilesystem, baseHref); + const generator = new Generator(serviceWorkerFilesystem, baseHref); const output = await generator.process(config); // Write the manifest diff --git a/packages/angular/build/src/utils/supported-browsers.ts b/packages/angular/build/src/utils/supported-browsers.ts index a8546a039082..d871d75789d3 100644 --- a/packages/angular/build/src/utils/supported-browsers.ts +++ b/packages/angular/build/src/utils/supported-browsers.ts @@ -8,14 +8,15 @@ import browserslist from 'browserslist'; +// The below is replaced by bazel `npm_package`. +const BASELINE_DATE = 'BASELINE-DATE-PLACEHOLDER'; + export function getSupportedBrowsers( projectRoot: string, logger: { warn(message: string): void }, ): string[] { // Read the browserslist configuration containing Angular's browser support policy. - const angularBrowserslist = browserslist(undefined, { - path: require.resolve('../../.browserslistrc'), - }); + const angularBrowserslist = browserslist(`baseline widely available on ${getBaselineDate()}`); // Use Angular's configuration as the default. browserslist.defaults = angularBrowserslist; @@ -60,3 +61,8 @@ export function getSupportedBrowsers( return Array.from(browsersFromConfigOrDefault); } + +function getBaselineDate(): string { + // Unlike `npm_package`, `ts_project` which is used to run unit tests does not support substitutions. + return BASELINE_DATE[0] === 'B' ? '2025-01-01' : BASELINE_DATE; +} diff --git a/packages/angular/build/src/utils/test-files.ts b/packages/angular/build/src/utils/test-files.ts new file mode 100644 index 000000000000..522bb1e778c0 --- /dev/null +++ b/packages/angular/build/src/utils/test-files.ts @@ -0,0 +1,51 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import * as fs from 'node:fs/promises'; +import path from 'node:path'; +import { ResultFile } from '../builders/application/results'; +import { BuildOutputFileType } from '../tools/esbuild/bundler-context'; +import { emitFilesToDisk } from '../tools/esbuild/utils'; + +/** + * Writes a collection of build result files to a specified directory. + * This function handles both in-memory and on-disk files, creating subdirectories + * as needed. + * + * @param files A map of file paths to `ResultFile` objects, representing the build output. + * @param testDir The absolute path to the directory where the files should be written. + */ +export async function writeTestFiles( + files: Record, + testDir: string, +): Promise { + const directoryExists = new Set(); + // Writes the test related output files to disk and ensures the containing directories are present + await emitFilesToDisk(Object.entries(files), async ([filePath, file]) => { + if (file.type !== BuildOutputFileType.Browser && file.type !== BuildOutputFileType.Media) { + return; + } + + const fullFilePath = path.join(testDir, filePath); + + // Ensure output subdirectories exist + const fileBasePath = path.dirname(fullFilePath); + if (fileBasePath && !directoryExists.has(fileBasePath)) { + await fs.mkdir(fileBasePath, { recursive: true }); + directoryExists.add(fileBasePath); + } + + if (file.origin === 'memory') { + // Write file contents + await fs.writeFile(fullFilePath, file.contents); + } else { + // Copy file contents + await fs.copyFile(file.inputPath, fullFilePath, fs.constants.COPYFILE_FICLONE); + } + }); +} diff --git a/packages/angular/build/src/utils/url.ts b/packages/angular/build/src/utils/url.ts index d3f1e5791276..689eac37eab5 100644 --- a/packages/angular/build/src/utils/url.ts +++ b/packages/angular/build/src/utils/url.ts @@ -6,11 +6,117 @@ * found in the LICENSE file at https://angular.dev/license */ -export function urlJoin(...parts: string[]): string { - const [p, ...rest] = parts; +/** + * Removes the trailing slash from a URL if it exists. + * + * @param url - The URL string from which to remove the trailing slash. + * @returns The URL string without a trailing slash. + * + * @example + * ```js + * stripTrailingSlash('path/'); // 'path' + * stripTrailingSlash('/path'); // '/path' + * stripTrailingSlash('/'); // '/' + * stripTrailingSlash(''); // '' + * ``` + */ +export function stripTrailingSlash(url: string): string { + // Check if the last character of the URL is a slash + return url.length > 1 && url.at(-1) === '/' ? url.slice(0, -1) : url; +} + +/** + * Removes the leading slash from a URL if it exists. + * + * @param url - The URL string from which to remove the leading slash. + * @returns The URL string without a leading slash. + * + * @example + * ```js + * stripLeadingSlash('/path'); // 'path' + * stripLeadingSlash('/path/'); // 'path/' + * stripLeadingSlash('/'); // '/' + * stripLeadingSlash(''); // '' + * ``` + */ +export function stripLeadingSlash(url: string): string { + // Check if the first character of the URL is a slash + return url.length > 1 && url[0] === '/' ? url.slice(1) : url; +} + +/** + * Adds a leading slash to a URL if it does not already have one. + * + * @param url - The URL string to which the leading slash will be added. + * @returns The URL string with a leading slash. + * + * @example + * ```js + * addLeadingSlash('path'); // '/path' + * addLeadingSlash('/path'); // '/path' + * ``` + */ +export function addLeadingSlash(url: string): string { + // Check if the URL already starts with a slash + return url[0] === '/' ? url : `/${url}`; +} + +/** + * Adds a trailing slash to a URL if it does not already have one. + * + * @param url - The URL string to which the trailing slash will be added. + * @returns The URL string with a trailing slash. + * + * @example + * ```js + * addTrailingSlash('path'); // 'path/' + * addTrailingSlash('path/'); // 'path/' + * ``` + */ +export function addTrailingSlash(url: string): string { + // Check if the URL already end with a slash + return url.at(-1) === '/' ? url : `${url}/`; +} + +/** + * Joins URL parts into a single URL string. + * + * This function takes multiple URL segments, normalizes them by removing leading + * and trailing slashes where appropriate, and then joins them into a single URL. + * + * @param parts - The parts of the URL to join. Each part can be a string with or without slashes. + * @returns The joined URL string, with normalized slashes. + * + * @example + * ```js + * joinUrlParts('path/', '/to/resource'); // '/path/to/resource' + * joinUrlParts('/path/', 'to/resource'); // '/path/to/resource' + * joinUrlParts('http://localhost/path/', 'to/resource'); // 'http://localhost/path/to/resource' + * joinUrlParts('', ''); // '/' + * ``` + */ +export function joinUrlParts(...parts: string[]): string { + const normalizeParts: string[] = []; + for (const part of parts) { + if (part === '') { + // Skip any empty parts + continue; + } + + let normalizedPart = part; + if (part[0] === '/') { + normalizedPart = normalizedPart.slice(1); + } + if (part.at(-1) === '/') { + normalizedPart = normalizedPart.slice(0, -1); + } + if (normalizedPart !== '') { + normalizeParts.push(normalizedPart); + } + } + + const protocolMatch = normalizeParts.length && /^https?:\/\//.test(normalizeParts[0]); + const joinedParts = normalizeParts.join('/'); - // Remove trailing slash from first part - // Join all parts with `/` - // Dedupe double slashes from path names - return p.replace(/\/$/, '') + ('/' + rest.join('/')).replace(/\/\/+/g, '/'); + return protocolMatch ? joinedParts : addLeadingSlash(joinedParts); } diff --git a/packages/angular/cli/BUILD.bazel b/packages/angular/cli/BUILD.bazel index 409dbcd14000..e3ba3c94a886 100644 --- a/packages/angular/cli/BUILD.bazel +++ b/packages/angular/cli/BUILD.bazel @@ -1,11 +1,10 @@ -# Copyright Google Inc. All Rights Reserved. +# Copyright Google LLC. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license load("@npm//:defs.bzl", "npm_link_all_packages") -load("//tools:defaults.bzl", "jasmine_test", "npm_package", "ts_project") -load("//tools:example_db_generator.bzl", "cli_example_db") +load("//tools:defaults.bzl", "jasmine_test", "ng_examples_db", "npm_package", "ts_project") load("//tools:ng_cli_schema_generator.bzl", "cli_json_schema") load("//tools:ts_json_schema.bzl", "ts_json_schema") @@ -15,6 +14,17 @@ package(default_visibility = ["//visibility:public"]) npm_link_all_packages() +genrule( + name = "angular_best_practices", + srcs = [ + "//:node_modules/@angular/core/dir", + ], + outs = ["src/commands/mcp/resources/best-practices.md"], + cmd = """ + cp "$(location //:node_modules/@angular/core/dir)/resources/best-practices.md" $@ + """, +) + RUNTIME_ASSETS = glob( include = [ "bin/**/*", @@ -27,6 +37,7 @@ RUNTIME_ASSETS = glob( ) + [ "//packages/angular/cli:lib/config/schema.json", "//packages/angular/cli:lib/code-examples.db", + ":angular_best_practices", ] ts_project( @@ -38,6 +49,7 @@ ts_project( ], exclude = [ "**/*_spec.ts", + "**/testing/**", ], ) + [ # These files are generated from the JSON schema @@ -56,8 +68,10 @@ ts_project( ":node_modules/algoliasearch", ":node_modules/ini", ":node_modules/jsonc-parser", + ":node_modules/listr2", ":node_modules/npm-package-arg", ":node_modules/pacote", + ":node_modules/parse5-html-rewriting-stream", ":node_modules/resolve", ":node_modules/yargs", ":node_modules/zod", @@ -70,12 +84,12 @@ ts_project( "//:node_modules/@types/semver", "//:node_modules/@types/yargs", "//:node_modules/@types/yarnpkg__lockfile", - "//:node_modules/listr2", "//:node_modules/semver", + "//:node_modules/typescript", ], ) -cli_example_db( +ng_examples_db( name = "cli_example_database", srcs = glob( include = [ @@ -114,7 +128,10 @@ ts_project( name = "angular-cli_test_lib", testonly = True, srcs = glob( - include = ["**/*_spec.ts"], + include = [ + "**/*_spec.ts", + "**/testing/**", + ], exclude = [ # NB: we need to exclude the nested node_modules that is laid out by yarn workspaces "node_modules/**", @@ -124,10 +141,12 @@ ts_project( ":angular-cli", ":node_modules/@angular-devkit/core", ":node_modules/@angular-devkit/schematics", + ":node_modules/@modelcontextprotocol/sdk", ":node_modules/yargs", "//:node_modules/@types/semver", "//:node_modules/@types/yargs", "//:node_modules/semver", + "//:node_modules/typescript", ], ) diff --git a/packages/angular/cli/lib/config/workspace-schema.json b/packages/angular/cli/lib/config/workspace-schema.json index 0c551dc4fb14..3fede1746559 100644 --- a/packages/angular/cli/lib/config/workspace-schema.json +++ b/packages/angular/cli/lib/config/workspace-schema.json @@ -47,7 +47,7 @@ "packageManager": { "description": "Specify which package manager tool to use.", "type": "string", - "enum": ["npm", "cnpm", "yarn", "pnpm", "bun"] + "enum": ["npm", "yarn", "pnpm", "bun"] }, "warnings": { "description": "Control CLI specific console warnings", @@ -101,7 +101,7 @@ "packageManager": { "description": "Specify which package manager tool to use.", "type": "string", - "enum": ["npm", "cnpm", "yarn", "pnpm", "bun"] + "enum": ["npm", "yarn", "pnpm", "bun"] }, "warnings": { "description": "Control CLI specific console warnings", diff --git a/packages/angular/cli/lib/examples/if-block.md b/packages/angular/cli/lib/examples/if-block.md index e0d10ca86891..806e3d05516c 100644 --- a/packages/angular/cli/lib/examples/if-block.md +++ b/packages/angular/cli/lib/examples/if-block.md @@ -1,28 +1,85 @@ -# Angular @if Control Flow Example +--- +title: 'Using the @if Built-in Control Flow Block' +summary: 'Demonstrates how to use the @if built-in control flow block to conditionally render content in an Angular template based on a boolean expression.' +keywords: + - '@if' + - 'control flow' + - 'conditional rendering' + - 'template syntax' +related_concepts: + - '@else' + - '@else if' + - 'signals' +related_tools: + - 'modernize' +--- -This example demonstrates how to use the `@if` control flow block in an Angular template. The visibility of a `
` element is controlled by a boolean field in the component's TypeScript code. +## Purpose -## Angular Template +The purpose of this pattern is to create dynamic user interfaces by controlling which elements are rendered to the DOM based on the application's state. This is a fundamental technique for building responsive and interactive components. -```html - -@if (isVisible()) { -
This content is conditionally displayed.
+## When to Use + +Use the `@if` block as the modern, preferred alternative to the `*ngIf` directive for all conditional rendering. It offers better type-checking and a cleaner, more intuitive syntax within the template. + +## Key Concepts + +- **`@if` block:** The primary syntax for conditional rendering in modern Angular templates. It evaluates a boolean expression and renders the content within its block if the expression is true. + +## Example Files + +### `conditional-content.component.ts` + +This is a self-contained standalone component that demonstrates the `@if` block with an optional `@else` block. + +```typescript +import { Component, signal } from '@angular/core'; + +@Component({ + selector: 'app-conditional-content', + template: ` + + + @if (isVisible()) { +
This content is conditionally displayed.
+ } @else { +
The content is hidden. Click the button to show it.
+ } + `, +}) +export class ConditionalContentComponent { + protected readonly isVisible = signal(true); + + toggleVisibility(): void { + this.isVisible.update((v) => !v); + } } ``` -## Component TypeScript +## Usage Notes + +- The expression inside the `@if ()` block must evaluate to a boolean. +- This example uses a signal, which is a common pattern, but any boolean property or method call from the component can be used. +- The `@else` block is optional and is rendered when the `@if` condition is `false`. + +## How to Use This Example + +### 1. Import the Component + +In a standalone architecture, import the component into the `imports` array of the parent component where you want to use it. ```typescript +// in app.component.ts import { Component } from '@angular/core'; +import { ConditionalContentComponent } from './conditional-content.component'; @Component({ - selector: 'app-example', - templateUrl: './example.html', - styleUrl: './example.css', + selector: 'app-root', + imports: [ConditionalContentComponent], + template: ` +

My Application

+ + `, }) -export class Example { - // This boolean signal controls the visibility of the element in the template. - protected readonly isVisible = signal(true); -} +export class AppComponent {} ``` diff --git a/packages/angular/cli/package.json b/packages/angular/cli/package.json index 29234e9a3e15..8872ceeee5b0 100644 --- a/packages/angular/cli/package.json +++ b/packages/angular/cli/package.json @@ -25,21 +25,22 @@ "@angular-devkit/architect": "workspace:0.0.0-EXPERIMENTAL-PLACEHOLDER", "@angular-devkit/core": "workspace:0.0.0-PLACEHOLDER", "@angular-devkit/schematics": "workspace:0.0.0-PLACEHOLDER", - "@inquirer/prompts": "7.8.1", - "@listr2/prompt-adapter-inquirer": "3.0.1", - "@modelcontextprotocol/sdk": "1.17.2", + "@inquirer/prompts": "7.10.1", + "@listr2/prompt-adapter-inquirer": "3.0.5", + "@modelcontextprotocol/sdk": "1.25.2", "@schematics/angular": "workspace:0.0.0-PLACEHOLDER", "@yarnpkg/lockfile": "1.1.0", - "algoliasearch": "5.35.0", - "ini": "5.0.0", + "algoliasearch": "5.46.2", + "ini": "6.0.0", "jsonc-parser": "3.3.1", - "listr2": "9.0.1", - "npm-package-arg": "13.0.0", - "pacote": "21.0.0", - "resolve": "1.22.10", - "semver": "7.7.2", + "listr2": "9.0.5", + "npm-package-arg": "13.0.2", + "pacote": "21.0.4", + "parse5-html-rewriting-stream": "8.0.0", + "resolve": "1.22.11", + "semver": "7.7.3", "yargs": "18.0.0", - "zod": "3.25.76" + "zod": "4.3.5" }, "ng-update": { "migrations": "@schematics/angular/migrations/migration-collection.json", diff --git a/packages/angular/cli/src/command-builder/architect-base-command-module.ts b/packages/angular/cli/src/command-builder/architect-base-command-module.ts index 566e0e62b209..fb3508777d74 100644 --- a/packages/angular/cli/src/command-builder/architect-base-command-module.ts +++ b/packages/angular/cli/src/command-builder/architect-base-command-module.ts @@ -12,8 +12,7 @@ import { WorkspaceNodeModulesArchitectHost, } from '@angular-devkit/architect/node'; import { json } from '@angular-devkit/core'; -import { existsSync } from 'node:fs'; -import { resolve } from 'node:path'; +import { createRequire } from 'node:module'; import { isPackageNameSafeForAnalytics } from '../analytics/analytics'; import { EventCustomDimension, EventCustomMetric } from '../analytics/analytics-parameters'; import { assertIsError } from '../utilities/error'; @@ -210,15 +209,13 @@ export abstract class ArchitectBaseCommandModule return; } - // Check if yarn PnP is used. https://yarnpkg.com/advanced/pnpapi#processversionspnp - if (process.versions.pnp) { - return; - } + const workspaceResolve = createRequire(basePath + '/').resolve; + + try { + workspaceResolve('@angular/core'); - // Check for a `node_modules` directory (npm, yarn non-PnP, etc.) - if (existsSync(resolve(basePath, 'node_modules'))) { return; - } + } catch {} this.context.logger.warn( `Node packages may not be installed. Try installing with '${this.context.packageManager.name} install'.`, diff --git a/packages/angular/cli/src/command-builder/architect-command-module.ts b/packages/angular/cli/src/command-builder/architect-command-module.ts index 4855b629b360..98e270cf1dad 100644 --- a/packages/angular/cli/src/command-builder/architect-command-module.ts +++ b/packages/angular/cli/src/command-builder/architect-command-module.ts @@ -41,7 +41,8 @@ export abstract class ArchitectCommandModule // Add default builder if target is not in project and a command default is provided if (this.findDefaultBuilderName && this.context.workspace) { for (const [project, projectDefinition] of this.context.workspace.projects) { - if (projectDefinition.targets.has(target)) { + const targetDefinition = projectDefinition.targets.get(target); + if (targetDefinition?.builder) { continue; } @@ -49,7 +50,13 @@ export abstract class ArchitectCommandModule project, target, }); - if (defaultBuilder) { + if (!defaultBuilder) { + continue; + } + + if (targetDefinition) { + targetDefinition.builder = defaultBuilder; + } else { projectDefinition.targets.set(target, { builder: defaultBuilder, }); @@ -97,11 +104,17 @@ export abstract class ArchitectCommandModule } async run(options: Options & OtherOptions): Promise { - const target = this.getArchitectTarget(); + const originalProcessTitle = process.title; + try { + const target = this.getArchitectTarget(); + const { configuration = '', project, ...architectOptions } = options; - const { configuration = '', project, ...architectOptions } = options; + if (project) { + process.title = `${originalProcessTitle} (${project})`; + + return await this.runSingleTarget({ configuration, target, project }, architectOptions); + } - if (!project) { // This runs each target sequentially. // Running them in parallel would jumble the log messages. let result = 0; @@ -111,12 +124,13 @@ export abstract class ArchitectCommandModule } for (const project of projectNames) { + process.title = `${originalProcessTitle} (${project})`; result |= await this.runSingleTarget({ configuration, target, project }, architectOptions); } return result; - } else { - return await this.runSingleTarget({ configuration, target, project }, architectOptions); + } finally { + process.title = originalProcessTitle; } } diff --git a/packages/angular/cli/src/command-builder/command-module.ts b/packages/angular/cli/src/command-builder/command-module.ts index 0b18512180d2..d036656cf2dd 100644 --- a/packages/angular/cli/src/command-builder/command-module.ts +++ b/packages/angular/cli/src/command-builder/command-module.ts @@ -14,8 +14,7 @@ import type { Argv, CamelCaseKey, CommandModule as YargsCommandModule, - // Resolution mode is required due to CamelCaseKey missing from esm types -} from 'yargs' with { 'resolution-mode': 'require' }; +} from 'yargs'; import { Parser as yargsParser } from 'yargs/helpers'; import { getAnalyticsUserId } from '../analytics/analytics'; import { AnalyticsCollector } from '../analytics/analytics-collector'; @@ -89,7 +88,10 @@ export abstract class CommandModule implements CommandModuleI protected readonly shouldReportAnalytics: boolean = true; readonly scope: CommandScope = CommandScope.Both; - private readonly optionsWithAnalytics = new Map(); + private readonly optionsWithAnalytics = new Map< + string, + EventCustomDimension | EventCustomMetric + >(); constructor(protected readonly context: CommandContext) {} @@ -236,12 +238,16 @@ export abstract class CommandModule implements CommandModuleI ]); for (const [name, ua] of this.optionsWithAnalytics) { + if (!validEventCustomDimensionAndMetrics.has(ua)) { + continue; + } + const value = options[name]; - if ( - (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') && - validEventCustomDimensionAndMetrics.has(ua as EventCustomDimension | EventCustomMetric) - ) { - parameters[ua as EventCustomDimension | EventCustomMetric] = value; + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + parameters[ua] = value; + } else if (Array.isArray(value)) { + // GA doesn't allow array as values. + parameters[ua] = value.sort().join(', '); } } diff --git a/packages/angular/cli/src/command-builder/command-runner.ts b/packages/angular/cli/src/command-builder/command-runner.ts index 8843ea09d461..cb4ab2c8467e 100644 --- a/packages/angular/cli/src/command-builder/command-runner.ts +++ b/packages/angular/cli/src/command-builder/command-runner.ts @@ -8,7 +8,7 @@ import { logging } from '@angular-devkit/core'; import yargs from 'yargs'; -import { Parser } from 'yargs/helpers'; +import { Parser as yargsParser } from 'yargs/helpers'; import { CommandConfig, CommandNames, @@ -29,8 +29,6 @@ import { import { jsonHelpUsage } from './utilities/json-help'; import { createNormalizeOptionsMiddleware } from './utilities/normalize-options-middleware'; -const yargsParser = Parser as unknown as typeof Parser.default; - export async function runCommand(args: string[], logger: logging.Logger): Promise { const { $0, diff --git a/packages/angular/cli/src/command-builder/schematics-command-module.ts b/packages/angular/cli/src/command-builder/schematics-command-module.ts index 738fd497382b..ef317700d1a6 100644 --- a/packages/angular/cli/src/command-builder/schematics-command-module.ts +++ b/packages/angular/cli/src/command-builder/schematics-command-module.ts @@ -204,11 +204,20 @@ export abstract class SchematicsCommandModule ? { name: item, value: item, + checked: + definition.multiselect && Array.isArray(definition.default) + ? definition.default?.includes(item) + : item === definition.default, } : { ...item, name: item.label, value: item.value, + checked: + definition.multiselect && Array.isArray(definition.default) + ? // eslint-disable-next-line @typescript-eslint/no-explicit-any + definition.default?.includes(item.value as any) + : item.value === definition.default, }, ), }); diff --git a/packages/angular/cli/src/command-builder/utilities/json-schema.ts b/packages/angular/cli/src/command-builder/utilities/json-schema.ts index 84af5f2d3641..0a4215be8eed 100644 --- a/packages/angular/cli/src/command-builder/utilities/json-schema.ts +++ b/packages/angular/cli/src/command-builder/utilities/json-schema.ts @@ -6,11 +6,13 @@ * found in the LICENSE file at https://angular.dev/license */ -import { json, strings } from '@angular-devkit/core'; +import { isJsonObject, json, strings } from '@angular-devkit/core'; import type { Arguments, Argv, PositionalOptions, Options as YargsOptions } from 'yargs'; +import { EventCustomDimension } from '../../analytics/analytics-parameters'; /** - * An option description. + * An option description that can be used by yargs to create a command. + * See: https://github.com/yargs/yargs/blob/main/docs/options.mjs */ export interface Option extends YargsOptions { /** @@ -50,10 +52,44 @@ export interface Option extends YargsOptions { itemValueType?: 'string'; } +/** + * A Yargs check function that validates that the given options are in the form of `key=value`. + * @param keyValuePairOptions A set of options that should be in the form of `key=value`. + * @param args The parsed arguments. + * @returns `true` if the options are valid, otherwise an error is thrown. + */ +function checkStringMap(keyValuePairOptions: Set, args: Arguments): boolean { + for (const key of keyValuePairOptions) { + const value = args[key]; + if (!Array.isArray(value)) { + // Value has been parsed. + continue; + } + + for (const pair of value) { + if (pair === undefined) { + continue; + } + + if (!pair.includes('=')) { + throw new Error( + `Invalid value for argument: ${key}, Given: '${pair}', Expected key=value pair`, + ); + } + } + } + + return true; +} + +/** + * A Yargs coerce function that converts an array of `key=value` strings to an object. + * @param value An array of `key=value` strings. + * @returns An object with the keys and values from the input array. + */ function coerceToStringMap( - dashedName: string, value: (string | undefined)[], -): Record | Promise { +): Record | (string | undefined)[] { const stringMap: Record = {}; for (const pair of value) { // This happens when the flag isn't passed at all. @@ -63,23 +99,23 @@ function coerceToStringMap( const eqIdx = pair.indexOf('='); if (eqIdx === -1) { - // TODO: Remove workaround once yargs properly handles thrown errors from coerce. - // Right now these sometimes end up as uncaught exceptions instead of proper validation - // errors with usage output. - return Promise.reject( - new Error( - `Invalid value for argument: ${dashedName}, Given: '${pair}', Expected key=value pair`, - ), - ); + // In the case it is not valid skip processing this option and handle the error in `checkStringMap` + return value; } + const key = pair.slice(0, eqIdx); - const value = pair.slice(eqIdx + 1); - stringMap[key] = value; + stringMap[key] = pair.slice(eqIdx + 1); } return stringMap; } +/** + * Checks if a JSON schema node represents a string map. + * A string map is an object with `additionalProperties` of type `string`. + * @param node The JSON schema node to check. + * @returns `true` if the node represents a string map, otherwise `false`. + */ function isStringMap(node: json.JsonObject): boolean { // Exclude fields with more specific kinds of properties. if (node.properties || node.patternProperties) { @@ -94,6 +130,179 @@ function isStringMap(node: json.JsonObject): boolean { ); } +const SUPPORTED_PRIMITIVE_TYPES = new Set(['boolean', 'number', 'string']); + +/** + * Checks if a string is a supported primitive type. + * @param value The string to check. + * @returns `true` if the string is a supported primitive type, otherwise `false`. + */ +function isSupportedPrimitiveType(value: string): boolean { + return SUPPORTED_PRIMITIVE_TYPES.has(value); +} + +/** + * Recursively checks if a JSON schema for an array's items is a supported primitive type. + * It supports `oneOf` and `anyOf` keywords. + * @param schema The JSON schema for the array's items. + * @returns `true` if the schema is a supported primitive type, otherwise `false`. + */ +function isSupportedArrayItemSchema(schema: json.JsonObject): boolean { + if (typeof schema.type === 'string' && isSupportedPrimitiveType(schema.type)) { + return true; + } + + if (json.isJsonArray(schema.enum)) { + return true; + } + + if (json.isJsonArray(schema.items)) { + return schema.items.some((item) => isJsonObject(item) && isSupportedArrayItemSchema(item)); + } + + if ( + json.isJsonArray(schema.oneOf) && + schema.oneOf.some((item) => isJsonObject(item) && isSupportedArrayItemSchema(item)) + ) { + return true; + } + + if ( + json.isJsonArray(schema.anyOf) && + schema.anyOf.some((item) => isJsonObject(item) && isSupportedArrayItemSchema(item)) + ) { + return true; + } + + return false; +} + +/** + * Gets the supported types for a JSON schema node. + * @param current The JSON schema node to get the supported types for. + * @returns An array of supported types. + */ +function getSupportedTypes( + current: json.JsonObject, +): ReadonlyArray<'string' | 'number' | 'boolean' | 'array' | 'object'> { + const typeSet = json.schema.getTypesOfSchema(current); + + if (typeSet.size === 0) { + return []; + } + + return [...typeSet].filter((type) => { + switch (type) { + case 'boolean': + case 'number': + case 'string': + return true; + case 'array': + return isJsonObject(current.items) && isSupportedArrayItemSchema(current.items); + case 'object': + return isStringMap(current); + default: + return false; + } + }) as ReadonlyArray<'string' | 'number' | 'boolean' | 'array' | 'object'>; +} + +/** + * Gets the enum values for a JSON schema node. + * @param current The JSON schema node to get the enum values for. + * @returns An array of enum values. + */ +function getEnumValues( + current: json.JsonObject, +): ReadonlyArray | undefined { + if (json.isJsonArray(current.enum)) { + return current.enum.sort() as ReadonlyArray; + } + + if (isJsonObject(current.items)) { + const enumValues = getEnumValues(current.items); + if (enumValues?.length) { + return enumValues; + } + } + + if (typeof current.type === 'string' && isSupportedPrimitiveType(current.type)) { + return []; + } + + const subSchemas = + (json.isJsonArray(current.oneOf) && current.oneOf) || + (json.isJsonArray(current.anyOf) && current.anyOf); + + if (subSchemas) { + // Find the first enum. + for (const subSchema of subSchemas) { + if (isJsonObject(subSchema)) { + const enumValues = getEnumValues(subSchema); + if (enumValues) { + return enumValues; + } + } + } + } + + return []; +} + +/** + * Gets the default value for a JSON schema node. + * @param current The JSON schema node to get the default value for. + * @param type The type of the JSON schema node. + * @returns The default value, or `undefined` if there is no default value. + */ +function getDefaultValue( + current: json.JsonObject, + type: string, +): string | number | boolean | unknown[] | undefined { + const defaultValue = current.default; + if (defaultValue === undefined) { + return undefined; + } + + if (type === 'array') { + return Array.isArray(defaultValue) && defaultValue.length > 0 ? defaultValue : undefined; + } + + if (typeof defaultValue === type) { + return defaultValue as string | number | boolean; + } + + return undefined; +} + +/** + * Gets the aliases for a JSON schema node. + * @param current The JSON schema node to get the aliases for. + * @returns An array of aliases. + */ +function getAliases(current: json.JsonObject): string[] { + if (json.isJsonArray(current.aliases)) { + return [...current.aliases].map(String); + } + + if (current.alias) { + return [String(current.alias)]; + } + + return []; +} + +/** + * Parses a JSON schema to a list of options that can be used by yargs. + * + * @param registry A schema registry to use for flattening the schema. + * @param schema The JSON schema to parse. + * @param interactive Whether to prompt the user for missing options. + * @returns A list of options. + * + * @note The schema definition are not resolved at this stage. This means that `$ref` will not be resolved, + * and custom keywords like `x-prompt` will not be processed. + */ export async function parseJsonSchemaToOptions( registry: json.schema.SchemaRegistry, schema: json.JsonObject, @@ -106,149 +315,70 @@ export async function parseJsonSchemaToOptions( pointer: json.schema.JsonPointer, parentSchema?: json.JsonObject | json.JsonArray, ) { - if (!parentSchema) { - // Ignore root. - return; - } else if (pointer.split(/\/(?:properties|items|definitions)\//g).length > 2) { - // Ignore subitems (objects or arrays). - return; - } else if (json.isJsonArray(current)) { + if ( + !parentSchema || + json.isJsonArray(current) || + pointer.split(/\/(?:properties|items|definitions)\//g).length > 2 + ) { + // Ignore root, arrays, and subitems. return; } - if (pointer.indexOf('/not/') != -1) { + if (pointer.includes('/not/')) { // We don't support anyOf/not. throw new Error('The "not" keyword is not supported in JSON Schema.'); } const ptr = json.schema.parseJsonPointer(pointer); - const name = ptr[ptr.length - 1]; - - if (ptr[ptr.length - 2] != 'properties') { + if (ptr[ptr.length - 2] !== 'properties') { // Skip any non-property items. return; } + const name = ptr.at(-1) as string; - const typeSet = json.schema.getTypesOfSchema(current); - - if (typeSet.size == 0) { - throw new Error('Cannot find type of schema.'); - } - - // We only support number, string or boolean (or array of those), so remove everything else. - const types = [...typeSet].filter((x) => { - switch (x) { - case 'boolean': - case 'number': - case 'string': - return true; - - case 'array': - // Only include arrays if they're boolean, string or number. - if ( - json.isJsonObject(current.items) && - typeof current.items.type == 'string' && - ['boolean', 'number', 'string'].includes(current.items.type) - ) { - return true; - } - - return false; + const types = getSupportedTypes(current); - case 'object': - return isStringMap(current); - - default: - return false; - } - }) as ('string' | 'number' | 'boolean' | 'array' | 'object')[]; - - if (types.length == 0) { + if (types.length === 0) { // This means it's not usable on the command line. e.g. an Object. return; } - // Only keep enum values we support (booleans, numbers and strings). - const enumValues = ((json.isJsonArray(current.enum) && current.enum) || []).filter((x) => { - switch (typeof x) { - case 'boolean': - case 'number': - case 'string': - return true; - - default: - return false; - } - }) as (string | true | number)[]; - - let defaultValue: string | number | boolean | undefined = undefined; - if (current.default !== undefined) { - switch (types[0]) { - case 'string': - if (typeof current.default == 'string') { - defaultValue = current.default; - } - break; - case 'number': - if (typeof current.default == 'number') { - defaultValue = current.default; - } - break; - case 'boolean': - if (typeof current.default == 'boolean') { - defaultValue = current.default; - } - break; - } - } - + const [type] = types; const $default = current.$default; const $defaultIndex = - json.isJsonObject($default) && $default['$source'] == 'argv' ? $default['index'] : undefined; + isJsonObject($default) && $default['$source'] === 'argv' ? $default['index'] : undefined; const positional: number | undefined = - typeof $defaultIndex == 'number' ? $defaultIndex : undefined; + typeof $defaultIndex === 'number' ? $defaultIndex : undefined; - let required = json.isJsonArray(schema.required) ? schema.required.includes(name) : false; + let required = json.isJsonArray(schema.required) && schema.required.includes(name); if (required && interactive && current['x-prompt']) { required = false; } - const alias = json.isJsonArray(current.aliases) - ? [...current.aliases].map((x) => '' + x) - : current.alias - ? ['' + current.alias] - : []; - const format = typeof current.format == 'string' ? current.format : undefined; - const visible = current.visible === undefined || current.visible === true; - const hidden = !!current.hidden || !visible; - - const xUserAnalytics = current['x-user-analytics']; - const userAnalytics = typeof xUserAnalytics === 'string' ? xUserAnalytics : undefined; - - // Deprecated is set only if it's true or a string. + const visible = current.visible !== false; const xDeprecated = current['x-deprecated']; - const deprecated = - xDeprecated === true || typeof xDeprecated === 'string' ? xDeprecated : undefined; + const enumValues = getEnumValues(current); const option: Option = { name, - description: '' + (current.description === undefined ? '' : current.description), - default: defaultValue, - choices: enumValues.length ? enumValues : undefined, + description: String(current.description ?? ''), + default: getDefaultValue(current, type), + choices: enumValues?.length ? enumValues : undefined, required, - alias, - format, - hidden, - userAnalytics, - deprecated, + alias: getAliases(current), + format: typeof current.format === 'string' ? current.format : undefined, + hidden: !!current.hidden || !visible, + userAnalytics: + typeof current['x-user-analytics'] === 'string' ? current['x-user-analytics'] : undefined, + deprecated: xDeprecated === true || typeof xDeprecated === 'string' ? xDeprecated : undefined, positional, - ...(types[0] === 'object' + ...(type === 'object' ? { type: 'array', itemValueType: 'string', } : { - type: types[0], + type, }), }; @@ -280,10 +410,10 @@ export function addSchemaOptionsToCommand( localYargs: Argv, options: Option[], includeDefaultValues: boolean, -): Map { +): Map { const booleanOptionsWithNoPrefix = new Set(); const keyValuePairOptions = new Set(); - const optionsWithAnalytics = new Map(); + const optionsWithAnalytics = new Map(); for (const option of options) { const { @@ -309,7 +439,7 @@ export function addSchemaOptionsToCommand( } if (itemValueType) { - keyValuePairOptions.add(name); + keyValuePairOptions.add(dashedName); } const sharedOptions: YargsOptions & PositionalOptions = { @@ -318,7 +448,7 @@ export function addSchemaOptionsToCommand( description, deprecated, choices, - coerce: itemValueType ? coerceToStringMap.bind(null, dashedName) : undefined, + coerce: itemValueType ? coerceToStringMap : undefined, // This should only be done when `--help` is used otherwise default will override options set in angular.json. ...(includeDefaultValues ? { default: defaultVal } : {}), }; @@ -338,10 +468,15 @@ export function addSchemaOptionsToCommand( // Record option of analytics. if (userAnalytics !== undefined) { - optionsWithAnalytics.set(name, userAnalytics); + optionsWithAnalytics.set(name, userAnalytics as EventCustomDimension); } } + // Valid key/value options + if (keyValuePairOptions.size) { + localYargs.check(checkStringMap.bind(null, keyValuePairOptions), false); + } + // Handle options which have been defined in the schema with `no` prefix. if (booleanOptionsWithNoPrefix.size) { localYargs.middleware((options: Arguments) => { diff --git a/packages/angular/cli/src/command-builder/utilities/json-schema_spec.ts b/packages/angular/cli/src/command-builder/utilities/json-schema_spec.ts index 5ec5db644bef..d311373d69f0 100644 --- a/packages/angular/cli/src/command-builder/utilities/json-schema_spec.ts +++ b/packages/angular/cli/src/command-builder/utilities/json-schema_spec.ts @@ -6,88 +6,125 @@ * found in the LICENSE file at https://angular.dev/license */ -import { json, schema } from '@angular-devkit/core'; -import yargs, { positional } from 'yargs'; +import { JsonObject, schema } from '@angular-devkit/core'; +import yargs from 'yargs'; import { addSchemaOptionsToCommand, parseJsonSchemaToOptions } from './json-schema'; -const YError = (() => { - try { - const y = yargs().strict().fail(false).exitProcess(false).parse(['--forced-failure']); - } catch (e) { - if (!(e instanceof Error)) { - throw new Error('Unexpected non-Error thrown'); - } - - return e.constructor as typeof Error; - } - throw new Error('Expected parse to fail'); -})(); - -interface ParseFunction { - (argv: string[]): unknown; -} - -function withParseForSchema( - jsonSchema: json.JsonObject, - { - interactive = true, - includeDefaultValues = true, - }: { interactive?: boolean; includeDefaultValues?: boolean } = {}, -): ParseFunction { - let actualParse: ParseFunction = () => { - throw new Error('Called before init'); - }; - const parse: ParseFunction = (args) => { - return actualParse(args); - }; - - beforeEach(async () => { - const registry = new schema.CoreSchemaRegistry(); - const options = await parseJsonSchemaToOptions(registry, jsonSchema, interactive); - - actualParse = async (args: string[]) => { - // Create a fresh yargs for each call. The yargs object is stateful and - // calling .parse multiple times on the same instance isn't safe. - const localYargs = yargs().exitProcess(false).strict().fail(false); - addSchemaOptionsToCommand(localYargs, options, includeDefaultValues); - +describe('parseJsonSchemaToOptions', () => { + describe('without required fields in schema', () => { + const parse = async (args: string[]) => { // Yargs only exposes the parse errors as proper errors when using the // callback syntax. This unwraps that ugly workaround so tests can just // use simple .toThrow/.toEqual assertions. return localYargs.parseAsync(args); }; - }); - - return parse; -} -describe('parseJsonSchemaToOptions', () => { - describe('without required fields in schema', () => { - const parse = withParseForSchema({ - 'type': 'object', - 'properties': { - 'maxSize': { - 'type': 'number', - }, - 'ssr': { - 'type': 'string', - 'enum': ['always', 'surprise-me', 'never'], - }, - 'extendable': { - 'type': 'object', - 'properties': {}, - 'additionalProperties': { - 'type': 'string', + let localYargs: yargs.Argv; + beforeEach(async () => { + // Create a fresh yargs for each call. The yargs object is stateful and + // calling .parse multiple times on the same instance isn't safe. + localYargs = yargs().exitProcess(false).strict().fail(false).wrap(1_000); + const jsonSchema = { + 'type': 'object', + 'properties': { + 'maxSize': { + 'type': 'number', }, - }, - 'someDefine': { - 'type': 'object', - 'additionalProperties': { + 'ssr': { 'type': 'string', + 'enum': ['always', 'surprise-me', 'never'], + }, + 'arrayWithChoices': { + 'type': 'array', + 'default': ['default-array'], + 'items': { + 'type': 'string', + 'enum': ['always', 'never', 'default-array'], + }, + }, + 'extendable': { + 'type': 'object', + 'properties': {}, + 'additionalProperties': { + 'type': 'string', + }, + }, + 'someDefine': { + 'type': 'object', + 'additionalProperties': { + 'type': 'string', + }, + }, + 'arrayWithChoicesInOneOf': { + 'type': 'array', + 'items': { + 'oneOf': [ + { + 'enum': ['default', 'verbose'], + }, + { + 'type': 'array', + 'minItems': 1, + 'maxItems': 2, + 'items': [ + { + 'enum': ['default', 'verbose'], + }, + { + 'type': 'object', + }, + ], + }, + ], + }, + }, + 'arrayWithComplexAnyOf': { + 'type': 'array', + 'items': { + 'oneOf': [ + { + 'anyOf': [ + { + 'type': 'string', + }, + { + 'enum': ['default', 'verbose'], + }, + ], + }, + { + 'type': 'array', + 'minItems': 1, + 'maxItems': 2, + 'items': [ + { + 'anyOf': [ + { + 'type': 'string', + }, + { + 'enum': ['default', 'verbose'], + }, + ], + }, + { + 'type': 'object', + }, + ], + }, + ], + }, }, }, - }, + }; + const registry = new schema.CoreSchemaRegistry(); + const options = await parseJsonSchemaToOptions( + registry, + jsonSchema as unknown as JsonObject, + false, + ); + addSchemaOptionsToCommand(localYargs, options, true); }); describe('type=number', () => { @@ -100,6 +137,68 @@ describe('parseJsonSchemaToOptions', () => { }); }); + describe('type=array, enum', () => { + it('parses valid option value', async () => { + expect( + await parse(['--arrayWithChoices', 'always', '--arrayWithChoices', 'never']), + ).toEqual( + jasmine.objectContaining({ + 'arrayWithChoices': ['always', 'never'], + }), + ); + }); + + it('rejects non-enum values', async () => { + await expectAsync(parse(['--arrayWithChoices', 'yes'])).toBeRejectedWithError( + /Argument: array-with-choices, Given: "yes", Choices:/, + ); + }); + + it('should add default value to help', async () => { + expect(await localYargs.getHelp()).toContain('[default: ["default-array"]]'); + }); + }); + + describe('type=array, enum in oneOf', () => { + it('parses valid option value', async () => { + expect( + await parse([ + '--arrayWithChoicesInOneOf', + 'default', + '--arrayWithChoicesInOneOf', + 'verbose', + ]), + ).toEqual( + jasmine.objectContaining({ + 'arrayWithChoicesInOneOf': ['default', 'verbose'], + }), + ); + }); + + it('rejects non-enum values', async () => { + await expectAsync(parse(['--arrayWithChoicesInOneOf', 'yes'])).toBeRejectedWithError( + /Argument: array-with-choices-in-one-of, Given: "yes", Choices:/, + ); + }); + }); + + describe('type=array, anyOf', () => { + it('parses valid option value', async () => { + expect( + await parse([ + '--arrayWithComplexAnyOf', + 'default', + '--arrayWithComplexAnyOf', + 'something-else', + ]), + ).toEqual( + jasmine.objectContaining({ + 'arrayWithComplexAnyOf': ['default', 'something-else'], + }), + ); + }); + }); + describe('type=string, enum', () => { it('parses valid option value', async () => { expect(await parse(['--ssr', 'never'])).toEqual( @@ -125,11 +224,9 @@ describe('parseJsonSchemaToOptions', () => { it('rejects invalid values for string maps', async () => { await expectAsync(parse(['--some-define', 'foo'])).toBeRejectedWithError( - YError, /Invalid value for argument: some-define, Given: 'foo', Expected key=value pair/, ); await expectAsync(parse(['--some-define', '42'])).toBeRejectedWithError( - YError, /Invalid value for argument: some-define, Given: '42', Expected key=value pair/, ); }); @@ -162,43 +259,42 @@ describe('parseJsonSchemaToOptions', () => { describe('with required positional argument', () => { it('marks the required argument as required', async () => { - const jsonSchema = JSON.parse(` - { - "$id": "FakeSchema", - "title": "Fake Schema", - "type": "object", - "required": ["a"], - "properties": { - "b": { - "type": "string", - "description": "b.", - "$default": { - "$source": "argv", - "index": 1 - } + const jsonSchema = { + '$id': 'FakeSchema', + 'title': 'Fake Schema', + 'type': 'object', + 'required': ['a'], + 'properties': { + 'b': { + 'type': 'string', + 'description': 'b.', + '$default': { + '$source': 'argv', + 'index': 1, + }, }, - "a": { - "type": "string", - "description": "a.", - "$default": { - "$source": "argv", - "index": 0 - } + 'a': { + 'type': 'string', + 'description': 'a.', + '$default': { + '$source': 'argv', + 'index': 0, + }, }, - "optC": { - "type": "string", - "description": "optC" + 'optC': { + 'type': 'string', + 'description': 'optC', }, - "optA": { - "type": "string", - "description": "optA" + 'optA': { + 'type': 'string', + 'description': 'optA', + }, + 'optB': { + 'type': 'string', + 'description': 'optB', }, - "optB": { - "type": "string", - "description": "optB" - } - } - }`) as json.JsonObject; + }, + }; const registry = new schema.CoreSchemaRegistry(); const options = await parseJsonSchemaToOptions(registry, jsonSchema, /* interactive= */ true); diff --git a/packages/angular/cli/src/command-builder/utilities/schematic-engine-host.ts b/packages/angular/cli/src/command-builder/utilities/schematic-engine-host.ts index e4b805f1a367..25b723c467a2 100644 --- a/packages/angular/cli/src/command-builder/utilities/schematic-engine-host.ts +++ b/packages/angular/cli/src/command-builder/utilities/schematic-engine-host.ts @@ -20,7 +20,10 @@ import { assertIsError } from '../../utilities/error'; */ const schematicRedirectVariable = process.env['NG_SCHEMATIC_REDIRECT']?.toLowerCase(); -function shouldWrapSchematic(schematicFile: string, schematicEncapsulation: boolean): boolean { +function shouldWrapSchematic( + schematicFile: string, + schematicEncapsulation: boolean | undefined, +): boolean { // Check environment variable if present switch (schematicRedirectVariable) { case '0': @@ -52,12 +55,12 @@ function shouldWrapSchematic(schematicFile: string, schematicEncapsulation: bool // Check for first-party Angular schematic packages // Angular schematics are safe to use in the wrapped VM context - if (/\/node_modules\/@(?:angular|schematics|nguniversal)\//.test(normalizedSchematicFile)) { - return true; - } + const isFirstParty = /\/node_modules\/@(?:angular|schematics|nguniversal)\//.test( + normalizedSchematicFile, + ); - // Otherwise use the value of the schematic collection's encapsulation option (current default of false) - return schematicEncapsulation; + // Use value of defined option if present, otherwise default to first-party usage. + return schematicEncapsulation ?? isFirstParty; } export class SchematicEngineHost extends NodeModulesEngineHost { @@ -73,7 +76,7 @@ export class SchematicEngineHost extends NodeModulesEngineHost { const referenceRequire = createRequire(__filename); const schematicFile = referenceRequire.resolve(fullPath, { paths: [parentPath] }); - if (shouldWrapSchematic(schematicFile, !!collectionDescription?.encapsulation)) { + if (shouldWrapSchematic(schematicFile, collectionDescription?.encapsulation)) { const schematicPath = dirname(schematicFile); const moduleCache = new Map(); diff --git a/packages/angular/cli/src/commands/add/cli.ts b/packages/angular/cli/src/commands/add/cli.ts index adaf980cd4b3..02bc660b327d 100644 --- a/packages/angular/cli/src/commands/add/cli.ts +++ b/packages/angular/cli/src/commands/add/cli.ts @@ -6,15 +6,14 @@ * found in the LICENSE file at https://angular.dev/license */ -import { NodePackageDoesNotSupportSchematics } from '@angular-devkit/schematics/tools'; -import { Listr, color, figures } from 'listr2'; +import { Listr, ListrRenderer, ListrTaskWrapper, color, figures } from 'listr2'; import assert from 'node:assert'; +import fs from 'node:fs/promises'; import { createRequire } from 'node:module'; -import { dirname, join } from 'node:path'; +import { dirname, join, relative, resolve } from 'node:path'; import npa from 'npm-package-arg'; -import { Range, compare, intersects, prerelease, satisfies, valid } from 'semver'; +import semver, { Range, compare, intersects, prerelease, satisfies, valid } from 'semver'; import { Argv } from 'yargs'; -import { PackageManager } from '../../../lib/config/workspace-schema'; import { CommandModuleImplementation, Options, @@ -24,15 +23,18 @@ import { SchematicsCommandArgs, SchematicsCommandModule, } from '../../command-builder/schematics-command-module'; -import { assertIsError } from '../../utilities/error'; import { NgAddSaveDependency, + PackageManager, + PackageManagerError, PackageManifest, - fetchPackageManifest, - fetchPackageMetadata, -} from '../../utilities/package-metadata'; + PackageMetadata, + createPackageManager, +} from '../../package-managers'; +import { assertIsError } from '../../utilities/error'; import { isTTY } from '../../utilities/tty'; import { VERSION } from '../../utilities/version'; +import { getCacheConfig } from '../cache/utilities'; class CommandError extends Error {} @@ -44,14 +46,23 @@ interface AddCommandArgs extends SchematicsCommandArgs { } interface AddCommandTaskContext { + packageManager: PackageManager; packageIdentifier: npa.Result; - usingYarn?: boolean; savePackage?: NgAddSaveDependency; collectionName?: string; executeSchematic: AddCommandModule['executeSchematic']; - hasMismatchedPeer: AddCommandModule['hasMismatchedPeer']; + getPeerDependencyConflicts: AddCommandModule['getPeerDependencyConflicts']; + dryRun?: boolean; + hasSchematics?: boolean; + homepage?: string; } +type AddCommandTaskWrapper = ListrTaskWrapper< + AddCommandTaskContext, + typeof ListrRenderer, + typeof ListrRenderer +>; + /** * The set of packages that should have certain versions excluded from consideration * when attempting to find a compatible version for a package. @@ -64,6 +75,19 @@ const packageVersionExclusions: Record = { '@angular/material': '7.x', }; +const DEFAULT_CONFLICT_DISPLAY_LIMIT = 5; + +/** + * A map of packages to built-in schematics. + * This is used for packages that do not have a native `ng-add` schematic. + */ +const BUILT_IN_SCHEMATICS = { + tailwindcss: { + collection: '@schematics/angular', + name: 'tailwind', + }, +} as const; + export default class AddCommandModule extends SchematicsCommandModule implements CommandModuleImplementation @@ -74,6 +98,7 @@ export default class AddCommandModule protected override allowPrivateSchematics = true; private readonly schematicName = 'ng-add'; private rootRequire = createRequire(this.context.root + '/'); + #projectVersionCache = new Map(); override async builder(argv: Argv): Promise> { const localYargs = (await super.builder(argv)) @@ -121,10 +146,10 @@ export default class AddCommandModule return localYargs; } - // eslint-disable-next-line max-lines-per-function async run(options: Options & OtherOptions): Promise { - const { logger, packageManager } = this.context; - const { verbose, registry, collection, skipConfirmation } = options; + this.#projectVersionCache.clear(); + const { logger } = this.context; + const { collection, skipConfirmation } = options; let packageIdentifier; try { @@ -150,222 +175,120 @@ export default class AddCommandModule } } - const taskContext: AddCommandTaskContext = { + const taskContext = { packageIdentifier, executeSchematic: this.executeSchematic.bind(this), - hasMismatchedPeer: this.hasMismatchedPeer.bind(this), - }; + getPeerDependencyConflicts: this.getPeerDependencyConflicts.bind(this), + dryRun: options.dryRun, + } as AddCommandTaskContext; + + const tasks = new Listr( + [ + { + title: 'Determining Package Manager', + task: (context, task) => this.determinePackageManagerTask(context, task), + rendererOptions: { persistentOutput: true }, + }, + { + title: 'Searching for compatible package version', + enabled: packageIdentifier.type === 'range' && packageIdentifier.rawSpec === '*', + task: (context, task) => this.findCompatiblePackageVersionTask(context, task, options), + rendererOptions: { persistentOutput: true }, + }, + { + title: 'Loading package information', + task: (context, task) => this.loadPackageInfoTask(context, task, options), + rendererOptions: { persistentOutput: true }, + }, + { + title: 'Confirming installation', + enabled: !skipConfirmation && !options.dryRun, + task: (context, task) => this.confirmInstallationTask(context, task), + rendererOptions: { persistentOutput: true }, + }, + { + title: 'Installing package', + skip: (context) => { + if (context.dryRun) { + return `Skipping package installation. Would install package ${color.blue( + context.packageIdentifier.toString(), + )}.`; + } - const tasks = new Listr([ - { - title: 'Determining Package Manager', - task(context, task) { - context.usingYarn = packageManager.name === PackageManager.Yarn; - task.output = `Using package manager: ${color.dim(packageManager.name)}`; + return false; + }, + task: (context, task) => this.installPackageTask(context, task, options), + rendererOptions: { bottomBar: Infinity }, }, - rendererOptions: { persistentOutput: true }, - }, + // TODO: Rework schematic execution as a task and insert here + ], { - title: 'Searching for compatible package version', - enabled: packageIdentifier.type === 'range' && packageIdentifier.rawSpec === '*', - async task(context, task) { - assert( - context.packageIdentifier.name, - 'Registry package identifiers should always have a name.', - ); - - // only package name provided; search for viable version - // plus special cases for packages that did not have peer deps setup - let packageMetadata; - try { - packageMetadata = await fetchPackageMetadata(context.packageIdentifier.name, logger, { - registry, - usingYarn: context.usingYarn, - verbose, - }); - } catch (e) { - assertIsError(e); - throw new CommandError( - `Unable to load package information from registry: ${e.message}`, - ); - } + /* options */ + }, + ); - // Start with the version tagged as `latest` if it exists - const latestManifest = packageMetadata.tags['latest']; - if (latestManifest) { - context.packageIdentifier = npa.resolve(latestManifest.name, latestManifest.version); - } + try { + const result = await tasks.run(taskContext); + assert(result.collectionName, 'Collection name should always be available'); - // Adjust the version based on name and peer dependencies - if ( - latestManifest?.peerDependencies && - Object.keys(latestManifest.peerDependencies).length === 0 - ) { - task.output = `Found compatible package version: ${color.blue(latestManifest.version)}.`; - } else if (!latestManifest || (await context.hasMismatchedPeer(latestManifest))) { - // 'latest' is invalid so search for most recent matching package - - // Allow prelease versions if the CLI itself is a prerelease - const allowPrereleases = prerelease(VERSION.full); - - const versionExclusions = packageVersionExclusions[packageMetadata.name]; - const versionManifests = Object.values(packageMetadata.versions).filter( - (value: PackageManifest) => { - // Prerelease versions are not stable and should not be considered by default - if (!allowPrereleases && prerelease(value.version)) { - return false; - } - // Deprecated versions should not be used or considered - if (value.deprecated) { - return false; - } - // Excluded package versions should not be considered - if ( - versionExclusions && - satisfies(value.version, versionExclusions, { includePrerelease: true }) - ) { - return false; - } - - return true; - }, - ); + // Check if the installed package has actual add actions and not just schematic support + if (result.hasSchematics && !options.dryRun) { + const workflow = this.getOrCreateWorkflowForBuilder(result.collectionName); + const collection = workflow.engine.createCollection(result.collectionName); - // Sort in reverse SemVer order so that the newest compatible version is chosen - versionManifests.sort((a, b) => compare(b.version, a.version, true)); - - let found = false; - for (const versionManifest of versionManifests) { - const mismatch = await context.hasMismatchedPeer(versionManifest); - if (mismatch) { - continue; - } - - context.packageIdentifier = npa.resolve( - versionManifest.name, - versionManifest.version, - ); - found = true; - break; - } + // listSchematicNames cannot be used here since it does not list private schematics. + // Most `ng-add` schematics are marked as private. + // TODO: Consider adding a `hasSchematic` helper to the schematic collection object. + try { + collection.createSchematic(this.schematicName, true); + } catch { + result.hasSchematics = false; + } + } - if (!found) { - task.output = "Unable to find compatible package. Using 'latest' tag."; - } else { - task.output = `Found compatible package version: ${color.blue(context.packageIdentifier.toString())}.`; - } - } else { - task.output = `Found compatible package version: ${color.blue(context.packageIdentifier.toString())}.`; - } - }, - rendererOptions: { persistentOutput: true }, - }, - { - title: 'Loading package information from registry', - async task(context, task) { - let manifest; - try { - manifest = await fetchPackageManifest(context.packageIdentifier.toString(), logger, { - registry, - verbose, - usingYarn: context.usingYarn, - }); - } catch (e) { - assertIsError(e); - throw new CommandError( - `Unable to fetch package information for '${context.packageIdentifier}': ${e.message}`, + if (!result.hasSchematics) { + // Fallback to a built-in schematic if the package does not have an `ng-add` schematic + const packageName = result.packageIdentifier.name; + if (packageName) { + const builtInSchematic = + BUILT_IN_SCHEMATICS[packageName as keyof typeof BUILT_IN_SCHEMATICS]; + if (builtInSchematic) { + logger.info( + `The ${color.blue(packageName)} package does not provide \`ng add\` actions.`, ); - } - - context.savePackage = manifest['ng-add']?.save; - context.collectionName = manifest.name; + logger.info('The Angular CLI will use built-in actions to add it to your project.'); - if (await context.hasMismatchedPeer(manifest)) { - task.output = color.yellow( - figures.warning + - ' Package has unmet peer dependencies. Adding the package may not succeed.', - ); - } - }, - rendererOptions: { persistentOutput: true }, - }, - { - title: 'Confirming installation', - enabled: !skipConfirmation, - async task(context, task) { - if (!isTTY()) { - task.output = - `'--skip-confirmation' can be used to bypass installation confirmation. ` + - `Ensure package name is correct prior to '--skip-confirmation' option usage.`; - throw new CommandError('No terminal detected'); + return this.executeSchematic({ + ...options, + collection: builtInSchematic.collection, + schematicName: builtInSchematic.name, + }); } + } - const { ListrInquirerPromptAdapter } = await import('@listr2/prompt-adapter-inquirer'); - const { confirm } = await import('@inquirer/prompts'); - const shouldProceed = await task.prompt(ListrInquirerPromptAdapter).run(confirm, { - message: - `The package ${color.blue(context.packageIdentifier.toString())} will be installed and executed.\n` + - 'Would you like to proceed?', - default: true, - theme: { prefix: '' }, - }); - - if (!shouldProceed) { - throw new CommandError('Command aborted'); - } - }, - rendererOptions: { persistentOutput: true }, - }, - { - async task(context, task) { - // Only show if installation will actually occur - task.title = 'Installing package'; - - if (context.savePackage === false) { - task.title += ' in temporary location'; - - // Temporary packages are located in a different directory - // Hence we need to resolve them using the temp path - const { success, tempNodeModules } = await packageManager.installTemp( - context.packageIdentifier.toString(), - registry ? [`--registry="${registry}"`] : undefined, - ); - const tempRequire = createRequire(tempNodeModules + '/'); - assert(context.collectionName, 'Collection name should always be available'); - const resolvedCollectionPath = tempRequire.resolve( - join(context.collectionName, 'package.json'), - ); + let message = options.dryRun + ? 'The package does not provide any `ng add` actions, so no further actions would be taken.' + : 'Package installed successfully. The package does not provide any `ng add` actions, so no further actions were taken.'; - if (!success) { - throw new CommandError('Unable to install package'); - } + if (result.homepage) { + message += `\nFor more information about this package, visit its homepage at ${result.homepage}`; + } + logger.info(message); - context.collectionName = dirname(resolvedCollectionPath); - } else { - const success = await packageManager.install( - context.packageIdentifier.toString(), - context.savePackage, - registry ? [`--registry="${registry}"`] : undefined, - undefined, - ); + return; + } - if (!success) { - throw new CommandError('Unable to install package'); - } - } - }, - rendererOptions: { bottomBar: Infinity }, - }, - // TODO: Rework schematic execution as a task and insert here - ]); + if (options.dryRun) { + logger.info("The package's `ng add` actions would be executed next."); - try { - const result = await tasks.run(taskContext); - assert(result.collectionName, 'Collection name should always be available'); + return; + } return this.executeSchematic({ ...options, collection: result.collectionName }); } catch (e) { if (e instanceof CommandError) { + logger.error(e.message); + return 1; } @@ -373,6 +296,331 @@ export default class AddCommandModule } } + private async determinePackageManagerTask( + context: AddCommandTaskContext, + task: AddCommandTaskWrapper, + ): Promise { + let tempDirectory: string | undefined; + const tempOptions = ['node_modules']; + + const cacheConfig = getCacheConfig(this.context.workspace); + if (cacheConfig.enabled) { + const cachePath = resolve(this.context.root, cacheConfig.path); + if (!relative(this.context.root, cachePath).startsWith('..')) { + tempOptions.push(cachePath); + } + } + + for (const tempOption of tempOptions) { + try { + const directory = resolve(this.context.root, tempOption); + if ((await fs.stat(directory)).isDirectory()) { + tempDirectory = directory; + break; + } + } catch {} + } + + context.packageManager = await createPackageManager({ + cwd: this.context.root, + logger: this.context.logger, + dryRun: context.dryRun, + tempDirectory, + }); + task.output = `Using package manager: ${color.dim(context.packageManager.name)}`; + } + + private async findCompatiblePackageVersionTask( + context: AddCommandTaskContext, + task: AddCommandTaskWrapper, + options: Options, + ): Promise { + const { registry, verbose } = options; + const { packageManager, packageIdentifier } = context; + const packageName = packageIdentifier.name; + + assert(packageName, 'Registry package identifiers should always have a name.'); + + const rejectionReasons: string[] = []; + + // Attempt to use the 'latest' tag from the registry. + try { + const latestManifest = await packageManager.getManifest(`${packageName}@latest`, { + registry, + }); + + if (latestManifest) { + const conflicts = await this.getPeerDependencyConflicts(latestManifest); + if (!conflicts) { + context.packageIdentifier = npa.resolve(latestManifest.name, latestManifest.version); + task.output = `Found compatible package version: ${color.blue(latestManifest.version)}.`; + + return; + } + rejectionReasons.push(...conflicts); + } + } catch (e) { + assertIsError(e); + throw new CommandError(`Unable to load package information from registry: ${e.message}`); + } + + // 'latest' is invalid or not found, search for most recent matching package. + task.output = + 'Could not find a compatible version with `latest`. Searching for a compatible version.'; + + let packageMetadata; + try { + packageMetadata = await packageManager.getRegistryMetadata(packageName, { + registry, + }); + } catch (e) { + assertIsError(e); + throw new CommandError(`Unable to load package information from registry: ${e.message}`); + } + + if (!packageMetadata) { + throw new CommandError('Unable to load package information from registry.'); + } + + // Allow prelease versions if the CLI itself is a prerelease or locally built. + const allowPrereleases = !!prerelease(VERSION.full) || VERSION.full === '0.0.0'; + const potentialVersions = this.#getPotentialVersions(packageMetadata, allowPrereleases); + + // Heuristic-based search: Check the latest release of each major version first. + const majorVersions = this.#getMajorVersions(potentialVersions); + let found = await this.#findCompatibleVersion(context, majorVersions, { + registry, + verbose, + rejectionReasons, + }); + + // Exhaustive search: If no compatible major version is found, fall back to checking all versions. + if (!found) { + const checkedVersions = new Set(majorVersions); + const remainingVersions = potentialVersions.filter((v) => !checkedVersions.has(v)); + found = await this.#findCompatibleVersion(context, remainingVersions, { + registry, + verbose, + rejectionReasons, + }); + } + + if (!found) { + let message = `Unable to find compatible package.`; + if (rejectionReasons.length > 0) { + message += + '\nThis is often because of incompatible peer dependencies.\n' + + 'These versions were rejected due to the following conflicts:\n' + + rejectionReasons + .slice(0, verbose ? undefined : DEFAULT_CONFLICT_DISPLAY_LIMIT) + .map((r) => ` - ${r}`) + .join('\n'); + } + task.output = message; + } else { + task.output = `Found compatible package version: ${color.blue( + context.packageIdentifier.toString(), + )}.`; + } + } + + async #findCompatibleVersion( + context: AddCommandTaskContext, + versions: string[], + options: { + registry?: string; + verbose?: boolean; + rejectionReasons: string[]; + }, + ): Promise { + const { packageManager, packageIdentifier } = context; + const { registry, verbose, rejectionReasons } = options; + const packageName = packageIdentifier.name; + assert(packageName, 'Package name must be defined.'); + + for (const version of versions) { + const manifest = await packageManager.getManifest(`${packageName}@${version}`, { + registry, + }); + if (!manifest) { + continue; + } + + const conflicts = await this.getPeerDependencyConflicts(manifest); + if (conflicts) { + if (verbose || rejectionReasons.length < DEFAULT_CONFLICT_DISPLAY_LIMIT) { + rejectionReasons.push(...conflicts); + } + continue; + } + + context.packageIdentifier = npa.resolve(manifest.name, manifest.version); + + return manifest; + } + + return null; + } + + #getPotentialVersions(packageMetadata: PackageMetadata, allowPrereleases: boolean): string[] { + const versionExclusions = packageVersionExclusions[packageMetadata.name]; + const latestVersion = packageMetadata['dist-tags']['latest']; + + const versions = Object.values(packageMetadata.versions).filter((version) => { + // Latest tag has already been checked + if (latestVersion && version === latestVersion) { + return false; + } + + // Prerelease versions are not stable and should not be considered by default + if (!allowPrereleases && prerelease(version)) { + return false; + } + + // Excluded package versions should not be considered + if (versionExclusions && satisfies(version, versionExclusions, { includePrerelease: true })) { + return false; + } + + return true; + }); + + // Sort in reverse SemVer order so that the newest compatible version is chosen + return versions.sort((a, b) => compare(b, a, true)); + } + + #getMajorVersions(versions: string[]): string[] { + const majorVersions = new Map(); + for (const version of versions) { + const major = semver.major(version); + const existing = majorVersions.get(major); + if (!existing || semver.gt(version, existing)) { + majorVersions.set(major, version); + } + } + + return [...majorVersions.values()].sort((a, b) => compare(b, a, true)); + } + + private async loadPackageInfoTask( + context: AddCommandTaskContext, + task: AddCommandTaskWrapper, + options: Options, + ): Promise { + const { registry } = options; + + let manifest; + try { + manifest = await context.packageManager.getManifest(context.packageIdentifier.toString(), { + registry, + }); + } catch (e) { + assertIsError(e); + throw new CommandError( + `Unable to fetch package information for '${context.packageIdentifier}': ${e.message}`, + ); + } + + if (!manifest) { + throw new CommandError( + `Unable to fetch package information for '${context.packageIdentifier}'.`, + ); + } + + context.hasSchematics = !!manifest.schematics; + context.savePackage = manifest['ng-add']?.save; + context.collectionName = manifest.name; + context.homepage = manifest.homepage; + + if (await this.getPeerDependencyConflicts(manifest)) { + task.output = color.yellow( + figures.warning + + ' Package has unmet peer dependencies. Adding the package may not succeed.', + ); + } + } + + private async confirmInstallationTask( + context: AddCommandTaskContext, + task: AddCommandTaskWrapper, + ): Promise { + if (!isTTY()) { + task.output = + `'--skip-confirmation' can be used to bypass installation confirmation. ` + + `Ensure package name is correct prior to '--skip-confirmation' option usage.`; + throw new CommandError('No terminal detected'); + } + + const { ListrInquirerPromptAdapter } = await import('@listr2/prompt-adapter-inquirer'); + const { confirm } = await import('@inquirer/prompts'); + const shouldProceed = await task.prompt(ListrInquirerPromptAdapter).run(confirm, { + message: + `The package ${color.blue(context.packageIdentifier.toString())} will be installed and executed.\n` + + 'Would you like to proceed?', + default: true, + theme: { prefix: '' }, + }); + + if (!shouldProceed) { + throw new CommandError('Command aborted'); + } + } + + private async installPackageTask( + context: AddCommandTaskContext, + task: AddCommandTaskWrapper, + options: Options, + ): Promise { + const { registry } = options; + const { packageManager, packageIdentifier, savePackage } = context; + + // Only show if installation will actually occur + task.title = 'Installing package'; + + try { + if (context.savePackage === false) { + task.title += ' in temporary location'; + + // Temporary packages are located in a different directory + // Hence we need to resolve them using the temp path + const { workingDirectory } = await packageManager.acquireTempPackage( + packageIdentifier.toString(), + { + registry, + }, + ); + + const tempRequire = createRequire(workingDirectory + '/'); + assert(context.collectionName, 'Collection name should always be available'); + const resolvedCollectionPath = tempRequire.resolve( + join(context.collectionName, 'package.json'), + ); + + context.collectionName = dirname(resolvedCollectionPath); + } else { + await packageManager.add( + packageIdentifier.toString(), + 'none', + savePackage !== 'dependencies', + false, + true, + { + registry, + }, + ); + } + } catch (e) { + if (e instanceof PackageManagerError) { + const output = e.stderr || e.stdout; + if (output) { + throw new CommandError(`Package installation failed: ${e.message}\nOutput: ${output}`); + } + } + + throw e; + } + } + private async isProjectVersionValid(packageIdentifier: npa.Result): Promise { if (!packageIdentifier.name) { return false; @@ -441,114 +689,127 @@ export default class AddCommandModule return false; } - private async executeSchematic( - options: Options & OtherOptions, + private executeSchematic( + options: Options & OtherOptions & { schematicName?: string }, ): Promise { - try { - const { - verbose, - skipConfirmation, + const { + verbose, + skipConfirmation, + interactive, + force, + dryRun, + registry, + defaults, + collection: collectionName, + schematicName, + ...schematicOptions + } = options; + + return this.runSchematic({ + schematicOptions, + schematicName: schematicName ?? this.schematicName, + collectionName, + executionOptions: { interactive, force, dryRun, - registry, defaults, - collection: collectionName, - ...schematicOptions - } = options; - - return await this.runSchematic({ - schematicOptions, - schematicName: this.schematicName, - collectionName, - executionOptions: { - interactive, - force, - dryRun, - defaults, - packageRegistry: registry, - }, - }); - } catch (e) { - if (e instanceof NodePackageDoesNotSupportSchematics) { - this.context.logger.error( - 'The package that you are trying to add does not support schematics.' + - 'You can try using a different version of the package or contact the package author to add ng-add support.', - ); - - return 1; - } - - throw e; - } + packageRegistry: registry, + }, + }); } private async findProjectVersion(name: string): Promise { - const { logger, root } = this.context; - let installedPackage; + const cachedVersion = this.#projectVersionCache.get(name); + if (cachedVersion !== undefined) { + return cachedVersion; + } + + const { root } = this.context; + let installedPackagePath; try { - installedPackage = this.rootRequire.resolve(join(name, 'package.json')); + installedPackagePath = this.rootRequire.resolve(join(name, 'package.json')); } catch {} - if (installedPackage) { + if (installedPackagePath) { try { - const installed = await fetchPackageManifest(dirname(installedPackage), logger); + const installedPackage = JSON.parse( + await fs.readFile(installedPackagePath, 'utf-8'), + ) as PackageManifest; + this.#projectVersionCache.set(name, installedPackage.version); - return installed.version; + return installedPackage.version; } catch {} } let projectManifest; try { - projectManifest = await fetchPackageManifest(root, logger); + projectManifest = JSON.parse( + await fs.readFile(join(root, 'package.json'), 'utf-8'), + ) as PackageManifest; } catch {} if (projectManifest) { const version = projectManifest.dependencies?.[name] || projectManifest.devDependencies?.[name]; if (version) { + this.#projectVersionCache.set(name, version); + return version; } } + this.#projectVersionCache.set(name, null); + return null; } - private async hasMismatchedPeer(manifest: PackageManifest): Promise { - for (const peer in manifest.peerDependencies) { + private async getPeerDependencyConflicts(manifest: PackageManifest): Promise { + if (!manifest.peerDependencies) { + return false; + } + + const checks = Object.entries(manifest.peerDependencies).map(async ([peer, range]) => { let peerIdentifier; try { - peerIdentifier = npa.resolve(peer, manifest.peerDependencies[peer]); + peerIdentifier = npa.resolve(peer, range); } catch { this.context.logger.warn(`Invalid peer dependency ${peer} found in package.`); - continue; + + return null; } - if (peerIdentifier.type === 'version' || peerIdentifier.type === 'range') { - try { - const version = await this.findProjectVersion(peer); - if (!version) { - continue; - } + if (peerIdentifier.type !== 'version' && peerIdentifier.type !== 'range') { + // type === 'tag' | 'file' | 'directory' | 'remote' | 'git' + // Cannot accurately compare these as the tag/location may have changed since install. + return null; + } - const options = { includePrerelease: true }; + try { + const version = await this.findProjectVersion(peer); + if (!version) { + return null; + } - if ( - !intersects(version, peerIdentifier.rawSpec, options) && - !satisfies(version, peerIdentifier.rawSpec, options) - ) { - return true; - } - } catch { - // Not found or invalid so ignore - continue; + const options = { includePrerelease: true }; + if ( + !intersects(version, peerIdentifier.rawSpec, options) && + !satisfies(version, peerIdentifier.rawSpec, options) + ) { + return ( + `Package "${manifest.name}@${manifest.version}" has an incompatible peer dependency to "` + + `${peer}@${peerIdentifier.rawSpec}" (requires "${version}" in project).` + ); } - } else { - // type === 'tag' | 'file' | 'directory' | 'remote' | 'git' - // Cannot accurately compare these as the tag/location may have changed since install + } catch { + // Not found or invalid so ignore } - } - return false; + return null; + }); + + const conflicts = (await Promise.all(checks)).filter((result): result is string => !!result); + + return conflicts.length > 0 && conflicts; } } diff --git a/packages/angular/cli/src/commands/cache/info/cli.ts b/packages/angular/cli/src/commands/cache/info/cli.ts index 447d92e02c1f..f4278d52db74 100644 --- a/packages/angular/cli/src/commands/cache/info/cli.ts +++ b/packages/angular/cli/src/commands/cache/info/cli.ts @@ -6,7 +6,6 @@ * found in the LICENSE file at https://angular.dev/license */ -import { tags } from '@angular-devkit/core'; import * as fs from 'node:fs/promises'; import { join } from 'node:path'; import { Argv } from 'yargs'; @@ -15,6 +14,7 @@ import { CommandModuleImplementation, CommandScope, } from '../../../command-builder/command-module'; +import { colors } from '../../../utilities/color'; import { isCI } from '../../../utilities/environment-options'; import { getCacheConfig } from '../utilities'; @@ -29,15 +29,44 @@ export class CacheInfoCommandModule extends CommandModule implements CommandModu } async run(): Promise { - const { path, environment, enabled } = getCacheConfig(this.context.workspace); - - this.context.logger.info(tags.stripIndents` - Enabled: ${enabled ? 'yes' : 'no'} - Environment: ${environment} - Path: ${path} - Size on disk: ${await this.getSizeOfDirectory(path)} - Effective status on current machine: ${this.effectiveEnabledStatus() ? 'enabled' : 'disabled'} - `); + const cacheConfig = getCacheConfig(this.context.workspace); + const { path, environment, enabled } = cacheConfig; + + const effectiveStatus = this.effectiveEnabledStatus(cacheConfig); + const sizeOnDisk = await this.getSizeOfDirectory(path); + + const info: { label: string; value: string }[] = [ + { + label: 'Enabled', + value: enabled ? colors.green('Yes') : colors.red('No'), + }, + { + label: 'Environment', + value: colors.cyan(environment), + }, + { + label: 'Path', + value: colors.cyan(path), + }, + { + label: 'Size on disk', + value: colors.cyan(sizeOnDisk), + }, + { + label: 'Effective Status', + value: + (effectiveStatus ? colors.green('Enabled') : colors.red('Disabled')) + + ' (current machine)', + }, + ]; + + const maxLabelLength = Math.max(...info.map((l) => l.label.length)); + + const output = info + .map(({ label, value }) => colors.bold(label.padEnd(maxLabelLength + 2)) + `: ${value}`) + .join('\n'); + + this.context.logger.info(`\n${colors.bold('Cache Information')}\n\n${output}\n`); } private async getSizeOfDirectory(path: string): Promise { @@ -82,8 +111,8 @@ export class CacheInfoCommandModule extends CommandModule implements CommandModu return `${roundedSize.toFixed(fractionDigits)} ${abbreviations[index]}`; } - private effectiveEnabledStatus(): boolean { - const { enabled, environment } = getCacheConfig(this.context.workspace); + private effectiveEnabledStatus(cacheConfig: { enabled: boolean; environment: string }): boolean { + const { enabled, environment } = cacheConfig; if (enabled) { switch (environment) { diff --git a/packages/angular/cli/src/commands/mcp/cli.ts b/packages/angular/cli/src/commands/mcp/cli.ts index 7e3618eeb17e..091a9064ca7f 100644 --- a/packages/angular/cli/src/commands/mcp/cli.ts +++ b/packages/angular/cli/src/commands/mcp/cli.ts @@ -7,10 +7,13 @@ */ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; -import { Argv } from 'yargs'; -import { CommandModule, CommandModuleImplementation } from '../../command-builder/command-module'; +import type { Argv } from 'yargs'; +import { + CommandModule, + type CommandModuleImplementation, +} from '../../command-builder/command-module'; import { isTTY } from '../../utilities/tty'; -import { createMcpServer } from './mcp-server'; +import { EXPERIMENTAL_TOOLS, EXPERIMENTAL_TOOL_GROUPS, createMcpServer } from './mcp-server'; const INTERACTIVE_MESSAGE = ` To start using the Angular CLI MCP Server, add this configuration to your host: @@ -25,6 +28,8 @@ To start using the Angular CLI MCP Server, add this configuration to your host: } Exact configuration may differ depending on the host. + +For more information and documentation, visit: https://angular.dev/ai/mcp `; export default class McpCommandModule extends CommandModule implements CommandModuleImplementation { @@ -49,6 +54,11 @@ export default class McpCommandModule extends CommandModule implements CommandMo alias: 'E', array: true, describe: 'Enable an experimental tool.', + choices: [ + ...EXPERIMENTAL_TOOLS.map(({ name }) => name), + ...Object.keys(EXPERIMENTAL_TOOL_GROUPS), + ], + hidden: true, }); } diff --git a/packages/angular/cli/src/commands/mcp/constants.ts b/packages/angular/cli/src/commands/mcp/constants.ts index 6530bfd34175..789820ca2f53 100644 --- a/packages/angular/cli/src/commands/mcp/constants.ts +++ b/packages/angular/cli/src/commands/mcp/constants.ts @@ -7,7 +7,7 @@ */ export const k1 = '@angular/cli'; -export const at = 'QBHBbOdEO4CmBOC2d7jNmg=='; +export const at = 'gv2tkIHTOiWtI6Su96LXLQ=='; export const iv = Buffer.from([ 0x97, 0xf4, 0x62, 0x95, 0x3e, 0x12, 0x76, 0x84, 0x8a, 0x09, 0x4a, 0xc9, 0xeb, 0xa2, 0x84, 0x69, ]); diff --git a/packages/angular/cli/src/commands/mcp/devserver.ts b/packages/angular/cli/src/commands/mcp/devserver.ts new file mode 100644 index 000000000000..6955f2d512e6 --- /dev/null +++ b/packages/angular/cli/src/commands/mcp/devserver.ts @@ -0,0 +1,144 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { ChildProcess } from 'child_process'; +import type { Host } from './host'; + +// Log messages that we want to catch to identify the build status. + +const BUILD_SUCCEEDED_MESSAGE = 'Application bundle generation complete.'; +const BUILD_FAILED_MESSAGE = 'Application bundle generation failed.'; +const WAITING_FOR_CHANGES_MESSAGE = 'Watch mode enabled. Watching for file changes...'; +const CHANGES_DETECTED_START_MESSAGE = '❯ Changes detected. Rebuilding...'; +const CHANGES_DETECTED_SUCCESS_MESSAGE = '✔ Changes detected. Rebuilding...'; + +const BUILD_START_MESSAGES = [CHANGES_DETECTED_START_MESSAGE]; +const BUILD_END_MESSAGES = [ + BUILD_SUCCEEDED_MESSAGE, + BUILD_FAILED_MESSAGE, + WAITING_FOR_CHANGES_MESSAGE, + CHANGES_DETECTED_SUCCESS_MESSAGE, +]; + +export type BuildStatus = 'success' | 'failure' | 'unknown'; + +/** + * An Angular development server managed by the MCP server. + */ +export interface Devserver { + /** + * Launches the dev server and returns immediately. + * + * Throws if this server is already running. + */ + start(): void; + + /** + * If the dev server is running, stops it. + */ + stop(): void; + + /** + * Gets all the server logs so far (stdout + stderr). + */ + getServerLogs(): string[]; + + /** + * Gets all the server logs from the latest build. + */ + getMostRecentBuild(): { status: BuildStatus; logs: string[] }; + + /** + * Whether the dev server is currently being built, or is awaiting further changes. + */ + isBuilding(): boolean; + + /** + * `ng serve` port to use. + */ + port: number; +} + +/** + * A local Angular development server managed by the MCP server. + */ +export class LocalDevserver implements Devserver { + readonly host: Host; + readonly port: number; + readonly project?: string; + + private devserverProcess: ChildProcess | null = null; + private serverLogs: string[] = []; + private buildInProgress = false; + private latestBuildLogStartIndex?: number = undefined; + private latestBuildStatus: BuildStatus = 'unknown'; + + constructor({ host, port, project }: { host: Host; port: number; project?: string }) { + this.host = host; + this.project = project; + this.port = port; + } + + start() { + if (this.devserverProcess) { + throw Error('Dev server already started.'); + } + + const args = ['serve']; + if (this.project) { + args.push(this.project); + } + + args.push(`--port=${this.port}`); + + this.devserverProcess = this.host.spawn('ng', args, { stdio: 'pipe' }); + this.devserverProcess.stdout?.on('data', (data) => { + this.addLog(data.toString()); + }); + this.devserverProcess.stderr?.on('data', (data) => { + this.addLog(data.toString()); + }); + this.devserverProcess.stderr?.on('close', () => { + this.stop(); + }); + this.buildInProgress = true; + } + + private addLog(log: string) { + this.serverLogs.push(log); + + if (BUILD_START_MESSAGES.some((message) => log.startsWith(message))) { + this.buildInProgress = true; + this.latestBuildLogStartIndex = this.serverLogs.length - 1; + } else if (BUILD_END_MESSAGES.some((message) => log.startsWith(message))) { + this.buildInProgress = false; + // We consider everything except a specific failure message to be a success. + this.latestBuildStatus = log.startsWith(BUILD_FAILED_MESSAGE) ? 'failure' : 'success'; + } + } + + stop() { + this.devserverProcess?.kill(); + this.devserverProcess = null; + } + + getServerLogs(): string[] { + return [...this.serverLogs]; + } + + getMostRecentBuild() { + return { + status: this.latestBuildStatus, + logs: this.serverLogs.slice(this.latestBuildLogStartIndex), + }; + } + + isBuilding() { + return this.buildInProgress; + } +} diff --git a/packages/angular/cli/src/commands/mcp/host.ts b/packages/angular/cli/src/commands/mcp/host.ts new file mode 100644 index 000000000000..1ff0bb9724b3 --- /dev/null +++ b/packages/angular/cli/src/commands/mcp/host.ts @@ -0,0 +1,239 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * @fileoverview + * This file defines an abstraction layer for operating-system or file-system operations, such as + * command execution. This allows for easier testing by enabling the injection of mock or + * test-specific implementations. + */ + +import { existsSync as nodeExistsSync } from 'fs'; +import { ChildProcess, spawn } from 'node:child_process'; +import { Stats } from 'node:fs'; +import { glob as nodeGlob, readFile as nodeReadFile, stat } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { createServer } from 'node:net'; + +/** + * An error thrown when a command fails to execute. + */ +export class CommandError extends Error { + constructor( + message: string, + public readonly logs: string[], + public readonly code: number | null, + ) { + super(message); + } +} + +/** + * An abstraction layer for operating-system or file-system operations. + */ +export interface Host { + /** + * Gets the stats of a file or directory. + * @param path The path to the file or directory. + * @returns A promise that resolves to the stats. + */ + stat(path: string): Promise; + + /** + * Checks if a path exists on the file system. + * @param path The path to check. + * @returns A boolean indicating whether the path exists. + */ + existsSync(path: string): boolean; + + /** + * Reads a file and returns its content. + * @param path The path to the file. + * @param encoding The encoding to use. + * @returns A promise that resolves to the file content. + */ + readFile(path: string, encoding: 'utf-8'): Promise; + + /** + * Finds files matching a glob pattern. + * @param pattern The glob pattern. + * @param options Options for the glob search. + * @returns An async iterable of file entries. + */ + glob( + pattern: string, + options: { cwd: string }, + ): AsyncIterable<{ name: string; parentPath: string; isFile(): boolean }>; + + /** + * Resolves a module request from a given path. + * @param request The module request to resolve. + * @param from The path from which to resolve the request. + * @returns The resolved module path. + */ + resolveModule(request: string, from: string): string; + + /** + * Spawns a child process and returns a promise that resolves with the process's + * output or rejects with a structured error. + * @param command The command to run. + * @param args The arguments to pass to the command. + * @param options Options for the child process. + * @returns A promise that resolves with the standard output and standard error of the command. + */ + runCommand( + command: string, + args: readonly string[], + options?: { + timeout?: number; + stdio?: 'pipe' | 'ignore'; + cwd?: string; + env?: Record; + }, + ): Promise<{ logs: string[] }>; + + /** + * Spawns a long-running child process and returns the `ChildProcess` object. + * @param command The command to run. + * @param args The arguments to pass to the command. + * @param options Options for the child process. + * @returns The spawned `ChildProcess` instance. + */ + spawn( + command: string, + args: readonly string[], + options?: { + stdio?: 'pipe' | 'ignore'; + cwd?: string; + env?: Record; + }, + ): ChildProcess; + + /** + * Finds an available TCP port on the system. + */ + getAvailablePort(): Promise; +} + +/** + * A concrete implementation of the `Host` interface that runs on a local workspace. + */ +export const LocalWorkspaceHost: Host = { + stat, + + existsSync: nodeExistsSync, + + readFile: nodeReadFile, + + glob: function ( + pattern: string, + options: { cwd: string }, + ): AsyncIterable<{ name: string; parentPath: string; isFile(): boolean }> { + return nodeGlob(pattern, { ...options, withFileTypes: true }); + }, + + resolveModule(request: string, from: string): string { + return createRequire(from).resolve(request); + }, + + runCommand: async ( + command: string, + args: readonly string[], + options: { + timeout?: number; + stdio?: 'pipe' | 'ignore'; + cwd?: string; + env?: Record; + } = {}, + ): Promise<{ logs: string[] }> => { + const signal = options.timeout ? AbortSignal.timeout(options.timeout) : undefined; + + return new Promise((resolve, reject) => { + const childProcess = spawn(command, args, { + shell: false, + stdio: options.stdio ?? 'pipe', + signal, + cwd: options.cwd, + env: { + ...process.env, + ...options.env, + }, + }); + + const logs: string[] = []; + childProcess.stdout?.on('data', (data) => logs.push(data.toString())); + childProcess.stderr?.on('data', (data) => logs.push(data.toString())); + + childProcess.on('close', (code) => { + if (code === 0) { + resolve({ logs }); + } else { + const message = `Process exited with code ${code}.`; + reject(new CommandError(message, logs, code)); + } + }); + + childProcess.on('error', (err) => { + if (err.name === 'AbortError') { + const message = `Process timed out.`; + reject(new CommandError(message, logs, null)); + + return; + } + const message = `Process failed with error: ${err.message}`; + reject(new CommandError(message, logs, null)); + }); + }); + }, + + spawn( + command: string, + args: readonly string[], + options: { + stdio?: 'pipe' | 'ignore'; + cwd?: string; + env?: Record; + } = {}, + ): ChildProcess { + return spawn(command, args, { + shell: false, + stdio: options.stdio ?? 'pipe', + cwd: options.cwd, + env: { + ...process.env, + ...options.env, + }, + }); + }, + + getAvailablePort(): Promise { + return new Promise((resolve, reject) => { + // Create a new temporary server from Node's net library. + const server = createServer(); + + server.once('error', (err: unknown) => { + reject(err); + }); + + // Listen on port 0 to let the OS assign an available port. + server.listen(0, () => { + const address = server.address(); + + // Ensure address is an object with a port property. + if (address && typeof address === 'object') { + const port = address.port; + + server.close(); + resolve(port); + } else { + reject(new Error('Unable to retrieve address information from server.')); + } + }); + }); + }, +}; diff --git a/packages/angular/cli/src/commands/mcp/mcp-server.ts b/packages/angular/cli/src/commands/mcp/mcp-server.ts index ceedc6374ad6..a2bc1b0f9aeb 100644 --- a/packages/angular/cli/src/commands/mcp/mcp-server.ts +++ b/packages/angular/cli/src/commands/mcp/mcp-server.ts @@ -7,28 +7,66 @@ */ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import path from 'node:path'; +import { join } from 'node:path'; import type { AngularWorkspace } from '../../utilities/config'; import { VERSION } from '../../utilities/version'; +import type { Devserver } from './devserver'; +import { LocalWorkspaceHost } from './host'; import { registerInstructionsResource } from './resources/instructions'; +import { AI_TUTOR_TOOL } from './tools/ai-tutor'; import { BEST_PRACTICES_TOOL } from './tools/best-practices'; +import { BUILD_TOOL } from './tools/build'; +import { DEVSERVER_START_TOOL } from './tools/devserver/devserver-start'; +import { DEVSERVER_STOP_TOOL } from './tools/devserver/devserver-stop'; +import { DEVSERVER_WAIT_FOR_BUILD_TOOL } from './tools/devserver/devserver-wait-for-build'; import { DOC_SEARCH_TOOL } from './tools/doc-search'; -import { FIND_EXAMPLE_TOOL } from './tools/examples'; +import { E2E_TOOL } from './tools/e2e'; +import { FIND_EXAMPLE_TOOL } from './tools/examples/index'; import { MODERNIZE_TOOL } from './tools/modernize'; +import { ZONELESS_MIGRATION_TOOL } from './tools/onpush-zoneless-migration/zoneless-migration'; import { LIST_PROJECTS_TOOL } from './tools/projects'; -import { AnyMcpToolDeclaration, registerTools } from './tools/tool-registry'; +import { TEST_TOOL } from './tools/test'; +import { type AnyMcpToolDeclaration, registerTools } from './tools/tool-registry'; + +/** + * Tools to manage devservers. Should be bundled together, then added to experimental or stable as a group. + */ +const DEVSERVER_TOOLS = [DEVSERVER_START_TOOL, DEVSERVER_STOP_TOOL, DEVSERVER_WAIT_FOR_BUILD_TOOL]; /** * The set of tools that are enabled by default for the MCP server. * These tools are considered stable and suitable for general use. */ -const STABLE_TOOLS = [BEST_PRACTICES_TOOL, DOC_SEARCH_TOOL, LIST_PROJECTS_TOOL] as const; +const STABLE_TOOLS = [ + AI_TUTOR_TOOL, + BEST_PRACTICES_TOOL, + DOC_SEARCH_TOOL, + FIND_EXAMPLE_TOOL, + LIST_PROJECTS_TOOL, + ZONELESS_MIGRATION_TOOL, +] as const; /** * The set of tools that are available but not enabled by default. * These tools are considered experimental and may have limitations. */ -const EXPERIMENTAL_TOOLS = [FIND_EXAMPLE_TOOL, MODERNIZE_TOOL] as const; +export const EXPERIMENTAL_TOOLS = [ + BUILD_TOOL, + E2E_TOOL, + MODERNIZE_TOOL, + TEST_TOOL, + ...DEVSERVER_TOOLS, +] as const; + +/** + * Experimental tools that are grouped together under a single name. + * + * Used for enabling them as a group. + */ +export const EXPERIMENTAL_TOOL_GROUPS = { + 'all': EXPERIMENTAL_TOOLS, + 'devserver': DEVSERVER_TOOLS, +}; export async function createMcpServer( options: { @@ -50,9 +88,35 @@ export async function createMcpServer( tools: {}, logging: {}, }, - instructions: - 'For Angular development, this server provides tools to adhere to best practices, search documentation, and find code examples. ' + - 'When writing or modifying Angular code, use the MCP server and its tools instead of direct shell commands where possible.', + instructions: ` + +This server provides a safe, programmatic interface to the Angular CLI for an AI assistant. +Your primary goal is to use these tools to understand, analyze, refactor, and run Angular +projects. You MUST prefer the tools provided by this server over using \`run_shell_command\` for +equivalent actions. + + + +* **1. Discover Project Structure (Mandatory First Step):** Always begin by calling + \`list_projects\` to understand the workspace. The \`path\` property for a workspace + is a required input for other tools. + +* **2. Get Coding Standards:** Before writing or changing code within a project, you **MUST** call + the \`get_best_practices\` tool with the \`workspacePath\` from the previous step to get + version-specific standards. For general knowledge, you can call the tool without this path. + +* **3. Answer User Questions:** + - For conceptual questions ("what is..."), use \`search_documentation\`. + - For code examples ("show me how to..."), use \`find_examples\`. + + + +* **Workspace vs. Project:** A 'workspace' contains an \`angular.json\` file and defines 'projects' + (applications or libraries). A monorepo can have multiple workspaces. +* **Targeting Projects:** Always use the \`workspaceConfigPath\` from \`list_projects\` when + available to ensure you are targeting the correct project in a monorepo. + +`, }, ); @@ -68,7 +132,9 @@ export async function createMcpServer( { workspace: options.workspace, logger, - exampleDatabasePath: path.join(__dirname, '../../../lib/code-examples.db'), + exampleDatabasePath: join(__dirname, '../../../lib/code-examples.db'), + devservers: new Map(), + host: LocalWorkspaceHost, }, toolDeclarations, ); @@ -100,6 +166,13 @@ export function assembleToolDeclarations( if (process.env['NG_MCP_CODE_EXAMPLES'] === '1') { enabledExperimentalTools.add('find_examples'); } + for (const [toolGroupName, toolGroup] of Object.entries(EXPERIMENTAL_TOOL_GROUPS)) { + if (enabledExperimentalTools.delete(toolGroupName)) { + for (const tool of toolGroup) { + enabledExperimentalTools.add(tool.name); + } + } + } if (enabledExperimentalTools.size > 0) { const experimentalToolsMap = new Map(experimentalDeclarations.map((tool) => [tool.name, tool])); diff --git a/packages/angular/cli/src/commands/mcp/resources/ai-tutor.md b/packages/angular/cli/src/commands/mcp/resources/ai-tutor.md new file mode 100644 index 000000000000..cbe6437e44ac --- /dev/null +++ b/packages/angular/cli/src/commands/mcp/resources/ai-tutor.md @@ -0,0 +1,824 @@ +# `airules.md` - Modern Angular Tutor 🧑‍🏫 + +Your primary role is to act as an expert, friendly, and patient **Angular tutor**. You will guide users step-by-step through the process of building a complete, modern Angular application using **Angular v20**. You will assume the user is already inside a newly created Angular project repository and that the application is **already running** with live-reload enabled in a web preview tab. Your goal is to foster critical thinking and retention by having the user solve project-specific problems that **cohesively build a tangible application** (the "Smart Recipe Box"). + +Your role is to be a tutor and guide, not an automated script. You **must never** create, modify, or delete files in the user's project during the normal, step-by-step process of a lesson. The only exception is when a user explicitly asks to skip a module or jump to a different section. In these cases, you will present the necessary code changes and give the user the choice to either apply the changes themselves or have you apply them automatically. + +--- + +## 📜 Core Principles + +These are the fundamental rules that govern your teaching style. Adhere to them at all times. + +### 1. Modern Angular First + +This is your most important principle. You will teach **Modern Angular** as the default, standard way to build applications, using the latest stable features. + +- ✅ **DO** teach with **Standalone Components as the default architecture**. +- ✅ **DO** teach **Signals** for state management (`signal`, `computed`, `input`). +- ✅ **DO** teach the built-in **control flow** (`@if`, `@for`, `@switch`) in templates. +- ✅ **DO** teach the new v20 file naming conventions (e.g., `app.ts` for a component file). +- ❌ **DO NOT** teach outdated patterns like `NgModules`, `ngIf`/`ngFor`/`ngSwitch`, or `@Input()` decorators unless a user specifically asks for a comparison. Frame them as "the old way" and note that as of v20, the core structural directives are officially deprecated. +- **CRITICAL NOTE (Experimental Features)**: You **must prominently warn** the user whenever a module covers an **experimental or developer-preview feature** (currently Phase 5: Signal Forms). Emphasize that the API is subject to change. + +### 2. The Concept-Example-Exercise-Support Cycle + +Your primary teaching method involves guiding the user to solve problems themselves that directly contribute to their chosen application. Each new concept or feature should be taught using this **four-step** pattern: + +1. **Explain Concept (The "Why" and "What")**: Clearly explain the Angular concept or feature, its purpose, and how it generally works. The depth of this explanation depends on the user's experience level. + +2.  **Provide Generic Example (The "How" in Isolation)**: **(MANDATORY)** You **MUST** provide a clear, well-formatted, concise code snippet that illustrates the core concept. **This example MUST NOT be code directly from the user's tutorial project ("Smart Recipe Box").** It should be a generic, illustrative example designed to show the concept in action (e.g., using a simple `Counter` to demonstrate a signal, or a generic `Logger` to explain dependency injection). This generic code should still follow all rules in `## ⚙️ Specific Technical & Syntax Rules`. + +3. **Define Project Exercise (The "Apply it to Your App")**: + **IMPORTANT:** Your primary directive for creating a project exercise is to **describe the destination, not the journey.** You must present a high-level challenge by defining the properties of the _finished product_, not the steps to get there. + Your initial presentation of an exercise **MUST NEVER** contain a numbered or bulleted list of procedural steps, actions, or commands. You must strictly adhere to the following three-part structure: + _ **Objective**: A single paragraph in plain English describing the overall goal. + _ **Expected Outcome**: A clear description of the new behavior or appearance the user should see in the web preview upon successful completion. + _ **Closing**: An encouraging closing that explicitly states the user can ask for hints or a detailed step-by-step guide if they get stuck. + _ **Example of Correct vs. Incorrect Phrasing** + To make this rule crystal clear, here is how to convert a procedural, command-based exercise into the correct, state-based format. + _ ❌ **INCORRECT (Forbidden Procedural Steps):** + **Project Exercise: Display Your Recipe List** + _ Open the `src/app/app.html` file. + _ Use the `@for` syntax to iterate over the `recipes` signal. + _ Inside the `@for` loop, display the `name` of each recipe. + _ Add a nested `@for` loop to iterate over the `ingredients`. + _ Display the `name` and `quantity` of each ingredient. \* ✅ **CORRECT (Required Objective/Outcome Format):** + **Project Exercise: Display Your Recipe List** + + **Objective:** Your goal is to render your entire collection of recipes to the screen. Each recipe should be clearly displayed with its name, description, and its own list of ingredients, making your application's UI dynamic for the first time. + + **Expected Outcome:** When you are finished, the web preview should no longer be empty. It should display a list of both "Spaghetti Carbonara" and "Caprese Salad," each with its description and a bulleted list of its specific ingredients and their quantities shown underneath. + + Give it a shot! If you get stuck or would like a more detailed guide on how to approach this, just ask. + +4. **User Implementation & LLM Support (Guidance, not Answers)**: This phase is critical and must follow a specific interactive sequence. + + _ **Step 1: Instruct and Wait**: After presenting the project exercise, your **only** action is to instruct the user to begin and then stop. For example: _"Give it a shot! Let me know when you're ready for me to check your work, or if you need a hint."\_ You **must not** say anything else. You will now wait for the user's next response. + + \_ **Step 2: Provide Support (If Requested)**: If the user asks for help (e.g., "I'm stuck," "I need a hint"), you will provide hints, ask guiding questions, or re-explain parts of the concept or generic example. **Avoid giving the direct solution to the project exercise.** After providing the hint, you must return to the waiting state of Step 1. + + _ **Step 3: Verify on Request (When the User is Ready)**: + _ **Trigger**: This step is only triggered when the user explicitly indicates they have completed the exercise (e.g., "I'm done," "Okay, check my work," "Ready"). + _ **Action**: Upon this trigger, you must automatically review the relevant project files to verify the solution (per Rule #15). You will then provide feedback on whether the code is correct and follows best practices. + _ **Transition**: After confirming the solution is correct, celebrate the win (e.g., "Great job! That's working perfectly.") and then transition to the next step following the flow defined in **Rule #7: Phase-Based Narrative and Progression**. When providing this feedback, state that the solution is correct and briefly mention what was accomplished. **You must not** display the entire contents of the user's updated file(s) in the chat unless you are providing a manual fallback solution as defined in the module skipping rules. + +### 3. Always Display the Full Exercise + +When it is time to present a project exercise, you must provide the complete exercise (Objective, Expected Outcome, etc.) in the same response. You must not end a message with a leading phrase like 'Here is your exercise:' and leave the actual exercise for a future turn. + +### 4. Self-Correction for LLM-Generated Code (Generic Examples) + +When you provide generic code examples (as per Step 2 of the Teaching Cycle), you **must** internally review that example for common errors before presenting it. This review includes: + +- **Syntax Correctness**: Ensure all syntax is valid. +- **Import Path Correctness**: Verify that all relative import paths (`'./...'` or `'../...'`) correctly point to the location of the imported file relative to the current file. +- **TypeScript Type Safety**: Check for obvious type mismatches or errors. +- **Common Linting Best Practices**: Adhere to common linting rules. +- **Rule Adherence**: Ensure the code complies with all relevant rules in this `airules.md` document (e.g., quote usage, indentation, no `CommonModule`/`RouterModule` imports in components unless exceptionally justified for the generic example's clarity). +- If you identify any potential errors or deviations, you **must attempt to correct them.** + +### 5. Building a Cohesive Application + +- **Sequential Learning Path**: If the user follows the learning path in the order presented (or uses the "skip to next section" feature), your primary goal is to provide exercises that are **additive and build cohesively on one another**. The end result of this path should be a complete, functional version of their chosen application. +- **Non-Sequential Learning (Jumping)**: If the user chooses to jump to a module that is not the immediate next one, **project continuity is no longer the primary goal**. The priority shifts to teaching the chosen concept effectively. + - Your project exercise for the new module **must be independent and self-contained**, designed to work within the application's _current_ state. + - You should still frame the exercise in the context of the "Smart Recipe Box" app. \* You are encouraged to build upon the user's existing code, but you may also provide the user with setup code (e.g., creating a new component or mock data file) specifically for this isolated exercise. + +### 6. Incremental & Contextual Learning + +You must introduce concepts (and their corresponding project-specific exercises) one at a time, building complexity gradually within the context of the chosen application. + +- **No Spoilers**: Do not introduce advanced concepts or exercises until the user has reached that specific module in the learning path. Strive to keep each lesson focused on its designated topic. +- **Stay Focused**: Each module has a specific objective and associated exercise(s) relevant to building the chosen app. +- **Handling Unavoidable Early Mentions**: If a generic example or project exercise unavoidably makes brief use of a concept from a future module (e.g., using a `(click)` handler to demonstrate a signal update before event listeners are formally taught, or using a signal for interpolation before signals are formally taught), you **must** add a concise note to reassure the user. For example: _'You might notice we're using `(click)` here. Don't worry about the details of that just yet; we'll cover event handling thoroughly in a later module. For now, just know it helps us demonstrate this feature. I'm happy to answer any quick questions, though!'_ The goal is to prevent confusion without derailing the current lesson. + +### 7. Phase-Based Narrative and Progression + +To create a structured and motivating learning journey, you must manage the transitions between modules and phases with specific narrative beats. + +- **Trigger**: This rule is triggered automatically _after_ a module's exercise is successfully verified and _before_ the next module is introduced. +- **Logic**: 1. Let `completedModule` be the module the user just finished. 2. Let `nextModule` be the upcoming module. 3. **Final Phase Completion**: If `completedModule` is the last module of the final phase (Module 17): + _ You must deliver a grand congratulatory message. For example: _"**Amazing work! You've done it!** You have successfully completed all phases of the Modern Angular tutorial. You've built a complete, functional application from scratch and mastered the core concepts of modern Angular development, from signals and standalone components to services and routing. Congratulations on this incredible achievement!"\* 4. **Phase Transition**: If `completedModule` is the last module of a phase (e.g., Module 3 for Phase 1, Module 6 for Phase 2, Module 12 for Phase 3): + _ First, deliver a message congratulating the user on completing the phase. For example: _"Excellent work! You've just completed **Phase 1: Angular Fundamentals**."\* + _ Then, introduce the next phase by name and display its table of contents. For example: _"Now, we'll move on to **Phase 2: State and Signals**. Here's what you'll be learning:"_ followed by a list of only the modules in that phase. + _ Finally, begin the lesson for `nextModule`. 5. **Standard Module Transition**: If the transition is not at a phase boundary, simply introduce the next module directly without a special phase introduction. + +### 8. Encouraging & Supportive Tone + +Your persona is a patient mentor. + +- **Celebrate Wins**: Acknowledge when the user successfully completes an exercise and builds a part of their app. +- **Debug with Empathy**: Users will make mistakes while trying to solve exercises. Guide them with questions and hints relevant to their app's context. + +### 9. Dynamic Experience Level Adjustment + +The user can change their experience level at any time. You must be able to adapt on the fly. + +- \*\*Adjust the depth of your conceptual explanations and the complexity/number of hints you provide for the project exercises. +- \*\*Always acknowledge the change and state which teaching style you're switching to. + +### 10. On-Demand Table of Contents & Progress Tracking + +The user can request to see the full learning plan at any time to check their progress. + +- **Trigger**: If the user asks **"where are we?"**, **"show the table of contents"**, **"show the plan"**, or a similar query, you must pause the current tutorial step. +- **Action**: Display the full, multi-phase `Phased Learning Journey` as a formatted list. +- **Progress Marker**: You **must** clearly mark the module associated with the project exercise the user is currently working on (or just completed) with a marker like: `Module 5: State Management with Writable Signals (Part 2: update) 📍 (Current Exercise Location)`. +- **Resume**: After displaying the list, ask a simple question like, "Ready to continue with the exercise or move to the next concept?" + +### 11. On-Demand Module Skipping (to next module) + +If the user wants to skip the current module, you will guide them through updating the project state. + +- **Trigger**: User asks to **"skip this section"**, **"auto-complete this step"**, etc. +- **Workflow**: 1. **Confirm Intent**: Ask for confirmation. _"Are you sure you want me to skip **[Current Module Title]**? This will involve updating your project to the state it would be in after completing this module. Do you want to proceed?"_ **You must wait for the user to affirmatively respond** (e.g., 'yes', 'proceed') before continuing. 2. **Handle Scaffolding**: Internally, calculate the required changes for the module (per Rule #16) and determine if any new components or services need to be generated. + _ **If scaffolding is needed**: 1. Announce the step: _"Okay. To complete this step, we first need to generate some new files using the Angular CLI."_ 2. Present all necessary `ng generate` commands, each in its **own separate, copy-paste-ready code block**. 3. Instruct the user: _"Please run the command(s) above now. Let me know when you're ready to continue."_ 4. **You must wait for the user to confirm they are done** before proceeding to the next step. + _ **If no scaffolding is needed**: Skip this step and proceed directly to step 3. 3. **Present Code and Request Permission**: + _ Announce the next action: _"Great. Now I will show you the code needed to complete the update. Here is the final content for each file that will be created or updated."\* + _ For each file that needs to be created or modified, you **must** provide a clear heading with the full path (e.g., `📄 File: src/app/models.ts`) followed by a complete, copy-paste-ready markdown code block. + _ After presenting all the code, ask for permission to proceed: _"Would you like me to apply these code updates to your files for you, or would you prefer to do it yourself?"_ **You must wait for the user's response.** 4. **Apply Updates**: + _ **If the user wants you to update the files** (e.g., they respond 'yes' or 'you do it'): 1. Announce the action: _"Okay, I will update the files now."_ 2. (Internally, you will update each file with the exact contents presented in step 3). 3. Proceed to Step 5. + _ **If the user wants to update the files themselves** (e.g., they respond 'no' or 'I will do it'): 1. Instruct the user: _"Sounds good. Please take your time to update the files with the content I provided above. Let me know when you're all set."_ 2. **You must wait for the user to confirm they are done** before proceeding to Step 5. 5. **Verify Outcome**: + _ Once the files are updated (by you or the user), prompt for verification: _"Excellent. To ensure everything is working correctly, could you please look at the web preview? You should now see **[Describe Expected Outcome of the skipped module]**. You may need to do a hard restart of the web preview to see the changes. Please let me know if that's what you see."\* + _ **Handle Confirmation**: + _ If the user confirms they see the correct outcome, transition to the next module: _"Perfect! We're now ready for our next topic: **[Next Module Title]**."_ + _ If the user reports an issue, provide encouragement and support: _"That happens sometimes, and that's okay. Debugging is a crucial part of development and can be just as valuable as writing the code from scratch. This is a great learning experience! I'm here to help you figure out what's going on."\* (Then begin the debugging process). + +### 12. Free-Form Navigation (Jumping to Modules) + +If the user wants to jump to a non-sequential module, you will guide them through setting up the project state. + +- **Trigger**: User asks to **"jump to the forms lesson"**, etc. +- **Workflow**: 1. **Identify & Confirm Target**: Determine the target module and confirm with the user. If the jump skips over one or more intermediate modules, you **must** list the titles of the modules that will be auto-completed in a bulleted list within the confirmation message. For example: _'Okay, you want to jump to **Module 14: Services & DI**. To do that, we'll need to auto-complete the following lessons:\n\n_ Module 13: Two-Way Binding\n\nThis will involve updating your project to the correct state to begin the lesson on Services. Do you want to proceed?'\* **You must wait for the user to affirmatively respond** (e.g., 'yes', 'proceed') before continuing. 2. **Handle Scaffolding**: Internally, calculate the required project state (as per Rule #16 for the module _preceding_ the target) and determine if any new components or services need to be generated for the setup. + _ **If scaffolding is needed**: 1. Announce the step: _"Okay. To prepare for this lesson, we first need to generate some new files using the Angular CLI."_ 2. Present all necessary `ng generate` commands, each in its **own separate, copy-paste-ready code block**. 3. Instruct the user: _"Please run the command(s) above now. Let me know when you're ready to continue."_ 4. **You must wait for the user to confirm they are done** before proceeding to the next step. + _ **If no scaffolding is needed**: Skip this step and proceed directly to step 3. 3. **Present Code and Request Permission**: + _ Announce the next action: _"Great. Now I will show you the setup code needed to begin our lesson. Here is the final content for each file that will be created or updated."\* + _ For each file required for the setup, you **must** provide a clear heading with the full path (e.g., `📄 File: src/app/models.ts`) followed by a complete, copy-paste-ready markdown code block. + _ After presenting all the code, ask for permission to proceed: _"Would you like me to apply this setup code to your files for you, or would you prefer to do it yourself?"_ **You must wait for the user's response.** 4. **Apply Updates**: + _ **If the user wants you to update the files**: 1. Announce the action: _"Okay, I will set up the files for you now."_ 2. (Internally, you will update each file with the exact contents presented in step 3). 3. Proceed to Step 5. + _ **If the user wants to update the files themselves**: 1. Instruct the user: _"Sounds good. Please take your time to update the files with the content I provided above. Let me know when you're ready to begin the lesson."_ 2. **You must wait for the user to confirm they are done** before proceeding to Step 5. 5. **Verify Outcome and Begin Lesson**: + _ Once the files are updated, prompt for verification: _"Excellent. To make sure we're starting from the right place, could you please check the web preview? You should see **[Describe Expected Outcome of the prerequisite state for the target module]**. You may need to do a hard restart of the web preview to see the changes. Please let me know if that's what you see."\* + _ **Handle Confirmation**: + _ If the user confirms they see the correct outcome, begin the lesson for the target module: _"Perfect! Now let's talk about **[Module Title]**."_ + _ If the user reports an issue, provide encouragement and support: _"That happens sometimes, and that's okay. Debugging is a crucial part of development and can be just as valuable as writing the code from scratch. This is a great learning experience! I'm here to help you figure out what's going on."\* (Then begin the debugging process). + +### 13. Aesthetic and Architectural Integrity + +A core part of this tutorial is building an application that is not only functional but also visually professional, aesthetically pleasing, and built on a sound structural foundation. You must proactively guide the user to implement modern design principles. + +- **Foundational Layout First**: Before adding colors or fonts, guide the user to establish a strong layout. Teach the modern CSS paradigms for their intended purposes: \* **CSS Flexbox (for Micro-Layouts)**: Instruct the user to use Flexbox for component-level layouts, such as aligning items within a header, a card, or a form. +- **Deliberate Visual Hierarchy**: Instruct the user to create a clear visual hierarchy to guide the user's eye. This should be achieved by teaching them to manipulate fundamental properties with clear intent: + _ **Size & Weight**: Guide them to use larger font sizes and heavier font weights (`font-weight`) for more important elements (like titles) and smaller, lighter weights for less important text. + _ **Color & Contrast**: When introducing color, emphasize using high-contrast colors for primary actions (like buttons) to make them stand out. +- **Purposeful Whitespace**: Teach the user that whitespace (or negative space) is an active and powerful design element. + _ **Macro Whitespace**: Encourage the use of `padding` on main layout containers to give the entire page "breathing room." + _ **Micro Whitespace**: Instruct on using `padding` within components (like cards) and adjusting `line-height` on text to improve readability. + +### 14. Accessibility First (A11y) + +An application cannot be considered well-designed if it is not accessible. You must treat accessibility as a core requirement, not an afterthought, and ensure all generated code and project exercises adhere to **WCAG 2.2 Level AA** standards. + +- **Mandate Semantic HTML**: Instruct the user to always use semantic HTML elements for their intended purpose (`
+ + +
+
ng generate component xyz
+
ng add @angular/material
+
ng add @angular/pwa
+
ng add _____
+
ng test
+
ng build
+
+ + + + + + + + + Gray Clouds Background + + +
+ + + + + + + + + + diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.component.spec.ts b/tests/e2e/assets/ssr-project-webpack/src/app/app.component.spec.ts similarity index 79% rename from tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.component.spec.ts rename to tests/e2e/assets/ssr-project-webpack/src/app/app.component.spec.ts index 7dfb0b7df47c..c3fc75313bcc 100644 --- a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.component.spec.ts +++ b/tests/e2e/assets/ssr-project-webpack/src/app/app.component.spec.ts @@ -3,10 +3,12 @@ import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; describe('AppComponent', () => { - beforeEach(() => TestBed.configureTestingModule({ - imports: [RouterModule.forRoot([])], - declarations: [AppComponent] - })); + beforeEach(() => + TestBed.configureTestingModule({ + imports: [RouterModule.forRoot([])], + declarations: [AppComponent], + }), + ); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); @@ -24,6 +26,8 @@ describe('AppComponent', () => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.nativeElement as HTMLElement; - expect(compiled.querySelector('.content span')?.textContent).toContain('20-ssr-project-webpack app is running!'); + expect(compiled.querySelector('.content span')?.textContent).toContain( + '20-ssr-project-webpack app is running!', + ); }); }); diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.component.ts b/tests/e2e/assets/ssr-project-webpack/src/app/app.component.ts similarity index 84% rename from tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.component.ts rename to tests/e2e/assets/ssr-project-webpack/src/app/app.component.ts index f643fddc3586..20b0fef78f45 100644 --- a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.component.ts +++ b/tests/e2e/assets/ssr-project-webpack/src/app/app.component.ts @@ -4,7 +4,7 @@ import { Component } from '@angular/core'; selector: 'app-root', standalone: false, templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] + styleUrls: ['./app.component.css'], }) export class AppComponent { title = '20-ssr-project-webpack'; diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.module.server.ts b/tests/e2e/assets/ssr-project-webpack/src/app/app.module.server.ts similarity index 83% rename from tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.module.server.ts rename to tests/e2e/assets/ssr-project-webpack/src/app/app.module.server.ts index 795380cd2294..d182a9f3e994 100644 --- a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.module.server.ts +++ b/tests/e2e/assets/ssr-project-webpack/src/app/app.module.server.ts @@ -5,10 +5,7 @@ import { AppModule } from './app.module'; import { AppComponent } from './app.component'; @NgModule({ - imports: [ - AppModule, - ServerModule, - ], + imports: [AppModule, ServerModule], bootstrap: [AppComponent], }) export class AppServerModule {} diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.module.ts b/tests/e2e/assets/ssr-project-webpack/src/app/app.module.ts similarity index 55% rename from tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.module.ts rename to tests/e2e/assets/ssr-project-webpack/src/app/app.module.ts index a06d9e8b06b4..700cb243fffa 100644 --- a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.module.ts +++ b/tests/e2e/assets/ssr-project-webpack/src/app/app.module.ts @@ -5,16 +5,9 @@ import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ - declarations: [ - AppComponent - ], - imports: [ - BrowserModule, - AppRoutingModule - ], - providers: [ - provideClientHydration() - ], - bootstrap: [AppComponent] + declarations: [AppComponent], + imports: [BrowserModule, AppRoutingModule], + providers: [provideClientHydration()], + bootstrap: [AppComponent], }) -export class AppModule { } +export class AppModule {} diff --git a/tests/legacy-cli/e2e/assets/17.0-project/src/assets/.gitkeep b/tests/e2e/assets/ssr-project-webpack/src/assets/.gitkeep similarity index 100% rename from tests/legacy-cli/e2e/assets/17.0-project/src/assets/.gitkeep rename to tests/e2e/assets/ssr-project-webpack/src/assets/.gitkeep diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/favicon.ico b/tests/e2e/assets/ssr-project-webpack/src/favicon.ico similarity index 100% rename from tests/legacy-cli/e2e/assets/ssr-project-webpack/src/favicon.ico rename to tests/e2e/assets/ssr-project-webpack/src/favicon.ico diff --git a/tests/e2e/assets/ssr-project-webpack/src/index.html b/tests/e2e/assets/ssr-project-webpack/src/index.html new file mode 100644 index 000000000000..28adeacc85ed --- /dev/null +++ b/tests/e2e/assets/ssr-project-webpack/src/index.html @@ -0,0 +1,13 @@ + + + + + 17SsrProjectWebpack + + + + + + + + diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/main.server.ts b/tests/e2e/assets/ssr-project-webpack/src/main.server.ts similarity index 100% rename from tests/legacy-cli/e2e/assets/ssr-project-webpack/src/main.server.ts rename to tests/e2e/assets/ssr-project-webpack/src/main.server.ts diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/main.ts b/tests/e2e/assets/ssr-project-webpack/src/main.ts similarity index 55% rename from tests/legacy-cli/e2e/assets/ssr-project-webpack/src/main.ts rename to tests/e2e/assets/ssr-project-webpack/src/main.ts index f3a8a045a0a7..55b91297823b 100644 --- a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/main.ts +++ b/tests/e2e/assets/ssr-project-webpack/src/main.ts @@ -1,5 +1,6 @@ import { platformBrowser } from '@angular/platform-browser'; import { AppModule } from './app/app.module'; -platformBrowser().bootstrapModule(AppModule) - .catch(err => console.error(err)); +platformBrowser() + .bootstrapModule(AppModule) + .catch((err) => console.error(err)); diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/styles.css b/tests/e2e/assets/ssr-project-webpack/src/styles.css similarity index 100% rename from tests/legacy-cli/e2e/assets/ssr-project-webpack/src/styles.css rename to tests/e2e/assets/ssr-project-webpack/src/styles.css diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/tsconfig.app.json b/tests/e2e/assets/ssr-project-webpack/tsconfig.app.json similarity index 71% rename from tests/legacy-cli/e2e/assets/ssr-project-webpack/tsconfig.app.json rename to tests/e2e/assets/ssr-project-webpack/tsconfig.app.json index 374cc9d294aa..84f1f992d275 100644 --- a/tests/legacy-cli/e2e/assets/ssr-project-webpack/tsconfig.app.json +++ b/tests/e2e/assets/ssr-project-webpack/tsconfig.app.json @@ -5,10 +5,6 @@ "outDir": "./out-tsc/app", "types": [] }, - "files": [ - "src/main.ts" - ], - "include": [ - "src/**/*.d.ts" - ] + "files": ["src/main.ts"], + "include": ["src/**/*.d.ts"] } diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/tsconfig.json b/tests/e2e/assets/ssr-project-webpack/tsconfig.json similarity index 94% rename from tests/legacy-cli/e2e/assets/ssr-project-webpack/tsconfig.json rename to tests/e2e/assets/ssr-project-webpack/tsconfig.json index 532ea4d30a62..bbc051d01524 100644 --- a/tests/legacy-cli/e2e/assets/ssr-project-webpack/tsconfig.json +++ b/tests/e2e/assets/ssr-project-webpack/tsconfig.json @@ -17,10 +17,7 @@ "importHelpers": true, "target": "ES2022", "module": "ES2022", - "lib": [ - "ES2022", - "dom" - ] + "lib": ["ES2022", "dom"] }, "angularCompilerOptions": { "enableI18nLegacyMessageIdFormat": false, diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/tsconfig.server.json b/tests/e2e/assets/ssr-project-webpack/tsconfig.server.json similarity index 65% rename from tests/legacy-cli/e2e/assets/ssr-project-webpack/tsconfig.server.json rename to tests/e2e/assets/ssr-project-webpack/tsconfig.server.json index e2ebe5a729be..3b9de71a23f6 100644 --- a/tests/legacy-cli/e2e/assets/ssr-project-webpack/tsconfig.server.json +++ b/tests/e2e/assets/ssr-project-webpack/tsconfig.server.json @@ -3,12 +3,7 @@ "extends": "./tsconfig.app.json", "compilerOptions": { "outDir": "./out-tsc/server", - "types": [ - "node" - ] + "types": ["node"] }, - "files": [ - "src/main.server.ts", - "server.ts" - ] + "files": ["src/main.server.ts", "server.ts"] } diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/tsconfig.spec.json b/tests/e2e/assets/ssr-project-webpack/tsconfig.spec.json similarity index 63% rename from tests/legacy-cli/e2e/assets/ssr-project-webpack/tsconfig.spec.json rename to tests/e2e/assets/ssr-project-webpack/tsconfig.spec.json index be7e9da76f7b..47e3dd755170 100644 --- a/tests/legacy-cli/e2e/assets/ssr-project-webpack/tsconfig.spec.json +++ b/tests/e2e/assets/ssr-project-webpack/tsconfig.spec.json @@ -3,12 +3,7 @@ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", - "types": [ - "jasmine" - ] + "types": ["jasmine"] }, - "include": [ - "src/**/*.spec.ts", - "src/**/*.d.ts" - ] + "include": ["src/**/*.spec.ts", "src/**/*.d.ts"] } diff --git a/tests/legacy-cli/e2e/initialize/300-log-environment.ts b/tests/e2e/initialize/300-log-environment.ts similarity index 100% rename from tests/legacy-cli/e2e/initialize/300-log-environment.ts rename to tests/e2e/initialize/300-log-environment.ts diff --git a/tests/legacy-cli/e2e/initialize/500-create-project.ts b/tests/e2e/initialize/500-create-project.ts similarity index 86% rename from tests/legacy-cli/e2e/initialize/500-create-project.ts rename to tests/e2e/initialize/500-create-project.ts index 837f54efbcde..b48c8733a9a5 100644 --- a/tests/legacy-cli/e2e/initialize/500-create-project.ts +++ b/tests/e2e/initialize/500-create-project.ts @@ -2,7 +2,7 @@ import { join } from 'node:path'; import { getGlobalVariable } from '../utils/env'; import { expectFileToExist } from '../utils/fs'; import { gitClean } from '../utils/git'; -import { setRegistry as setNPMConfigRegistry } from '../utils/packages'; +import { getActivePackageManager, setRegistry as setNPMConfigRegistry } from '../utils/packages'; import { ng } from '../utils/process'; import { prepareProjectForE2e, updateJsonFile } from '../utils/project'; @@ -20,7 +20,16 @@ export default async function () { // Ensure local test registry is used when outside a project await setNPMConfigRegistry(true); - await ng('new', 'test-project', '--skip-install'); + await ng( + 'new', + 'test-project', + '--skip-install', + '--test-runner', + 'karma', + '--package-manager', + getActivePackageManager(), + ); + await expectFileToExist(join(process.cwd(), 'test-project')); process.chdir('./test-project'); @@ -55,6 +64,9 @@ export default async function () { const test = json['projects']['test-project']['architect']['test']; test.builder = '@angular-devkit/build-angular:karma'; + test.options ??= {}; + test.options.tsConfig = 'tsconfig.spec.json'; + delete test.options.runner; }); await updateJsonFile('tsconfig.json', (tsconfig) => { delete tsconfig.compilerOptions.esModuleInterop; diff --git a/tests/legacy-cli/e2e/initialize/BUILD.bazel b/tests/e2e/initialize/BUILD.bazel similarity index 88% rename from tests/legacy-cli/e2e/initialize/BUILD.bazel rename to tests/e2e/initialize/BUILD.bazel index da2466d90621..2ab5b570925f 100644 --- a/tests/legacy-cli/e2e/initialize/BUILD.bazel +++ b/tests/e2e/initialize/BUILD.bazel @@ -11,6 +11,6 @@ ts_project( ], deps = [ "//:node_modules/@types/node", - "//tests/legacy-cli/e2e/utils", + "//tests/e2e/utils", ], ) diff --git a/tests/legacy-cli/e2e/ng-snapshot/BUILD.bazel b/tests/e2e/ng-snapshot/BUILD.bazel similarity index 100% rename from tests/legacy-cli/e2e/ng-snapshot/BUILD.bazel rename to tests/e2e/ng-snapshot/BUILD.bazel diff --git a/tests/e2e/ng-snapshot/package.json b/tests/e2e/ng-snapshot/package.json new file mode 100644 index 000000000000..8596480909b7 --- /dev/null +++ b/tests/e2e/ng-snapshot/package.json @@ -0,0 +1,22 @@ +{ + "description": "snapshot versions of Angular for e2e testing", + "private": true, + "dependencies": { + "@angular/animations": "github:angular/animations-builds#7d1d574e722bddf23658ba2aecbe90f7a20d3dcb", + "@angular/cdk": "github:angular/cdk-builds#5e4b9d2f2cd548245d09f554364610762a5a2c47", + "@angular/common": "github:angular/common-builds#f3deca7ff0a46c2993c08e875b5881257c8f757a", + "@angular/compiler": "github:angular/compiler-builds#31af18615c849a3ce319a281b00333ba2cf8d641", + "@angular/compiler-cli": "github:angular/compiler-cli-builds#9e3870e2c1eee645d15c561c09fceb18df897ab6", + "@angular/core": "github:angular/core-builds#2838839f900584dd9d556455afbd518bc585a4b2", + "@angular/forms": "github:angular/forms-builds#0b9bdccb4aea204c00a1da591775d1650a5cce1e", + "@angular/language-service": "github:angular/language-service-builds#8dc7bc4d774289732fb4c887a8fbacb234eb2725", + "@angular/localize": "github:angular/localize-builds#2aaeba1a3f84c3593cf8971d8f23ce6275460bb4", + "@angular/material": "github:angular/material-builds#3f6bda06d3e7fcac8a993810b87f79a0b2b83ce3", + "@angular/material-moment-adapter": "github:angular/material-moment-adapter-builds#e9656894438ed6fac288b62fc822d2a70a0a4a17", + "@angular/platform-browser": "github:angular/platform-browser-builds#81df68a32060014f1c5e1ab20fddc481e6c293fb", + "@angular/platform-browser-dynamic": "github:angular/platform-browser-dynamic-builds#09ba5aa26d445ec7f07ef8b21d9fc6a76b15742b", + "@angular/platform-server": "github:angular/platform-server-builds#88c1f8a56e9e78d93b92daa7245958fab732a9d9", + "@angular/router": "github:angular/router-builds#3162b28b4e94c04f52b263291b9b54074b93fc94", + "@angular/service-worker": "github:angular/service-worker-builds#80a6ec33d78fce9ceb1e289f2fe1e35231b441fa" + } +} diff --git a/tests/legacy-cli/e2e/setup/002-npm-sandbox.ts b/tests/e2e/setup/001-npm-sandbox.ts similarity index 100% rename from tests/legacy-cli/e2e/setup/002-npm-sandbox.ts rename to tests/e2e/setup/001-npm-sandbox.ts diff --git a/tests/legacy-cli/e2e/setup/010-local-publish.ts b/tests/e2e/setup/010-local-publish.ts similarity index 100% rename from tests/legacy-cli/e2e/setup/010-local-publish.ts rename to tests/e2e/setup/010-local-publish.ts diff --git a/tests/legacy-cli/e2e/setup/100-global-cli.ts b/tests/e2e/setup/100-global-cli.ts similarity index 94% rename from tests/legacy-cli/e2e/setup/100-global-cli.ts rename to tests/e2e/setup/100-global-cli.ts index 63db2d365a4a..9f587fa5c38d 100644 --- a/tests/legacy-cli/e2e/setup/100-global-cli.ts +++ b/tests/e2e/setup/100-global-cli.ts @@ -5,8 +5,8 @@ import { globalNpm } from '../utils/process'; const PACKAGE_MANAGER_VERSION = { 'npm': '10.8.1', 'yarn': '1.22.22', - 'pnpm': '9.3.0', - 'bun': '1.1.13', + 'pnpm': '10.17.1', + 'bun': '1.3.2', }; export default async function () { diff --git a/tests/legacy-cli/e2e/setup/200-create-project-dir.ts b/tests/e2e/setup/200-create-project-dir.ts similarity index 100% rename from tests/legacy-cli/e2e/setup/200-create-project-dir.ts rename to tests/e2e/setup/200-create-project-dir.ts diff --git a/tests/legacy-cli/e2e/setup/BUILD.bazel b/tests/e2e/setup/BUILD.bazel similarity index 85% rename from tests/legacy-cli/e2e/setup/BUILD.bazel rename to tests/e2e/setup/BUILD.bazel index 0b83d8f92d7f..36fe39fa3409 100644 --- a/tests/legacy-cli/e2e/setup/BUILD.bazel +++ b/tests/e2e/setup/BUILD.bazel @@ -8,6 +8,6 @@ ts_project( srcs = glob(["**/*.ts"]), deps = [ "//:node_modules/@types/node", - "//tests/legacy-cli/e2e/utils", + "//tests/e2e/utils", ], ) diff --git a/tests/legacy-cli/e2e/tests/BUILD.bazel b/tests/e2e/tests/BUILD.bazel similarity index 81% rename from tests/legacy-cli/e2e/tests/BUILD.bazel rename to tests/e2e/tests/BUILD.bazel index 55f5019b568f..891814cb24eb 100644 --- a/tests/legacy-cli/e2e/tests/BUILD.bazel +++ b/tests/e2e/tests/BUILD.bazel @@ -12,7 +12,9 @@ ts_project( "//:node_modules/@types/semver", "//:node_modules/express", "//:node_modules/fast-glob", + "//:node_modules/puppeteer", "//:node_modules/semver", - "//tests/legacy-cli/e2e/utils", + "//:node_modules/undici", + "//tests/e2e/utils", ], ) diff --git a/tests/e2e/tests/architect_cli/direct_execution.ts b/tests/e2e/tests/architect_cli/direct_execution.ts new file mode 100644 index 000000000000..b91010d46283 --- /dev/null +++ b/tests/e2e/tests/architect_cli/direct_execution.ts @@ -0,0 +1,14 @@ +import * as assert from 'node:assert/strict'; +import { exec } from '../../utils/process'; +import { join } from 'node:path'; + +export default async function () { + // Run help command + const binPath = join('node_modules', '.bin', 'architect'); + const { stdout } = await exec(binPath, '--help'); + + assert.ok( + stdout.includes('architect [project][:target][:configuration] [options, ...]'), + 'Expected stdout to contain usage information.', + ); +} diff --git a/tests/e2e/tests/architect_cli/package_execution.ts b/tests/e2e/tests/architect_cli/package_execution.ts new file mode 100644 index 000000000000..60b3964b7521 --- /dev/null +++ b/tests/e2e/tests/architect_cli/package_execution.ts @@ -0,0 +1,22 @@ +import * as assert from 'node:assert/strict'; +import { exec } from '../../utils/process'; +import { installPackage, uninstallPackage } from '../../utils/packages'; +import { join } from 'node:path'; + +export default async function () { + // Install CLI package + await installPackage('@angular-devkit/architect-cli'); + + try { + // Run help command + const binPath = join('node_modules', '.bin', 'architect'); + const { stdout } = await exec(binPath, '--help'); + + assert.ok( + stdout.includes('architect [project][:target][:configuration] [options, ...]'), + 'Expected stdout to contain usage information.', + ); + } finally { + await uninstallPackage('@angular-devkit/architect-cli'); + } +} diff --git a/tests/legacy-cli/e2e/tests/basic/aot.ts b/tests/e2e/tests/basic/aot.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/basic/aot.ts rename to tests/e2e/tests/basic/aot.ts diff --git a/tests/legacy-cli/e2e/tests/basic/build.ts b/tests/e2e/tests/basic/build.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/basic/build.ts rename to tests/e2e/tests/basic/build.ts diff --git a/tests/legacy-cli/e2e/tests/basic/command-scope.ts b/tests/e2e/tests/basic/command-scope.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/basic/command-scope.ts rename to tests/e2e/tests/basic/command-scope.ts diff --git a/tests/legacy-cli/e2e/tests/basic/rebuild.ts b/tests/e2e/tests/basic/rebuild.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/basic/rebuild.ts rename to tests/e2e/tests/basic/rebuild.ts diff --git a/tests/legacy-cli/e2e/tests/basic/run.ts b/tests/e2e/tests/basic/run.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/basic/run.ts rename to tests/e2e/tests/basic/run.ts diff --git a/tests/legacy-cli/e2e/tests/basic/scripts-array.ts b/tests/e2e/tests/basic/scripts-array.ts similarity index 96% rename from tests/legacy-cli/e2e/tests/basic/scripts-array.ts rename to tests/e2e/tests/basic/scripts-array.ts index 09bca1c04fb9..0721b120da2b 100644 --- a/tests/legacy-cli/e2e/tests/basic/scripts-array.ts +++ b/tests/e2e/tests/basic/scripts-array.ts @@ -58,7 +58,6 @@ export default async function () { await expectFileToMatch( 'dist/test-project/browser/index.html', [ - '', '', '', '', @@ -69,7 +68,6 @@ export default async function () { 'dist/test-project/browser/index.html', [ '', - '', '', '', '', diff --git a/tests/legacy-cli/e2e/tests/basic/serve.ts b/tests/e2e/tests/basic/serve.ts similarity index 85% rename from tests/legacy-cli/e2e/tests/basic/serve.ts rename to tests/e2e/tests/basic/serve.ts index 7623cc3a6afc..eac4823a3126 100644 --- a/tests/legacy-cli/e2e/tests/basic/serve.ts +++ b/tests/e2e/tests/basic/serve.ts @@ -1,6 +1,7 @@ import assert from 'node:assert/strict'; import { killAllProcesses } from '../../utils/process'; import { ngServe } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; export default async function () { // Serve works without HMR @@ -11,6 +12,8 @@ export default async function () { // Serve works with HMR const hmrPort = await ngServe('--hmr'); await verifyResponse(hmrPort); + + await executeBrowserTest({ baseUrl: `http://localhost:${hmrPort}/` }); } async function verifyResponse(port: number): Promise { diff --git a/tests/legacy-cli/e2e/tests/basic/styles-array.ts b/tests/e2e/tests/basic/styles-array.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/basic/styles-array.ts rename to tests/e2e/tests/basic/styles-array.ts diff --git a/tests/legacy-cli/e2e/tests/basic/test.ts b/tests/e2e/tests/basic/test.ts similarity index 84% rename from tests/legacy-cli/e2e/tests/basic/test.ts rename to tests/e2e/tests/basic/test.ts index d9066946ae8e..50580581d442 100644 --- a/tests/legacy-cli/e2e/tests/basic/test.ts +++ b/tests/e2e/tests/basic/test.ts @@ -1,5 +1,6 @@ import { ng } from '../../utils/process'; import { writeMultipleFiles } from '../../utils/fs'; +import { getGlobalVariable } from '../../utils/env'; export default async function () { // make sure both --watch=false work @@ -48,5 +49,11 @@ export default async function () { `, }); - await ng('test', '--watch=false', '--karma-config=karma.conf.bis.js'); + const isWebpack = !getGlobalVariable('argv')['esbuild']; + + if (isWebpack) { + await ng('test', '--watch=false', '--karma-config=karma.conf.bis.js'); + } else { + await ng('test', '--watch=false', '--runner-config=karma.conf.bis.js'); + } } diff --git a/tests/legacy-cli/e2e/tests/build/app-shell/app-shell-ngmodule.ts b/tests/e2e/tests/build/app-shell/app-shell-ngmodule.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/app-shell/app-shell-ngmodule.ts rename to tests/e2e/tests/build/app-shell/app-shell-ngmodule.ts diff --git a/tests/legacy-cli/e2e/tests/build/app-shell/app-shell-with-schematic.ts b/tests/e2e/tests/build/app-shell/app-shell-with-schematic.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/app-shell/app-shell-with-schematic.ts rename to tests/e2e/tests/build/app-shell/app-shell-with-schematic.ts diff --git a/tests/legacy-cli/e2e/tests/build/app-shell/app-shell-with-service-worker.ts b/tests/e2e/tests/build/app-shell/app-shell-with-service-worker.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/app-shell/app-shell-with-service-worker.ts rename to tests/e2e/tests/build/app-shell/app-shell-with-service-worker.ts diff --git a/tests/legacy-cli/e2e/tests/build/assets.ts b/tests/e2e/tests/build/assets.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/assets.ts rename to tests/e2e/tests/build/assets.ts diff --git a/tests/legacy-cli/e2e/tests/build/auto-csp.ts b/tests/e2e/tests/build/auto-csp.ts similarity index 56% rename from tests/legacy-cli/e2e/tests/build/auto-csp.ts rename to tests/e2e/tests/build/auto-csp.ts index 1839b160d549..f9e30efe2de9 100644 --- a/tests/legacy-cli/e2e/tests/build/auto-csp.ts +++ b/tests/e2e/tests/build/auto-csp.ts @@ -1,9 +1,11 @@ -import assert from 'node:assert'; +import assert from 'node:assert/strict'; +import { setTimeout } from 'node:timers/promises'; import { getGlobalVariable } from '../../utils/env'; import { expectFileToMatch, writeFile, writeMultipleFiles } from '../../utils/fs'; import { findFreePort } from '../../utils/network'; import { execAndWaitForOutputToMatch, ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; const CSP_META_TAG = / `, - 'e2e/src/app.e2e-spec.ts': ` - import { browser, by, element } from 'protractor'; - import * as webdriver from 'selenium-webdriver'; - - function allConsoleWarnMessagesAndErrors() { - return browser - .manage() - .logs() - .get('browser') - .then(function (browserLog: any[]) { - const warnMessages: any[] = []; - browserLog.filter((logEntry) => { - const msg = logEntry.message; - console.log('>> ' + msg); - if (logEntry.level.value >= webdriver.logging.Level.INFO.value) { - warnMessages.push(msg); - } - }); - return warnMessages; - }); - } - - describe('Hello world E2E Tests', () => { - beforeAll(async () => { - await browser.waitForAngularEnabled(true); - }); - - it('should display: Welcome and run all scripts in order', async () => { - // Load the page without waiting for Angular since it is not bootstrapped automatically. - await browser.driver.get(browser.baseUrl); - - // Test the contents. - expect(await element(by.css('h1')).getText()).toMatch('Hello'); - - // Make sure all scripts ran and there were no client side errors. - const consoleMessages = await allConsoleWarnMessagesAndErrors(); - expect(consoleMessages.length).toEqual(4); // No additional errors - // Extract just the printed messages from the console data. - const printedMessages = consoleMessages.map(m => m.match(/"(.*?)"/)[1]); - expect(printedMessages).toEqual([ - // All messages printed in order because execution order is preserved. - "Inline Script Head", - "Inline Script Body: 1339", - "First External Script: 1338", - "Second External Script: 1337", - ]); - }); - }); - `, }); async function spawnServer(): Promise { @@ -137,7 +90,49 @@ export default async function () { // Make sure if contains the critical CSS inlining CSP code. await expectFileToMatch('dist/test-project/browser/index.html', 'ngCspMedia'); - // Make sure that our e2e protractor tests run to confirm that our angular project runs. + // Make sure that our e2e tests run to confirm that our angular project runs. const port = await spawnServer(); - await ng('e2e', `--base-url=http://localhost:${port}`, '--dev-server-target='); + await executeBrowserTest({ + baseUrl: `http://localhost:${port}/`, + checkFn: async (page) => { + const warnMessages: string[] = []; + page.on('console', (msg) => { + if (msg.type() === 'warning') { + warnMessages.push(msg.text()); + } + }); + + // Reload to ensure we capture messages from the start if needed, + // although executeBrowserTest already navigated. + await page.reload(); + + // Wait for the expected number of warnings + let retries = 50; + while (warnMessages.length < 4 && retries > 0) { + await setTimeout(100); + retries--; + } + + assert.strictEqual( + warnMessages.length, + 4, + `Expected 4 console warnings, but got ${warnMessages.length}:\n${warnMessages.join('\n')}`, + ); + + const expectedMessages = [ + 'Inline Script Head', + 'Inline Script Body: 1339', + 'First External Script: 1338', + 'Second External Script: 1337', + ]; + + for (let i = 0; i < expectedMessages.length; i++) { + if (!warnMessages[i].includes(expectedMessages[i])) { + assert.fail( + `Expected warning ${i} to include '${expectedMessages[i]}', but got '${warnMessages[i]}'`, + ); + } + } + }, + }); } diff --git a/tests/legacy-cli/e2e/tests/build/bundle-budgets.ts b/tests/e2e/tests/build/bundle-budgets.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/bundle-budgets.ts rename to tests/e2e/tests/build/bundle-budgets.ts diff --git a/tests/e2e/tests/build/chunk-optimizer-lazy.ts b/tests/e2e/tests/build/chunk-optimizer-lazy.ts new file mode 100644 index 000000000000..7f57e6d88e68 --- /dev/null +++ b/tests/e2e/tests/build/chunk-optimizer-lazy.ts @@ -0,0 +1,52 @@ +import assert from 'node:assert/strict'; +import { readdir } from 'node:fs/promises'; +import { replaceInFile } from '../../utils/fs'; +import { execWithEnv, ng } from '../../utils/process'; + +export default async function () { + // Add lazy routes. + await ng('generate', 'component', 'lazy-a'); + await ng('generate', 'component', 'lazy-b'); + await ng('generate', 'component', 'lazy-c'); + await replaceInFile( + 'src/app/app.routes.ts', + 'routes: Routes = [];', + `routes: Routes = [ + { + path: 'lazy-a', + loadComponent: () => import('./lazy-a/lazy-a').then(m => m.LazyA), + }, + { + path: 'lazy-b', + loadComponent: () => import('./lazy-b/lazy-b').then(m => m.LazyB), + }, + { + path: 'lazy-c', + loadComponent: () => import('./lazy-c/lazy-c').then(m => m.LazyC), + }, + ];`, + ); + + // Build without chunk optimization + await ng('build', '--output-hashing=none'); + const unoptimizedFiles = await readdir('dist/test-project/browser'); + const unoptimizedJsFiles = unoptimizedFiles.filter((f) => f.endsWith('.js')); + + // Build with chunk optimization + await execWithEnv('ng', ['build', '--output-hashing=none'], { + ...process.env, + NG_BUILD_OPTIMIZE_CHUNKS: '1', + }); + const optimizedFiles = await readdir('dist/test-project/browser'); + const optimizedJsFiles = optimizedFiles.filter((f) => f.endsWith('.js')); + + // Check that the number of chunks is reduced but not all combined + assert.ok( + optimizedJsFiles.length < unoptimizedJsFiles.length, + `Expected chunk count to be less than ${unoptimizedJsFiles.length}, but was ${optimizedJsFiles.length}.`, + ); + assert.ok( + optimizedJsFiles.length > 1, + `Expected more than one chunk, but found ${optimizedJsFiles.length}.`, + ); +} diff --git a/tests/legacy-cli/e2e/tests/build/chunk-optimizer.ts b/tests/e2e/tests/build/chunk-optimizer.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/chunk-optimizer.ts rename to tests/e2e/tests/build/chunk-optimizer.ts diff --git a/tests/legacy-cli/e2e/tests/build/config-file-fallback.ts b/tests/e2e/tests/build/config-file-fallback.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/config-file-fallback.ts rename to tests/e2e/tests/build/config-file-fallback.ts diff --git a/tests/legacy-cli/e2e/tests/build/css-urls.ts b/tests/e2e/tests/build/css-urls.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/css-urls.ts rename to tests/e2e/tests/build/css-urls.ts diff --git a/tests/legacy-cli/e2e/tests/build/disk-cache-purge.ts b/tests/e2e/tests/build/disk-cache-purge.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/disk-cache-purge.ts rename to tests/e2e/tests/build/disk-cache-purge.ts diff --git a/tests/legacy-cli/e2e/tests/build/disk-cache.ts b/tests/e2e/tests/build/disk-cache.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/disk-cache.ts rename to tests/e2e/tests/build/disk-cache.ts diff --git a/tests/legacy-cli/e2e/tests/build/esbuild-unsupported.ts b/tests/e2e/tests/build/esbuild-unsupported.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/esbuild-unsupported.ts rename to tests/e2e/tests/build/esbuild-unsupported.ts diff --git a/tests/legacy-cli/e2e/tests/build/extract-licenses.ts b/tests/e2e/tests/build/extract-licenses.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/extract-licenses.ts rename to tests/e2e/tests/build/extract-licenses.ts diff --git a/tests/legacy-cli/e2e/tests/build/incremental-watch.ts b/tests/e2e/tests/build/incremental-watch.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/incremental-watch.ts rename to tests/e2e/tests/build/incremental-watch.ts diff --git a/tests/legacy-cli/e2e/tests/build/jit-ngmodule.ts b/tests/e2e/tests/build/jit-ngmodule.ts similarity index 77% rename from tests/legacy-cli/e2e/tests/build/jit-ngmodule.ts rename to tests/e2e/tests/build/jit-ngmodule.ts index 910f8993a16d..aa6b3fda86bb 100644 --- a/tests/legacy-cli/e2e/tests/build/jit-ngmodule.ts +++ b/tests/e2e/tests/build/jit-ngmodule.ts @@ -1,13 +1,10 @@ import { getGlobalVariable } from '../../utils/env'; import { ng } from '../../utils/process'; -import { updateJsonFile, useCIChrome, useCIDefaults } from '../../utils/project'; +import { updateJsonFile, useCIDefaults } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; export default async function () { await ng('generate', 'app', 'test-project-two', '--no-standalone', '--skip-install'); - await ng('generate', 'private-e2e', '--related-app-name=test-project-two'); - - // Setup testing to use CI Chrome. - await useCIChrome('test-project-two', './projects/test-project-two/e2e'); await useCIDefaults('test-project-two'); // Make prod use JIT. @@ -46,6 +43,6 @@ export default async function () { serve.builder = '@angular-devkit/build-angular:dev-server'; }); // Test it works - await ng('e2e', 'test-project-two', '--configuration=production'); - await ng('e2e', 'test-project-two', '--configuration=development'); + await executeBrowserTest({ project: 'test-project-two', configuration: 'production' }); + await executeBrowserTest({ project: 'test-project-two', configuration: 'development' }); } diff --git a/tests/legacy-cli/e2e/tests/build/jit-prod.ts b/tests/e2e/tests/build/jit-prod.ts similarity index 85% rename from tests/legacy-cli/e2e/tests/build/jit-prod.ts rename to tests/e2e/tests/build/jit-prod.ts index 2042b0a8c93d..b2dc9d0bdddc 100644 --- a/tests/legacy-cli/e2e/tests/build/jit-prod.ts +++ b/tests/e2e/tests/build/jit-prod.ts @@ -1,6 +1,6 @@ import { getGlobalVariable } from '../../utils/env'; -import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; export default async function () { // Make prod use JIT. @@ -18,5 +18,5 @@ export default async function () { }); // Test it works - await ng('e2e', '--configuration=production'); + await executeBrowserTest({ configuration: 'production' }); } diff --git a/tests/legacy-cli/e2e/tests/build/lazy-load-syntax.ts b/tests/e2e/tests/build/lazy-load-syntax.ts similarity index 52% rename from tests/legacy-cli/e2e/tests/build/lazy-load-syntax.ts rename to tests/e2e/tests/build/lazy-load-syntax.ts index 2b91b3f63b45..bc0a375673dc 100644 --- a/tests/legacy-cli/e2e/tests/build/lazy-load-syntax.ts +++ b/tests/e2e/tests/build/lazy-load-syntax.ts @@ -5,10 +5,11 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ -import { setTimeout } from 'node:timers/promises'; -import { replaceInFile, writeFile } from '../../utils/fs'; + +import { replaceInFile } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; export default async function () { // Add lazy route. @@ -22,29 +23,6 @@ export default async function () { }];`, ); - // Add lazy route e2e - await writeFile( - 'e2e/src/app.e2e-spec.ts', - ` - import { browser, logging, element, by } from 'protractor'; - - describe('workspace-project App', () => { - it('should display lazy route', async () => { - await browser.get(browser.baseUrl + '/lazy'); - expect(await element(by.css('app-lazy-comp p')).getText()).toEqual('lazy-comp works!'); - }); - - afterEach(async () => { - // Assert that there are no errors emitted from the browser - const logs = await browser.manage().logs().get(logging.Type.BROWSER); - expect(logs).not.toContain(jasmine.objectContaining({ - level: logging.Level.SEVERE, - })); - }); - }); - `, - ); - // Convert the default config to use JIT and prod to just do AOT. // This way we can use `ng e2e` to test JIT and `ng e2e --configuration=production` to test AOT. await updateJsonFile('angular.json', (json) => { @@ -53,7 +31,17 @@ export default async function () { buildTarget['configurations']['development']['aot'] = false; }); - await ng('e2e'); - await setTimeout(500); - await ng('e2e', '--configuration=production'); + const checkFn = async (page: any) => { + await page.goto(page.url() + 'lazy'); + await page.waitForFunction( + () => + !!(globalThis as any).document + .querySelector('app-lazy-comp p') + ?.textContent?.includes('lazy-comp works!'), + { timeout: 10000 }, + ); + }; + + await executeBrowserTest({ checkFn }); + await executeBrowserTest({ configuration: 'production', checkFn }); } diff --git a/tests/legacy-cli/e2e/tests/build/library-with-demo-app.ts b/tests/e2e/tests/build/library-with-demo-app.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/library-with-demo-app.ts rename to tests/e2e/tests/build/library-with-demo-app.ts diff --git a/tests/e2e/tests/build/library/lib-consumption-full-aot.ts b/tests/e2e/tests/build/library/lib-consumption-full-aot.ts new file mode 100644 index 000000000000..08d114f1de4a --- /dev/null +++ b/tests/e2e/tests/build/library/lib-consumption-full-aot.ts @@ -0,0 +1,14 @@ +import { ng } from '../../../utils/process'; +import { executeBrowserTest } from '../../../utils/puppeteer'; +import { browserCheck, libraryConsumptionSetup } from './setup'; + +export default async function () { + await libraryConsumptionSetup(); + + // Build library in full mode (development) + await ng('build', 'my-lib', '--configuration=development'); + + // Check that the e2e succeeds prod and non prod mode + await executeBrowserTest({ configuration: 'production', checkFn: browserCheck }); + await executeBrowserTest({ configuration: 'development', checkFn: browserCheck }); +} diff --git a/tests/legacy-cli/e2e/tests/build/library/lib-consumption-full-jit.ts b/tests/e2e/tests/build/library/lib-consumption-full-jit.ts similarity index 73% rename from tests/legacy-cli/e2e/tests/build/library/lib-consumption-full-jit.ts rename to tests/e2e/tests/build/library/lib-consumption-full-jit.ts index e63130e77c86..906a920dba44 100644 --- a/tests/legacy-cli/e2e/tests/build/library/lib-consumption-full-jit.ts +++ b/tests/e2e/tests/build/library/lib-consumption-full-jit.ts @@ -1,8 +1,8 @@ -import { setTimeout } from 'node:timers/promises'; import { updateJsonFile } from '../../../utils/project'; import { expectFileToMatch } from '../../../utils/fs'; import { ng } from '../../../utils/process'; -import { libraryConsumptionSetup } from './setup'; +import { executeBrowserTest } from '../../../utils/puppeteer'; +import { browserCheck, libraryConsumptionSetup } from './setup'; import { getGlobalVariable } from '../../../utils/env'; export default async function () { @@ -21,10 +21,9 @@ export default async function () { } }); - // Check that the e2e succeeds prod and non prod mode - await ng('e2e', '--configuration=production'); - await setTimeout(500); - await ng('e2e', '--configuration=development'); + // Ensure app works in prod and non prod mode + await executeBrowserTest({ configuration: 'production', checkFn: browserCheck }); + await executeBrowserTest({ configuration: 'development', checkFn: browserCheck }); // Validate that sourcemaps for the library exists. await ng('build', '--configuration=development'); diff --git a/tests/e2e/tests/build/library/lib-consumption-partial-aot.ts b/tests/e2e/tests/build/library/lib-consumption-partial-aot.ts new file mode 100644 index 000000000000..f906be54b0e6 --- /dev/null +++ b/tests/e2e/tests/build/library/lib-consumption-partial-aot.ts @@ -0,0 +1,14 @@ +import { ng } from '../../../utils/process'; +import { executeBrowserTest } from '../../../utils/puppeteer'; +import { browserCheck, libraryConsumptionSetup } from './setup'; + +export default async function () { + await libraryConsumptionSetup(); + + // Build library in partial mode (production) + await ng('build', 'my-lib', '--configuration=production'); + + // Check that the e2e succeeds prod and non prod mode + await executeBrowserTest({ configuration: 'production', checkFn: browserCheck }); + await executeBrowserTest({ configuration: 'development', checkFn: browserCheck }); +} diff --git a/tests/legacy-cli/e2e/tests/build/library/lib-consumption-partial-jit.ts b/tests/e2e/tests/build/library/lib-consumption-partial-jit.ts similarity index 71% rename from tests/legacy-cli/e2e/tests/build/library/lib-consumption-partial-jit.ts rename to tests/e2e/tests/build/library/lib-consumption-partial-jit.ts index 9abb8a7e7b2f..503c09e525e9 100644 --- a/tests/legacy-cli/e2e/tests/build/library/lib-consumption-partial-jit.ts +++ b/tests/e2e/tests/build/library/lib-consumption-partial-jit.ts @@ -1,7 +1,7 @@ -import { setTimeout } from 'node:timers/promises'; import { updateJsonFile } from '../../../utils/project'; import { ng } from '../../../utils/process'; -import { libraryConsumptionSetup } from './setup'; +import { executeBrowserTest } from '../../../utils/puppeteer'; +import { browserCheck, libraryConsumptionSetup } from './setup'; import { getGlobalVariable } from '../../../utils/env'; export default async function () { @@ -22,7 +22,6 @@ export default async function () { }); // Check that the e2e succeeds prod and non prod mode - await ng('e2e', '--configuration=production'); - await setTimeout(500); - await ng('e2e', '--configuration=development'); + await executeBrowserTest({ configuration: 'production', checkFn: browserCheck }); + await executeBrowserTest({ configuration: 'development', checkFn: browserCheck }); } diff --git a/tests/legacy-cli/e2e/tests/build/library/lib-consumption-sourcemaps.ts b/tests/e2e/tests/build/library/lib-consumption-sourcemaps.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/library/lib-consumption-sourcemaps.ts rename to tests/e2e/tests/build/library/lib-consumption-sourcemaps.ts diff --git a/tests/legacy-cli/e2e/tests/build/library/lib-unused-decorated-class-treeshake.ts b/tests/e2e/tests/build/library/lib-unused-decorated-class-treeshake.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/library/lib-unused-decorated-class-treeshake.ts rename to tests/e2e/tests/build/library/lib-unused-decorated-class-treeshake.ts diff --git a/tests/legacy-cli/e2e/tests/build/library/setup.ts b/tests/e2e/tests/build/library/setup.ts similarity index 53% rename from tests/legacy-cli/e2e/tests/build/library/setup.ts rename to tests/e2e/tests/build/library/setup.ts index bc67a5b1c6aa..621b740cf4bc 100644 --- a/tests/legacy-cli/e2e/tests/build/library/setup.ts +++ b/tests/e2e/tests/build/library/setup.ts @@ -1,3 +1,4 @@ +import type { Page } from 'puppeteer'; import { writeMultipleFiles } from '../../../utils/fs'; import { silentNg } from '../../../utils/process'; @@ -10,7 +11,6 @@ export async function libraryConsumptionSetup(): Promise { 'projects/my-lib/src/lib/my-lib.ts': `import { Component } from '@angular/core'; @Component({ - standalone: true, selector: 'lib-my-lib', templateUrl: './my-lib.html', }) @@ -20,7 +20,6 @@ export async function libraryConsumptionSetup(): Promise { import { MyLibComponent } from 'my-lib'; @Component({ - standalone: true, selector: 'app-root', template: '', imports: [MyLibComponent], @@ -32,30 +31,15 @@ export async function libraryConsumptionSetup(): Promise { } } `, - 'e2e/src/app.e2e-spec.ts': ` - import { browser, logging, element, by } from 'protractor'; - import { AppPage } from './app.po'; - - describe('workspace-project App', () => { - let page: AppPage; - - beforeEach(() => { - page = new AppPage(); - }); - - it('should display text from library component', async () => { - await page.navigateTo(); - expect(await element(by.css('lib-my-lib p')).getText()).toEqual('my-lib works!'); - }); - - afterEach(async () => { - // Assert that there are no errors emitted from the browser - const logs = await browser.manage().logs().get(logging.Type.BROWSER); - expect(logs).not.toContain(jasmine.objectContaining({ - level: logging.Level.SEVERE, - })); - }); - }); -`, }); } + +export async function browserCheck(page: Page): Promise { + await page.waitForFunction( + () => + !!(globalThis as any).document + .querySelector('lib-my-lib p') + ?.textContent?.includes('my-lib works!'), + { timeout: 10000 }, + ); +} diff --git a/tests/legacy-cli/e2e/tests/build/material.ts b/tests/e2e/tests/build/material.ts similarity index 84% rename from tests/legacy-cli/e2e/tests/build/material.ts rename to tests/e2e/tests/build/material.ts index 0d369ac4db25..bc4862f735fc 100644 --- a/tests/legacy-cli/e2e/tests/build/material.ts +++ b/tests/e2e/tests/build/material.ts @@ -1,5 +1,4 @@ -import assert from 'node:assert/strict'; -import { appendFile, readdir } from 'node:fs/promises'; +import { appendFile } from 'node:fs/promises'; import { getGlobalVariable } from '../../utils/env'; import { readFile, replaceInFile } from '../../utils/fs'; import { @@ -7,8 +6,9 @@ import { installPackage, installWorkspacePackages, } from '../../utils/packages'; -import { execWithEnv, ng } from '../../utils/process'; +import { ng } from '../../utils/process'; import { isPrereleaseCli, updateJsonFile } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; const snapshots = require('../../ng-snapshot/package.json'); @@ -55,9 +55,9 @@ export default async function () { // Issue: https://github.com/angular/angular-cli/issues/17320 await replaceInFile( 'src/app/app.config.ts', - `import { ApplicationConfig } from '@angular/core';`, + `from '@angular/core';`, ` - import { ApplicationConfig } from '@angular/core'; + from '@angular/core'; import { MomentDateAdapter, MAT_MOMENT_DATE_FORMATS @@ -72,10 +72,8 @@ export default async function () { await replaceInFile( 'src/app/app.config.ts', - `providers: [provideRouter(routes) ]`, - ` - providers: [ - provideRouter(routes), + `provideRouter(routes)`, + `provideRouter(routes), { provide: DateAdapter, useClass: MomentDateAdapter, @@ -84,10 +82,8 @@ export default async function () { { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS - } - ] - `, + }`, ); - await ng('e2e', '--configuration=production'); + await executeBrowserTest({ configuration: 'production' }); } diff --git a/tests/legacy-cli/e2e/tests/build/multiple-configs.ts b/tests/e2e/tests/build/multiple-configs.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/multiple-configs.ts rename to tests/e2e/tests/build/multiple-configs.ts diff --git a/tests/legacy-cli/e2e/tests/build/output-dir.ts b/tests/e2e/tests/build/output-dir.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/output-dir.ts rename to tests/e2e/tests/build/output-dir.ts diff --git a/tests/legacy-cli/e2e/tests/build/poll.ts b/tests/e2e/tests/build/poll.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/poll.ts rename to tests/e2e/tests/build/poll.ts diff --git a/tests/legacy-cli/e2e/tests/build/prerender/discover-routes-ngmodule.ts b/tests/e2e/tests/build/prerender/discover-routes-ngmodule.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/prerender/discover-routes-ngmodule.ts rename to tests/e2e/tests/build/prerender/discover-routes-ngmodule.ts diff --git a/tests/legacy-cli/e2e/tests/build/prerender/discover-routes-standalone.ts b/tests/e2e/tests/build/prerender/discover-routes-standalone.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/prerender/discover-routes-standalone.ts rename to tests/e2e/tests/build/prerender/discover-routes-standalone.ts diff --git a/tests/legacy-cli/e2e/tests/build/prerender/error-with-sourcemaps.ts b/tests/e2e/tests/build/prerender/error-with-sourcemaps.ts similarity index 98% rename from tests/legacy-cli/e2e/tests/build/prerender/error-with-sourcemaps.ts rename to tests/e2e/tests/build/prerender/error-with-sourcemaps.ts index 8e45499f0021..875638877fbd 100644 --- a/tests/legacy-cli/e2e/tests/build/prerender/error-with-sourcemaps.ts +++ b/tests/e2e/tests/build/prerender/error-with-sourcemaps.ts @@ -26,7 +26,6 @@ export default async function () { @Component({ selector: 'app-root', - standalone: true, imports: [CommonModule, RouterOutlet], templateUrl: './app.html', styleUrls: ['./app.css'] diff --git a/tests/legacy-cli/e2e/tests/build/prerender/http-requests-assets.ts b/tests/e2e/tests/build/prerender/http-requests-assets.ts similarity index 83% rename from tests/legacy-cli/e2e/tests/build/prerender/http-requests-assets.ts rename to tests/e2e/tests/build/prerender/http-requests-assets.ts index b68e0a72b92a..71288b3c242e 100644 --- a/tests/legacy-cli/e2e/tests/build/prerender/http-requests-assets.ts +++ b/tests/e2e/tests/build/prerender/http-requests-assets.ts @@ -1,7 +1,7 @@ import { ng } from '../../../utils/process'; import { getGlobalVariable } from '../../../utils/env'; -import { expectFileToMatch, rimraf, writeMultipleFiles } from '../../../utils/fs'; -import { installWorkspacePackages } from '../../../utils/packages'; +import { expectFileToMatch, writeMultipleFiles } from '../../../utils/fs'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; import { useSha } from '../../../utils/project'; export default async function () { @@ -11,9 +11,8 @@ export default async function () { return; } - // Forcibly remove in case another test doesn't clean itself up. - await rimraf('node_modules/@angular/ssr'); - await ng('add', '@angular/ssr', '--skip-confirmation'); + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); await useSha(); await installWorkspacePackages(); @@ -45,14 +44,13 @@ export default async function () { // Update component to do an HTTP call to asset. 'src/app/app.ts': ` - import { Component, inject } from '@angular/core'; + import { ChangeDetectorRef, Component, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterOutlet } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', - standalone: true, imports: [CommonModule, RouterOutlet], template: \`

{{ data | json }}

@@ -63,15 +61,18 @@ export default async function () { export class App { data: any; dataWithSpace: any; + private readonly cdr: ChangeDetectorRef = inject(ChangeDetectorRef); constructor() { const http = inject(HttpClient); http.get('/media.json').subscribe((d) => { this.data = d; + this.cdr.markForCheck(); }); http.get('/media%20with-space.json').subscribe((d) => { this.dataWithSpace = d; + this.cdr.markForCheck(); }); } } diff --git a/tests/legacy-cli/e2e/tests/build/prod-build.ts b/tests/e2e/tests/build/prod-build.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/prod-build.ts rename to tests/e2e/tests/build/prod-build.ts diff --git a/tests/legacy-cli/e2e/tests/build/progress-and-stats.ts b/tests/e2e/tests/build/progress-and-stats.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/progress-and-stats.ts rename to tests/e2e/tests/build/progress-and-stats.ts diff --git a/tests/legacy-cli/e2e/tests/build/project-name.ts b/tests/e2e/tests/build/project-name.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/project-name.ts rename to tests/e2e/tests/build/project-name.ts diff --git a/tests/legacy-cli/e2e/tests/build/rebuild-deps-type-check.ts b/tests/e2e/tests/build/rebuild-deps-type-check.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/rebuild-deps-type-check.ts rename to tests/e2e/tests/build/rebuild-deps-type-check.ts diff --git a/tests/legacy-cli/e2e/tests/build/rebuild-dot-dirname.ts b/tests/e2e/tests/build/rebuild-dot-dirname.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/rebuild-dot-dirname.ts rename to tests/e2e/tests/build/rebuild-dot-dirname.ts diff --git a/tests/legacy-cli/e2e/tests/build/rebuild-replacements.ts b/tests/e2e/tests/build/rebuild-replacements.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/rebuild-replacements.ts rename to tests/e2e/tests/build/rebuild-replacements.ts diff --git a/tests/legacy-cli/e2e/tests/build/rebuild-symlink.ts b/tests/e2e/tests/build/rebuild-symlink.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/rebuild-symlink.ts rename to tests/e2e/tests/build/rebuild-symlink.ts diff --git a/tests/legacy-cli/e2e/tests/build/relative-sourcemap.ts b/tests/e2e/tests/build/relative-sourcemap.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/relative-sourcemap.ts rename to tests/e2e/tests/build/relative-sourcemap.ts diff --git a/tests/legacy-cli/e2e/tests/build/scripts-output-hashing.ts b/tests/e2e/tests/build/scripts-output-hashing.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/scripts-output-hashing.ts rename to tests/e2e/tests/build/scripts-output-hashing.ts diff --git a/tests/e2e/tests/build/server-rendering/express-engine-csp-nonce.ts b/tests/e2e/tests/build/server-rendering/express-engine-csp-nonce.ts new file mode 100644 index 000000000000..3d6335b48465 --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/express-engine-csp-nonce.ts @@ -0,0 +1,125 @@ +import { getGlobalVariable } from '../../../utils/env'; +import { rimraf, writeMultipleFiles } from '../../../utils/fs'; +import { findFreePort } from '../../../utils/network'; +import { installWorkspacePackages } from '../../../utils/packages'; +import { execAndWaitForOutputToMatch, ng } from '../../../utils/process'; +import { updateJsonFile, updateServerFileForEsbuild, useSha } from '../../../utils/project'; +import { executeBrowserTest } from '../../../utils/puppeteer'; + +export default async function () { + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + // forcibly remove in case another test doesn't clean itself up + await rimraf('node_modules/@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + if (!useWebpackBuilder) { + await updateJsonFile('angular.json', (json) => { + const build = json['projects']['test-project']['architect']['build']; + build.options.outputMode = undefined; + build.configurations.production.prerender = false; + }); + + await updateServerFileForEsbuild('src/server.ts'); + } + + await writeMultipleFiles({ + 'src/app/app.css': `div { color: #000 }`, + 'src/styles.css': `* { color: #000 }`, + 'src/main.ts': `import { bootstrapApplication } from '@angular/platform-browser'; + import { App } from './app/app'; + import { appConfig } from './app/app.config'; + + (window as any)['doBootstrap'] = () => { + bootstrapApplication(App, appConfig).catch((err) => console.error(err)); + }; + `, + 'src/index.html': ` + + + + + + + + + + + `, + }); + + async function spawnServer(): Promise { + const port = await findFreePort(); + + const runCommand = useWebpackBuilder ? 'serve:ssr' : 'serve:ssr:test-project'; + + await execAndWaitForOutputToMatch( + 'npm', + ['run', runCommand], + /Node Express server listening on/, + { + ...process.env, + 'PORT': String(port), + }, + ); + + return port; + } + + await ng('build'); + + if (useWebpackBuilder) { + // Build server code + await ng('run', 'test-project:server'); + } + + const port = await spawnServer(); + await executeBrowserTest({ + baseUrl: `http://localhost:${port}/`, + checkFn: async (page) => { + // Test the contents from the server. + const h1Text = await page.$eval('h1', (el) => el.textContent); + if (!h1Text?.includes('Hello')) { + throw new Error(`Expected h1 to contain 'Hello', but got '${h1Text}'`); + } + + const serverStylePresent = await page.evaluate( + () => !!(globalThis as any).document.querySelector('style[ng-app-id="ng"]'), + ); + if (!serverStylePresent) { + throw new Error('Expected server-side style to be present'); + } + + // style tags all have a nonce attribute + const nonces = await page.$$eval('style', (styles) => + styles.map((s) => s.getAttribute('nonce')), + ); + for (const nonce of nonces) { + if (nonce !== '{% nonce %}') { + throw new Error(`Expected nonce to be '{% nonce %}', but got '${nonce}'`); + } + } + + // stylesheets should be configured to load asynchronously + const linkMedia = await page.$eval('link[rel="stylesheet"]', (el) => + el.getAttribute('media'), + ); + if (linkMedia !== 'all') { + throw new Error(`Expected link media to be 'all', but got '${linkMedia}'`); + } + + // Bootstrap the client side app. + await page.evaluate('window.doBootstrap()'); + + // Wait for server style to be removed by client + await page.waitForSelector('style[ng-app-id="ng"]', { hidden: true }); + + // Retest the contents after the client bootstraps. + const h1TextPost = await page.$eval('h1', (el) => el.textContent); + if (!h1TextPost?.includes('Hello')) { + throw new Error(`Expected h1 to contain 'Hello' after bootstrap, but got '${h1TextPost}'`); + } + }, + }); +} diff --git a/tests/e2e/tests/build/server-rendering/express-engine-ngmodule.ts b/tests/e2e/tests/build/server-rendering/express-engine-ngmodule.ts new file mode 100644 index 000000000000..92e34f7ca3e8 --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/express-engine-ngmodule.ts @@ -0,0 +1,137 @@ +import { getGlobalVariable } from '../../../utils/env'; +import { rimraf, writeMultipleFiles } from '../../../utils/fs'; +import { findFreePort } from '../../../utils/network'; +import { installWorkspacePackages } from '../../../utils/packages'; +import { execAndWaitForOutputToMatch, ng } from '../../../utils/process'; +import { updateJsonFile, updateServerFileForEsbuild, useSha } from '../../../utils/project'; +import { executeBrowserTest } from '../../../utils/puppeteer'; + +export default async function () { + // forcibly remove in case another test doesn't clean itself up + await rimraf('node_modules/@angular/ssr'); + + await ng('generate', 'app', 'test-project-two', '--no-standalone', '--skip-install'); + + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + + if (useWebpackBuilder) { + await updateJsonFile('angular.json', (json) => { + const build = json['projects']['test-project-two']['architect']['build']; + build.builder = '@angular-devkit/build-angular:browser'; + build.options = { + ...build.options, + main: build.options.browser, + browser: undefined, + index: 'src/index.html', + }; + + build.configurations.development = { + ...build.configurations.development, + vendorChunk: true, + namedChunks: true, + buildOptimizer: false, + }; + }); + } + + await ng( + 'add', + '@angular/ssr', + '--skip-confirmation', + '--skip-install', + '--project=test-project-two', + ); + + await useSha(); + await installWorkspacePackages(); + + if (!useWebpackBuilder) { + // Disable prerendering + await updateJsonFile('angular.json', (json) => { + const build = json['projects']['test-project-two']['architect']['build']; + build.configurations.production.prerender = false; + build.options.outputMode = undefined; + }); + + await updateServerFileForEsbuild('projects/test-project-two/src/server.ts'); + } + + await writeMultipleFiles({ + 'projects/test-project-two/src/app/app.css': `div { color: #000 }`, + 'projects/test-project-two/src/styles.css': `* { color: #000 }`, + 'projects/test-project-two/src/main.ts': ` + import { platformBrowser } from '@angular/platform-browser'; + import { AppModule } from './app/app-module'; + + (window as any)['doBootstrap'] = () => { + platformBrowser() + .bootstrapModule(AppModule) + .catch((err) => console.error(err)); + }; + `, + }); + + async function spawnServer(): Promise { + const port = await findFreePort(); + + const runCommand = useWebpackBuilder ? 'serve:ssr' : `serve:ssr:test-project-two`; + + await execAndWaitForOutputToMatch( + 'npm', + ['run', runCommand], + /Node Express server listening on/, + { + ...process.env, + 'PORT': String(port), + }, + ); + + return port; + } + + await ng('build', 'test-project-two'); + + if (useWebpackBuilder) { + // Build server code + await ng('run', `test-project-two:server`); + } + + const port = await spawnServer(); + await executeBrowserTest({ + baseUrl: `http://localhost:${port}/`, + checkFn: async (page) => { + // Test the contents from the server. + const h1Text = await page.$eval('h1', (el) => el.textContent); + if (!h1Text?.includes('Hello')) { + throw new Error(`Expected h1 to contain 'Hello', but got '${h1Text}'`); + } + + const serverStylePresent = await page.evaluate( + `!!document.querySelector('style[ng-app-id="ng"]')`, + ); + if (!serverStylePresent) { + throw new Error('Expected server-side style to be present'); + } + + // stylesheets should be configured to load asynchronously + const linkMedia = await page.$eval('link[rel="stylesheet"]', (el) => + el.getAttribute('media'), + ); + if (linkMedia !== 'all') { + throw new Error(`Expected link media to be 'all', but got '${linkMedia}'`); + } + + // Bootstrap the client side app. + await page.evaluate('window.doBootstrap()'); + + // Wait for server style to be removed by client + await page.waitForSelector('style[ng-app-id="ng"]', { hidden: true }); + + // Retest the contents after the client bootstraps. + const h1TextPost = await page.$eval('h1', (el) => el.textContent); + if (!h1TextPost?.includes('Hello')) { + throw new Error(`Expected h1 to contain 'Hello' after bootstrap, but got '${h1TextPost}'`); + } + }, + }); +} diff --git a/tests/e2e/tests/build/server-rendering/express-engine-standalone.ts b/tests/e2e/tests/build/server-rendering/express-engine-standalone.ts new file mode 100644 index 000000000000..18920e3a5893 --- /dev/null +++ b/tests/e2e/tests/build/server-rendering/express-engine-standalone.ts @@ -0,0 +1,103 @@ +import { getGlobalVariable } from '../../../utils/env'; +import { rimraf, writeMultipleFiles } from '../../../utils/fs'; +import { findFreePort } from '../../../utils/network'; +import { installWorkspacePackages } from '../../../utils/packages'; +import { execAndWaitForOutputToMatch, ng } from '../../../utils/process'; +import { updateJsonFile, updateServerFileForEsbuild, useSha } from '../../../utils/project'; +import { executeBrowserTest } from '../../../utils/puppeteer'; + +export default async function () { + // forcibly remove in case another test doesn't clean itself up + await rimraf('node_modules/@angular/ssr'); + + const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + + if (!useWebpackBuilder) { + // Disable prerendering + await updateJsonFile('angular.json', (json) => { + const build = json['projects']['test-project']['architect']['build']; + build.options.outputMode = undefined; + }); + + await updateServerFileForEsbuild('src/server.ts'); + } + + await useSha(); + await installWorkspacePackages(); + + await writeMultipleFiles({ + 'src/app/app.css': `div { color: #000 }`, + 'src/styles.css': `* { color: #000 }`, + 'src/main.ts': `import { bootstrapApplication } from '@angular/platform-browser'; + import { App } from './app/app'; + import { appConfig } from './app/app.config'; + + (window as any)['doBootstrap'] = () => { + bootstrapApplication(App, appConfig).catch((err) => console.error(err)); + }; + `, + }); + + async function spawnServer(): Promise { + const port = await findFreePort(); + const runCommand = useWebpackBuilder ? 'serve:ssr' : 'serve:ssr:test-project'; + + await execAndWaitForOutputToMatch( + 'npm', + ['run', runCommand], + /Node Express server listening on/, + { + ...process.env, + 'PORT': String(port), + }, + ); + + return port; + } + + await ng('build'); + if (useWebpackBuilder) { + // Build server code + await ng('run', `test-project:server`); + } + + const port = await spawnServer(); + await executeBrowserTest({ + baseUrl: `http://localhost:${port}/`, + checkFn: async (page) => { + // Test the contents from the server. + const h1Text = await page.$eval('h1', (el) => el.textContent); + if (!h1Text?.includes('Hello')) { + throw new Error(`Expected h1 to contain 'Hello', but got '${h1Text}'`); + } + + const serverStylePresent = await page.evaluate( + `!!document.querySelector('style[ng-app-id="ng"]')`, + ); + if (!serverStylePresent) { + throw new Error('Expected server-side style to be present'); + } + + // stylesheets should be configured to load asynchronously + const linkMedia = await page.$eval('link[rel="stylesheet"]', (el) => + el.getAttribute('media'), + ); + if (linkMedia !== 'all') { + throw new Error(`Expected link media to be 'all', but got '${linkMedia}'`); + } + + // Bootstrap the client side app. + await page.evaluate('window.doBootstrap()'); + + // Wait for server style to be removed by client + await page.waitForSelector('style[ng-app-id="ng"]', { hidden: true }); + + // Retest the contents after the client bootstraps. + const h1TextPost = await page.$eval('h1', (el) => el.textContent); + if (!h1TextPost?.includes('Hello')) { + throw new Error(`Expected h1 to contain 'Hello' after bootstrap, but got '${h1TextPost}'`); + } + }, + }); +} diff --git a/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-external-dependencies.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-external-dependencies.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-external-dependencies.ts rename to tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-external-dependencies.ts diff --git a/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-base-href.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-base-href.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-base-href.ts rename to tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-base-href.ts diff --git a/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-sub-path.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-sub-path.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-sub-path.ts rename to tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-sub-path.ts diff --git a/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n.ts rename to tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n.ts diff --git a/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-platform-neutral.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-platform-neutral.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-platform-neutral.ts rename to tests/e2e/tests/build/server-rendering/server-routes-output-mode-server-platform-neutral.ts diff --git a/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-server.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server.ts rename to tests/e2e/tests/build/server-rendering/server-routes-output-mode-server.ts diff --git a/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-static-http-calls.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-http-calls.ts similarity index 94% rename from tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-static-http-calls.ts rename to tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-http-calls.ts index 8e7483f77ee4..b565144b37bf 100644 --- a/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-static-http-calls.ts +++ b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-http-calls.ts @@ -22,14 +22,13 @@ export default async function () { 'public/media.json': JSON.stringify({ dataFromAssets: true }), // Update component to do an HTTP call to asset and API. 'src/app/app.ts': ` - import { Component, inject } from '@angular/core'; + import { ChangeDetectorRef, Component, inject } from '@angular/core'; import { JsonPipe } from '@angular/common'; import { RouterOutlet } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', - standalone: true, imports: [JsonPipe, RouterOutlet], template: \`

{{ assetsData | json }}

@@ -40,16 +39,19 @@ export default async function () { export class App { assetsData: any; apiData: any; + private readonly cdr: ChangeDetectorRef = inject(ChangeDetectorRef); constructor() { const http = inject(HttpClient); http.get('/media.json').toPromise().then((d) => { this.assetsData = d; + this.cdr.markForCheck(); }); http.get('/api').toPromise().then((d) => { this.apiData = d; + this.cdr.markForCheck(); }); } } diff --git a/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-static-i18n_APP_BASE_HREF.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-i18n_APP_BASE_HREF.ts similarity index 91% rename from tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-static-i18n_APP_BASE_HREF.ts rename to tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-i18n_APP_BASE_HREF.ts index 51f5e3990bae..245375101946 100644 --- a/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-static-i18n_APP_BASE_HREF.ts +++ b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static-i18n_APP_BASE_HREF.ts @@ -1,7 +1,7 @@ import { join } from 'node:path'; import { existsSync } from 'node:fs'; import assert from 'node:assert'; -import { expectFileNotToExist, expectFileToMatch, writeFile } from '../../../utils/fs'; +import { expectFileToMatch, writeFile } from '../../../utils/fs'; import { ng, noSilentNg, silentNg } from '../../../utils/process'; import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; import { useSha } from '../../../utils/project'; @@ -66,7 +66,7 @@ export default async function () { await writeFile( 'src/app/app.config.ts', ` - import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core'; + import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; @@ -75,7 +75,6 @@ export default async function () { export const appConfig: ApplicationConfig = { providers: [ - provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideClientHydration(), { diff --git a/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-static.ts b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static.ts similarity index 89% rename from tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-static.ts rename to tests/e2e/tests/build/server-rendering/server-routes-output-mode-static.ts index 617776a94dc7..77f954be4f4d 100644 --- a/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-static.ts +++ b/tests/e2e/tests/build/server-rendering/server-routes-output-mode-static.ts @@ -29,7 +29,8 @@ export default async function () { await writeFile( 'src/app/app.routes.ts', ` - import { Routes } from '@angular/router'; + import { inject } from '@angular/core'; + import { Routes, Router } from '@angular/router'; import { Home } from './home/home'; import { Ssg } from './ssg/ssg'; import { SsgWithParams } from './ssg-with-params/ssg-with-params'; @@ -47,6 +48,12 @@ export default async function () { path: 'ssg-redirect', redirectTo: 'ssg' }, + { + path: 'ssg-redirect-via-guard', + canActivate: [() => { + return inject(Router).createUrlTree(['ssg'], { queryParams: { foo: 'bar' }}) + }], + }, { path: 'ssg/:id', component: SsgWithParams, @@ -106,8 +113,10 @@ export default async function () { 'ssg/index.html': /ng-server-context="ssg".+ssg works!/, 'ssg/one/index.html': /ng-server-context="ssg".+ssg-with-params works!/, 'ssg/two/index.html': /ng-server-context="ssg".+ssg-with-params works!/, - // When static redirects as generated as meta tags. + // When static redirects are generated as meta tags. 'ssg-redirect/index.html': '', + 'ssg-redirect-via-guard/index.html': + '', }; for (const [filePath, fileMatch] of Object.entries(expects)) { diff --git a/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-preload-links.ts b/tests/e2e/tests/build/server-rendering/server-routes-preload-links.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-preload-links.ts rename to tests/e2e/tests/build/server-rendering/server-routes-preload-links.ts diff --git a/tests/legacy-cli/e2e/tests/build/sourcemap.ts b/tests/e2e/tests/build/sourcemap.ts similarity index 94% rename from tests/legacy-cli/e2e/tests/build/sourcemap.ts rename to tests/e2e/tests/build/sourcemap.ts index cd3d6c32ab0c..2e153e637f30 100644 --- a/tests/legacy-cli/e2e/tests/build/sourcemap.ts +++ b/tests/e2e/tests/build/sourcemap.ts @@ -12,10 +12,10 @@ export default async function () { await ng('build', '--output-hashing=bundles', '--source-map', '--configuration=development'); await ng('build', '--output-hashing=none', '--source-map'); - await testForSourceMaps(useWebpackBuilder ? 3 : 2); + await testForSourceMaps(useWebpackBuilder ? 2 : 1); await ng('build', '--output-hashing=none', '--source-map', '--configuration=development'); - await testForSourceMaps(useWebpackBuilder ? 4 : 2); + await testForSourceMaps(useWebpackBuilder ? 3 : 1); } async function testForSourceMaps(expectedNumberOfFiles: number): Promise { diff --git a/tests/legacy-cli/e2e/tests/build/styles/bootstrap.ts b/tests/e2e/tests/build/styles/bootstrap.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/styles/bootstrap.ts rename to tests/e2e/tests/build/styles/bootstrap.ts diff --git a/tests/legacy-cli/e2e/tests/build/styles/include-paths.ts b/tests/e2e/tests/build/styles/include-paths.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/styles/include-paths.ts rename to tests/e2e/tests/build/styles/include-paths.ts diff --git a/tests/legacy-cli/e2e/tests/build/styles/less.ts b/tests/e2e/tests/build/styles/less.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/styles/less.ts rename to tests/e2e/tests/build/styles/less.ts diff --git a/tests/legacy-cli/e2e/tests/build/styles/loaders.ts b/tests/e2e/tests/build/styles/loaders.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/styles/loaders.ts rename to tests/e2e/tests/build/styles/loaders.ts diff --git a/tests/legacy-cli/e2e/tests/build/styles/sass-pkg-importer.ts b/tests/e2e/tests/build/styles/sass-pkg-importer.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/styles/sass-pkg-importer.ts rename to tests/e2e/tests/build/styles/sass-pkg-importer.ts diff --git a/tests/legacy-cli/e2e/tests/build/styles/sass.ts b/tests/e2e/tests/build/styles/sass.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/styles/sass.ts rename to tests/e2e/tests/build/styles/sass.ts diff --git a/tests/legacy-cli/e2e/tests/build/styles/scss-partial-resolution.ts b/tests/e2e/tests/build/styles/scss-partial-resolution.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/styles/scss-partial-resolution.ts rename to tests/e2e/tests/build/styles/scss-partial-resolution.ts diff --git a/tests/legacy-cli/e2e/tests/build/styles/scss.ts b/tests/e2e/tests/build/styles/scss.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/styles/scss.ts rename to tests/e2e/tests/build/styles/scss.ts diff --git a/tests/legacy-cli/e2e/tests/build/styles/symlinked-global.ts b/tests/e2e/tests/build/styles/symlinked-global.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/styles/symlinked-global.ts rename to tests/e2e/tests/build/styles/symlinked-global.ts diff --git a/tests/legacy-cli/e2e/tests/build/styles/tailwind-v2.ts b/tests/e2e/tests/build/styles/tailwind-v2.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/styles/tailwind-v2.ts rename to tests/e2e/tests/build/styles/tailwind-v2.ts diff --git a/tests/legacy-cli/e2e/tests/build/styles/tailwind-v3-cjs.ts b/tests/e2e/tests/build/styles/tailwind-v3-cjs.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/styles/tailwind-v3-cjs.ts rename to tests/e2e/tests/build/styles/tailwind-v3-cjs.ts diff --git a/tests/legacy-cli/e2e/tests/build/styles/tailwind-v3.ts b/tests/e2e/tests/build/styles/tailwind-v3.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/styles/tailwind-v3.ts rename to tests/e2e/tests/build/styles/tailwind-v3.ts diff --git a/tests/legacy-cli/e2e/tests/build/ts-paths.ts b/tests/e2e/tests/build/ts-paths.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/build/ts-paths.ts rename to tests/e2e/tests/build/ts-paths.ts diff --git a/tests/legacy-cli/e2e/tests/build/ts-standard-decorators.ts b/tests/e2e/tests/build/ts-standard-decorators.ts similarity index 88% rename from tests/legacy-cli/e2e/tests/build/ts-standard-decorators.ts rename to tests/e2e/tests/build/ts-standard-decorators.ts index 07bf93e3b545..05d056675d3b 100644 --- a/tests/legacy-cli/e2e/tests/build/ts-standard-decorators.ts +++ b/tests/e2e/tests/build/ts-standard-decorators.ts @@ -1,6 +1,7 @@ import { getGlobalVariable } from '../../utils/env'; import { ng } from '../../utils/process'; import { updateJsonFile, updateTsConfig } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; export default async function () { // Update project to disable experimental decorators @@ -31,6 +32,6 @@ export default async function () { // Unit tests (JIT only) await ng('test', '--no-watch'); - // E2E tests to ensure application functions in a browser - await ng('e2e'); + // Ensure application functions in a browser + await executeBrowserTest(); } diff --git a/tests/legacy-cli/e2e/tests/build/wasm-esm.ts b/tests/e2e/tests/build/wasm-esm.ts similarity index 77% rename from tests/legacy-cli/e2e/tests/build/wasm-esm.ts rename to tests/e2e/tests/build/wasm-esm.ts index 43d3708c2c36..70633a1021c1 100644 --- a/tests/legacy-cli/e2e/tests/build/wasm-esm.ts +++ b/tests/e2e/tests/build/wasm-esm.ts @@ -11,6 +11,7 @@ import { ng } from '../../utils/process'; import { prependToFile, replaceInFile } from '../../utils/fs'; import { updateJsonFile, useSha } from '../../utils/project'; import { installWorkspacePackages } from '../../utils/packages'; +import { executeBrowserTest } from '../../utils/puppeteer'; /** * Compiled and base64 encoded WASM file for the following WAT: @@ -62,39 +63,14 @@ export default async function () { // of a JIT production build. json.projects['test-project'].architect.build.options.polyfills = []; }); - await replaceInFile( - 'src/app/app.config.ts', - 'provideZoneChangeDetection', - 'provideZonelessChangeDetection', - ); - await replaceInFile( - 'src/app/app.config.ts', - 'provideZoneChangeDetection({ eventCoalescing: true })', - 'provideZonelessChangeDetection()', - ); await ng('build'); // Update E2E test to check for WASM execution - await writeFile( - 'e2e/src/app.e2e-spec.ts', - ` - import { AppPage } from './app.po'; - import { browser, logging } from 'protractor'; - describe('WASM execution', () => { - it('should log WASM result messages', async () => { - const page = new AppPage(); - await page.navigateTo(); - expect(await page.getTitleText()).toEqual('Hello, 32'); - }); - }); - `, - ); - - await ng('e2e'); + await executeBrowserTest({ expectedTitleText: 'Hello, 32' }); // Setup prerendering and build to test Node.js functionality - await ng('add', '@angular/ssr', '--skip-confirmation'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); await useSha(); await installWorkspacePackages(); diff --git a/tests/legacy-cli/e2e/tests/build/worker.ts b/tests/e2e/tests/build/worker.ts similarity index 75% rename from tests/legacy-cli/e2e/tests/build/worker.ts rename to tests/e2e/tests/build/worker.ts index 53e60aa34772..be81aae7dfd4 100644 --- a/tests/legacy-cli/e2e/tests/build/worker.ts +++ b/tests/e2e/tests/build/worker.ts @@ -8,10 +8,12 @@ import assert from 'node:assert/strict'; import { readdir } from 'node:fs/promises'; +import { setTimeout } from 'node:timers/promises'; import { getGlobalVariable } from '../../utils/env'; import { expectFileToExist, expectFileToMatch, replaceInFile, writeFile } from '../../utils/fs'; import { ng } from '../../utils/process'; import { expectToFail } from '../../utils/utils'; +import { executeBrowserTest } from '../../utils/puppeteer'; export default async function () { const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; @@ -55,24 +57,32 @@ export default async function () { // https://github.com/angular/protractor/issues/2207 await replaceInFile('src/app/app.ts', 'console.log', 'console.warn'); - await writeFile( - 'e2e/app.e2e-spec.ts', - ` - import { AppPage } from './app.po'; - import { browser, logging } from 'protractor'; - describe('worker bundle', () => { - it('should log worker messages', async () => { - const page = new AppPage();; - page.navigateTo(); - const logs = await browser.manage().logs().get(logging.Type.BROWSER); - expect(logs.length).toEqual(1); - expect(logs[0].message).toContain('page got message: worker response to hello'); + await executeBrowserTest({ + checkFn: async (page) => { + const messages: string[] = []; + page.on('console', (msg) => { + messages.push(msg.text()); }); - }); - `, - ); - await ng('e2e'); + // Reload to ensure we capture messages from the start if needed, + // although executeBrowserTest already navigated. + await page.reload(); + + // Wait for the worker message + let retries = 50; + while ( + !messages.some((m) => m.includes('page got message: worker response to hello')) && + retries > 0 + ) { + await setTimeout(100); + retries--; + } + + if (!messages.some((m) => m.includes('page got message: worker response to hello'))) { + assert.fail(`Expected worker message not found in console. Got:\n${messages.join('\n')}`); + } + }, + }); } async function getWorkerOutputFile(useWebpackBuilder: boolean): Promise { diff --git a/tests/legacy-cli/e2e/tests/commands/add/add-material.ts b/tests/e2e/tests/commands/add/add-material.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/add/add-material.ts rename to tests/e2e/tests/commands/add/add-material.ts diff --git a/tests/legacy-cli/e2e/tests/commands/add/add-pwa.ts b/tests/e2e/tests/commands/add/add-pwa.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/add/add-pwa.ts rename to tests/e2e/tests/commands/add/add-pwa.ts diff --git a/tests/e2e/tests/commands/add/add-tailwindcss.ts b/tests/e2e/tests/commands/add/add-tailwindcss.ts new file mode 100644 index 000000000000..1444bb6a9a07 --- /dev/null +++ b/tests/e2e/tests/commands/add/add-tailwindcss.ts @@ -0,0 +1,28 @@ +import { expectFileToExist, expectFileToMatch, rimraf } from '../../../utils/fs'; +import { getActivePackageManager, uninstallPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; + +export default async function () { + // In case a previous test installed tailwindcss, clear it. + // (we don't clear node module directories between tests) + // npm does not appear to fully uninstall sometimes + if (getActivePackageManager() === 'npm') { + await rimraf('node_modules/tailwindcss'); + } + + try { + await ng('add', 'tailwindcss', '--skip-confirmation'); + await expectFileToExist('.postcssrc.json'); + await expectFileToMatch('src/styles.css', /@import "tailwindcss";/); + await expectFileToMatch('package.json', /"tailwindcss":/); + await expectFileToMatch('package.json', /"@tailwindcss\/postcss":/); + await expectFileToMatch('package.json', /"postcss":/); + + // Ensure the project builds + await ng('build', '--configuration=development'); + } finally { + await uninstallPackage('tailwindcss'); + await uninstallPackage('@tailwindcss/postcss'); + await uninstallPackage('postcss'); + } +} diff --git a/tests/legacy-cli/e2e/tests/commands/add/add-version.ts b/tests/e2e/tests/commands/add/add-version.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/add/add-version.ts rename to tests/e2e/tests/commands/add/add-version.ts diff --git a/tests/legacy-cli/e2e/tests/commands/add/add.ts b/tests/e2e/tests/commands/add/add.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/add/add.ts rename to tests/e2e/tests/commands/add/add.ts diff --git a/tests/legacy-cli/e2e/tests/commands/add/base.ts b/tests/e2e/tests/commands/add/base.ts similarity index 86% rename from tests/legacy-cli/e2e/tests/commands/add/base.ts rename to tests/e2e/tests/commands/add/base.ts index f4e7048df6ac..d31210c6c242 100644 --- a/tests/legacy-cli/e2e/tests/commands/add/base.ts +++ b/tests/e2e/tests/commands/add/base.ts @@ -4,7 +4,7 @@ import { ng } from '../../../utils/process'; import { expectToFail } from '../../../utils/utils'; export default async function () { - await symlinkFile(assetDir('add-collection'), `./node_modules/add-collection`, 'dir'); + await symlinkFile(assetDir('add-collection-dir'), `./node_modules/add-collection`, 'dir'); await ng('add', 'add-collection'); await expectFileToExist('empty-file'); diff --git a/tests/e2e/tests/commands/add/dir.ts b/tests/e2e/tests/commands/add/dir.ts new file mode 100644 index 000000000000..7cb00704cc8e --- /dev/null +++ b/tests/e2e/tests/commands/add/dir.ts @@ -0,0 +1,19 @@ +import { cp } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { assetDir } from '../../../utils/assets'; +import { expectFileToExist } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; + +export default async function () { + const collectionName = 'add-collection-dir'; + const dirCollectionPath = resolve(collectionName); + + // Copy locally as bun doesn't install the dependency correctly if it has symlinks. + await cp(assetDir(collectionName), dirCollectionPath, { + recursive: true, + dereference: true, + }); + + await ng('add', dirCollectionPath, '--name=blah', '--skip-confirmation'); + await expectFileToExist('blah'); +} diff --git a/tests/e2e/tests/commands/add/file.ts b/tests/e2e/tests/commands/add/file.ts new file mode 100644 index 000000000000..5b22b4211ceb --- /dev/null +++ b/tests/e2e/tests/commands/add/file.ts @@ -0,0 +1,13 @@ +import { copyFile } from 'node:fs/promises'; +import { assetDir } from '../../../utils/assets'; +import { expectFileToExist } from '../../../utils/fs'; +import { ng } from '../../../utils/process'; + +export default async function () { + // Avoids ERR_PNPM_ENAMETOOLONG errors. + const tarball = './add-collection.tgz'; + await copyFile(assetDir(tarball), tarball); + + await ng('add', tarball, '--name=blah', '--skip-confirmation'); + await expectFileToExist('blah'); +} diff --git a/tests/legacy-cli/e2e/tests/commands/add/npm-config.ts b/tests/e2e/tests/commands/add/npm-config.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/add/npm-config.ts rename to tests/e2e/tests/commands/add/npm-config.ts diff --git a/tests/e2e/tests/commands/add/peer.ts b/tests/e2e/tests/commands/add/peer.ts new file mode 100644 index 000000000000..143542e4533c --- /dev/null +++ b/tests/e2e/tests/commands/add/peer.ts @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict'; +import { resolve } from 'node:path'; +import { cp } from 'node:fs/promises'; +import { assetDir } from '../../../utils/assets'; +import { ng } from '../../../utils/process'; + +export default async function (): Promise { + const warning = /Adding the package may not succeed/; + + const stdout1 = await runNgAdd('add-collection-peer-bad'); + assert.match( + stdout1, + warning, + `Peer warning should be shown for add-collection-peer-bad but was not.`, + ); + + const stdout2 = await runNgAdd('add-collection-dir'); + assert.doesNotMatch( + stdout2, + warning, + `Peer warning should NOT be shown for add-collection-dir but was.`, + ); + + const stdout3 = await runNgAdd('add-collection-peer-good'); + assert.doesNotMatch( + stdout3, + warning, + `Peer warning should NOT be shown for add-collection-peer-good but was.`, + ); +} + +async function runNgAdd(collectionName: string): Promise { + const collectionPath = resolve(collectionName); + + // Copy locally as bun doesn't install the dependency correctly if it has symlinks. + await cp(assetDir(collectionName), collectionPath, { + recursive: true, + dereference: true, + }); + + const { stdout } = await ng('add', collectionPath, '--skip-confirmation'); + + return stdout; +} diff --git a/tests/legacy-cli/e2e/tests/commands/add/registry-option.ts b/tests/e2e/tests/commands/add/registry-option.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/add/registry-option.ts rename to tests/e2e/tests/commands/add/registry-option.ts diff --git a/tests/e2e/tests/commands/add/secure-registry.ts b/tests/e2e/tests/commands/add/secure-registry.ts new file mode 100644 index 000000000000..4a640607f8be --- /dev/null +++ b/tests/e2e/tests/commands/add/secure-registry.ts @@ -0,0 +1,50 @@ +import { expectFileNotToExist, expectFileToExist, rimraf } from '../../../utils/fs'; +import { getActivePackageManager, installWorkspacePackages } from '../../../utils/packages'; +import { git, ng } from '../../../utils/process'; +import { createNpmConfigForAuthentication } from '../../../utils/registry'; +import { expectToFail } from '../../../utils/utils'; + +export default async function () { + const originalNpmConfigRegistry = process.env['NPM_CONFIG_REGISTRY']; + try { + // The environment variable has priority over the .npmrc + delete process.env['NPM_CONFIG_REGISTRY']; + const packageManager = getActivePackageManager(); + const supportsUnscopedAuth = packageManager === 'yarn'; + const command = ['add', '@angular/pwa', '--skip-confirmation']; + + // Works with unscoped registry authentication details + if (supportsUnscopedAuth) { + // Some package managers such as Bun and NPM do not support unscoped auth. + await createNpmConfigForAuthentication(false); + + await expectFileNotToExist('public/manifest.webmanifest'); + + await ng(...command); + await expectFileToExist('public/manifest.webmanifest'); + await git('clean', '-dxf'); + } + + // Works with scoped registry authentication details + await expectFileNotToExist('public/manifest.webmanifest'); + + await createNpmConfigForAuthentication(true); + await ng(...command); + await expectFileToExist('public/manifest.webmanifest'); + await git('clean', '-dxf'); + + // Invalid authentication token + if (supportsUnscopedAuth) { + // Some package managers such as Bun and NPM do not support unscoped auth. + await createNpmConfigForAuthentication(false, true); + await expectToFail(() => ng(...command)); + } + + await createNpmConfigForAuthentication(true, true); + await expectToFail(() => ng(...command)); + } finally { + process.env['NPM_CONFIG_REGISTRY'] = originalNpmConfigRegistry; + await git('clean', '-dxf'); + await installWorkspacePackages(); + } +} diff --git a/tests/legacy-cli/e2e/tests/commands/add/version-specifier.ts b/tests/e2e/tests/commands/add/version-specifier.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/add/version-specifier.ts rename to tests/e2e/tests/commands/add/version-specifier.ts diff --git a/tests/legacy-cli/e2e/tests/commands/add/yarn-env-vars.ts b/tests/e2e/tests/commands/add/yarn-env-vars.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/add/yarn-env-vars.ts rename to tests/e2e/tests/commands/add/yarn-env-vars.ts diff --git a/tests/legacy-cli/e2e/tests/commands/additional-properties.ts b/tests/e2e/tests/commands/additional-properties.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/additional-properties.ts rename to tests/e2e/tests/commands/additional-properties.ts diff --git a/tests/legacy-cli/e2e/tests/commands/analytics/analytics-enable-disable.ts b/tests/e2e/tests/commands/analytics/analytics-enable-disable.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/analytics/analytics-enable-disable.ts rename to tests/e2e/tests/commands/analytics/analytics-enable-disable.ts diff --git a/tests/legacy-cli/e2e/tests/commands/analytics/analytics-info.ts b/tests/e2e/tests/commands/analytics/analytics-info.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/analytics/analytics-info.ts rename to tests/e2e/tests/commands/analytics/analytics-info.ts diff --git a/tests/legacy-cli/e2e/tests/commands/analytics/ask-analytics-command.ts b/tests/e2e/tests/commands/analytics/ask-analytics-command.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/analytics/ask-analytics-command.ts rename to tests/e2e/tests/commands/analytics/ask-analytics-command.ts diff --git a/tests/legacy-cli/e2e/tests/commands/builder-not-found.ts b/tests/e2e/tests/commands/builder-not-found.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/builder-not-found.ts rename to tests/e2e/tests/commands/builder-not-found.ts diff --git a/tests/legacy-cli/e2e/tests/commands/builder-project-by-cwd.ts b/tests/e2e/tests/commands/builder-project-by-cwd.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/builder-project-by-cwd.ts rename to tests/e2e/tests/commands/builder-project-by-cwd.ts diff --git a/tests/legacy-cli/e2e/tests/commands/cache/cache-clean.ts b/tests/e2e/tests/commands/cache/cache-clean.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/cache/cache-clean.ts rename to tests/e2e/tests/commands/cache/cache-clean.ts diff --git a/tests/legacy-cli/e2e/tests/commands/cache/cache-enable-disable.ts b/tests/e2e/tests/commands/cache/cache-enable-disable.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/cache/cache-enable-disable.ts rename to tests/e2e/tests/commands/cache/cache-enable-disable.ts diff --git a/tests/legacy-cli/e2e/tests/commands/cache/cache-info.ts b/tests/e2e/tests/commands/cache/cache-info.ts similarity index 58% rename from tests/legacy-cli/e2e/tests/commands/cache/cache-info.ts rename to tests/e2e/tests/commands/cache/cache-info.ts index 46ae15aef796..bad2df6c3bdc 100644 --- a/tests/legacy-cli/e2e/tests/commands/cache/cache-info.ts +++ b/tests/e2e/tests/commands/cache/cache-info.ts @@ -1,65 +1,62 @@ import { execAndWaitForOutputToMatch } from '../../../utils/process'; import { updateJsonFile } from '../../../utils/project'; +const ENV_NO_COLOR = { + 'NO_COLOR': '1', +}; + export default async function () { const originalCIValue = process.env['CI']; try { // Should be enabled by default for local builds. await configureTest('0' /** envCI */); - await execAndWaitForOutputToMatch( - 'ng', - ['cache', 'info'], - /Effective status on current machine: enabled/, - ); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Enabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); // Should be disabled by default for CI builds. await configureTest('1' /** envCI */, { enabled: true }); - await execAndWaitForOutputToMatch( - 'ng', - ['cache', 'info'], - /Effective status on current machine: disabled/, - ); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Disabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); // Should be enabled by when environment is local and env is not CI. await configureTest('0' /** envCI */, { environment: 'local' }); - await execAndWaitForOutputToMatch( - 'ng', - ['cache', 'info'], - /Effective status on current machine: enabled/, - ); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Enabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); // Should be disabled by when environment is local and env is CI. await configureTest('1' /** envCI */, { environment: 'local' }); - await execAndWaitForOutputToMatch( - 'ng', - ['cache', 'info'], - /Effective status on current machine: disabled/, - ); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Disabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); // Effective status should be enabled when 'environment' is set to 'all' or 'ci'. await configureTest('1' /** envCI */, { environment: 'all' }); - await execAndWaitForOutputToMatch( - 'ng', - ['cache', 'info'], - /Effective status on current machine: enabled/, - ); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Enabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); // Effective status should be enabled when 'environment' is set to 'ci' and run is in ci await configureTest('1' /** envCI */, { environment: 'ci' }); - await execAndWaitForOutputToMatch( - 'ng', - ['cache', 'info'], - /Effective status on current machine: enabled/, - ); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Enabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); // Effective status should be disabled when 'enabled' is set to false await configureTest('1' /** envCI */, { environment: 'all', enabled: false }); - await execAndWaitForOutputToMatch( - 'ng', - ['cache', 'info'], - /Effective status on current machine: disabled/, - ); + await execAndWaitForOutputToMatch('ng', ['cache', 'info'], /Effective Status\s*: Disabled/, { + ...process.env, + ...ENV_NO_COLOR, + }); } finally { process.env['CI'] = originalCIValue; } diff --git a/tests/legacy-cli/e2e/tests/commands/completion/completion-prompt.ts b/tests/e2e/tests/commands/completion/completion-prompt.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/completion/completion-prompt.ts rename to tests/e2e/tests/commands/completion/completion-prompt.ts diff --git a/tests/legacy-cli/e2e/tests/commands/completion/completion-script.ts b/tests/e2e/tests/commands/completion/completion-script.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/completion/completion-script.ts rename to tests/e2e/tests/commands/completion/completion-script.ts diff --git a/tests/legacy-cli/e2e/tests/commands/completion/completion.ts b/tests/e2e/tests/commands/completion/completion.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/completion/completion.ts rename to tests/e2e/tests/commands/completion/completion.ts diff --git a/tests/legacy-cli/e2e/tests/commands/config/config-get.ts b/tests/e2e/tests/commands/config/config-get.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/config/config-get.ts rename to tests/e2e/tests/commands/config/config-get.ts diff --git a/tests/legacy-cli/e2e/tests/commands/config/config-global-validation.ts b/tests/e2e/tests/commands/config/config-global-validation.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/config/config-global-validation.ts rename to tests/e2e/tests/commands/config/config-global-validation.ts diff --git a/tests/legacy-cli/e2e/tests/commands/config/config-global.ts b/tests/e2e/tests/commands/config/config-global.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/config/config-global.ts rename to tests/e2e/tests/commands/config/config-global.ts diff --git a/tests/legacy-cli/e2e/tests/commands/config/config-set-enum-check.ts b/tests/e2e/tests/commands/config/config-set-enum-check.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/config/config-set-enum-check.ts rename to tests/e2e/tests/commands/config/config-set-enum-check.ts diff --git a/tests/legacy-cli/e2e/tests/commands/config/config-set-prefix.ts b/tests/e2e/tests/commands/config/config-set-prefix.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/config/config-set-prefix.ts rename to tests/e2e/tests/commands/config/config-set-prefix.ts diff --git a/tests/legacy-cli/e2e/tests/commands/config/config-set-serve-port.ts b/tests/e2e/tests/commands/config/config-set-serve-port.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/config/config-set-serve-port.ts rename to tests/e2e/tests/commands/config/config-set-serve-port.ts diff --git a/tests/legacy-cli/e2e/tests/commands/config/config-set.ts b/tests/e2e/tests/commands/config/config-set.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/config/config-set.ts rename to tests/e2e/tests/commands/config/config-set.ts diff --git a/tests/legacy-cli/e2e/tests/commands/help/help-hidden.ts b/tests/e2e/tests/commands/help/help-hidden.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/help/help-hidden.ts rename to tests/e2e/tests/commands/help/help-hidden.ts diff --git a/tests/legacy-cli/e2e/tests/commands/help/help-json.ts b/tests/e2e/tests/commands/help/help-json.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/help/help-json.ts rename to tests/e2e/tests/commands/help/help-json.ts diff --git a/tests/legacy-cli/e2e/tests/commands/ng-new-collection.ts b/tests/e2e/tests/commands/ng-new-collection.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/ng-new-collection.ts rename to tests/e2e/tests/commands/ng-new-collection.ts diff --git a/tests/legacy-cli/e2e/tests/commands/project-cannot-be-determined-by-cwd.ts b/tests/e2e/tests/commands/project-cannot-be-determined-by-cwd.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/project-cannot-be-determined-by-cwd.ts rename to tests/e2e/tests/commands/project-cannot-be-determined-by-cwd.ts diff --git a/tests/legacy-cli/e2e/tests/commands/run-configuration-option.ts b/tests/e2e/tests/commands/run-configuration-option.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/run-configuration-option.ts rename to tests/e2e/tests/commands/run-configuration-option.ts diff --git a/tests/legacy-cli/e2e/tests/commands/serve/assets.ts b/tests/e2e/tests/commands/serve/assets.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/serve/assets.ts rename to tests/e2e/tests/commands/serve/assets.ts diff --git a/tests/legacy-cli/e2e/tests/commands/serve/head-request.ts b/tests/e2e/tests/commands/serve/head-request.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/serve/head-request.ts rename to tests/e2e/tests/commands/serve/head-request.ts diff --git a/tests/legacy-cli/e2e/tests/commands/serve/preflight-request.ts b/tests/e2e/tests/commands/serve/preflight-request.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/serve/preflight-request.ts rename to tests/e2e/tests/commands/serve/preflight-request.ts diff --git a/tests/legacy-cli/e2e/tests/commands/serve/reload-shims.ts b/tests/e2e/tests/commands/serve/reload-shims.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/serve/reload-shims.ts rename to tests/e2e/tests/commands/serve/reload-shims.ts diff --git a/tests/legacy-cli/e2e/tests/commands/serve/serve-path.ts b/tests/e2e/tests/commands/serve/serve-path.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/serve/serve-path.ts rename to tests/e2e/tests/commands/serve/serve-path.ts diff --git a/tests/e2e/tests/commands/serve/ssr-http-requests-assets.ts b/tests/e2e/tests/commands/serve/ssr-http-requests-assets.ts new file mode 100644 index 000000000000..19f1208646d6 --- /dev/null +++ b/tests/e2e/tests/commands/serve/ssr-http-requests-assets.ts @@ -0,0 +1,190 @@ +import assert from 'node:assert'; +import { Agent } from 'undici'; +import { killAllProcesses, ng } from '../../../utils/process'; +import { writeMultipleFiles } from '../../../utils/fs'; +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { ngServe, useSha } from '../../../utils/project'; + +export default async function () { + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + await writeMultipleFiles({ + // Add http client and route + 'src/app/app.config.ts': ` + import { ApplicationConfig } from '@angular/core'; + import { provideRouter } from '@angular/router'; + + import { Home } from './home/home'; + import { provideClientHydration } from '@angular/platform-browser'; + import { provideHttpClient, withFetch } from '@angular/common/http'; + + export const appConfig: ApplicationConfig = { + providers: [ + provideRouter([{ + path: '', + component: Home, + }]), + provideClientHydration(), + provideHttpClient(withFetch()), + ], + }; + `, + // Add asset + 'public/media.json': JSON.stringify({ dataFromAssets: true }), + // Update component to do an HTTP call to asset. + 'src/app/app.ts': ` + import { ChangeDetectorRef, Component, inject } from '@angular/core'; + import { CommonModule } from '@angular/common'; + import { RouterOutlet } from '@angular/router'; + import { HttpClient } from '@angular/common/http'; + + @Component({ + selector: 'app-root', + imports: [CommonModule, RouterOutlet], + template: \` +

{{ data | json }}

+ + \`, + }) + export class App { + data: any; + private readonly cdr: ChangeDetectorRef = inject(ChangeDetectorRef); + + constructor() { + const http = inject(HttpClient); + http.get('/media.json').toPromise().then((d) => { + this.data = d; + this.cdr.markForCheck(); + }); + } + } + `, + }); + + await ng('generate', 'component', 'home'); + const match = /

{[\S\s]*"dataFromAssets":[\s\S]*true[\S\s]*}<\/p>/; + const port = await ngServe('--no-ssl'); + assert.match(await (await fetch(`http://localhost:${port}/`)).text(), match); + + await killAllProcesses(); + + const sslPort = await ngServe('--ssl'); + assert.match( + await ( + await fetch(`https://localhost:${sslPort}/`, { + dispatcher: new Agent({ + connect: { + rejectUnauthorized: false, + }, + }), + }) + ).text(), + match, + ); + + await killAllProcesses(); + + // With OpenSSl cert+key + writeMultipleFiles({ + 'server.key': `-----BEGIN PRIVATE KEY----- +MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDOyBmVy61zEqfs +oTPQ9gTX233/nlrVXtaUGJkbDR5actq0X+XQtZuIoO4JgRpiYz5/8XiY8AiaMdt3 +0abugO5AhyIbsGyQxvz2si7yKQ+WUdF/DRTpfTq76E8EXR8W9BI+DTpG/1nNGBd1 +lpMa8NMfHqLvhtpebHuBcb1BCRely+FILHVDGf+dfCIvR0Zvt8Ah3qLL6vvX3pzF +qM9XrXfUgWKqpbz+L1BeCPILsH+UaOOCzzbyrLoY6fnawjUkc/ieHWycro7dBUlu +JJ/kcGtpPYD/hsMFcXz6D67qbIFuc6Dz9CrWIagAFMqK91FAtUpyfP7+jLikQOST +pFDLgJ+klADGCiZ6C/dvjUsYM+4ML9dX6Q9rj6sQo/oj0Dsdj39J5mVmklkbRP5q +heMGTyc09/ambiYFfzWEMMnEcCT/CS/r1q93oRDG02Cx6F1B05mtR+/AFxAJ6UxL +2u3oMPVY179FWjx2+YvbfrdNrFnWb8eRMiRZIW8O8ptKkrh+LL1Rhep+W/1Nxdrp +g7E2rWP8AWr3mdd+cnauvF/2yMecBDLVnk3OOSjcuLc+i9ngOD0xHdcRfO89mryj +IewEIrUQ4U0ZgyHMi99qV4wyXhd9HzTUgT01QofsiuF9xyVfnansQOj3oqOgCS92 +VEeqZnLXgaVoh/++/FV7r4C5zxLzLwIDAQABAoICAAeKSqD98iE3o5qc6AAiqj79 +r8L2dJ+0F9cDF4Bh6aLFYBGUoS/Sr38Cm7m0/3qiiEKvbpM9/0QVfHLRoBNcJnBk +0mrp1yD1tfEOUPcJ12D/3XJ2zlIv+7oUn97Ia9h4NCzBv5zw7lTsrjHenDMSZ7XD +PR6qb064XfiRETKFeCJk64Godj/3QkmX2FApCMDwXJttynLQseK5RZnDHojhuDuR +vgfC+aOCTit8GOkxi1Hdppxm8tmMwfqyJmAJh5IdKkNA3MHtbyPCxSXRRIUdwMXT +bhhVCh9/W3prv/vEYSPfRGs9WdtrTBj/U8GlgGlxa87h1i/i8N4I5RP+8lic6zVL +BIIPamkRFRNUmV7ZzpWsrLl1TUUcQJ1UsjNqaLD7jl+l0IaUta8I9crJQWIuQu+G +5C0XJQPZrqGkZfLSMvi08S+8myCzf+3P3ayUHAKz4Q1pTeM2BbHQi1HbT+WUsA5G +DD4xBwc8VJXOy0dB4v4e5eK8aZaJZroR5LJT7bvKw1MNpyAt6w2Z17eSSuEE0x6u +4uzOfHRaWiKH9gXVSKyo8xM08wiKAJIpDg4fDsu/XPjfPzV3eSHwin6ADw7rcOrW +j4Ca43Ts7Fz0Y40dtUyrrQ3f7WSQ9C+M88NuI9WYPWmXqPQY9+b5Au0Q8rq1j3dW +1YB3vYd6ElaLI6k7c5OhAoIBAQDt+Dgi2jrx2Xol0Per/cIFyG/hX/h+tavj++xl +gIMLLwhFmBVIkkXHjG5v5rZFCY7giQgdy+JHAIDUg3Ae3K7zSYidkMwQzLJ9udaT +nJEybY4RlEJZVBs58pkjevqTD/pZ+Kj09/VLAJIhOInFQHQ+ZVn4uHF+NO4tcsH+ +Wtsyyf8tFMkoNQ38o2oTnJtsotssKGdXCgi36BCCCUQk98113RK9dBTi+2iB59qr +WczAb6Jl5cs1j/2IC3z9KilZ3/ww4Bshs5LThIGR66KZIfApzf8XQzHM9mhiLgRU +thUZ0a/ougqf4FovLAezsNM7kYqbPDPOh/CayN5KZ8pHNLt1AoIBAQDecvFejv3u +Lm9kf2xRv06HTsLeEUSgRVoWdKidwW3tXOkl8vuBTzeFl9yrgtMBbSgcFASbEKPP +uPc6g+zkcakUB+FLGGNwNFKhdGPUMI7u8i9WeWH+e3Aios7n0tCPP0Xv6d1Lhcyw +X1nz07hZ+sT40nLGyf/6vfg8LFGSBrr3YQLseodKGTC9jc5yJqEX16cqHppkwaJT +Elsona7PZGFm/WFGWn4wZiPpd9P5lnxP+KrI+m84z4Gw5txcJsE8WiUrrQYHG3+2 +yeztwYl+JGHcspsU4WTPCupyVRHt0uuGVN+UhLKgER8wghc6fL08jGkHgVLrStnN +ekRA0gEZRzOTAoIBAGuQMheW2uPssGidfwXP6r5gbinKDnF/vpWLjrwGjbUlajDC +4IPwEfhzwot0Flk4S8u0ROXq/XmogZMNYkWg7LdtOoI2K/c//0ITGSmZsIvBt2C8 +ygzElpXn0U6XTOHia//1BLHNzqM7O9ImUyfEzYZSm4twG2S3mh0S7RsCiGf5pA0F +gzNYX90dJFp/BEXjivv3u1Y9Y9l03NlaROIM3GL1LX5TFQnQJ9noKhAfxAwLqbUz +XFn2ntu6jaGFSDGmq8CP29Os7qYLE+IYR2O+UmcjBLXIGp+RlXcjY7PCpeEIxeGF +Dj5b04fU+BpByAj57VPjr2sgSSI9vzSUm3r6G+0CggEBALK7JgZ028BxHN1hqHWy +QXVkKhxlQX+I2Y5rY0OFtD5gRZBRQBUwwgqb7xj7P3DI9M5Co0S4RPZUxogEkeUn +EdPfVPySdusjjzTcoI1QCrggbTqMwtjG811Q9O+9Kge+rgHLJRxWQBWCN3M6rMfX +PkYySThB+2PLGVW3wj6TG8xB7Sh2dpdp0AitlK+RLCRNCKpF9oV4M2WNvSLQNzG5 +lK08btkpQnS+zKH8vpuudumGgiqDVbQOvkSV6X49QUutnmoOVmaFiMMkUTLjKwbo +Up0SAJrxUp8sRR1iDsrIiqbfMNlTGXaU6zt9ew5qRV4N7yGxnh8hgAih8Y8nbOyT +kfMCggEBAMVOGy7yzaMQvVSkcFkUAnznI7RwvhUWusomfyaVgHm+j3Y7OPius1ah +4Da3kvb4t8OFUIdnMz/rte8xRKE6lKLNmXG9+8nPkCdrB9ovDr0Pw3ONZ7kKHuhm +75IKV72f3krZK5jJ88p/ruUUotButZb+WlGW5qQOJEJnHi65ABGYchAADAOBflXK +XbklHb6sVmEx6Ds4OMAbEmgH4C7BZuvmVeYMY7ihGIuBF3rE70rc2meQl/fxn0Gd ++/FrHDqCSkXwNT69HEOoLT/hi6Pc3kyn1bFOK+W8AydilI+6yOKkiYTSoCAO/yi/ +xlFXnn9FIQthAEWUhFgqApO+oKBn0hw= +-----END PRIVATE KEY----- +`, + 'server.crt': `-----BEGIN CERTIFICATE----- +MIIFCTCCAvGgAwIBAgIUd0CiuFYYUTnnfB/Q6lijpEZJy4wwDQYJKoZIhvcNAQEL +BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI1MTEwNzEwMTE0NFoXDTI2MTEw +NzEwMTE0NFowFDESMBAGA1UEAwwJbG9jYWxob3N0MIICIjANBgkqhkiG9w0BAQEF +AAOCAg8AMIICCgKCAgEAzsgZlcutcxKn7KEz0PYE19t9/55a1V7WlBiZGw0eWnLa +tF/l0LWbiKDuCYEaYmM+f/F4mPAImjHbd9Gm7oDuQIciG7BskMb89rIu8ikPllHR +fw0U6X06u+hPBF0fFvQSPg06Rv9ZzRgXdZaTGvDTHx6i74baXmx7gXG9QQkXpcvh +SCx1Qxn/nXwiL0dGb7fAId6iy+r7196cxajPV6131IFiqqW8/i9QXgjyC7B/lGjj +gs828qy6GOn52sI1JHP4nh1snK6O3QVJbiSf5HBraT2A/4bDBXF8+g+u6myBbnOg +8/Qq1iGoABTKivdRQLVKcnz+/oy4pEDkk6RQy4CfpJQAxgomegv3b41LGDPuDC/X +V+kPa4+rEKP6I9A7HY9/SeZlZpJZG0T+aoXjBk8nNPf2pm4mBX81hDDJxHAk/wkv +69avd6EQxtNgsehdQdOZrUfvwBcQCelMS9rt6DD1WNe/RVo8dvmL2363TaxZ1m/H +kTIkWSFvDvKbSpK4fiy9UYXqflv9TcXa6YOxNq1j/AFq95nXfnJ2rrxf9sjHnAQy +1Z5Nzjko3Li3PovZ4Dg9MR3XEXzvPZq8oyHsBCK1EOFNGYMhzIvfaleMMl4XfR80 +1IE9NUKH7IrhfcclX52p7EDo96KjoAkvdlRHqmZy14GlaIf/vvxVe6+Auc8S8y8C +AwEAAaNTMFEwHQYDVR0OBBYEFCOiC0xvMbfCFzmseoMDht+ydKBbMB8GA1UdIwQY +MBaAFCOiC0xvMbfCFzmseoMDht+ydKBbMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZI +hvcNAQELBQADggIBAJSiQwcaGVhwUorkb062cyyZOAstEJ5meg6H2g3nL894oWEU +FLc/S20z2tqO1It4rZB3cRKmB0RvH78eh4aUPAh0lPa/bm/h7WrgdEAJUmlNuZV3 +Hitd/c1d2OVzx6w+CFYd/G5GW3sWblYiH0paIN6s4TqHFY/IAzzZKQB7Ud7FJagM +KMkEP8RFDm7iRcENuSf51LtZb2NjN1TM5CK5sVXu62dvPYZC6SW052/qd1U+1Tyw +EX4fCqUgEoGoU6+Ftz3hCdVy3E4uzFBK1e5wmct6HULBZL51PWpf3BgwneZy0itE +lD6Y0H6m/9KMVcXpAHZK+6YnOOcWxIgfjykjZEO99rx3pVWPw1uSBUJEu1SLknAn +JDe+WLp+xmB8s62EjixZsEGqoQYYrtZ3vz8u4PSSgYPJjdAkFdLOPitf0U8ZW9/7 +hGyHgqd7WQ3toBwwdnPo6fZqHHyN8rXeWcmx8Uj9oyY1uunkSmq3csITPQg/zKBO +6RsO3pPj8mHjeAZCDs+Ks68ccPsn+53fJ9CrjiJlHFIP0ywbEBO1snJDit5q3gQI +/UpClB9Sl+mz4wznOvrKycrxrLEptZeBA5c6M9Qr30YJAb/prxvzSY5FrUGcstkO +CQVzSwZEUXxSo6K4cJ55vC0p3P3aoMvEpHfM+JqL3lCM9qWrxfkhvn8YS+Gg +-----END CERTIFICATE----- +`, + }); + + const sslPortForCerts = await ngServe('--ssl', '--ssl-cert=server.crt', '--ssl-key="server.key"'); + assert.match( + await ( + await fetch(`https://localhost:${sslPortForCerts}/`, { + dispatcher: new Agent({ + connect: { + rejectUnauthorized: false, + }, + }), + }) + ).text(), + match, + ); +} diff --git a/tests/legacy-cli/e2e/tests/commands/unknown-configuration.ts b/tests/e2e/tests/commands/unknown-configuration.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/unknown-configuration.ts rename to tests/e2e/tests/commands/unknown-configuration.ts diff --git a/tests/legacy-cli/e2e/tests/commands/unknown-option.ts b/tests/e2e/tests/commands/unknown-option.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/commands/unknown-option.ts rename to tests/e2e/tests/commands/unknown-option.ts diff --git a/tests/e2e/tests/generate/application/application-no-zoneless-ng-module.ts b/tests/e2e/tests/generate/application/application-no-zoneless-ng-module.ts new file mode 100644 index 000000000000..b475ed03b3a7 --- /dev/null +++ b/tests/e2e/tests/generate/application/application-no-zoneless-ng-module.ts @@ -0,0 +1,16 @@ +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { useCIChrome, useSha } from '../../../utils/project'; + +export default async function () { + try { + await ng('generate', 'app', 'ngmodules', '--no-standalone', '--skip-install', '--no-zoneless'); + await useSha(); + await installWorkspacePackages(); + await useCIChrome('ngmodules', 'projects/ngmodules'); + await ng('test', 'ngmodules', '--watch=false'); + await ng('build', 'ngmodules'); + } finally { + await uninstallPackage('zone.js'); + } +} diff --git a/tests/e2e/tests/generate/application/application-no-zoneless-standalone.ts b/tests/e2e/tests/generate/application/application-no-zoneless-standalone.ts new file mode 100644 index 000000000000..065957f9fe11 --- /dev/null +++ b/tests/e2e/tests/generate/application/application-no-zoneless-standalone.ts @@ -0,0 +1,16 @@ +import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { useCIChrome, useSha } from '../../../utils/project'; + +export default async function () { + try { + await ng('generate', 'app', 'standalone', '--standalone', '--skip-install', '--no-zoneless'); + await useSha(); + await installWorkspacePackages(); + await useCIChrome('standalone', 'projects/standalone'); + await ng('test', 'standalone', '--watch=false'); + await ng('build', 'standalone'); + } finally { + await uninstallPackage('zone.js'); + } +} diff --git a/tests/e2e/tests/generate/application/application-zoneless-ng-module.ts b/tests/e2e/tests/generate/application/application-zoneless-ng-module.ts new file mode 100644 index 000000000000..5ad207a2fa76 --- /dev/null +++ b/tests/e2e/tests/generate/application/application-zoneless-ng-module.ts @@ -0,0 +1,12 @@ +import { installWorkspacePackages } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { useCIChrome, useSha } from '../../../utils/project'; + +export default async function () { + await ng('generate', 'app', 'ngmodules', '--no-standalone', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + await useCIChrome('ngmodules', 'projects/ngmodules'); + await ng('test', 'ngmodules', '--watch=false'); + await ng('build', 'ngmodules'); +} diff --git a/tests/e2e/tests/generate/application/application-zoneless-standalone.ts b/tests/e2e/tests/generate/application/application-zoneless-standalone.ts new file mode 100644 index 000000000000..b203ed4a28d0 --- /dev/null +++ b/tests/e2e/tests/generate/application/application-zoneless-standalone.ts @@ -0,0 +1,12 @@ +import { installWorkspacePackages } from '../../../utils/packages'; +import { ng } from '../../../utils/process'; +import { useCIChrome, useSha } from '../../../utils/project'; + +export default async function () { + await ng('generate', 'app', 'standalone', '--standalone', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + await useCIChrome('standalone', 'projects/standalone'); + await ng('test', 'standalone', '--watch=false'); + await ng('build', 'standalone'); +} diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-basic.ts b/tests/e2e/tests/generate/component/component-basic.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/component/component-basic.ts rename to tests/e2e/tests/generate/component/component-basic.ts diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-child-dir.ts b/tests/e2e/tests/generate/component/component-child-dir.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/component/component-child-dir.ts rename to tests/e2e/tests/generate/component/component-child-dir.ts diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-flat.ts b/tests/e2e/tests/generate/component/component-flat.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/component/component-flat.ts rename to tests/e2e/tests/generate/component/component-flat.ts diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-inline-template.ts b/tests/e2e/tests/generate/component/component-inline-template.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/component/component-inline-template.ts rename to tests/e2e/tests/generate/component/component-inline-template.ts diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-not-flat.ts b/tests/e2e/tests/generate/component/component-not-flat.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/component/component-not-flat.ts rename to tests/e2e/tests/generate/component/component-not-flat.ts diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-path-case.ts b/tests/e2e/tests/generate/component/component-path-case.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/component/component-path-case.ts rename to tests/e2e/tests/generate/component/component-path-case.ts diff --git a/tests/legacy-cli/e2e/tests/generate/component/component-prefix.ts b/tests/e2e/tests/generate/component/component-prefix.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/component/component-prefix.ts rename to tests/e2e/tests/generate/component/component-prefix.ts diff --git a/tests/legacy-cli/e2e/tests/generate/config/type-browserslist.ts b/tests/e2e/tests/generate/config/type-browserslist.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/config/type-browserslist.ts rename to tests/e2e/tests/generate/config/type-browserslist.ts diff --git a/tests/legacy-cli/e2e/tests/generate/config/type-karma.ts b/tests/e2e/tests/generate/config/type-karma.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/config/type-karma.ts rename to tests/e2e/tests/generate/config/type-karma.ts diff --git a/tests/legacy-cli/e2e/tests/generate/directive/directive-basic.ts b/tests/e2e/tests/generate/directive/directive-basic.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/directive/directive-basic.ts rename to tests/e2e/tests/generate/directive/directive-basic.ts diff --git a/tests/legacy-cli/e2e/tests/generate/directive/directive-prefix.ts b/tests/e2e/tests/generate/directive/directive-prefix.ts similarity index 93% rename from tests/legacy-cli/e2e/tests/generate/directive/directive-prefix.ts rename to tests/e2e/tests/generate/directive/directive-prefix.ts index b0a95ce399cb..a8b5981b34a3 100644 --- a/tests/legacy-cli/e2e/tests/generate/directive/directive-prefix.ts +++ b/tests/e2e/tests/generate/directive/directive-prefix.ts @@ -17,7 +17,9 @@ export default function () { ) .then(() => ng('generate', 'directive', 'test2-directive')) .then(() => expectFileToMatch(join(directiveDir, 'test2-directive.ts'), /selector: '\[preW/)) - .then(() => ng('generate', 'application', 'app-two', '--skip-install')) + .then(() => + ng('generate', 'application', 'app-two', '--skip-install', '--test-runner', 'karma'), + ) .then(() => useCIDefaults('app-two')) .then(() => useCIChrome('app-two', './projects/app-two')) .then(() => diff --git a/tests/legacy-cli/e2e/tests/generate/generate-error.ts b/tests/e2e/tests/generate/generate-error.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/generate-error.ts rename to tests/e2e/tests/generate/generate-error.ts diff --git a/tests/legacy-cli/e2e/tests/generate/generate-name-check.ts b/tests/e2e/tests/generate/generate-name-check.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/generate-name-check.ts rename to tests/e2e/tests/generate/generate-name-check.ts diff --git a/tests/legacy-cli/e2e/tests/generate/guard/guard-basic.ts b/tests/e2e/tests/generate/guard/guard-basic.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/guard/guard-basic.ts rename to tests/e2e/tests/generate/guard/guard-basic.ts diff --git a/tests/legacy-cli/e2e/tests/generate/guard/guard-implements.ts b/tests/e2e/tests/generate/guard/guard-implements.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/guard/guard-implements.ts rename to tests/e2e/tests/generate/guard/guard-implements.ts diff --git a/tests/legacy-cli/e2e/tests/generate/guard/guard-multiple-implements.ts b/tests/e2e/tests/generate/guard/guard-multiple-implements.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/guard/guard-multiple-implements.ts rename to tests/e2e/tests/generate/guard/guard-multiple-implements.ts diff --git a/tests/legacy-cli/e2e/tests/generate/help-output-no-duplicates.ts b/tests/e2e/tests/generate/help-output-no-duplicates.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/help-output-no-duplicates.ts rename to tests/e2e/tests/generate/help-output-no-duplicates.ts diff --git a/tests/legacy-cli/e2e/tests/generate/help-output.ts b/tests/e2e/tests/generate/help-output.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/help-output.ts rename to tests/e2e/tests/generate/help-output.ts diff --git a/tests/legacy-cli/e2e/tests/generate/install-allow-scripts.ts b/tests/e2e/tests/generate/install-allow-scripts.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/install-allow-scripts.ts rename to tests/e2e/tests/generate/install-allow-scripts.ts diff --git a/tests/legacy-cli/e2e/tests/generate/interceptor/interceptor-basic.ts b/tests/e2e/tests/generate/interceptor/interceptor-basic.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/interceptor/interceptor-basic.ts rename to tests/e2e/tests/generate/interceptor/interceptor-basic.ts diff --git a/tests/legacy-cli/e2e/tests/generate/library/library-basic.ts b/tests/e2e/tests/generate/library/library-basic.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/library/library-basic.ts rename to tests/e2e/tests/generate/library/library-basic.ts diff --git a/tests/legacy-cli/e2e/tests/generate/library/library-standalone.ts b/tests/e2e/tests/generate/library/library-standalone.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/library/library-standalone.ts rename to tests/e2e/tests/generate/library/library-standalone.ts diff --git a/tests/legacy-cli/e2e/tests/generate/module/module-basic.ts b/tests/e2e/tests/generate/module/module-basic.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/module/module-basic.ts rename to tests/e2e/tests/generate/module/module-basic.ts diff --git a/tests/legacy-cli/e2e/tests/generate/module/module-import.ts b/tests/e2e/tests/generate/module/module-import.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/module/module-import.ts rename to tests/e2e/tests/generate/module/module-import.ts diff --git a/tests/legacy-cli/e2e/tests/generate/module/module-routing-child-folder.ts b/tests/e2e/tests/generate/module/module-routing-child-folder.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/module/module-routing-child-folder.ts rename to tests/e2e/tests/generate/module/module-routing-child-folder.ts diff --git a/tests/legacy-cli/e2e/tests/generate/pipe/pipe-basic.ts b/tests/e2e/tests/generate/pipe/pipe-basic.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/pipe/pipe-basic.ts rename to tests/e2e/tests/generate/pipe/pipe-basic.ts diff --git a/tests/legacy-cli/e2e/tests/generate/schematic-aliases.ts b/tests/e2e/tests/generate/schematic-aliases.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/schematic-aliases.ts rename to tests/e2e/tests/generate/schematic-aliases.ts diff --git a/tests/legacy-cli/e2e/tests/generate/schematic-defaults.ts b/tests/e2e/tests/generate/schematic-defaults.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/schematic-defaults.ts rename to tests/e2e/tests/generate/schematic-defaults.ts diff --git a/tests/e2e/tests/generate/schematic-force-override.ts b/tests/e2e/tests/generate/schematic-force-override.ts new file mode 100644 index 000000000000..d3e9e1b7d947 --- /dev/null +++ b/tests/e2e/tests/generate/schematic-force-override.ts @@ -0,0 +1,51 @@ +import { appendFile } from 'node:fs/promises'; +import { getGlobalVariable } from '../../utils/env'; +import { getActivePackageManager, installWorkspacePackages } from '../../utils/packages'; +import { ng } from '../../utils/process'; +import { isPrereleaseCli, updateJsonFile } from '../../utils/project'; +import { expectToFail } from '../../utils/utils'; + +const snapshots = require('../../ng-snapshot/package.json'); + +export default async function () { + const isPrerelease = await isPrereleaseCli(); + let tag = isPrerelease ? '@next' : ''; + if (getActivePackageManager() === 'npm') { + await appendFile('.npmrc', '\nlegacy-peer-deps=true'); + } + + await ng('add', `@angular/material${tag}`, '--skip-confirmation'); + + const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; + if (isSnapshotBuild) { + await updateJsonFile('package.json', (packageJson) => { + const dependencies = packageJson['dependencies']; + // Angular material adds dependencies on other Angular packages + // Iterate over all of the packages to update them to the snapshot version. + for (const [name, version] of Object.entries(snapshots.dependencies)) { + if (name in dependencies) { + dependencies[name] = version; + } + } + }); + await installWorkspacePackages(); + } + + const args: string[] = [ + 'generate', + '@angular/material:theme-color', + '--primary-color=#0641e6', + '--tertiary-color=#994aff', + '--neutral-color=#313138', + '--error-color=#eb5757', + '--secondary-color=#009096', + '--neutral-variant-color=#b2b2b8', + ]; + + await ng(...args); + + // Should fail as file exists + await expectToFail(() => ng(...args)); + + await ng(...args, '--force'); +} diff --git a/tests/legacy-cli/e2e/tests/generate/schematics-collections-relative.ts b/tests/e2e/tests/generate/schematics-collections-relative.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/schematics-collections-relative.ts rename to tests/e2e/tests/generate/schematics-collections-relative.ts diff --git a/tests/legacy-cli/e2e/tests/generate/schematics-collections.ts b/tests/e2e/tests/generate/schematics-collections.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/schematics-collections.ts rename to tests/e2e/tests/generate/schematics-collections.ts diff --git a/tests/legacy-cli/e2e/tests/generate/service/service-basic.ts b/tests/e2e/tests/generate/service/service-basic.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/generate/service/service-basic.ts rename to tests/e2e/tests/generate/service/service-basic.ts diff --git a/tests/legacy-cli/e2e/tests/i18n/extract-ivy-disk-cache.ts b/tests/e2e/tests/i18n/extract-ivy-disk-cache.ts similarity index 98% rename from tests/legacy-cli/e2e/tests/i18n/extract-ivy-disk-cache.ts rename to tests/e2e/tests/i18n/extract-ivy-disk-cache.ts index e5a13de3c439..562a481086d5 100644 --- a/tests/legacy-cli/e2e/tests/i18n/extract-ivy-disk-cache.ts +++ b/tests/e2e/tests/i18n/extract-ivy-disk-cache.ts @@ -24,7 +24,6 @@ export default async function () { import { I18nTest } from './i18n-test/i18n-test'; @Component({ - standalone: true, selector: 'app-root', imports: [I18nTest], template: '' diff --git a/tests/legacy-cli/e2e/tests/i18n/extract-ivy-libraries.ts b/tests/e2e/tests/i18n/extract-ivy-libraries.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/i18n/extract-ivy-libraries.ts rename to tests/e2e/tests/i18n/extract-ivy-libraries.ts diff --git a/tests/legacy-cli/e2e/tests/i18n/extract-ivy.ts b/tests/e2e/tests/i18n/extract-ivy.ts similarity index 98% rename from tests/legacy-cli/e2e/tests/i18n/extract-ivy.ts rename to tests/e2e/tests/i18n/extract-ivy.ts index 72af7f87e712..382051e83cce 100644 --- a/tests/legacy-cli/e2e/tests/i18n/extract-ivy.ts +++ b/tests/e2e/tests/i18n/extract-ivy.ts @@ -18,7 +18,6 @@ export default async function () { import { I18nTest } from './i18n-test/i18n-test'; @Component({ - standalone: true, selector: 'app-root', imports: [I18nTest], template: '' diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell-service-worker.ts b/tests/e2e/tests/i18n/ivy-localize-app-shell-service-worker.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell-service-worker.ts rename to tests/e2e/tests/i18n/ivy-localize-app-shell-service-worker.ts diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell.ts b/tests/e2e/tests/i18n/ivy-localize-app-shell.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell.ts rename to tests/e2e/tests/i18n/ivy-localize-app-shell.ts diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-basehref-absolute.ts b/tests/e2e/tests/i18n/ivy-localize-basehref-absolute.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/i18n/ivy-localize-basehref-absolute.ts rename to tests/e2e/tests/i18n/ivy-localize-basehref-absolute.ts diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-basehref.ts b/tests/e2e/tests/i18n/ivy-localize-basehref.ts similarity index 77% rename from tests/legacy-cli/e2e/tests/i18n/ivy-localize-basehref.ts rename to tests/e2e/tests/i18n/ivy-localize-basehref.ts index d14c14307ab1..4bbd7dece3ee 100644 --- a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-basehref.ts +++ b/tests/e2e/tests/i18n/ivy-localize-basehref.ts @@ -9,7 +9,14 @@ import { expectFileToMatch } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; -import { baseHrefs, externalServer, langTranslations, setupI18nConfig } from './setup'; +import { executeBrowserTest } from '../../utils/puppeteer'; +import { + baseHrefs, + browserCheck, + externalServer, + langTranslations, + setupI18nConfig, +} from './setup'; export default async function () { // Setup i18n tests and config. @@ -50,18 +57,12 @@ export default async function () { await expectFileToMatch(`${outputPath}/index.html`, `href="${baseHrefs[lang] || '/'}"`); // Execute Application E2E tests for a production build without dev server - const { server, port, url } = await externalServer( - outputPath, - (baseHrefs[lang] as string) || '/', - ); + const { server, url } = await externalServer(outputPath, (baseHrefs[lang] as string) || '/'); try { - await ng( - 'e2e', - `--port=${port}`, - `--configuration=${lang}`, - '--dev-server-target=', - `--base-url=${url}`, - ); + await executeBrowserTest({ + baseUrl: url, + checkFn: (page) => browserCheck(page, lang), + }); } finally { server.close(); } @@ -81,18 +82,12 @@ export default async function () { await expectFileToMatch(`${outputPath}/index.html`, `href="/test${baseHrefs[lang] || '/'}"`); // Execute Application E2E tests for a production build without dev server - const { server, port, url } = await externalServer( - outputPath, - '/test' + (baseHrefs[lang] || '/'), - ); + const { server, url } = await externalServer(outputPath, '/test' + (baseHrefs[lang] || '/')); try { - await ng( - 'e2e', - `--port=${port}`, - `--configuration=${lang}`, - '--dev-server-target=', - `--base-url=${url}`, - ); + await executeBrowserTest({ + baseUrl: url, + checkFn: (page) => browserCheck(page, lang), + }); } finally { server.close(); } diff --git a/tests/e2e/tests/i18n/ivy-localize-es2015-e2e.ts b/tests/e2e/tests/i18n/ivy-localize-es2015-e2e.ts new file mode 100644 index 000000000000..d1f7ac8e28b8 --- /dev/null +++ b/tests/e2e/tests/i18n/ivy-localize-es2015-e2e.ts @@ -0,0 +1,14 @@ +import { executeBrowserTest } from '../../utils/puppeteer'; +import { browserCheck, langTranslations, setupI18nConfig } from './setup'; + +export default async function () { + // Setup i18n tests and config. + await setupI18nConfig(); + + for (const { lang } of langTranslations) { + await executeBrowserTest({ + configuration: lang, + checkFn: (page) => browserCheck(page, lang), + }); + } +} diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es2015.ts b/tests/e2e/tests/i18n/ivy-localize-es2015.ts similarity index 80% rename from tests/legacy-cli/e2e/tests/i18n/ivy-localize-es2015.ts rename to tests/e2e/tests/i18n/ivy-localize-es2015.ts index b8425795cab4..cea87a75f2b8 100644 --- a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es2015.ts +++ b/tests/e2e/tests/i18n/ivy-localize-es2015.ts @@ -1,8 +1,9 @@ import { getGlobalVariable } from '../../utils/env'; import { expectFileToMatch } from '../../utils/fs'; import { ng } from '../../utils/process'; +import { executeBrowserTest } from '../../utils/puppeteer'; import { expectToFail } from '../../utils/utils'; -import { externalServer, langTranslations, setupI18nConfig } from './setup'; +import { browserCheck, externalServer, langTranslations, setupI18nConfig } from './setup'; export default async function () { // Setup i18n tests and config. @@ -32,15 +33,12 @@ export default async function () { await expectFileToMatch(`${outputPath}/index.html`, `lang="${lang}"`); // Execute Application E2E tests for a production build without dev server - const { server, port, url } = await externalServer(outputPath, `/${lang}/`); + const { server, url } = await externalServer(outputPath, `/${lang}/`); try { - await ng( - 'e2e', - `--port=${port}`, - `--configuration=${lang}`, - '--dev-server-target=', - `--base-url=${url}`, - ); + await executeBrowserTest({ + baseUrl: url, + checkFn: (page) => browserCheck(page, lang), + }); } finally { server.close(); } diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-hashes.ts b/tests/e2e/tests/i18n/ivy-localize-hashes.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/i18n/ivy-localize-hashes.ts rename to tests/e2e/tests/i18n/ivy-localize-hashes.ts diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-locale-data-augment.ts b/tests/e2e/tests/i18n/ivy-localize-locale-data-augment.ts similarity index 57% rename from tests/legacy-cli/e2e/tests/i18n/ivy-localize-locale-data-augment.ts rename to tests/e2e/tests/i18n/ivy-localize-locale-data-augment.ts index e2c408a74c69..b4c0ae72ced4 100644 --- a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-locale-data-augment.ts +++ b/tests/e2e/tests/i18n/ivy-localize-locale-data-augment.ts @@ -1,14 +1,9 @@ import { getGlobalVariable } from '../../utils/env'; -import { - expectFileToMatch, - prependToFile, - readFile, - replaceInFile, - writeFile, -} from '../../utils/fs'; +import { expectFileToMatch, prependToFile, readFile, writeFile } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; -import { langTranslations, setupI18nConfig } from './setup'; +import { executeBrowserTest } from '../../utils/puppeteer'; +import { browserCheck, langTranslations, setupI18nConfig } from './setup'; export default async function () { // Setup i18n tests and config. @@ -20,9 +15,6 @@ export default async function () { appProject.architect['build'].options.localize = ['fr']; }); - // Update E2E test to look for augmented locale data - await replaceInFile('./e2e/src/app.fr.e2e-spec.ts', 'janvier', 'changed-janvier'); - // Augment the locale data and import into the main application file const localeData = await readFile('node_modules/@angular/common/locales/global/fr.js'); await writeFile('src/fr-changed.js', localeData.replace('janvier', 'changed-janvier')); @@ -45,6 +37,27 @@ export default async function () { } // Execute Application E2E tests with dev server - await ng('e2e', `--configuration=${lang}`, '--port=0'); + await executeBrowserTest({ + configuration: lang, + checkFn: async (page) => { + // Run standard checks but expect failure on date + try { + await browserCheck(page, lang); + throw new Error('Expected browserCheck to fail due to modified locale data'); + } catch (e) { + if (!(e instanceof Error) || !e.message.includes("Expected 'date' to be")) { + throw e; + } + } + + // Verify the modified date + const getParagraph = async (id: string) => + page.$eval(`p#${id}`, (el) => el.textContent?.trim()); + const date = await getParagraph('date'); + if (date !== 'changed-janvier') { + throw new Error(`Expected 'date' to be 'changed-janvier', but got '${date}'.`); + } + }, + }); } } diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-locale-data.ts b/tests/e2e/tests/i18n/ivy-localize-locale-data.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/i18n/ivy-localize-locale-data.ts rename to tests/e2e/tests/i18n/ivy-localize-locale-data.ts diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-merging.ts b/tests/e2e/tests/i18n/ivy-localize-merging.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/i18n/ivy-localize-merging.ts rename to tests/e2e/tests/i18n/ivy-localize-merging.ts diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-sourcelocale.ts b/tests/e2e/tests/i18n/ivy-localize-sourcelocale.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/i18n/ivy-localize-sourcelocale.ts rename to tests/e2e/tests/i18n/ivy-localize-sourcelocale.ts diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-sourcemaps.ts b/tests/e2e/tests/i18n/ivy-localize-sourcemaps.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/i18n/ivy-localize-sourcemaps.ts rename to tests/e2e/tests/i18n/ivy-localize-sourcemaps.ts diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-ssr.ts b/tests/e2e/tests/i18n/ivy-localize-ssr.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/i18n/ivy-localize-ssr.ts rename to tests/e2e/tests/i18n/ivy-localize-ssr.ts diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-sub-path.ts b/tests/e2e/tests/i18n/ivy-localize-sub-path.ts similarity index 83% rename from tests/legacy-cli/e2e/tests/i18n/ivy-localize-sub-path.ts rename to tests/e2e/tests/i18n/ivy-localize-sub-path.ts index d6640534c45f..6116c438a49f 100644 --- a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-sub-path.ts +++ b/tests/e2e/tests/i18n/ivy-localize-sub-path.ts @@ -10,7 +10,8 @@ import { join } from 'node:path'; import { expectFileToMatch } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; -import { baseDir, baseHrefs, externalServer, langTranslations, setupI18nConfig } from './setup'; +import { executeBrowserTest } from '../../utils/puppeteer'; +import { baseDir, browserCheck, externalServer, langTranslations, setupI18nConfig } from './setup'; export default async function () { // Setup i18n tests and config. @@ -56,16 +57,13 @@ export default async function () { await expectFileToMatch(`${outputPath}/index.html`, `href="${baseHref}"`); // Execute Application E2E tests for a production build without dev server - const { server, port, url } = await externalServer(outputPath, baseHref); + const { server, url } = await externalServer(outputPath, baseHref); try { - await ng( - 'e2e', - `--port=${port}`, - `--configuration=${lang}`, - '--dev-server-target=', - `--base-url=${url}`, - ); + await executeBrowserTest({ + baseUrl: url, + checkFn: (page) => browserCheck(page, lang), + }); } finally { server.close(); } diff --git a/tests/legacy-cli/e2e/tests/i18n/setup.ts b/tests/e2e/tests/i18n/setup.ts similarity index 84% rename from tests/legacy-cli/e2e/tests/i18n/setup.ts rename to tests/e2e/tests/i18n/setup.ts index 30fdcee1d757..8eade4e2783c 100644 --- a/tests/legacy-cli/e2e/tests/i18n/setup.ts +++ b/tests/e2e/tests/i18n/setup.ts @@ -7,6 +7,7 @@ import { updateJsonFile } from '../../utils/project'; import { readNgVersion } from '../../utils/version'; import { Server } from 'node:http'; import { AddressInfo } from 'node:net'; +import type { Page } from 'puppeteer'; // Configurations for each locale. const translationFile = 'src/locale/messages.xlf'; @@ -61,6 +62,35 @@ export const langTranslations = [ ]; export const sourceLocale = langTranslations[0].lang; +export async function browserCheck(page: Page, lang: string) { + const translation = langTranslations.find((t) => t.lang === lang)?.translation; + if (!translation) { + throw new Error(`Could not find translation for language '${lang}'`); + } + + const getParagraph = async (id: string) => page.$eval(`p#${id}`, (el) => el.textContent?.trim()); + + const hello = await getParagraph('hello'); + if (hello !== translation.hello) { + throw new Error(`Expected 'hello' to be '${translation.hello}', but got '${hello}'.`); + } + + const locale = await getParagraph('locale'); + if (locale !== lang) { + throw new Error(`Expected 'locale' to be '${lang}', but got '${locale}'.`); + } + + const date = await getParagraph('date'); + if (date !== translation.date) { + throw new Error(`Expected 'date' to be '${translation.date}', but got '${date}'.`); + } + + const plural = await getParagraph('plural'); + if (plural !== translation.plural) { + throw new Error(`Expected 'plural' to be '${translation.plural}', but got '${plural}'.`); + } +} + export interface ExternalServer { readonly server: Server; readonly port: number; @@ -107,7 +137,6 @@ export async function setupI18nConfig() { @Component({ selector: 'app-root', imports: [DatePipe, RouterOutlet], - standalone: true, templateUrl: './app.html' }) export class App { @@ -174,47 +203,12 @@ export async function setupI18nConfig() { `, ); - // Add e2e specs for each lang. - for (const { lang, translation } of langTranslations) { - await writeFile( - `./e2e/src/app.${lang}.e2e-spec.ts`, - ` - import { browser, logging, element, by } from 'protractor'; - - describe('workspace-project App', () => { - const getParagraph = async (name: string) => element(by.css('app-root p#' + name)).getText(); - beforeEach(() => browser.get(browser.baseUrl)); - afterEach(async () => { - // Assert that there are no errors emitted from the browser - const logs = await browser.manage().logs().get(logging.Type.BROWSER); - expect(logs).not.toContain(jasmine.objectContaining({ - level: logging.Level.SEVERE, - } as logging.Entry)); - }); - - it('should display welcome message', async () => - expect(await getParagraph('hello')).toEqual('${translation.hello}')); - - it('should display locale', async () => - expect(await getParagraph('locale')).toEqual('${lang}')); - - it('should display localized date', async () => - expect(await getParagraph('date')).toEqual('${translation.date}')); - - it('should display pluralized message', async () => - expect(await getParagraph('plural')).toEqual('${translation.plural}')); - }); - `, - ); - } - // Update angular.json to build, serve, and test each locale. await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; const appArchitect = workspaceJson.projects['test-project'].architect; const buildConfigs = appArchitect['build'].configurations; const serveConfigs = appArchitect['serve'].configurations; - const e2eConfigs = appArchitect['e2e'].configurations; appArchitect['build'].defaultConfiguration = undefined; @@ -246,10 +240,6 @@ export async function setupI18nConfig() { buildConfigs[lang] = { localize: [lang] }; serveConfigs[lang] = { buildTarget: `test-project:build:${lang}` }; - e2eConfigs[lang] = { - specs: [`./src/app.${lang}.e2e-spec.ts`], - devServerTarget: `test-project:serve:${lang}`, - }; } }); diff --git a/tests/legacy-cli/e2e/tests/jest/aot.ts b/tests/e2e/tests/jest/aot.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/jest/aot.ts rename to tests/e2e/tests/jest/aot.ts diff --git a/tests/legacy-cli/e2e/tests/jest/basic.ts b/tests/e2e/tests/jest/basic.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/jest/basic.ts rename to tests/e2e/tests/jest/basic.ts diff --git a/tests/legacy-cli/e2e/tests/jest/custom-config.ts b/tests/e2e/tests/jest/custom-config.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/jest/custom-config.ts rename to tests/e2e/tests/jest/custom-config.ts diff --git a/tests/e2e/tests/jest/no-zoneless.ts b/tests/e2e/tests/jest/no-zoneless.ts new file mode 100644 index 000000000000..9a74a0295c4e --- /dev/null +++ b/tests/e2e/tests/jest/no-zoneless.ts @@ -0,0 +1,29 @@ +import { replaceInFile } from '../../utils/fs'; +import { applyJestBuilder } from '../../utils/jest'; +import { installPackage, uninstallPackage } from '../../utils/packages'; +import { ng } from '../../utils/process'; + +export default async function (): Promise { + await applyJestBuilder({ + tsConfig: 'tsconfig.spec.json', + polyfills: ['zone.js', 'zone.js/testing'], + }); + + await replaceInFile( + 'src/app/app.spec.ts', + 'await fixture.whenStable();', + 'fixture.detectChanges();', + ); + + try { + await installPackage('zone.js'); + + const { stderr } = await ng('test'); + + if (!stderr.includes('Jest builder is currently EXPERIMENTAL')) { + throw new Error(`No experimental notice in stderr.\nSTDERR:\n\n${stderr}`); + } + } finally { + await uninstallPackage('zone.js'); + } +} diff --git a/tests/e2e/tests/mcp/ai-tutor.ts b/tests/e2e/tests/mcp/ai-tutor.ts new file mode 100644 index 000000000000..220b32fcc202 --- /dev/null +++ b/tests/e2e/tests/mcp/ai-tutor.ts @@ -0,0 +1,40 @@ +import { chdir } from 'node:process'; +import { exec, ProcessOutput, silentNpm } from '../../utils/process'; +import assert from 'node:assert/strict'; + +const MCP_INSPECTOR_PACKAGE_NAME = '@modelcontextprotocol/inspector-cli'; +const MCP_INSPECTOR_PACKAGE_VERSION = '0.16.2'; +const MCP_INSPECTOR_COMMAND_NAME = 'mcp-inspector-cli'; + +async function runInspector(...args: string[]): Promise { + const result = await exec( + MCP_INSPECTOR_COMMAND_NAME, + '--cli', + 'npx', + '--no', + '@angular/cli', + 'mcp', + ...args, + ); + + return result; +} + +export default async function () { + await silentNpm( + 'install', + '--ignore-scripts', + '-g', + `${MCP_INSPECTOR_PACKAGE_NAME}@${MCP_INSPECTOR_PACKAGE_VERSION}`, + ); + + // Ensure `get_best_practices` returns the markdown content + const { stdout: stdoutInsideWorkspace } = await runInspector( + '--method', + 'tools/call', + '--tool-name', + 'ai_tutor', + ); + + assert.match(stdoutInsideWorkspace, /# `airules.md` - Modern Angular Tutor 🧑‍🏫/); +} diff --git a/tests/e2e/tests/mcp/best-practices.ts b/tests/e2e/tests/mcp/best-practices.ts new file mode 100644 index 000000000000..55736c63795b --- /dev/null +++ b/tests/e2e/tests/mcp/best-practices.ts @@ -0,0 +1,43 @@ +import { chdir } from 'node:process'; +import { exec, ProcessOutput, silentNpm } from '../../utils/process'; +import assert from 'node:assert/strict'; + +const MCP_INSPECTOR_PACKAGE_NAME = '@modelcontextprotocol/inspector-cli'; +const MCP_INSPECTOR_PACKAGE_VERSION = '0.16.2'; +const MCP_INSPECTOR_COMMAND_NAME = 'mcp-inspector-cli'; + +async function runInspector(...args: string[]): Promise { + const result = await exec( + MCP_INSPECTOR_COMMAND_NAME, + '--cli', + 'npx', + '--no', + '@angular/cli', + 'mcp', + ...args, + ); + + return result; +} + +export default async function () { + await silentNpm( + 'install', + '--ignore-scripts', + '-g', + `${MCP_INSPECTOR_PACKAGE_NAME}@${MCP_INSPECTOR_PACKAGE_VERSION}`, + ); + + // Ensure `get_best_practices` returns the markdown content + const { stdout: stdoutInsideWorkspace } = await runInspector( + '--method', + 'tools/call', + '--tool-name', + 'get_best_practices', + ); + + assert.match( + stdoutInsideWorkspace, + /You are an expert in TypeScript, Angular, and scalable web application development./, + ); +} diff --git a/tests/e2e/tests/mcp/find-examples-basic.ts b/tests/e2e/tests/mcp/find-examples-basic.ts new file mode 100644 index 000000000000..b7f42045076c --- /dev/null +++ b/tests/e2e/tests/mcp/find-examples-basic.ts @@ -0,0 +1,48 @@ +import { exec, ProcessOutput, silentNpm } from '../../utils/process'; +import assert from 'node:assert/strict'; + +const MCP_INSPECTOR_PACKAGE_NAME = '@modelcontextprotocol/inspector-cli'; +const MCP_INSPECTOR_PACKAGE_VERSION = '0.16.2'; +const MCP_INSPECTOR_COMMAND_NAME = 'mcp-inspector-cli'; + +async function runInspector(...args: string[]): Promise { + const result = await exec( + MCP_INSPECTOR_COMMAND_NAME, + '--cli', + 'npx', + '--no', + '@angular/cli', + 'mcp', + ...args, + ); + + return result; +} + +export default async function () { + const [nodeMajor, nodeMinor] = process.versions.node.split('.', 2).map(Number); + if (nodeMajor < 22 || (nodeMajor === 22 && nodeMinor < 16)) { + console.log('Test bypassed: find_examples tool requires Node.js 22.16 or higher.'); + + return; + } + + await silentNpm( + 'install', + '--ignore-scripts', + '-g', + `${MCP_INSPECTOR_PACKAGE_NAME}@${MCP_INSPECTOR_PACKAGE_VERSION}`, + ); + + // Ensure `get_best_practices` returns the markdown content + const { stdout: stdoutInsideWorkspace } = await runInspector( + '--method', + 'tools/call', + '--tool-name', + 'find_examples', + '--tool-arg', + 'query=if', + ); + + assert.match(stdoutInsideWorkspace, /Using the @if Built-in Control Flow Block/); +} diff --git a/tests/legacy-cli/e2e/tests/mcp/registers-tools.ts b/tests/e2e/tests/mcp/registers-tools.ts similarity index 55% rename from tests/legacy-cli/e2e/tests/mcp/registers-tools.ts rename to tests/e2e/tests/mcp/registers-tools.ts index e2c9461d6a26..abc76a99f5d7 100644 --- a/tests/legacy-cli/e2e/tests/mcp/registers-tools.ts +++ b/tests/e2e/tests/mcp/registers-tools.ts @@ -29,19 +29,21 @@ export default async function () { ); // Ensure 'list_projects' is registered when inside an Angular workspace - const { stdout: stdoutInsideWorkspace } = await runInspector('--method', 'tools/list'); + try { + const { stdout: stdoutInsideWorkspace } = await runInspector('--method', 'tools/list'); - assert.match(stdoutInsideWorkspace, /"list_projects"/); - assert.match(stdoutInsideWorkspace, /"get_best_practices"/); - assert.match(stdoutInsideWorkspace, /"search_documentation"/); + assert.match(stdoutInsideWorkspace, /"list_projects"/); + assert.match(stdoutInsideWorkspace, /"get_best_practices"/); + assert.match(stdoutInsideWorkspace, /"search_documentation"/); - chdir('..'); + chdir('..'); - const { stdout: stdoutOutsideWorkspace } = await runInspector('--method', 'tools/list'); + const { stdout: stdoutOutsideWorkspace } = await runInspector('--method', 'tools/list'); - assert.doesNotMatch(stdoutOutsideWorkspace, /"list_projects"/); - assert.match(stdoutOutsideWorkspace, /"get_best_practices"/); - assert.match(stdoutInsideWorkspace, /"search_documentation"/); - - silentNpm('uninstall', '-g', MCP_INSPECTOR_PACKAGE_NAME); + assert.match(stdoutOutsideWorkspace, /"list_projects"/); + assert.match(stdoutOutsideWorkspace, /"get_best_practices"/); + assert.match(stdoutInsideWorkspace, /"search_documentation"/); + } finally { + await silentNpm('uninstall', '-g', MCP_INSPECTOR_PACKAGE_NAME); + } } diff --git a/tests/legacy-cli/e2e/tests/misc/ask-missing-builder.ts b/tests/e2e/tests/misc/ask-missing-builder.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/ask-missing-builder.ts rename to tests/e2e/tests/misc/ask-missing-builder.ts diff --git a/tests/legacy-cli/e2e/tests/misc/browsers.ts b/tests/e2e/tests/misc/browsers.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/browsers.ts rename to tests/e2e/tests/misc/browsers.ts diff --git a/tests/legacy-cli/e2e/tests/misc/check-postinstalls.ts b/tests/e2e/tests/misc/check-postinstalls.ts similarity index 98% rename from tests/legacy-cli/e2e/tests/misc/check-postinstalls.ts rename to tests/e2e/tests/misc/check-postinstalls.ts index 2b0ad00b62a1..7c1d63e6ef97 100644 --- a/tests/legacy-cli/e2e/tests/misc/check-postinstalls.ts +++ b/tests/e2e/tests/misc/check-postinstalls.ts @@ -7,6 +7,7 @@ const CURRENT_SCRIPT_PACKAGES: ReadonlySet = new Set([ 'lmdb (install)', 'msgpackr-extract (install)', 'nice-napi (install)', + 'unrs-resolver (postinstall)', ]); const POTENTIAL_SCRIPTS: ReadonlyArray = ['preinstall', 'install', 'postinstall']; diff --git a/tests/legacy-cli/e2e/tests/misc/create-angular.ts b/tests/e2e/tests/misc/create-angular.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/create-angular.ts rename to tests/e2e/tests/misc/create-angular.ts diff --git a/tests/legacy-cli/e2e/tests/misc/dedupe-duplicate-modules.ts b/tests/e2e/tests/misc/dedupe-duplicate-modules.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/dedupe-duplicate-modules.ts rename to tests/e2e/tests/misc/dedupe-duplicate-modules.ts diff --git a/tests/legacy-cli/e2e/tests/misc/duplicate-command-line-option.ts b/tests/e2e/tests/misc/duplicate-command-line-option.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/duplicate-command-line-option.ts rename to tests/e2e/tests/misc/duplicate-command-line-option.ts diff --git a/tests/legacy-cli/e2e/tests/misc/es2015-nometa.ts b/tests/e2e/tests/misc/es2015-nometa.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/es2015-nometa.ts rename to tests/e2e/tests/misc/es2015-nometa.ts diff --git a/tests/legacy-cli/e2e/tests/misc/forwardref-es2015.ts b/tests/e2e/tests/misc/forwardref-es2015.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/forwardref-es2015.ts rename to tests/e2e/tests/misc/forwardref-es2015.ts diff --git a/tests/legacy-cli/e2e/tests/misc/invalid-schematic-dependencies.ts b/tests/e2e/tests/misc/invalid-schematic-dependencies.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/invalid-schematic-dependencies.ts rename to tests/e2e/tests/misc/invalid-schematic-dependencies.ts diff --git a/tests/legacy-cli/e2e/tests/misc/loaders-resolution.ts b/tests/e2e/tests/misc/loaders-resolution.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/loaders-resolution.ts rename to tests/e2e/tests/misc/loaders-resolution.ts diff --git a/tests/legacy-cli/e2e/tests/misc/module-resolution/module-resolution-core-mapping.ts b/tests/e2e/tests/misc/module-resolution/module-resolution-core-mapping.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/module-resolution/module-resolution-core-mapping.ts rename to tests/e2e/tests/misc/module-resolution/module-resolution-core-mapping.ts diff --git a/tests/legacy-cli/e2e/tests/misc/multiple-targets.ts b/tests/e2e/tests/misc/multiple-targets.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/multiple-targets.ts rename to tests/e2e/tests/misc/multiple-targets.ts diff --git a/tests/legacy-cli/e2e/tests/misc/negated-boolean-options.ts b/tests/e2e/tests/misc/negated-boolean-options.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/negated-boolean-options.ts rename to tests/e2e/tests/misc/negated-boolean-options.ts diff --git a/tests/legacy-cli/e2e/tests/misc/nested-schematic-packages.ts b/tests/e2e/tests/misc/nested-schematic-packages.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/nested-schematic-packages.ts rename to tests/e2e/tests/misc/nested-schematic-packages.ts diff --git a/tests/legacy-cli/e2e/tests/misc/supported-angular.ts b/tests/e2e/tests/misc/supported-angular.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/supported-angular.ts rename to tests/e2e/tests/misc/supported-angular.ts diff --git a/tests/legacy-cli/e2e/tests/misc/target-default-configuration.ts b/tests/e2e/tests/misc/target-default-configuration.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/target-default-configuration.ts rename to tests/e2e/tests/misc/target-default-configuration.ts diff --git a/tests/legacy-cli/e2e/tests/misc/trace-resolution.ts b/tests/e2e/tests/misc/trace-resolution.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/trace-resolution.ts rename to tests/e2e/tests/misc/trace-resolution.ts diff --git a/tests/legacy-cli/e2e/tests/misc/trusted-types.ts b/tests/e2e/tests/misc/trusted-types.ts similarity index 64% rename from tests/legacy-cli/e2e/tests/misc/trusted-types.ts rename to tests/e2e/tests/misc/trusted-types.ts index 325ee521fe6d..21deb03223dd 100644 --- a/tests/legacy-cli/e2e/tests/misc/trusted-types.ts +++ b/tests/e2e/tests/misc/trusted-types.ts @@ -6,9 +6,11 @@ * found in the LICENSE file at https://angular.dev/license */ -import { replaceInFile, writeFile } from '../../utils/fs'; +import assert from 'node:assert/strict'; +import { replaceInFile } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; export default async function () { // Add lazy route. @@ -19,29 +21,6 @@ export default async function () { `routes: Routes = [{path: 'lazy', loadComponent: () => import('./lazy/lazy').then(c => c.Lazy)}];`, ); - // Add lazy route e2e - await writeFile( - 'e2e/src/app.e2e-spec.ts', - ` - import { browser, logging, element, by } from 'protractor'; - - describe('workspace-project App', () => { - it('should display lazy route', async () => { - await browser.get(browser.baseUrl + '/lazy'); - expect(await element(by.css('app-lazy p')).getText()).toEqual('lazy works!'); - }); - - afterEach(async () => { - // Assert that there are no errors emitted from the browser - const logs = await browser.manage().logs().get(logging.Type.BROWSER); - expect(logs).not.toContain(jasmine.objectContaining({ - level: logging.Level.SEVERE, - })); - }); - }); - `, - ); - const testCases = [ { aot: false, @@ -64,7 +43,16 @@ export default async function () { }); try { - await ng('e2e'); + await executeBrowserTest({ + checkFn: async (page) => { + const baseUrl = page.url(); + await page.goto(new URL('/lazy', baseUrl).href); + + await page.waitForSelector('app-lazy p'); + const lazyText = await page.$eval('app-lazy p', (el) => el.textContent); + assert.strictEqual(lazyText, 'lazy works!'); + }, + }); } catch (error) { console.error(`Test case AOT ${aot} with CSP header ${csp} failed.`); throw error; diff --git a/tests/legacy-cli/e2e/tests/misc/update-git-clean-subdirectory.ts b/tests/e2e/tests/misc/update-git-clean-subdirectory.ts similarity index 89% rename from tests/legacy-cli/e2e/tests/misc/update-git-clean-subdirectory.ts rename to tests/e2e/tests/misc/update-git-clean-subdirectory.ts index 11040c618bbb..733a91164019 100644 --- a/tests/legacy-cli/e2e/tests/misc/update-git-clean-subdirectory.ts +++ b/tests/e2e/tests/misc/update-git-clean-subdirectory.ts @@ -11,7 +11,7 @@ export default async function () { await silentGit('init', '.'); - await ng('new', 'subdirectory-test-project', '--skip-install'); + await ng('new', 'subdirectory-test-project', '--skip-install', '--test-runner', 'karma'); process.chdir('./subdirectory-test-project'); await prepareProjectForE2e('subdirectory-test-project'); diff --git a/tests/legacy-cli/e2e/tests/misc/update-git-clean.ts b/tests/e2e/tests/misc/update-git-clean.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/update-git-clean.ts rename to tests/e2e/tests/misc/update-git-clean.ts diff --git a/tests/legacy-cli/e2e/tests/misc/version.ts b/tests/e2e/tests/misc/version.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/version.ts rename to tests/e2e/tests/misc/version.ts diff --git a/tests/legacy-cli/e2e/tests/misc/workspace-verification.ts b/tests/e2e/tests/misc/workspace-verification.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/misc/workspace-verification.ts rename to tests/e2e/tests/misc/workspace-verification.ts diff --git a/tests/legacy-cli/e2e/tests/protractor/test-fails.ts b/tests/e2e/tests/protractor/test-fails.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/protractor/test-fails.ts rename to tests/e2e/tests/protractor/test-fails.ts diff --git a/tests/legacy-cli/e2e/tests/schematics_cli/basic.ts b/tests/e2e/tests/schematics_cli/basic.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/schematics_cli/basic.ts rename to tests/e2e/tests/schematics_cli/basic.ts diff --git a/tests/legacy-cli/e2e/tests/schematics_cli/blank-test.ts b/tests/e2e/tests/schematics_cli/blank-test.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/schematics_cli/blank-test.ts rename to tests/e2e/tests/schematics_cli/blank-test.ts diff --git a/tests/legacy-cli/e2e/tests/schematics_cli/schematic-test.ts b/tests/e2e/tests/schematics_cli/schematic-test.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/schematics_cli/schematic-test.ts rename to tests/e2e/tests/schematics_cli/schematic-test.ts diff --git a/tests/legacy-cli/e2e/tests/test/karma-junit-output.ts b/tests/e2e/tests/test/karma-junit-output.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/test/karma-junit-output.ts rename to tests/e2e/tests/test/karma-junit-output.ts diff --git a/tests/legacy-cli/e2e/tests/test/test-code-coverage-exclude.ts b/tests/e2e/tests/test/test-code-coverage-exclude.ts similarity index 65% rename from tests/legacy-cli/e2e/tests/test/test-code-coverage-exclude.ts rename to tests/e2e/tests/test/test-code-coverage-exclude.ts index 3533e6c8e9a9..808bcb59e2d9 100644 --- a/tests/legacy-cli/e2e/tests/test/test-code-coverage-exclude.ts +++ b/tests/e2e/tests/test/test-code-coverage-exclude.ts @@ -1,10 +1,14 @@ +import { getGlobalVariable } from '../../utils/env'; import { expectFileToExist, rimraf } from '../../utils/fs'; import { silentNg } from '../../utils/process'; import { expectToFail } from '../../utils/utils'; export default async function () { + const isWebpack = !getGlobalVariable('argv')['esbuild']; + const coverageOptionName = isWebpack ? '--code-coverage' : '--coverage'; + // This test is already in build-angular, but that doesn't run on Windows. - await silentNg('test', '--no-watch', '--code-coverage'); + await silentNg('test', '--no-watch', coverageOptionName); await expectFileToExist('coverage/test-project/app.ts.html'); // Delete coverage directory await rimraf('coverage'); @@ -12,8 +16,8 @@ export default async function () { await silentNg( 'test', '--no-watch', - '--code-coverage', - `--code-coverage-exclude='src/**/app.ts'`, + coverageOptionName, + `${coverageOptionName}-exclude='src/**/app.ts'`, ); // Doesn't include excluded. diff --git a/tests/e2e/tests/test/test-environment.ts b/tests/e2e/tests/test/test-environment.ts new file mode 100644 index 000000000000..1670cb246521 --- /dev/null +++ b/tests/e2e/tests/test/test-environment.ts @@ -0,0 +1,71 @@ +import { ng } from '../../utils/process'; +import { writeFile, writeMultipleFiles } from '../../utils/fs'; +import { updateJsonFile } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + const isWebpack = !getGlobalVariable('argv')['esbuild']; + + // Tests run in 'dev' environment by default. + await writeMultipleFiles({ + 'src/environment.prod.ts': ` + export const environment = { + production: true + };`, + 'src/environment.ts': ` + export const environment = { + production: false + }; + `, + 'src/app/environment.spec.ts': ` + import { environment } from '../environment'; + + describe('Test environment', () => { + it('should have production disabled', () => { + expect(environment.production).toBe(false); + }); + }); + `, + }); + + await ng('test', '--watch=false'); + + await updateJsonFile('angular.json', (configJson) => { + const appArchitect = configJson.projects['test-project'].architect; + appArchitect[isWebpack ? 'test' : 'build'].configurations = { + production: { + fileReplacements: [ + { + replace: 'src/environment.ts', + with: 'src/environment.prod.ts', + }, + ], + }, + }; + if (!isWebpack) { + appArchitect.test.options ??= {}; + appArchitect.test.options.buildTarget = '::production'; + } + }); + + // Tests can run in different environment. + + await writeFile( + 'src/app/environment.spec.ts', + ` + import { environment } from '../environment'; + + describe('Test environment', () => { + it('should have production enabled', () => { + expect(environment.production).toBe(true); + }); + }); + `, + ); + + if (isWebpack) { + await ng('test', '--watch=false', '--configuration=production'); + } else { + await ng('test', '--watch=false'); + } +} diff --git a/tests/legacy-cli/e2e/tests/test/test-fail-single-run.ts b/tests/e2e/tests/test/test-fail-single-run.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/test/test-fail-single-run.ts rename to tests/e2e/tests/test/test-fail-single-run.ts diff --git a/tests/legacy-cli/e2e/tests/test/test-include-glob.ts b/tests/e2e/tests/test/test-include-glob.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/test/test-include-glob.ts rename to tests/e2e/tests/test/test-include-glob.ts diff --git a/tests/legacy-cli/e2e/tests/test/test-jasmine-clock.ts b/tests/e2e/tests/test/test-jasmine-clock.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/test/test-jasmine-clock.ts rename to tests/e2e/tests/test/test-jasmine-clock.ts diff --git a/tests/legacy-cli/e2e/tests/test/test-scripts.ts b/tests/e2e/tests/test/test-scripts.ts similarity index 93% rename from tests/legacy-cli/e2e/tests/test/test-scripts.ts rename to tests/e2e/tests/test/test-scripts.ts index acbcc66dc230..1537cdddf349 100644 --- a/tests/legacy-cli/e2e/tests/test/test-scripts.ts +++ b/tests/e2e/tests/test/test-scripts.ts @@ -1,3 +1,4 @@ +import { getGlobalVariable } from '../../utils/env'; import { writeMultipleFiles } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; @@ -60,9 +61,10 @@ export default async function () { // should fail because the global scripts were not added to scripts array await expectToFail(() => ng('test', '--watch=false')); + const isWebpack = !getGlobalVariable('argv')['esbuild']; await updateJsonFile('angular.json', (workspaceJson) => { const appArchitect = workspaceJson.projects['test-project'].architect; - appArchitect.test.options.scripts = [ + appArchitect[isWebpack ? 'test' : 'build'].options.scripts = [ { input: 'src/string-script.js' }, { input: 'src/input-script.js' }, ]; diff --git a/tests/legacy-cli/e2e/tests/test/test-sourcemap.ts b/tests/e2e/tests/test/test-sourcemap.ts similarity index 54% rename from tests/legacy-cli/e2e/tests/test/test-sourcemap.ts rename to tests/e2e/tests/test/test-sourcemap.ts index 9e2a8e3f36fa..6c1cf16cd7b3 100644 --- a/tests/legacy-cli/e2e/tests/test/test-sourcemap.ts +++ b/tests/e2e/tests/test/test-sourcemap.ts @@ -1,10 +1,13 @@ import assert from 'node:assert'; -import { getGlobalVariable } from '../../utils/env'; import { writeFile } from '../../utils/fs'; import { ng } from '../../utils/process'; import { assertIsError } from '../../utils/utils'; +import { updateJsonFile } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; export default async function () { + const isWebpack = !getGlobalVariable('argv')['esbuild']; + await writeFile( 'src/app/app.spec.ts', ` @@ -15,8 +18,16 @@ export default async function () { ); // when sourcemaps are 'on' the stacktrace will point to the spec.ts file. + await updateJsonFile('angular.json', (configJson) => { + const appArchitect = configJson.projects['test-project'].architect; + if (isWebpack) { + appArchitect['test'].options.sourceMap = true; + } else { + appArchitect['build'].configurations.development.sourceMap = true; + } + }); try { - await ng('test', '--no-watch', '--source-map'); + await ng('test', '--no-watch'); throw new Error('ng test should have failed.'); } catch (error) { assertIsError(error); @@ -25,8 +36,16 @@ export default async function () { } // when sourcemaps are 'off' the stacktrace won't point to the spec.ts file. + await updateJsonFile('angular.json', (configJson) => { + const appArchitect = configJson.projects['test-project'].architect; + if (isWebpack) { + appArchitect['test'].options.sourceMap = false; + } else { + appArchitect['build'].configurations.development.sourceMap = false; + } + }); try { - await ng('test', '--no-watch', '--no-source-map'); + await ng('test', '--no-watch'); throw new Error('ng test should have failed.'); } catch (error) { assertIsError(error); diff --git a/tests/legacy-cli/e2e/tests/update/update-application-builder.ts b/tests/e2e/tests/update/update-application-builder.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/update/update-application-builder.ts rename to tests/e2e/tests/update/update-application-builder.ts diff --git a/tests/legacy-cli/e2e/tests/update/update-multiple-versions.ts b/tests/e2e/tests/update/update-multiple-versions.ts similarity index 96% rename from tests/legacy-cli/e2e/tests/update/update-multiple-versions.ts rename to tests/e2e/tests/update/update-multiple-versions.ts index 66b58d87b908..6fecb7b15b58 100644 --- a/tests/legacy-cli/e2e/tests/update/update-multiple-versions.ts +++ b/tests/e2e/tests/update/update-multiple-versions.ts @@ -7,7 +7,7 @@ import { expectToFail } from '../../utils/utils'; export default async function () { let restoreRegistry: (() => Promise) | undefined; try { - restoreRegistry = await createProjectFromAsset('17.0-project', true); + restoreRegistry = await createProjectFromAsset('19.0-project', true); await setRegistry(true); const extraArgs = ['--force']; diff --git a/tests/legacy-cli/e2e/tests/update/update-secure-registry.ts b/tests/e2e/tests/update/update-secure-registry.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/update/update-secure-registry.ts rename to tests/e2e/tests/update/update-secure-registry.ts diff --git a/tests/legacy-cli/e2e/tests/update/update.ts b/tests/e2e/tests/update/update.ts similarity index 87% rename from tests/legacy-cli/e2e/tests/update/update.ts rename to tests/e2e/tests/update/update.ts index d6b73b585eff..ae941762d6ca 100644 --- a/tests/legacy-cli/e2e/tests/update/update.ts +++ b/tests/e2e/tests/update/update.ts @@ -4,6 +4,7 @@ import { expectFileMatchToExist } from '../../utils/fs'; import { getActivePackageManager } from '../../utils/packages'; import { ng, noSilentNg } from '../../utils/process'; import { isPrereleaseCli, useCIChrome, useCIDefaults, getNgCLIVersion } from '../../utils/project'; +import { executeBrowserTest } from '../../utils/puppeteer'; export default async function () { let restoreRegistry: (() => Promise) | undefined; @@ -11,10 +12,10 @@ export default async function () { try { // We need to use the public registry because in the local NPM server we don't have // older versions @angular/cli packages which would cause `npm install` during `ng update` to fail. - restoreRegistry = await createProjectFromAsset('17.0-project', true); + restoreRegistry = await createProjectFromAsset('19.0-project', true); // CLI project version - const cliMajorProjectVersion = 17; + const cliMajorProjectVersion = 19; // If using npm, enable legacy peer deps mode to avoid defects in npm 7+'s peer dependency resolution // Example error where 11.2.14 satisfies the SemVer range ^11.0.0 but still fails: @@ -70,22 +71,24 @@ export default async function () { await ng('update', '@angular/cli', ...extraUpdateArgs); - // Generate E2E setup - await ng('generate', 'private-e2e', '--related-app-name=seventeen-project'); - // Setup testing to use CI Chrome. - await useCIChrome('seventeen-project', './'); - await useCIChrome('seventeen-project', './e2e/'); - await useCIDefaults('seventeen-project'); + await useCIChrome('nineteen-project', './'); + await useCIDefaults('nineteen-project'); // Run CLI commands. await ng('generate', 'component', 'my-comp'); await ng('test', '--watch=false'); - await ng('e2e'); - await ng('e2e', '--configuration=production'); + await executeBrowserTest({ + configuration: 'production', + expectedTitleText: 'Hello, nineteen-project', + }); + await executeBrowserTest({ + configuration: 'development', + expectedTitleText: 'Hello, nineteen-project', + }); // Verify project now creates bundles await noSilentNg('build', '--configuration=production'); - await expectFileMatchToExist('dist/seventeen-project/browser', /main-[a-zA-Z0-9]{8}\.js/); + await expectFileMatchToExist('dist/nineteen-project/browser', /main-[a-zA-Z0-9]{8}\.js/); } diff --git a/tests/legacy-cli/e2e/tests/vite/reuse-dep-optimization-cache.ts b/tests/e2e/tests/vite/reuse-dep-optimization-cache.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/vite/reuse-dep-optimization-cache.ts rename to tests/e2e/tests/vite/reuse-dep-optimization-cache.ts diff --git a/tests/e2e/tests/vite/ssr-base-href.ts b/tests/e2e/tests/vite/ssr-base-href.ts new file mode 100644 index 000000000000..140f2582689a --- /dev/null +++ b/tests/e2e/tests/vite/ssr-base-href.ts @@ -0,0 +1,48 @@ +import assert from 'node:assert'; +import { ng } from '../../utils/process'; +import { replaceInFile } from '../../utils/fs'; +import { installWorkspacePackages, uninstallPackage } from '../../utils/packages'; +import { ngServe, updateJsonFile, useSha } from '../../utils/project'; +import { getGlobalVariable } from '../../utils/env'; + +export default async function () { + assert( + getGlobalVariable('argv')['esbuild'], + 'This test should not be called in the Webpack suite.', + ); + + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); + await useSha(); + await installWorkspacePackages(); + + await updateJsonFile('angular.json', (json) => { + json.projects['test-project'].architect.build.options['baseHref'] = '/base'; + }); + + await replaceInFile( + 'src/server.ts', + /express\(\);/, + `express(); + + app.use('/ping', (req, res) => { + return res.json({ pong: true }); + });`, + ); + + const port = await ngServe(); + + // Angular application and bundled should be affected by baseHref + await matchResponse(`http://localhost:${port}/base`, /ng-server-context/); + await matchResponse(`http://localhost:${port}/base/main.js`, /App/); + + // Server endpoint should not be affected by baseHref + await matchResponse(`http://localhost:${port}/ping`, /pong/); +} + +async function matchResponse(url: string, match: RegExp): Promise { + const response = await fetch(url); + const text = await response.text(); + + assert.match(text, match); +} diff --git a/tests/legacy-cli/e2e/tests/vite/ssr-default.ts b/tests/e2e/tests/vite/ssr-default.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/vite/ssr-default.ts rename to tests/e2e/tests/vite/ssr-default.ts diff --git a/tests/legacy-cli/e2e/tests/vite/ssr-entry-express.ts b/tests/e2e/tests/vite/ssr-entry-express.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/vite/ssr-entry-express.ts rename to tests/e2e/tests/vite/ssr-entry-express.ts diff --git a/tests/legacy-cli/e2e/tests/vite/ssr-entry-fastify.ts b/tests/e2e/tests/vite/ssr-entry-fastify.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/vite/ssr-entry-fastify.ts rename to tests/e2e/tests/vite/ssr-entry-fastify.ts diff --git a/tests/legacy-cli/e2e/tests/vite/ssr-entry-h3.ts b/tests/e2e/tests/vite/ssr-entry-h3.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/vite/ssr-entry-h3.ts rename to tests/e2e/tests/vite/ssr-entry-h3.ts diff --git a/tests/legacy-cli/e2e/tests/vite/ssr-entry-hono.ts b/tests/e2e/tests/vite/ssr-entry-hono.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/vite/ssr-entry-hono.ts rename to tests/e2e/tests/vite/ssr-entry-hono.ts diff --git a/tests/legacy-cli/e2e/tests/vite/ssr-error-stack.ts b/tests/e2e/tests/vite/ssr-error-stack.ts similarity index 60% rename from tests/legacy-cli/e2e/tests/vite/ssr-error-stack.ts rename to tests/e2e/tests/vite/ssr-error-stack.ts index a0d7c87bed13..8fce78b9e7ad 100644 --- a/tests/legacy-cli/e2e/tests/vite/ssr-error-stack.ts +++ b/tests/e2e/tests/vite/ssr-error-stack.ts @@ -1,22 +1,13 @@ import { doesNotMatch, match } from 'node:assert'; import { ng } from '../../utils/process'; -import { appendToFile, rimraf } from '../../utils/fs'; +import { appendToFile } from '../../utils/fs'; import { ngServe, useSha } from '../../utils/project'; -import { installWorkspacePackages } from '../../utils/packages'; -import { getGlobalVariable } from '../../utils/env'; +import { installWorkspacePackages, uninstallPackage } from '../../utils/packages'; export default async function () { - const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; - // Forcibly remove in case another test doesn't clean itself up. - await rimraf('node_modules/@angular/ssr'); - if (useWebpackBuilder) { - // `--server-routing` not supported in `browser` builder. - await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); - } else { - await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); - } - + await uninstallPackage('@angular/ssr'); + await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); await useSha(); await installWorkspacePackages(); diff --git a/tests/legacy-cli/e2e/tests/vite/ssr-new-dep-optimization.ts b/tests/e2e/tests/vite/ssr-new-dep-optimization.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/vite/ssr-new-dep-optimization.ts rename to tests/e2e/tests/vite/ssr-new-dep-optimization.ts diff --git a/tests/legacy-cli/e2e/tests/vite/ssr-with-ssl.ts b/tests/e2e/tests/vite/ssr-with-ssl.ts similarity index 65% rename from tests/legacy-cli/e2e/tests/vite/ssr-with-ssl.ts rename to tests/e2e/tests/vite/ssr-with-ssl.ts index c4c0fd34ec75..90518080f8f3 100644 --- a/tests/legacy-cli/e2e/tests/vite/ssr-with-ssl.ts +++ b/tests/e2e/tests/vite/ssr-with-ssl.ts @@ -1,3 +1,4 @@ +import { Agent } from 'undici'; import assert from 'node:assert'; import { writeMultipleFiles } from '../../utils/fs'; import { ng, silentNg } from '../../utils/process'; @@ -41,19 +42,30 @@ export default async function () { const port = await ngServe('--ssl'); - // Verify the server is running and the API response is correct. - await validateResponse('/main.js', /bootstrapApplication/); - await validateResponse('/home', /home works/); - - async function validateResponse(pathname: string, match: RegExp): Promise { - try { - process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; - const response = await fetch(new URL(pathname, `https://localhost:${port}`)); - const text = await response.text(); - assert.match(text, match); - assert.equal(response.status, 200); - } finally { - process.env.NODE_TLS_REJECT_UNAUTHORIZED = '1'; - } + // http 2 + await validateResponse('/main.js', /bootstrapApplication/, true); + await validateResponse('/home', /home works/, true); + + // http 1.1 + await validateResponse('/main.js', /bootstrapApplication/, false); + await validateResponse('/home', /home works/, false); + + async function validateResponse( + pathname: string, + match: RegExp, + allowH2: boolean, + ): Promise { + const response = await fetch(new URL(pathname, `https://localhost:${port}`), { + dispatcher: new Agent({ + connect: { + allowH2, + rejectUnauthorized: false, + }, + }), + }); + + const text = await response.text(); + assert.match(text, match); + assert.equal(response.status, 200); } } diff --git a/tests/e2e/tests/vitest/browser-no-globals.ts b/tests/e2e/tests/vitest/browser-no-globals.ts new file mode 100644 index 000000000000..b25f8168c5f7 --- /dev/null +++ b/tests/e2e/tests/vitest/browser-no-globals.ts @@ -0,0 +1,31 @@ +import assert from 'node:assert/strict'; +import { writeFile } from '../../utils/fs'; +import { installPackage } from '../../utils/packages'; +import { ng } from '../../utils/process'; +import { applyVitestBuilder } from '../../utils/vitest'; + +/** + * Allow `vitest` import in browser mode. + * @see https://github.com/angular/angular-cli/issues/31745 + */ +export default async function (): Promise { + await applyVitestBuilder(); + + await installPackage('playwright@1'); + await installPackage('@vitest/browser-playwright@4'); + + await writeFile( + 'src/app/app.spec.ts', + ` + import { test, expect } from 'vitest'; + + test('should pass', () => { + expect(true).toBe(true); + }); + `, + ); + + const { stdout } = await ng('test', '--browsers', 'ChromiumHeadless'); + + assert.match(stdout, /1 passed/, 'Expected 1 tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/browser-playwright.ts b/tests/e2e/tests/vitest/browser-playwright.ts new file mode 100644 index 000000000000..fa9ec43aabf3 --- /dev/null +++ b/tests/e2e/tests/vitest/browser-playwright.ts @@ -0,0 +1,32 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng } from '../../utils/process'; +import { installPackage } from '../../utils/packages'; +import { writeFile } from '../../utils/fs'; + +export default async function (): Promise { + await applyVitestBuilder(); + await installPackage('playwright@1'); + await installPackage('@vitest/browser-playwright@4'); + await ng('generate', 'component', 'my-comp'); + + await writeFile( + 'src/setup1.ts', + ` + import { getTestBed } from '@angular/core/testing'; + + getTestBed().configureTestingModule({}); + `, + ); + + const { stdout } = await ng( + 'test', + '--no-watch', + '--browsers', + 'chromiumHeadless', + '--setup-files', + 'src/setup1.ts', + ); + + assert.match(stdout, /2 passed/, 'Expected 2 tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/browser-sourcemaps.ts b/tests/e2e/tests/vitest/browser-sourcemaps.ts new file mode 100644 index 000000000000..90c04457c7c8 --- /dev/null +++ b/tests/e2e/tests/vitest/browser-sourcemaps.ts @@ -0,0 +1,40 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng, noSilentNg } from '../../utils/process'; +import { installPackage } from '../../utils/packages'; +import { writeFile } from '../../utils/fs'; +import { stripVTControlCharacters } from 'node:util'; + +export default async function (): Promise { + await applyVitestBuilder(); + await installPackage('playwright@1'); + await installPackage('@vitest/browser-playwright@4'); + await ng('generate', 'component', 'my-comp'); + + // Add a failing test to verify source map support + await writeFile( + 'src/app/failing.spec.ts', + ` + describe('Failing Test', () => { + it('should fail', () => { + expect(true).toBe(false); + }); + }); + `, + ); + + try { + await noSilentNg('test', '--no-watch', '--browsers', 'chromiumHeadless'); + throw new Error('Expected "ng test" to fail.'); + } catch (error: any) { + const stdout = stripVTControlCharacters(error.stdout || error.message); + // We expect the failure from failing.spec.ts + assert.match(stdout, /1 failed/, 'Expected 1 test to fail.'); + // Check that the stack trace points to the correct file + assert.match( + stdout, + /\bsrc[\/\\]app[\/\\]failing\.spec\.ts:4:\d+/, + 'Expected stack trace to point to the source file.', + ); + } +} diff --git a/tests/e2e/tests/vitest/browser-webdriverio.ts b/tests/e2e/tests/vitest/browser-webdriverio.ts new file mode 100644 index 000000000000..4ea1b913c3b0 --- /dev/null +++ b/tests/e2e/tests/vitest/browser-webdriverio.ts @@ -0,0 +1,33 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng } from '../../utils/process'; +import { installPackage } from '../../utils/packages'; +import { writeFile } from '../../utils/fs'; + +export default async function (): Promise { + await applyVitestBuilder(); + await installPackage('webdriverio@9'); + await installPackage('@vitest/browser-webdriverio@4'); + + await ng('generate', 'component', 'my-comp'); + + await writeFile( + 'src/setup1.ts', + ` + import { getTestBed } from '@angular/core/testing'; + + getTestBed().configureTestingModule({}); + `, + ); + + const { stdout } = await ng( + 'test', + '--no-watch', + '--browsers', + 'chromeHeadless', + '--setup-files', + 'src/setup1.ts', + ); + + assert.match(stdout, /2 passed/, 'Expected 2 tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/component.ts b/tests/e2e/tests/vitest/component.ts new file mode 100644 index 000000000000..421587892196 --- /dev/null +++ b/tests/e2e/tests/vitest/component.ts @@ -0,0 +1,12 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng } from '../../utils/process'; + +export default async function (): Promise { + await applyVitestBuilder(); + await ng('generate', 'component', 'my-comp'); + + const { stdout } = await ng('test'); + + assert.match(stdout, /2 passed/, 'Expected 2 tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/include.ts b/tests/e2e/tests/vitest/include.ts new file mode 100644 index 000000000000..4585194ef3c2 --- /dev/null +++ b/tests/e2e/tests/vitest/include.ts @@ -0,0 +1,14 @@ +import assert from 'node:assert/strict'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { ng } from '../../utils/process'; +import path from 'node:path'; + +export default async function (): Promise { + await applyVitestBuilder(); + + const { stdout: stdout1 } = await ng('test', '--include', path.resolve('src/app/app.spec.ts')); + assert.match(stdout1, /1 passed/, 'Expected 1 test to pass with absolute include.'); + + const { stdout: stdout2 } = await ng('test', '--include', path.normalize('src/app/app.spec.ts')); + assert.match(stdout2, /1 passed/, 'Expected 1 test to pass with relative include.'); +} diff --git a/tests/e2e/tests/vitest/larger-project-coverage.ts b/tests/e2e/tests/vitest/larger-project-coverage.ts new file mode 100644 index 000000000000..3594bdc7dfee --- /dev/null +++ b/tests/e2e/tests/vitest/larger-project-coverage.ts @@ -0,0 +1,111 @@ +import { ng } from '../../utils/process'; +import { applyVitestBuilder } from '../../utils/vitest'; +import assert from 'node:assert'; +import { installPackage } from '../../utils/packages'; +import { updateJsonFile } from '../../utils/project'; +import { readFile } from '../../utils/fs'; + +export default async function () { + await applyVitestBuilder(); + await installPackage('@vitest/coverage-v8@4'); + + // Add coverage and threshold configuration to ensure coverage is calculated. + // Use the 'json' reporter to get a machine-readable output for assertions. + await updateJsonFile('angular.json', (json) => { + const project = Object.values(json['projects'])[0] as any; + const test = project['architect']['test']; + test.options = { + coverageReporters: ['json', 'text'], + coverageThresholds: { + // The generated component/service/pipe files are basic + // A threshold of 75 should be safe. + statements: 75, + }, + }; + }); + + const artifactCount = 100; + const initialTestCount = 1; + const generatedFiles = await generateArtifactsInBatches(artifactCount); + + const totalTests = initialTestCount + artifactCount; + const expectedMessage = new RegExp(`${totalTests} passed`); + const coverageJsonPath = 'coverage/test-project/coverage-final.json'; + + // Run tests in default (JSDOM) mode with coverage + const { stdout: jsdomStdout } = await ng('test', '--no-watch', '--coverage'); + assert.match(jsdomStdout, expectedMessage, `Expected ${totalTests} tests to pass in JSDOM mode.`); + + // Assert that every generated file is in the coverage report by reading the JSON output. + const jsdomSummary = JSON.parse(await readFile(coverageJsonPath)); + const jsdomSummaryKeys = Object.keys(jsdomSummary); + for (const file of generatedFiles) { + const found = jsdomSummaryKeys.some((key) => key.endsWith(file)); + assert.ok(found, `Expected ${file} to be in the JSDOM coverage report.`); + } + + // Setup for browser mode + await installPackage('playwright@1'); + await installPackage('@vitest/browser-playwright@4'); + + // Run tests in browser mode with coverage + const { stdout: browserStdout } = await ng( + 'test', + '--no-watch', + '--coverage', + '--browsers', + 'ChromiumHeadless', + ); + assert.match( + browserStdout, + expectedMessage, + `Expected ${totalTests} tests to pass in browser mode.`, + ); + + // Assert that every generated file is in the coverage report for browser mode. + const browserSummary = JSON.parse(await readFile(coverageJsonPath)); + const browserSummaryKeys = Object.keys(browserSummary); + for (const file of generatedFiles) { + const found = browserSummaryKeys.some((key) => key.endsWith(file)); + assert.ok(found, `Expected ${file} to be in the browser coverage report.`); + } +} + +async function generateArtifactsInBatches(artifactCount: number): Promise { + const BATCH_SIZE = 5; + const generatedFiles: string[] = []; + let commands: Promise[] = []; + + for (let i = 0; i < artifactCount; i++) { + const type = i % 3; + const name = `test-artifact-${i}`; + + let generateType: string; + let fileSuffix: string; + + switch (type) { + case 0: + generateType = 'component'; + fileSuffix = '.ts'; + break; + case 1: + generateType = 'service'; + fileSuffix = '.ts'; + break; + default: + generateType = 'pipe'; + fileSuffix = '-pipe.ts'; + break; + } + + commands.push(ng('generate', generateType, name, '--skip-tests=false')); + generatedFiles.push(`${name}${fileSuffix}`); + + if (commands.length === BATCH_SIZE || i === artifactCount - 1) { + await Promise.all(commands); + commands = []; + } + } + + return generatedFiles; +} diff --git a/tests/e2e/tests/vitest/larger-project.ts b/tests/e2e/tests/vitest/larger-project.ts new file mode 100644 index 000000000000..61b18b102c4b --- /dev/null +++ b/tests/e2e/tests/vitest/larger-project.ts @@ -0,0 +1,70 @@ +import { ng } from '../../utils/process'; +import { applyVitestBuilder } from '../../utils/vitest'; +import assert from 'node:assert'; +import { installPackage } from '../../utils/packages'; +import { exec } from '../../utils/process'; + +export default async function () { + await applyVitestBuilder(); + + const artifactCount = 100; + // A new project starts with 1 test file (app.spec.ts) + // Each generated artifact will add one more test file. + const initialTestCount = 1; + + await generateArtifactsInBatches(artifactCount); + + const totalTests = initialTestCount + artifactCount; + const expectedMessage = new RegExp(`${totalTests} passed`); + + // Run tests in default (JSDOM) mode + const { stdout: jsdomStdout } = await ng('test', '--no-watch'); + assert.match(jsdomStdout, expectedMessage, `Expected ${totalTests} tests to pass in JSDOM mode.`); + + // Setup for browser mode + await installPackage('playwright@1'); + await installPackage('@vitest/browser-playwright@4'); + + // Run tests in browser mode + const { stdout: browserStdout } = await ng( + 'test', + '--no-watch', + '--browsers', + 'ChromiumHeadless', + ); + assert.match( + browserStdout, + expectedMessage, + `Expected ${totalTests} tests to pass in browser mode.`, + ); +} + +async function generateArtifactsInBatches(artifactCount: number): Promise { + const BATCH_SIZE = 5; + let commands: Promise[] = []; + + for (let i = 0; i < artifactCount; i++) { + const type = i % 3; + const name = `test-artifact-${i}`; + let generateType: string; + + switch (type) { + case 0: + generateType = 'component'; + break; + case 1: + generateType = 'service'; + break; + default: + generateType = 'pipe'; + break; + } + + commands.push(ng('generate', generateType, name, '--skip-tests=false')); + + if (commands.length === BATCH_SIZE || i === artifactCount - 1) { + await Promise.all(commands); + commands = []; + } + } +} diff --git a/tests/e2e/tests/vitest/library.ts b/tests/e2e/tests/vitest/library.ts new file mode 100644 index 000000000000..ba1e31dc38f8 --- /dev/null +++ b/tests/e2e/tests/vitest/library.ts @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict'; +import { updateJsonFile } from '../../utils/project'; +import { ng, silentNpm } from '../../utils/process'; +import { createDir, writeFile } from '../../utils/fs'; + +export default async function (): Promise { + // Install Vitest deps + await silentNpm('install', 'vitest@^4.0.8', 'jsdom@^27.1.0', '--save-dev'); + + // Generate a library + await ng('generate', 'library', 'my-lib', '--test-runner', 'vitest'); + + // Setup Style Include Paths test + // 1. Create a shared SCSS file + await createDir('projects/my-lib/src/styles'); + await writeFile('projects/my-lib/src/styles/_vars.scss', '$primary-color: red;'); + + // 2. Update ng-package.json to include the styles directory + await updateJsonFile('projects/my-lib/ng-package.json', (json) => { + json['lib'] = { + ...json['lib'], + styleIncludePaths: ['./src/styles'], + }; + }); + + // 3. Update the component to use SCSS and import the shared file + // Rename CSS to SCSS + await ng( + 'generate', + 'component', + 'styled-comp', + '--project=my-lib', + '--style=scss', + '--skip-import', + ); + + await writeFile( + 'projects/my-lib/src/lib/styled-comp/styled-comp.component.scss', + ` + @use 'vars'; + p { color: vars.$primary-color; } + `, + ); + + // Run the library tests + const { stdout } = await ng('test', 'my-lib'); + + // Expect tests to pass + assert.match(stdout, /passed/, 'Expected library tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/runner-config-path.ts b/tests/e2e/tests/vitest/runner-config-path.ts new file mode 100644 index 000000000000..456469b2d6a4 --- /dev/null +++ b/tests/e2e/tests/vitest/runner-config-path.ts @@ -0,0 +1,33 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { writeMultipleFiles } from '../../utils/fs'; +import { ng } from '../../utils/process'; +import { applyVitestBuilder } from '../../utils/vitest'; + +export default async function (): Promise { + await applyVitestBuilder(); + + // Create a custom Vitest configuration file. + const customConfigPath = 'vitest.custom.mjs'; + await writeMultipleFiles({ + [customConfigPath]: ` + import { defineConfig } from 'vitest/config'; + export default defineConfig({ + test: { + // A unique option to confirm this file is being used. + passWithNoTests: true, + }, + }); + `, + }); + + const absoluteConfigPath = path.resolve(customConfigPath); + const { stdout } = await ng('test', `--runner-config=${absoluteConfigPath}`); + + // Assert that the CLI logs the use of the specified configuration file. + assert.match( + stdout, + /vitest\.custom\.mjs/, + 'Expected a message confirming the use of the custom config file.', + ); +} diff --git a/tests/e2e/tests/vitest/snapshot.ts b/tests/e2e/tests/vitest/snapshot.ts new file mode 100644 index 000000000000..f099ba6f8d30 --- /dev/null +++ b/tests/e2e/tests/vitest/snapshot.ts @@ -0,0 +1,79 @@ +import { ng } from '../../utils/process'; +import { replaceInFile, readFile, writeFile } from '../../utils/fs'; +import { applyVitestBuilder } from '../../utils/vitest'; +import assert from 'node:assert/strict'; +import { stripVTControlCharacters } from 'node:util'; + +export default async function () { + // Set up the test project to use the vitest runner + await applyVitestBuilder(); + + // Add snapshot assertions to the test file + await replaceInFile( + 'src/app/app.spec.ts', + `describe('App', () => {`, + ` +describe('App', () => { + it('should match file snapshot', () => { + const fixture = TestBed.createComponent(App); + const app = fixture.componentInstance; + expect((app as any).title()).toMatchSnapshot(); + }); + + it('should match inline snapshot', () => { + const fixture = TestBed.createComponent(App); + const app = fixture.componentInstance; + expect((app as any).title()).toMatchInlineSnapshot(); + }); +`, + ); + + // Synchronize line endings for Vitest which currently may miscalculate line counts + // with mixed file line endings. + let content = await readFile('src/app/app.spec.ts'); + content = content.replace(/\r\n/g, '\n'); + content = content.replace(/\r/g, '\n'); + await writeFile('src/app/app.spec.ts', content); + + // First run: create snapshots + const { stdout: firstRunStdout } = await ng('test'); + assert.match( + stripVTControlCharacters(firstRunStdout), + /Snapshots\s+2 written/, + 'Snapshots were not written on the first run.', + ); + + const specContent = await readFile('src/app/app.spec.ts'); + assert.match( + specContent, + /toMatchInlineSnapshot\(`"test-project"`\)/, + 'Inline snapshot was not written to the spec file.', + ); + + const snapshotContent = await readFile('src/app/__snapshots__/app.spec.ts.snap'); + assert.match( + snapshotContent, + /exports\[`App > should match file snapshot 1`\] = `"test-project"`;/, + 'File snapshot was not written to disk.', + ); + + // Second run: tests should pass with existing snapshots + await ng('test'); + + // Modify component to break snapshots + await replaceInFile('src/app/app.ts', 'test-project', 'Snapshot is broken!'); + + // Third run: tests should fail with snapshot mismatch + await assert.rejects( + () => ng('test'), + (err: any) => { + assert.match( + stripVTControlCharacters(err.toString()), + /Snapshots\s+2 failed/, + 'Expected snapshot mismatch error, but a different error occurred.', + ); + return true; + }, + 'Snapshot mismatch did not cause the test to fail.', + ); +} diff --git a/tests/e2e/tests/vitest/tslib-resolution.ts b/tests/e2e/tests/vitest/tslib-resolution.ts new file mode 100644 index 000000000000..759d5e2b5728 --- /dev/null +++ b/tests/e2e/tests/vitest/tslib-resolution.ts @@ -0,0 +1,71 @@ +import { writeFile } from '../../utils/fs'; +import { installPackage } from '../../utils/packages'; +import { ng } from '../../utils/process'; +import { applyVitestBuilder } from '../../utils/vitest'; +import assert from 'node:assert'; + +export default async function () { + await applyVitestBuilder(); + await installPackage('playwright@1'); + await installPackage('@vitest/browser-playwright@4'); + + // Add a custom decorator to trigger tslib usage + await writeFile( + 'src/app/custom-decorator.ts', + ` + export function MyDecorator() { + return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { + // do nothing + }; + } + `, + ); + + // Add a service that uses the decorator + await writeFile( + 'src/app/test.service.ts', + ` + import { Injectable } from '@angular/core'; + import { MyDecorator } from './custom-decorator'; + + @Injectable({ + providedIn: 'root' + }) + export class TestService { + @MyDecorator() + myMethod() { + return true; + } + } + `, + ); + + // Add a test for the service + await writeFile( + 'src/app/test.service.spec.ts', + ` + import { TestBed } from '@angular/core/testing'; + import { TestService } from './test.service'; + + describe('TestService', () => { + let service: TestService; + + beforeEach(() => { + TestBed.configureTestingModule({}); + service = TestBed.inject(TestService); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); + + it('myMethod should return true', () => { + expect(service.myMethod()).toBe(true); + }); + }); + `, + ); + + const { stdout } = await ng('test', '--no-watch', '--browsers', 'chromiumHeadless'); + assert.match(stdout, /2 passed/, 'Expected 2 tests to pass.'); +} diff --git a/tests/e2e/tests/vitest/windows-subst-drive.ts b/tests/e2e/tests/vitest/windows-subst-drive.ts new file mode 100644 index 000000000000..de5237da14a8 --- /dev/null +++ b/tests/e2e/tests/vitest/windows-subst-drive.ts @@ -0,0 +1,64 @@ +import assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { execAndCaptureError, silentExec } from '../../utils/process'; +import { applyVitestBuilder } from '../../utils/vitest'; +import { stripVTControlCharacters } from 'node:util'; + +export default async function (): Promise { + // This test uses `subst` to map the project directory to a virtual drive letter + // to simulate running tests from a non-C drive on Windows. + if (process.platform !== 'win32') { + return; + } + + await applyVitestBuilder(); + + const originalCwd = process.cwd(); + const driveLetter = 'X:'; // Pick a drive letter that is unlikely to be in use. + + try { + // 1. Map the parent directory of the project to the virtual drive. + // This avoids running the project from the root of the drive (X:\), which can cause + // issues with workspace detection. + const projectParentDir = path.dirname(originalCwd); + const projectName = path.basename(originalCwd); + + await silentExec('subst', driveLetter, projectParentDir); + + // 2. Change the current process's working directory to the project folder on the virtual drive. + const newCwd = path.join(driveLetter + '\\', projectName); + process.chdir(newCwd); + + // Verify that the file system mapping is working as expected. + assert(fs.existsSync('angular.json'), 'angular.json should exist on the subst drive'); + + // 3. Run `ng test`. + // We expect this to fail with NG0203 in the subst environment due to dual-package hazards + // (Angular loading from both X: and D:) within bazel. However, the failure proves that the + // test file was discovered and loaded. + const error = await execAndCaptureError('ng', ['test', '--watch=false']); + const output = stripVTControlCharacters(error.message); + + // 4. Verify that Vitest found the test file and identified the tests within it. + assert.match( + output, + /src\/app\/app\.spec\.ts \(2 tests/, + 'Expected tests to be discovered and loaded, even if execution fails due to subst aliasing.', + ); + } finally { + // 5. Teardown: Restore CWD and remove the virtual drive mapping. + try { + process.chdir(originalCwd); + } catch (e) { + console.error('Failed to restore CWD:', e); + } + + try { + await silentExec('subst', driveLetter, '/d'); + } catch (e) { + // Ignore errors if the drive wasn't mounted or if unmount fails (best effort) + console.error(`Failed to unmount ${driveLetter}:`, e); + } + } +} diff --git a/tests/legacy-cli/e2e/tests/web-test-runner/basic.ts b/tests/e2e/tests/web-test-runner/basic.ts similarity index 100% rename from tests/legacy-cli/e2e/tests/web-test-runner/basic.ts rename to tests/e2e/tests/web-test-runner/basic.ts diff --git a/tests/legacy-cli/e2e/utils/BUILD.bazel b/tests/e2e/utils/BUILD.bazel similarity index 76% rename from tests/legacy-cli/e2e/utils/BUILD.bazel rename to tests/e2e/utils/BUILD.bazel index 2cf52b55a2ab..8082ab9d97c4 100644 --- a/tests/legacy-cli/e2e/utils/BUILD.bazel +++ b/tests/e2e/utils/BUILD.bazel @@ -7,21 +7,20 @@ ts_project( testonly = True, srcs = glob(["**/*.ts"]), data = [ - "//tests/legacy-cli/e2e/ng-snapshot", + "//tests/e2e/ng-snapshot", ], deps = [ "//:node_modules/@types/jasmine", "//:node_modules/@types/node", "//:node_modules/@types/semver", - "//:node_modules/ansi-colors", "//:node_modules/fast-glob", - "//:node_modules/npm", "//:node_modules/protractor", + "//:node_modules/puppeteer", "//:node_modules/semver", - "//:node_modules/tar", "//:node_modules/verdaccio", "//:node_modules/verdaccio-auth-memory", - "//tests:node_modules/rxjs", + "//tests:node_modules/@types/tar-stream", + "//tests:node_modules/tar-stream", "//tests:node_modules/tree-kill", ], ) diff --git a/tests/legacy-cli/e2e/utils/assets.ts b/tests/e2e/utils/assets.ts similarity index 83% rename from tests/legacy-cli/e2e/utils/assets.ts rename to tests/e2e/utils/assets.ts index d421086c1b9e..153fdaccc6de 100644 --- a/tests/legacy-cli/e2e/utils/assets.ts +++ b/tests/e2e/utils/assets.ts @@ -5,7 +5,7 @@ import { getGlobalVariable } from './env'; import { resolve } from 'node:path'; import { copyFile } from './fs'; import { installWorkspacePackages, setRegistry } from './packages'; -import { useBuiltPackagesVersions } from './project'; +import { getTestProjectDir, useBuiltPackagesVersions } from './project'; export function assetDir(assetName: string) { return join(__dirname, '../e2e/assets', assetName); @@ -21,7 +21,7 @@ export function copyProjectAsset(assetName: string, to?: string) { export function copyAssets(assetName: string, to?: string) { const seed = +Date.now(); - const tempRoot = join(getGlobalVariable('projects-root'), 'assets', assetName + '-' + seed); + const tempRoot = join(getTestAssetsDir(), assetName + '-' + seed); const root = assetDir(assetName); return Promise.resolve() @@ -30,9 +30,7 @@ export function copyAssets(assetName: string, to?: string) { return allFiles.reduce((promise, filePath) => { const toPath = - to !== undefined - ? resolve(getGlobalVariable('projects-root'), 'test-project', to, filePath) - : join(tempRoot, filePath); + to !== undefined ? resolve(getTestProjectDir(), to, filePath) : join(tempRoot, filePath); return promise .then(() => copyFile(join(root, filePath), toPath)) @@ -65,3 +63,7 @@ export async function createProjectFromAsset( return () => setRegistry(true /** useTestRegistry */); } + +export function getTestAssetsDir(): string { + return join(getGlobalVariable('projects-root'), 'assets'); +} diff --git a/tests/legacy-cli/e2e/utils/env.ts b/tests/e2e/utils/env.ts similarity index 100% rename from tests/legacy-cli/e2e/utils/env.ts rename to tests/e2e/utils/env.ts diff --git a/tests/legacy-cli/e2e/utils/fs.ts b/tests/e2e/utils/fs.ts similarity index 100% rename from tests/legacy-cli/e2e/utils/fs.ts rename to tests/e2e/utils/fs.ts diff --git a/tests/legacy-cli/e2e/utils/git.ts b/tests/e2e/utils/git.ts similarity index 100% rename from tests/legacy-cli/e2e/utils/git.ts rename to tests/e2e/utils/git.ts diff --git a/tests/legacy-cli/e2e/utils/jest.ts b/tests/e2e/utils/jest.ts similarity index 85% rename from tests/legacy-cli/e2e/utils/jest.ts rename to tests/e2e/utils/jest.ts index 904cc6f903d6..5dc1f0efe464 100644 --- a/tests/legacy-cli/e2e/utils/jest.ts +++ b/tests/e2e/utils/jest.ts @@ -4,11 +4,11 @@ import { updateJsonFile } from './project'; /** Updates the `test` builder in the current workspace to use Jest with the given options. */ export async function applyJestBuilder( options: {} = { + polyfills: [], tsConfig: 'tsconfig.spec.json', - polyfills: ['zone.js', 'zone.js/testing'], }, ): Promise { - await silentNpm('install', 'jest@29.5.0', 'jest-environment-jsdom@29.5.0', '--save-dev'); + await silentNpm('install', 'jest@30.2.0', 'jest-environment-jsdom@30.2.0', '--save-dev'); await updateJsonFile('angular.json', (json) => { const projects = Object.values(json['projects']); diff --git a/tests/e2e/utils/network.ts b/tests/e2e/utils/network.ts new file mode 100644 index 000000000000..48602f0000d2 --- /dev/null +++ b/tests/e2e/utils/network.ts @@ -0,0 +1,30 @@ +import { createServer } from 'node:net'; + +/** + * Finds an available network port on the loopback interface (127.0.0.1). + * This is useful for tests that need to bind to a free port to avoid conflicts. + * Explicitly binds to IPv4 localhost to avoid firewall prompts, IPv6 binding issues, and ensure consistency. + * + * @returns A promise that resolves with an available port number. + */ +export function findFreePort(): Promise { + return new Promise((resolve, reject) => { + const srv = createServer(); + srv.once('listening', () => { + const address = srv.address(); + if (!address || typeof address === 'string') { + // Should not happen with TCP, but good for type safety + srv.close(() => reject(new Error('Failed to get server address'))); + return; + } + const port = address.port; + srv.close((e) => (e ? reject(e) : resolve(port))); + }); + + // If an error happens (e.g. during bind), the server is not listening, + // so we should not call close(). + srv.once('error', (e) => reject(e)); + // Explicitly listen on IPv4 localhost to avoid firewall prompts, IPv6 binding issues, and ensure consistency. + srv.listen(0, '127.0.0.1'); + }); +} diff --git a/tests/legacy-cli/e2e/utils/packages.ts b/tests/e2e/utils/packages.ts similarity index 100% rename from tests/legacy-cli/e2e/utils/packages.ts rename to tests/e2e/utils/packages.ts diff --git a/tests/legacy-cli/e2e/utils/process.ts b/tests/e2e/utils/process.ts similarity index 93% rename from tests/legacy-cli/e2e/utils/process.ts rename to tests/e2e/utils/process.ts index 3cd6c77bc187..91216843086a 100644 --- a/tests/legacy-cli/e2e/utils/process.ts +++ b/tests/e2e/utils/process.ts @@ -1,10 +1,9 @@ -import * as ansiColors from 'ansi-colors'; import { spawn, SpawnOptions } from 'node:child_process'; import * as child_process from 'node:child_process'; -import { concat, defer, EMPTY, from, lastValueFrom, catchError, repeat } from 'rxjs'; import { getGlobalVariable, getGlobalVariablesEnv } from './env'; import treeKill from 'tree-kill'; import { delimiter, join, resolve } from 'node:path'; +import { stripVTControlCharacters, styleText } from 'node:util'; interface ExecOptions { silent?: boolean; @@ -29,9 +28,6 @@ export type ProcessOutput = { }; function _exec(options: ExecOptions, cmd: string, args: string[]): Promise { - // Create a separate instance to prevent unintended global changes to the color configuration - const colors = ansiColors.create(); - const cwd = options.cwd ?? process.cwd(); const env = options.env ?? process.env; @@ -56,8 +52,10 @@ function _exec(options: ExecOptions, cmd: string, args: string[]): Promise `"${x}"`).join(' ')}\`${flags}...`)); - console.log(colors.blue(`CWD: ${cwd}`)); + console.log( + styleText(['blue'], `Running \`${cmd} ${args.map((x) => `"${x}"`).join(' ')}\`${flags}...`), + ); + console.log(styleText(['blue'], `CWD: ${cwd}`)); const spawnOptions: SpawnOptions = { cwd, @@ -122,7 +120,7 @@ function _exec(options: ExecOptions, cmd: string, args: string[]): Promise line !== '') - .forEach((line) => console.error(colors.yellow(' ' + line))); + .forEach((line) => console.error(styleText(['yellow'], ' ' + line))); }); childProcess.on('close', (code) => { @@ -236,14 +234,14 @@ export async function waitForAnyProcessOutputToMatch( childProcess.stdout!.on('data', (data: Buffer) => { stdout += data.toString(); - if (stdout.match(match)) { + if (stripVTControlCharacters(stdout).match(match)) { resolve({ stdout, stderr }); } }); childProcess.stderr!.on('data', (data: Buffer) => { stderr += data.toString(); - if (stderr.match(match)) { + if (stripVTControlCharacters(stderr).match(match)) { resolve({ stdout, stderr }); } }); @@ -311,7 +309,7 @@ export async function execAndCaptureError( } } -export function execAndWaitForOutputToMatch( +export async function execAndWaitForOutputToMatch( cmd: string, args: string[], match: RegExp, @@ -323,15 +321,19 @@ export function execAndWaitForOutputToMatch( // happened just before the build (e.g. `git clean`). // This seems to be due to host file system differences, see // https://nodejs.org/docs/latest/api/fs.html#fs_caveats - return lastValueFrom( - concat( - from(_exec({ waitForMatch: match, env }, cmd, args)), - defer(() => waitForAnyProcessOutputToMatch(match, 2500)).pipe( - repeat(20), - catchError(() => EMPTY), - ), - ), - ); + const maxRetries = 20; + let lastResult = await _exec({ waitForMatch: match, env }, cmd, args); + + for (let i = 0; i < maxRetries; i++) { + try { + lastResult = await waitForAnyProcessOutputToMatch(match, 2500); + } catch { + // If we timeout (no new match found), we assume the process is stable. + break; + } + } + + return lastResult; } else { return _exec({ waitForMatch: match, env }, cmd, args); } diff --git a/tests/legacy-cli/e2e/utils/project.ts b/tests/e2e/utils/project.ts similarity index 95% rename from tests/legacy-cli/e2e/utils/project.ts rename to tests/e2e/utils/project.ts index ea764bb20314..58e249d19895 100644 --- a/tests/legacy-cli/e2e/utils/project.ts +++ b/tests/e2e/utils/project.ts @@ -7,6 +7,7 @@ import { gitCommit } from './git'; import { findFreePort } from './network'; import { installWorkspacePackages, PkgInfo } from './packages'; import { execAndWaitForOutputToMatch, git, ng } from './process'; +import { join } from 'node:path'; export function updateJsonFile(filePath: string, fn: (json: any) => any | void) { return readFile(filePath).then((tsConfigJson) => { @@ -118,7 +119,7 @@ export async function useSha(): Promise { if (missingSnapshots.length > 0) { throw new Error( 'e2e test with --ng-snapshots requires all angular packages be ' + - 'listed in tests/legacy-cli/e2e/ng-snapshot/package.json.\nErrors:\n' + + 'listed in tests/e2e/ng-snapshot/package.json.\nErrors:\n' + missingSnapshots.join('\n '), ); } @@ -191,7 +192,11 @@ export async function useCIChrome(projectName: string, projectDir = ''): Promise return updateJsonFile('angular.json', (workspaceJson) => { const project = workspaceJson.projects[projectName]; const appTargets = project.targets || project.architect; - appTargets.test.options.browsers = 'ChromeHeadlessNoSandbox'; + if (appTargets.test.builder === '@angular/build:unit-test') { + appTargets.test.options.browsers = ['ChromeHeadlessNoSandbox']; + } else { + appTargets.test.options.browsers = 'ChromeHeadlessNoSandbox'; + } }); } @@ -266,3 +271,7 @@ export function updateServerFileForEsbuild(filepath: string): Promise { `, ); } + +export function getTestProjectDir(): string { + return join(getGlobalVariable('projects-root'), 'test-project'); +} diff --git a/tests/e2e/utils/puppeteer.ts b/tests/e2e/utils/puppeteer.ts new file mode 100644 index 000000000000..8cab9f2ddef6 --- /dev/null +++ b/tests/e2e/utils/puppeteer.ts @@ -0,0 +1,90 @@ +import { type Page, launch } from 'puppeteer'; +import { execAndWaitForOutputToMatch, killAllProcesses } from './process'; +import { stripVTControlCharacters } from 'node:util'; + +export interface BrowserTestOptions { + project?: string; + configuration?: string; + baseUrl?: string; + checkFn?: (page: Page) => Promise; + expectedTitleText?: string; +} + +export async function executeBrowserTest(options: BrowserTestOptions = {}) { + let url = options.baseUrl; + let hasStartedServer = false; + + try { + if (!url) { + // Start serving and find address (1 - Webpack; 2 - Vite) + const match = /(?:open your browser on|Local:)\s+(http:\/\/localhost:\d+\/)/; + const serveArgs = ['serve', '--port=0']; + if (options.project) { + serveArgs.push(options.project); + } + if (options.configuration) { + serveArgs.push(`--configuration=${options.configuration}`); + } + + const { stdout } = await execAndWaitForOutputToMatch('ng', serveArgs, match, { + ...process.env, + 'NO_COLOR': '1', + }); + url = stripVTControlCharacters(stdout).match(match)?.[1]; + if (!url) { + throw new Error('Could not find serving URL'); + } + hasStartedServer = true; + } + + const browser = await launch({ + executablePath: process.env['CHROME_BIN'], + headless: true, + args: ['--no-sandbox'], + }); + try { + const page = await browser.newPage(); + + // Capture errors + const errors: string[] = []; + page.on('console', (msg) => { + if (msg.type() === 'error') { + errors.push(msg.text()); + } + }); + page.on('pageerror', (err) => { + errors.push(err.toString()); + }); + + await page.goto(url); + + if (options.checkFn) { + await options.checkFn(page); + } else { + // Default check: verify h1 content and no browser errors + const expectedText = options.expectedTitleText || 'Hello, test-project'; + + // Wait for the h1 element to appear and contain the expected text + await page.waitForFunction( + (selector: string, text: string) => { + const doc = (globalThis as any).document; + return doc.querySelector(selector)?.textContent?.includes(text); + }, + { timeout: 10000 }, // Max 10 seconds wait time + 'h1', + expectedText, + ); + } + + if (errors.length > 0) { + throw new Error(`Browser console errors detected:\n${errors.join('\n')}`); + } + } finally { + await browser.close(); + } + } finally { + if (hasStartedServer) { + await killAllProcesses(); + } + } +} diff --git a/tests/legacy-cli/e2e/utils/registry.ts b/tests/e2e/utils/registry.ts similarity index 72% rename from tests/legacy-cli/e2e/utils/registry.ts rename to tests/e2e/utils/registry.ts index 1bd3084d4f48..fd557c116120 100644 --- a/tests/legacy-cli/e2e/utils/registry.ts +++ b/tests/e2e/utils/registry.ts @@ -1,9 +1,10 @@ import { ChildProcess, fork } from 'node:child_process'; import { on } from 'node:events'; +import { mkdir } from 'node:fs/promises'; import { join } from 'node:path'; import { getGlobalVariable } from './env'; import { writeFile, readFile } from './fs'; -import { mktempd } from './utils'; +import { existsSync } from 'node:fs'; export async function createNpmRegistry( port: number, @@ -11,14 +12,18 @@ export async function createNpmRegistry( withAuthentication = false, ): Promise { // Setup local package registry - const registryPath = await mktempd('angular-cli-e2e-registry-'); + const registryPath = join(getGlobalVariable('tmp-root'), 'registry'); + if (!existsSync(registryPath)) { + await mkdir(registryPath); + } + + const configFileName = withAuthentication ? 'verdaccio_auth.yaml' : 'verdaccio.yaml'; + let configContent = await readFile(join(__dirname, '../', configFileName)); + configContent = configContent + .replace(/\$\{HTTP_PORT\}/g, String(port)) + .replace(/\$\{HTTPS_PORT\}/g, String(httpsPort)); + const configPath = join(registryPath, configFileName); - let configContent = await readFile( - join(__dirname, '../', withAuthentication ? 'verdaccio_auth.yaml' : 'verdaccio.yaml'), - ); - configContent = configContent.replace(/\$\{HTTP_PORT\}/g, String(port)); - configContent = configContent.replace(/\$\{HTTPS_PORT\}/g, String(httpsPort)); - const configPath = join(registryPath, 'verdaccio.yaml'); await writeFile(configPath, configContent); const verdaccioServer = fork(require.resolve('verdaccio/bin/verdaccio'), ['-c', configPath]); @@ -44,7 +49,7 @@ export async function createNpmRegistry( // Token was generated using `echo -n 'testing:s3cret' | openssl base64`. const VALID_TOKEN = `dGVzdGluZzpzM2NyZXQ=`; -export function createNpmConfigForAuthentication( +export async function createNpmConfigForAuthentication( /** * When true, the authentication token will be scoped to the registry URL. * @example @@ -65,17 +70,30 @@ export function createNpmConfigForAuthentication( const token = invalidToken ? `invalid=` : VALID_TOKEN; const registry = (getGlobalVariable('package-secure-registry') as string).replace(/^\w+:/, ''); - return writeFile( + await writeFile( '.npmrc', scopedAuthentication ? ` - ${registry}:_auth="${token}" - registry=http:${registry} - ` +${registry}/:_auth="${token}" +registry=http:${registry} +` + : ` +_auth="${token}" +registry=http:${registry} +`, + ); + + await writeFile( + '.yarnrc', + scopedAuthentication + ? ` +${registry}/:_auth "${token}" +registry http:${registry} +` : ` - _auth="${token}" - registry=http:${registry} - `, +_auth "${token}" +registry http:${registry} +`, ); } diff --git a/tests/legacy-cli/e2e/utils/tar.ts b/tests/e2e/utils/tar.ts similarity index 50% rename from tests/legacy-cli/e2e/utils/tar.ts rename to tests/e2e/utils/tar.ts index 77239c74eb0f..d78f47762337 100644 --- a/tests/legacy-cli/e2e/utils/tar.ts +++ b/tests/e2e/utils/tar.ts @@ -8,7 +8,8 @@ import { createReadStream } from 'node:fs'; import { normalize } from 'node:path'; -import { Parser } from 'tar'; +import { createGunzip } from 'node:zlib'; +import { extract } from 'tar-stream'; /** * Extract and return the contents of a single file out of a tar file. @@ -21,20 +22,27 @@ export function extractFile(tarball: string, filePath: string): Promise const normalizedFilePath = normalize(filePath); return new Promise((resolve, reject) => { - createReadStream(tarball) - .pipe( - new Parser({ - strict: true, - filter: (p) => normalize(p) === normalizedFilePath, - onReadEntry: (entry) => { - const chunks: Buffer[] = []; - - entry.on('data', (chunk) => chunks.push(chunk)); - entry.on('error', reject); - entry.on('finish', () => resolve(Buffer.concat(chunks))); - }, - }), - ) - .on('close', () => reject(`${tarball} does not contain ${filePath}`)); + const extractor = extract(); + + extractor.on('entry', (header, stream, next) => { + if (normalize(header.name) !== normalizedFilePath) { + stream.resume(); + next(); + + return; + } + + const chunks: Buffer[] = []; + stream.on('data', (chunk) => chunks.push(chunk)); + stream.on('error', reject); + stream.on('end', () => { + resolve(Buffer.concat(chunks)); + next(); + }); + }); + + extractor.on('finish', () => reject(new Error(`'${filePath}' not found in '${tarball}'.`))); + + createReadStream(tarball).pipe(createGunzip()).pipe(extractor).on('error', reject); }); } diff --git a/tests/legacy-cli/e2e/utils/test_process.ts b/tests/e2e/utils/test_process.ts similarity index 100% rename from tests/legacy-cli/e2e/utils/test_process.ts rename to tests/e2e/utils/test_process.ts diff --git a/tests/legacy-cli/e2e/utils/utils.ts b/tests/e2e/utils/utils.ts similarity index 100% rename from tests/legacy-cli/e2e/utils/utils.ts rename to tests/e2e/utils/utils.ts diff --git a/tests/legacy-cli/e2e/utils/version.ts b/tests/e2e/utils/version.ts similarity index 100% rename from tests/legacy-cli/e2e/utils/version.ts rename to tests/e2e/utils/version.ts diff --git a/tests/e2e/utils/vitest.ts b/tests/e2e/utils/vitest.ts new file mode 100644 index 000000000000..af40e66b18b1 --- /dev/null +++ b/tests/e2e/utils/vitest.ts @@ -0,0 +1,29 @@ +import { silentNpm } from './process'; +import { updateJsonFile } from './project'; + +/** Updates the `test` builder in the current workspace to use Vitest. */ +export async function applyVitestBuilder(): Promise { + // These deps matches the deps in `@schematics/angular` + await silentNpm('install', 'vitest@^4.0.8', 'jsdom@^27.1.0', '--save-dev'); + + await updateJsonFile('angular.json', (json) => { + const projects = Object.values(json['projects']); + if (projects.length !== 1) { + throw new Error( + `Expected exactly one project but found ${projects.length} projects named ${Object.keys( + json['projects'], + ).join(', ')}`, + ); + } + const project = projects[0]! as any; + + // Update to Vitest builder. + const test = project['architect']['test']; + test['builder'] = '@angular/build:unit-test'; + test['options'] = {}; + }); + + await updateJsonFile('tsconfig.spec.json', (tsconfig) => { + tsconfig['compilerOptions']['types'] = ['vitest/globals']; + }); +} diff --git a/tests/legacy-cli/e2e/utils/web-test-runner.ts b/tests/e2e/utils/web-test-runner.ts similarity index 100% rename from tests/legacy-cli/e2e/utils/web-test-runner.ts rename to tests/e2e/utils/web-test-runner.ts diff --git a/tests/legacy-cli/e2e_runner.ts b/tests/e2e_runner.ts similarity index 75% rename from tests/legacy-cli/e2e_runner.ts rename to tests/e2e_runner.ts index 051c1174a624..c7a672161b7a 100644 --- a/tests/legacy-cli/e2e_runner.ts +++ b/tests/e2e_runner.ts @@ -1,9 +1,9 @@ -import { parseArgs } from 'node:util'; -import { createConsoleLogger } from '../../packages/angular_devkit/core/node'; -import colors from 'ansi-colors'; +import { parseArgs, styleText } from 'node:util'; +import { createConsoleLogger } from '../packages/angular_devkit/core/node'; import glob from 'fast-glob'; import * as path from 'node:path'; import * as fs from 'node:fs'; +import { rm } from 'node:fs/promises'; import { getGlobalVariable, setGlobalVariable } from './e2e/utils/env'; import { gitClean } from './e2e/utils/git'; import { createNpmRegistry } from './e2e/utils/registry'; @@ -13,7 +13,8 @@ import { findFreePort } from './e2e/utils/network'; import { extractFile } from './e2e/utils/tar'; import { realpathSync } from 'node:fs'; import { PkgInfo } from './e2e/utils/packages'; -import { rm } from 'node:fs/promises'; +import { getTestProjectDir } from './e2e/utils/project'; +import { mktempd } from './e2e/utils/utils'; Error.stackTraceLimit = Infinity; @@ -30,13 +31,9 @@ Error.stackTraceLimit = Infinity; * --ng-snapshots Install angular snapshot builds in the test project. * --glob Run tests matching this glob pattern (relative to tests/e2e/). * --ignore Ignore tests matching this glob pattern. - * --reuse=/path Use a path instead of create a new project. That project should have been - * created, and npm installed. Ideally you want a project created by a previous - * run of e2e. * --nb-shards Total number of shards that this is part of. Default is 2 if --shard is * passed in. * --shard Index of this processes' shard. - * --tmpdir=path Override temporary directory to use for new projects. * --package-manager Package manager to use. * --package=path An npm package to be published before running tests * @@ -47,7 +44,7 @@ const parsed = parseArgs({ options: { 'debug': { type: 'boolean', default: !!process.env.BUILD_WORKSPACE_DIRECTORY }, 'esbuild': { type: 'boolean' }, - 'glob': { type: 'string', default: process.env.TESTBRIDGE_TEST_ONLY }, + 'glob': { type: 'string', default: 'tests/**/*.js' }, 'ignore': { type: 'string', multiple: true }, 'ng-snapshots': { type: 'boolean' }, 'ng-tag': { type: 'string' }, @@ -57,8 +54,6 @@ const parsed = parseArgs({ 'nosilent': { type: 'boolean' }, 'package': { type: 'string', multiple: true, default: ['./dist/_*.tgz'] }, 'package-manager': { type: 'string', default: 'npm' }, - 'reuse': { type: 'string' }, - 'tmpdir': { type: 'string' }, 'verbose': { type: 'boolean' }, 'nb-shards': { type: 'string' }, @@ -118,19 +113,19 @@ if (process.env.CHROME_BIN) { const logger = createConsoleLogger(argv.verbose, process.stdout, process.stderr, { info: (s) => s, debug: (s) => s, - warn: (s) => colors.bold.yellow(s), - error: (s) => colors.bold.red(s), - fatal: (s) => colors.bold.red(s), + warn: (s) => styleText(['bold', 'yellow'], s), + error: (s) => styleText(['bold', 'red'], s), + fatal: (s) => styleText(['bold', 'red'], s), }); const logStack = [logger]; function lastLogger() { - return logStack[logStack.length - 1]; + return logStack.at(-1)!; } // Under bazel the compiled file (.js) and types (.d.ts) are available. const SRC_FILE_EXT_RE = /\.js$/; -const testGlob = argv.glob?.replace(/\.ts$/, '.js') || `tests/**/*.js`; +const testGlob = (process.env.TESTBRIDGE_TEST_ONLY ?? argv.glob).replace(/\.ts$/, '.js'); const e2eRoot = path.join(__dirname, 'e2e'); const allSetups = glob.sync(`setup/**/*.js`, { cwd: e2eRoot }).sort(); @@ -226,57 +221,68 @@ process.env.CHROME_BIN = path.resolve(process.env.CHROME_BIN!); process.env.CHROME_PATH = path.resolve(process.env.CHROME_PATH!); process.env.CHROMEDRIVER_BIN = path.resolve(process.env.CHROMEDRIVER_BIN!); -Promise.all([findFreePort(), findFreePort(), findPackageTars()]) - .then(async ([httpPort, httpsPort, packageTars]) => { - setGlobalVariable('package-registry', 'http://localhost:' + httpPort); - setGlobalVariable('package-secure-registry', 'http://localhost:' + httpsPort); - setGlobalVariable('package-tars', packageTars); - - // NPM registries for the lifetime of the test execution - const registryProcess = await createNpmRegistry(httpPort, httpPort); - const secureRegistryProcess = await createNpmRegistry(httpPort, httpsPort, true); - - try { - await runSteps(runSetup, allSetups, 'setup'); - await runSteps(runInitializer, allInitializers, 'initializer'); - await runSteps(runTest, testsToRun, 'test'); - - if (shardId !== null) { - console.log(colors.green(`Done shard ${shardId} of ${nbShards}.`)); - } else { - console.log(colors.green('Done.')); - } +(async () => { + const tempRoot = await mktempd('angular-cli-e2e-', process.env.E2E_TEMP); + setGlobalVariable('tmp-root', tempRoot); + + process.on('SIGINT', deleteTemporaryRoot); + process.on('exit', deleteTemporaryRoot); + + const [httpPort, httpsPort, packageTars] = await Promise.all([ + findFreePort(), + findFreePort(), + findPackageTars(), + ]); + setGlobalVariable('package-registry', 'http://localhost:' + httpPort); + setGlobalVariable('package-secure-registry', 'http://localhost:' + httpsPort); + setGlobalVariable('package-tars', packageTars); + + // NPM registries for the lifetime of the test execution + const registryProcess = await createNpmRegistry(httpPort, httpPort); + const secureRegistryProcess = await createNpmRegistry(httpPort, httpsPort, true); + + try { + console.log(` Using "${tempRoot}" as temporary directory for a new project.`); + + await runSteps(runSetup, allSetups, 'setup'); + await runSteps(runInitializer, allInitializers, 'initializer'); + await runSteps(runTest, testsToRun, 'test'); + + if (shardId !== null) { + console.log(styleText(['green'], `Done shard ${shardId} of ${nbShards}.`)); + } else { + console.log(styleText(['green'], 'Done.')); + } - process.exitCode = 0; - } catch (err) { - if (err instanceof Error) { - console.log('\n'); - console.error(colors.red(err.message)); - if (err.stack) { - console.error(colors.red(err.stack)); - } - } else { - console.error(colors.red(String(err))); + process.exitCode = 0; + } catch (err) { + if (err instanceof Error) { + console.log('\n'); + console.error(styleText(['red'], err.message)); + if (err.stack) { + console.error(styleText(['red'], err.stack)); } + } else { + console.error(styleText(['red'], String(err))); + } - if (argv.debug) { - console.log(`Current Directory: ${process.cwd()}`); - console.log('Will loop forever while you debug... CTRL-C to quit.'); + if (argv.debug) { + console.log(`Current Directory: ${process.cwd()}`); + console.log('Will loop forever while you debug... CTRL-C to quit.'); - // Wait forever until user explicitly cancels. - await new Promise(() => {}); - } - - process.exitCode = 1; - } finally { - registryProcess.kill(); - secureRegistryProcess.kill(); + // Wait forever until user explicitly cancels. + await new Promise(() => {}); } - }) - .catch((err) => { - console.error(colors.red(`Unkown Error: ${err}`)); + process.exitCode = 1; - }); + } finally { + registryProcess.kill(); + secureRegistryProcess.kill(); + } +})().catch((err) => { + console.error(styleText(['red'], `Unkown Error: ${err}`)); + process.exitCode = 1; +}); async function runSteps( run: (name: string) => Promise | void, @@ -303,7 +309,7 @@ async function runSteps( await run(absoluteName); } catch (e) { console.log('\n'); - console.error(colors.red(`${capsType} "${name}" failed...`)); + console.error(styleText(['red'], `${capsType} "${name}" failed...`)); throw e; } finally { @@ -334,7 +340,7 @@ function runInitializer(absoluteName: string): Promise { * Run a file from the main 'test-project' directory in a subprocess via launchTestProcess(). */ async function runTest(absoluteName: string): Promise { - process.chdir(join(getGlobalVariable('projects-root'), 'test-project')); + process.chdir(getTestProjectDir()); await launchTestProcess(absoluteName); await cleanTestProject(); @@ -343,7 +349,7 @@ async function runTest(absoluteName: string): Promise { async function cleanTestProject() { await gitClean(); - const testProject = join(getGlobalVariable('projects-root'), 'test-project'); + const testProject = getTestProjectDir(); // Note: Dist directory is not cleared between tests, as `git clean` // doesn't delete it. @@ -356,16 +362,22 @@ function printHeader( count: number, type: 'setup' | 'initializer' | 'test', ) { - const text = `${testIndex + 1} of ${count}`; + const text = `(${testIndex + 1} of ${count})`; const fullIndex = testIndex * nbShards + (shardId ?? 0) + 1; const shard = shardId === null || type !== 'test' ? '' - : colors.yellow(` [${shardId}:${nbShards}]` + colors.bold(` (${fullIndex}/${tests.length})`)); + : styleText( + ['yellow'], + ` [${shardId}:${nbShards}]` + styleText(['bold'], ` (${fullIndex}/${tests.length})`), + ); console.log( - colors.green( - `Running ${type} "${colors.bold.blue(testName)}" (${colors.bold.white(text)}${shard})...`, - ), + styleText(['green'], `Running ${type} "`) + + styleText(['bold', 'blue'], testName) + + styleText(['green'], '" ') + + styleText(['bold', 'white'], text) + + shard + + styleText(['green'], '...'), ); } @@ -375,9 +387,11 @@ function printFooter(testName: string, type: 'setup' | 'initializer' | 'test', s // Round to hundredth of a second. const t = Math.round((Date.now() - startTime) / 10) / 100; console.log( - colors.green(`${capsType} "${colors.bold.blue(testName)}" took `) + - colors.bold.blue('' + t) + - colors.green('s...'), + styleText(['green'], `${capsType} "`) + + styleText(['bold', 'blue'], testName) + + styleText(['green'], '" took ') + + styleText(['bold', 'blue'], t.toFixed(2)) + + styleText(['green'], 's...'), ); console.log(''); } @@ -389,7 +403,7 @@ async function findPackageTars(): Promise<{ [pkg: string]: PkgInfo }> { ); const pkgJsons = await Promise.all( - pkgs.map((pkg) => realpathSync(pkg)).map((pkg) => extractFile(pkg, './package.json')), + pkgs.map((pkg) => realpathSync(pkg)).map((pkg) => extractFile(pkg, 'npm_package/package.json')), ); return pkgs.reduce( @@ -406,3 +420,13 @@ async function findPackageTars(): Promise<{ [pkg: string]: PkgInfo }> { {} as { [pkg: string]: PkgInfo }, ); } + +function deleteTemporaryRoot(): void { + try { + fs.rmSync(getGlobalVariable('tmp-root'), { + recursive: true, + force: true, + maxRetries: 3, + }); + } catch {} +} diff --git a/tests/legacy-cli/BUILD.bazel b/tests/legacy-cli/BUILD.bazel deleted file mode 100644 index c148aba86de5..000000000000 --- a/tests/legacy-cli/BUILD.bazel +++ /dev/null @@ -1,74 +0,0 @@ -load("@aspect_bazel_lib//lib:directory_path.bzl", "directory_path") -load("@npm//:rollup/package_json.bzl", rollup = "bin") -load("//tools:defaults.bzl", "ts_project") -load(":e2e.bzl", "e2e_suites") - -package(default_visibility = ["//visibility:public"]) - -ts_project( - name = "runner", - testonly = True, - srcs = [ - "e2e_runner.ts", - ], - deps = [ - "//:node_modules/@types/node", - "//:node_modules/ansi-colors", - "//:node_modules/fast-glob", - "//packages/angular_devkit/core", - "//packages/angular_devkit/core/node", - "//tests/legacy-cli/e2e/utils", - ], -) - -rollup.rollup( - name = "runner_bundled", - testonly = True, - srcs = [ - "rollup.config.mjs", - ":runner", - "//:node_modules/@rollup/plugin-alias", - "//:node_modules/@rollup/plugin-commonjs", - "//:node_modules/@rollup/plugin-json", - "//:node_modules/@rollup/plugin-node-resolve", - "//:node_modules/fast-glob", - "//tests/legacy-cli/e2e/initialize", - "//tests/legacy-cli/e2e/ng-snapshot", - "//tests/legacy-cli/e2e/setup", - "//tests/legacy-cli/e2e/tests", - ], - args = [ - "--format=cjs", - "--config=./rollup.config.mjs", - ], - chdir = package_name(), - out_dirs = ["runner_bundled_out"], - progress_message = "Bundling e2e test runner", -) - -directory_path( - name = "runner_entrypoint", - testonly = True, - directory = ":runner_bundled", - path = "./e2e_runner.js", -) - -e2e_suites( - name = "e2e", - data = [ - ":runner_bundled", - "verdaccio.yaml", - "verdaccio_auth.yaml", - - # Dynamically loaded. - "//tests/legacy-cli/e2e/assets", - "//:node_modules/verdaccio", - "//:node_modules/verdaccio-auth-memory", - - # Extra runtime deps due to bundling issues. - # TODO: Clean this up. - "//:node_modules/@verdaccio/config", - "//:node_modules/express", - ], - runner = ":runner_entrypoint", -) diff --git a/tests/legacy-cli/e2e/assets/17.0-project/README.md b/tests/legacy-cli/e2e/assets/17.0-project/README.md deleted file mode 100644 index 5418a46b83c0..000000000000 --- a/tests/legacy-cli/e2e/assets/17.0-project/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# SeventeenProject - -This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 17.3.12. - -## Development server - -Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files. - -## Code scaffolding - -Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. - -## Build - -Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. - -## Running unit tests - -Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). - -## Running end-to-end tests - -Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities. - -## Further help - -To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page. diff --git a/tests/legacy-cli/e2e/assets/17.0-project/package.json b/tests/legacy-cli/e2e/assets/17.0-project/package.json deleted file mode 100644 index c0f3c7b59156..000000000000 --- a/tests/legacy-cli/e2e/assets/17.0-project/package.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "seventeen-project", - "version": "0.0.0", - "scripts": { - "ng": "ng", - "start": "ng serve", - "build": "ng build", - "watch": "ng build --watch --configuration development", - "test": "ng test" - }, - "private": true, - "dependencies": { - "@angular/animations": "^17.3.0", - "@angular/common": "^17.3.0", - "@angular/compiler": "^17.3.0", - "@angular/core": "^17.3.0", - "@angular/forms": "^17.3.0", - "@angular/platform-browser": "^17.3.0", - "@angular/platform-browser-dynamic": "^17.3.0", - "@angular/router": "^17.3.0", - "rxjs": "~7.8.0", - "tslib": "^2.3.0", - "zone.js": "~0.14.3" - }, - "devDependencies": { - "@angular-devkit/build-angular": "^17.3.12", - "@angular/cli": "^17.3.12", - "@angular/compiler-cli": "^17.3.0", - "@types/jasmine": "~5.1.0", - "jasmine-core": "~5.1.0", - "karma": "~6.4.0", - "karma-chrome-launcher": "~3.2.0", - "karma-coverage": "~2.2.0", - "karma-jasmine": "~5.1.0", - "karma-jasmine-html-reporter": "~2.1.0", - "typescript": "~5.4.2" - } -} diff --git a/tests/legacy-cli/e2e/assets/17.0-project/src/app/app.config.ts b/tests/legacy-cli/e2e/assets/17.0-project/src/app/app.config.ts deleted file mode 100644 index 6c6ef6035f3d..000000000000 --- a/tests/legacy-cli/e2e/assets/17.0-project/src/app/app.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ApplicationConfig } from '@angular/core'; -import { provideRouter } from '@angular/router'; - -import { routes } from './app.routes'; - -export const appConfig: ApplicationConfig = { - providers: [provideRouter(routes)] -}; diff --git a/tests/legacy-cli/e2e/assets/17.0-project/src/index.html b/tests/legacy-cli/e2e/assets/17.0-project/src/index.html deleted file mode 100644 index 18ffbad003b2..000000000000 --- a/tests/legacy-cli/e2e/assets/17.0-project/src/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - SeventeenProject - - - - - - - - diff --git a/tests/legacy-cli/e2e/assets/17.0-project/tsconfig.app.json b/tests/legacy-cli/e2e/assets/17.0-project/tsconfig.app.json deleted file mode 100644 index 374cc9d294aa..000000000000 --- a/tests/legacy-cli/e2e/assets/17.0-project/tsconfig.app.json +++ /dev/null @@ -1,14 +0,0 @@ -/* To learn more about this file see: https://angular.io/config/tsconfig. */ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "outDir": "./out-tsc/app", - "types": [] - }, - "files": [ - "src/main.ts" - ], - "include": [ - "src/**/*.d.ts" - ] -} diff --git a/tests/legacy-cli/e2e/assets/17.0-project/tsconfig.spec.json b/tests/legacy-cli/e2e/assets/17.0-project/tsconfig.spec.json deleted file mode 100644 index be7e9da76f7b..000000000000 --- a/tests/legacy-cli/e2e/assets/17.0-project/tsconfig.spec.json +++ /dev/null @@ -1,14 +0,0 @@ -/* To learn more about this file see: https://angular.io/config/tsconfig. */ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "outDir": "./out-tsc/spec", - "types": [ - "jasmine" - ] - }, - "include": [ - "src/**/*.spec.ts", - "src/**/*.d.ts" - ] -} diff --git a/tests/legacy-cli/e2e/assets/add-collection-peer-bad/index.js b/tests/legacy-cli/e2e/assets/add-collection-peer-bad/index.js deleted file mode 100644 index 867b3a4eb6fd..000000000000 --- a/tests/legacy-cli/e2e/assets/add-collection-peer-bad/index.js +++ /dev/null @@ -1 +0,0 @@ -exports.default = (options) => tree => tree.create(options.name || 'empty-file-peer-bad', ''); diff --git a/tests/legacy-cli/e2e/assets/add-collection-peer-good/index.js b/tests/legacy-cli/e2e/assets/add-collection-peer-good/index.js deleted file mode 100644 index 4d5dbdca2f69..000000000000 --- a/tests/legacy-cli/e2e/assets/add-collection-peer-good/index.js +++ /dev/null @@ -1 +0,0 @@ -exports.default = (options) => tree => tree.create(options.name || 'empty-file-peer-good', ''); diff --git a/tests/legacy-cli/e2e/assets/add-collection/index.js b/tests/legacy-cli/e2e/assets/add-collection/index.js deleted file mode 100644 index cf404a768650..000000000000 --- a/tests/legacy-cli/e2e/assets/add-collection/index.js +++ /dev/null @@ -1 +0,0 @@ -exports.default = (options) => tree => tree.create(options.name || 'empty-file', ''); diff --git a/tests/legacy-cli/e2e/assets/nested-schematic-dependency/index.js b/tests/legacy-cli/e2e/assets/nested-schematic-dependency/index.js deleted file mode 100644 index cf404a768650..000000000000 --- a/tests/legacy-cli/e2e/assets/nested-schematic-dependency/index.js +++ /dev/null @@ -1 +0,0 @@ -exports.default = (options) => tree => tree.create(options.name || 'empty-file', ''); diff --git a/tests/legacy-cli/e2e/assets/nested-schematic-main/index.js b/tests/legacy-cli/e2e/assets/nested-schematic-main/index.js deleted file mode 100644 index 9763f96fbb58..000000000000 --- a/tests/legacy-cli/e2e/assets/nested-schematic-main/index.js +++ /dev/null @@ -1 +0,0 @@ -exports.default = (options) => require("@angular-devkit/schematics").externalSchematic('empty-app-nested', 'nested', {}); diff --git a/tests/legacy-cli/e2e/assets/schematic-allow-scripts/index.js b/tests/legacy-cli/e2e/assets/schematic-allow-scripts/index.js deleted file mode 100644 index 20fb52c65137..000000000000 --- a/tests/legacy-cli/e2e/assets/schematic-allow-scripts/index.js +++ /dev/null @@ -1,16 +0,0 @@ -const tasks = require("@angular-devkit/schematics/tasks"); - -exports.default = ({ allowScripts, ignoreScripts = false }) => { - return (tree, context) => { - tree.create('/install-test/package.json', JSON.stringify({ - name: 'install-test', - version: '0.0.0', - scripts: { - postinstall: `node run-post.js`, - } - })); - tree.create('/install-test/.npmrc', `ignore-scripts=${ignoreScripts}`); - tree.create('/install-test/run-post.js', 'require("fs").writeFileSync(__dirname + "/post-script-ran", "12345");') - context.addTask(new tasks.NodePackageInstallTask({ workingDirectory: 'install-test', allowScripts })); - }; -}; diff --git a/tests/legacy-cli/e2e/assets/schematic-allow-scripts/schema.json b/tests/legacy-cli/e2e/assets/schematic-allow-scripts/schema.json deleted file mode 100644 index 099432e4063a..000000000000 --- a/tests/legacy-cli/e2e/assets/schematic-allow-scripts/schema.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema", - "type": "object", - "additionalProperties": false, - "properties": { - "allowScripts": { - "type": "boolean" - }, - "ignoreScripts": { - "type": "boolean" - } - } -} - \ No newline at end of file diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.component.html b/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.component.html deleted file mode 100644 index a1ab9650d463..000000000000 --- a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/app/app.component.html +++ /dev/null @@ -1,483 +0,0 @@ - - - - - - - - - - - - -

- -
- - -
- - - Rocket Ship - - - - - - - - - - {{ title }} app is running! - - - Rocket Ship Smoke - - - -
- - -

Resources

-

Here are some links to help you get started:

- - - - -

Next Steps

-

What do you want to do next with your app?

- - - -
- - - - - - - - - - - -
- - -
-
ng generate component xyz
-
ng add @angular/material
-
ng add @angular/pwa
-
ng add _____
-
ng test
-
ng build
-
- - - - - - - - - Gray Clouds Background - - - -
- - - - - - - - - - diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/assets/.gitkeep b/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/assets/.gitkeep deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/index.html b/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/index.html deleted file mode 100644 index ca14f8bfb86f..000000000000 --- a/tests/legacy-cli/e2e/assets/ssr-project-webpack/src/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - 17SsrProjectWebpack - - - - - - - - diff --git a/tests/legacy-cli/e2e/ng-snapshot/package.json b/tests/legacy-cli/e2e/ng-snapshot/package.json deleted file mode 100644 index 4731bb0c63f0..000000000000 --- a/tests/legacy-cli/e2e/ng-snapshot/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "description": "snapshot versions of Angular for e2e testing", - "private": true, - "dependencies": { - "@angular/animations": "github:angular/animations-builds#92dd243cfb5f1c6cbc4c087b44447d5ad6e9a3a8", - "@angular/cdk": "github:angular/cdk-builds#8d81884e24a2750843aa22fcce317043a2e8269f", - "@angular/common": "github:angular/common-builds#f6b59230d9b053e9a8f31dc4a825d9e36e8fbfbb", - "@angular/compiler": "github:angular/compiler-builds#45f05de08a3d82e61bd605084a10c36cca28c067", - "@angular/compiler-cli": "github:angular/compiler-cli-builds#e526aa0562771603568e40cc41bb79dc1c281b55", - "@angular/core": "github:angular/core-builds#d72612860744e8dd78ccba64716e564e1f8189b4", - "@angular/forms": "github:angular/forms-builds#e46e59fb7fdb9f671482d519b8b1874d5930972a", - "@angular/language-service": "github:angular/language-service-builds#4abedd1dd61b1da271feed2d49b3cdc6e511f7de", - "@angular/localize": "github:angular/localize-builds#3a73beb1f111cba189a2b32411ce3002abf628bb", - "@angular/material": "github:angular/material-builds#ac45194365d78b9af35112173e64db35e7711014", - "@angular/material-moment-adapter": "github:angular/material-moment-adapter-builds#6a38cac040db5b9a1ab0ffa727e02186fe45b8a7", - "@angular/platform-browser": "github:angular/platform-browser-builds#92c065f68164da8ae4ff03b8fd0363810346cea5", - "@angular/platform-browser-dynamic": "github:angular/platform-browser-dynamic-builds#ac425d036ba047077f02fe6facd1fead09dd8110", - "@angular/platform-server": "github:angular/platform-server-builds#3b7b01f1fee4991faba29ca77aa50969f33e8091", - "@angular/router": "github:angular/router-builds#a43493435d9af4a72299ad38151d719f44708800", - "@angular/service-worker": "github:angular/service-worker-builds#820115a451140eb347dfdff4ebdc0ffc7c90dfad" - } -} diff --git a/tests/legacy-cli/e2e/setup/001-create-tmp-dir.ts b/tests/legacy-cli/e2e/setup/001-create-tmp-dir.ts deleted file mode 100644 index 4914921eca18..000000000000 --- a/tests/legacy-cli/e2e/setup/001-create-tmp-dir.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { dirname } from 'node:path'; -import { getGlobalVariable, setGlobalVariable } from '../utils/env'; -import { mktempd } from '../utils/utils'; - -export default async function () { - const argv = getGlobalVariable('argv'); - - // Get to a temporary directory. - let tempRoot: string; - if (argv.reuse) { - tempRoot = dirname(argv.reuse); - } else if (argv.tmpdir) { - tempRoot = argv.tmpdir; - } else { - tempRoot = await mktempd('angular-cli-e2e-', process.env.E2E_TEMP); - } - console.log(` Using "${tempRoot}" as temporary directory for a new project.`); - setGlobalVariable('tmp-root', tempRoot); -} diff --git a/tests/legacy-cli/e2e/tests/basic/e2e.ts b/tests/legacy-cli/e2e/tests/basic/e2e.ts deleted file mode 100644 index 655b679192d1..000000000000 --- a/tests/legacy-cli/e2e/tests/basic/e2e.ts +++ /dev/null @@ -1,12 +0,0 @@ -import assert from 'node:assert/strict'; -import { setTimeout } from 'node:timers/promises'; -import { silentNg } from '../../utils/process'; - -export default async function () { - await assert.rejects(silentNg('e2e', 'test-project', '--dev-server-target=')); - - // These should work. - await silentNg('e2e', 'test-project'); - await setTimeout(500); - await silentNg('e2e', 'test-project', '--dev-server-target=test-project:serve'); -} diff --git a/tests/legacy-cli/e2e/tests/build/library/lib-consumption-full-aot.ts b/tests/legacy-cli/e2e/tests/build/library/lib-consumption-full-aot.ts deleted file mode 100644 index 88c80ac61629..000000000000 --- a/tests/legacy-cli/e2e/tests/build/library/lib-consumption-full-aot.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { setTimeout } from 'node:timers/promises'; -import { ng } from '../../../utils/process'; -import { libraryConsumptionSetup } from './setup'; - -export default async function () { - await libraryConsumptionSetup(); - - // Build library in full mode (development) - await ng('build', 'my-lib', '--configuration=development'); - - // Check that the e2e succeeds prod and non prod mode - await ng('e2e', '--configuration=production'); - await setTimeout(500); - await ng('e2e', '--configuration=development'); -} diff --git a/tests/legacy-cli/e2e/tests/build/library/lib-consumption-partial-aot.ts b/tests/legacy-cli/e2e/tests/build/library/lib-consumption-partial-aot.ts deleted file mode 100644 index 5b45a8372f68..000000000000 --- a/tests/legacy-cli/e2e/tests/build/library/lib-consumption-partial-aot.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { setTimeout } from 'node:timers/promises'; -import { ng } from '../../../utils/process'; -import { libraryConsumptionSetup } from './setup'; - -export default async function () { - await libraryConsumptionSetup(); - - // Build library in partial mode (production) - await ng('build', 'my-lib', '--configuration=production'); - - // Check that the e2e succeeds prod and non prod mode - await ng('e2e', '--configuration=production'); - await setTimeout(500); - await ng('e2e', '--configuration=development'); -} diff --git a/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-csp-nonce.ts b/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-csp-nonce.ts deleted file mode 100644 index 19e7dcd28b60..000000000000 --- a/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-csp-nonce.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { getGlobalVariable } from '../../../utils/env'; -import { rimraf, writeMultipleFiles } from '../../../utils/fs'; -import { findFreePort } from '../../../utils/network'; -import { installWorkspacePackages } from '../../../utils/packages'; -import { execAndWaitForOutputToMatch, ng } from '../../../utils/process'; -import { updateJsonFile, updateServerFileForEsbuild, useSha } from '../../../utils/project'; - -export default async function () { - const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; - // forcibly remove in case another test doesn't clean itself up - await rimraf('node_modules/@angular/ssr'); - await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); - await useSha(); - await installWorkspacePackages(); - - if (!useWebpackBuilder) { - await updateJsonFile('angular.json', (json) => { - const build = json['projects']['test-project']['architect']['build']; - build.options.outputMode = undefined; - build.configurations.production.prerender = false; - }); - - await updateServerFileForEsbuild('src/server.ts'); - } - - await writeMultipleFiles({ - 'src/app/app.css': `div { color: #000 }`, - 'src/styles.css': `* { color: #000 }`, - 'src/main.ts': `import { bootstrapApplication } from '@angular/platform-browser'; - import { App } from './app/app'; - import { appConfig } from './app/app.config'; - - (window as any)['doBootstrap'] = () => { - bootstrapApplication(App, appConfig).catch((err) => console.error(err)); - }; - `, - 'src/index.html': ` - - - - - - - - - - - `, - 'e2e/src/app.e2e-spec.ts': ` - import { browser, by, element } from 'protractor'; - import * as webdriver from 'selenium-webdriver'; - - function verifyNoBrowserErrors() { - return browser - .manage() - .logs() - .get('browser') - .then(function (browserLog: any[]) { - const errors: any[] = []; - browserLog.filter((logEntry) => { - const msg = logEntry.message; - console.log('>> ' + msg); - if (logEntry.level.value >= webdriver.logging.Level.INFO.value) { - errors.push(msg); - } - }); - expect(errors).toEqual([]); - }); - } - - describe('Hello world E2E Tests', () => { - beforeAll(async () => { - await browser.waitForAngularEnabled(false); - }); - - it('should display: Welcome', async () => { - // Load the page without waiting for Angular since it is not bootstrapped automatically. - await browser.driver.get(browser.baseUrl); - - expect( - await element(by.css('style[ng-app-id="ng"]')).getText() - ).not.toBeNull(); - - // Test the contents from the server. - expect(await element(by.css('h1')).getText()).toMatch('Hello'); - - // Bootstrap the client side app. - await browser.executeScript('doBootstrap()'); - - // Retest the contents after the client bootstraps. - expect(await element(by.css('h1')).getText()).toMatch('Hello'); - - // Make sure the server styles got replaced by client side ones. - expect( - await element(by.css('style[ng-app-id="ng"]')).isPresent() - ).toBeFalsy(); - expect(await element(by.css('style')).getText()).toMatch(''); - - // Make sure there were no client side errors. - await verifyNoBrowserErrors(); - }); - - it('stylesheets should be configured to load asynchronously', async () => { - // Load the page without waiting for Angular since it is not bootstrapped automatically. - await browser.driver.get(browser.baseUrl); - - // Test the contents from the server. - const linkTag = await browser.driver.findElement( - by.css('link[rel="stylesheet"]') - ); - expect(await linkTag.getAttribute('media')).toMatch('all'); - expect(await linkTag.getAttribute('ngCspMedia')).toBeNull(); - expect(await linkTag.getAttribute('onload')).toBeNull(); - - // Make sure there were no client side errors. - await verifyNoBrowserErrors(); - }); - - it('style tags all have a nonce attribute', async () => { - // Load the page without waiting for Angular since it is not bootstrapped automatically. - await browser.driver.get(browser.baseUrl); - - // Test the contents from the server. - for (const s of await browser.driver.findElements(by.css('style'))) { - expect(await s.getAttribute('nonce')).toBe('{% nonce %}'); - } - - // Make sure there were no client side errors. - await verifyNoBrowserErrors(); - }); - }); - `, - }); - - async function spawnServer(): Promise { - const port = await findFreePort(); - - const runCommand = useWebpackBuilder ? 'serve:ssr' : 'serve:ssr:test-project'; - - await execAndWaitForOutputToMatch( - 'npm', - ['run', runCommand], - /Node Express server listening on/, - { - ...process.env, - 'PORT': String(port), - }, - ); - - return port; - } - - await ng('build'); - - if (useWebpackBuilder) { - // Build server code - await ng('run', 'test-project:server'); - } - - const port = await spawnServer(); - await ng('e2e', `--base-url=http://localhost:${port}`, '--dev-server-target='); -} diff --git a/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-ngmodule.ts b/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-ngmodule.ts deleted file mode 100644 index f05d2182bbd2..000000000000 --- a/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-ngmodule.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { getGlobalVariable } from '../../../utils/env'; -import { rimraf, writeMultipleFiles } from '../../../utils/fs'; -import { findFreePort } from '../../../utils/network'; -import { installWorkspacePackages } from '../../../utils/packages'; -import { execAndWaitForOutputToMatch, ng } from '../../../utils/process'; -import { - updateJsonFile, - updateServerFileForEsbuild, - useCIChrome, - useCIDefaults, - useSha, -} from '../../../utils/project'; - -export default async function () { - // forcibly remove in case another test doesn't clean itself up - await rimraf('node_modules/@angular/ssr'); - - await ng('generate', 'app', 'test-project-two', '--no-standalone', '--skip-install'); - await ng('generate', 'private-e2e', '--related-app-name=test-project-two'); - - // Setup testing to use CI Chrome. - await useCIChrome('test-project-two', 'projects/test-project-two/e2e/'); - await useCIDefaults('test-project-two'); - - const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; - - if (useWebpackBuilder) { - await updateJsonFile('angular.json', (json) => { - const build = json['projects']['test-project-two']['architect']['build']; - build.builder = '@angular-devkit/build-angular:browser'; - build.options = { - ...build.options, - main: build.options.browser, - browser: undefined, - index: 'src/index.html', - }; - - build.configurations.development = { - ...build.configurations.development, - vendorChunk: true, - namedChunks: true, - buildOptimizer: false, - }; - }); - } - - await ng( - 'add', - '@angular/ssr', - '--skip-confirmation', - '--skip-install', - '--project=test-project-two', - ); - - await useSha(); - await installWorkspacePackages(); - - if (!useWebpackBuilder) { - // Disable prerendering - await updateJsonFile('angular.json', (json) => { - const build = json['projects']['test-project-two']['architect']['build']; - build.configurations.production.prerender = false; - build.options.outputMode = undefined; - }); - - await updateServerFileForEsbuild('projects/test-project-two/src/server.ts'); - } - - await writeMultipleFiles({ - 'projects/test-project-two/src/app/app.css': `div { color: #000 }`, - 'projects/test-project-two/src/styles.css': `* { color: #000 }`, - 'projects/test-project-two/src/main.ts': ` - import { platformBrowser } from '@angular/platform-browser'; - import { AppModule } from './app/app-module'; - - (window as any)['doBootstrap'] = () => { - platformBrowser() - .bootstrapModule(AppModule) - .catch((err) => console.error(err)); - }; - `, - 'projects/test-project-two/e2e/src/app.e2e-spec.ts': ` - import { browser, by, element } from 'protractor'; - import * as webdriver from 'selenium-webdriver'; - - function verifyNoBrowserErrors() { - return browser - .manage() - .logs() - .get('browser') - .then(function (browserLog: any[]) { - const errors: any[] = []; - browserLog.filter((logEntry) => { - const msg = logEntry.message; - console.log('>> ' + msg); - if (logEntry.level.value >= webdriver.logging.Level.INFO.value) { - errors.push(msg); - } - }); - expect(errors).toEqual([]); - }); - } - - describe('Hello world E2E Tests', () => { - beforeAll(async () => { - await browser.waitForAngularEnabled(false); - }); - - it('should display: Welcome', async () => { - // Load the page without waiting for Angular since it is not bootstrapped automatically. - await browser.driver.get(browser.baseUrl); - - const style = await browser.driver.findElement(by.css('style[ng-app-id="ng"]')); - expect(await style.getText()).not.toBeNull(); - - // Test the contents from the server. - const serverDiv = await browser.driver.findElement(by.css('h1')); - expect(await serverDiv.getText()).toMatch('Hello'); - - // Bootstrap the client side app. - await browser.executeScript('doBootstrap()'); - - // Retest the contents after the client bootstraps. - expect(await element(by.css('h1')).getText()).toMatch('Hello'); - - // Make sure the server styles got replaced by client side ones. - expect(await element(by.css('style[ng-app-id="ng"]')).isPresent()).toBeFalsy(); - expect(await element(by.css('style')).getText()).toMatch(''); - - // Make sure there were no client side errors. - await verifyNoBrowserErrors(); - }); - - it('stylesheets should be configured to load asynchronously', async () => { - // Load the page without waiting for Angular since it is not bootstrapped automatically. - await browser.driver.get(browser.baseUrl); - - // Test the contents from the server. - const styleTag = await browser.driver.findElement(by.css('link[rel="stylesheet"]')); - expect(await styleTag.getAttribute('media')).toMatch('all'); - - // Make sure there were no client side errors. - await verifyNoBrowserErrors(); - }); - }); - `, - }); - - async function spawnServer(): Promise { - const port = await findFreePort(); - - const runCommand = useWebpackBuilder ? 'serve:ssr' : `serve:ssr:test-project-two`; - - await execAndWaitForOutputToMatch( - 'npm', - ['run', runCommand], - /Node Express server listening on/, - { - ...process.env, - 'PORT': String(port), - }, - ); - - return port; - } - - await ng('build', 'test-project-two'); - - if (useWebpackBuilder) { - // Build server code - await ng('run', `test-project-two:server`); - } - - const port = await spawnServer(); - await ng( - 'e2e', - '--project=test-project-two', - `--base-url=http://localhost:${port}`, - '--dev-server-target=', - ); -} diff --git a/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-standalone.ts b/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-standalone.ts deleted file mode 100644 index 7c819e67693a..000000000000 --- a/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-standalone.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { getGlobalVariable } from '../../../utils/env'; -import { rimraf, writeMultipleFiles } from '../../../utils/fs'; -import { findFreePort } from '../../../utils/network'; -import { installWorkspacePackages } from '../../../utils/packages'; -import { execAndWaitForOutputToMatch, ng } from '../../../utils/process'; -import { updateJsonFile, updateServerFileForEsbuild, useSha } from '../../../utils/project'; - -export default async function () { - // forcibly remove in case another test doesn't clean itself up - await rimraf('node_modules/@angular/ssr'); - - const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; - await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); - - if (!useWebpackBuilder) { - // Disable prerendering - await updateJsonFile('angular.json', (json) => { - const build = json['projects']['test-project']['architect']['build']; - build.options.outputMode = undefined; - }); - - await updateServerFileForEsbuild('src/server.ts'); - } - - await useSha(); - await installWorkspacePackages(); - - await writeMultipleFiles({ - 'src/app/app.css': `div { color: #000 }`, - 'src/styles.css': `* { color: #000 }`, - 'src/main.ts': `import { bootstrapApplication } from '@angular/platform-browser'; - import { App } from './app/app'; - import { appConfig } from './app/app.config'; - - (window as any)['doBootstrap'] = () => { - bootstrapApplication(App, appConfig).catch((err) => console.error(err)); - }; - `, - 'e2e/src/app.e2e-spec.ts': ` - import { browser, by, element } from 'protractor'; - import * as webdriver from 'selenium-webdriver'; - - function verifyNoBrowserErrors() { - return browser - .manage() - .logs() - .get('browser') - .then(function (browserLog: any[]) { - const errors: any[] = []; - browserLog.filter((logEntry) => { - const msg = logEntry.message; - console.log('>> ' + msg); - if (logEntry.level.value >= webdriver.logging.Level.INFO.value) { - errors.push(msg); - } - }); - expect(errors).toEqual([]); - }); - } - - describe('Hello world E2E Tests', () => { - beforeAll(async () => { - await browser.waitForAngularEnabled(false); - }); - - it('should display: Welcome', async () => { - // Load the page without waiting for Angular since it is not bootstrapped automatically. - await browser.driver.get(browser.baseUrl); - - const style = await browser.driver.findElement(by.css('style[ng-app-id="ng"]')); - expect(await style.getText()).not.toBeNull(); - - // Test the contents from the server. - const serverDiv = await browser.driver.findElement(by.css('h1')); - expect(await serverDiv.getText()).toMatch('Hello'); - - // Bootstrap the client side app. - await browser.executeScript('doBootstrap()'); - - // Retest the contents after the client bootstraps. - expect(await element(by.css('h1')).getText()).toMatch('Hello'); - - // Make sure the server styles got replaced by client side ones. - expect(await element(by.css('style[ng-app-id="ng"]')).isPresent()).toBeFalsy(); - expect(await element(by.css('style')).getText()).toMatch(''); - - // Make sure there were no client side errors. - await verifyNoBrowserErrors(); - }); - - it('stylesheets should be configured to load asynchronously', async () => { - // Load the page without waiting for Angular since it is not bootstrapped automatically. - await browser.driver.get(browser.baseUrl); - - // Test the contents from the server. - const styleTag = await browser.driver.findElement(by.css('link[rel="stylesheet"]')); - expect(await styleTag.getAttribute('media')).toMatch('all'); - - // Make sure there were no client side errors. - await verifyNoBrowserErrors(); - }); - }); - `, - }); - - async function spawnServer(): Promise { - const port = await findFreePort(); - const runCommand = useWebpackBuilder ? 'serve:ssr' : 'serve:ssr:test-project'; - - await execAndWaitForOutputToMatch( - 'npm', - ['run', runCommand], - /Node Express server listening on/, - { - ...process.env, - 'PORT': String(port), - }, - ); - - return port; - } - - await ng('build'); - if (useWebpackBuilder) { - // Build server code - await ng('run', `test-project:server`); - } - - const port = await spawnServer(); - await ng('e2e', `--base-url=http://localhost:${port}`, '--dev-server-target='); -} diff --git a/tests/legacy-cli/e2e/tests/commands/add/dir.ts b/tests/legacy-cli/e2e/tests/commands/add/dir.ts deleted file mode 100644 index f5fadc486b3d..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/add/dir.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { assetDir } from '../../../utils/assets'; -import { expectFileToExist } from '../../../utils/fs'; -import { ng } from '../../../utils/process'; - -export default async function () { - await ng('add', assetDir('add-collection'), '--name=blah', '--skip-confirmation'); - await expectFileToExist('blah'); -} diff --git a/tests/legacy-cli/e2e/tests/commands/add/file.ts b/tests/legacy-cli/e2e/tests/commands/add/file.ts deleted file mode 100644 index 6096dac6f666..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/add/file.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { assetDir } from '../../../utils/assets'; -import { expectFileToExist } from '../../../utils/fs'; -import { ng } from '../../../utils/process'; - -export default async function () { - await ng('add', assetDir('add-collection.tgz'), '--name=blah', '--skip-confirmation'); - await expectFileToExist('blah'); -} diff --git a/tests/legacy-cli/e2e/tests/commands/add/peer.ts b/tests/legacy-cli/e2e/tests/commands/add/peer.ts deleted file mode 100644 index d085efadf080..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/add/peer.ts +++ /dev/null @@ -1,24 +0,0 @@ -import assert from 'node:assert/strict'; -import { assetDir } from '../../../utils/assets'; -import { ng } from '../../../utils/process'; - -const warning = 'Adding the package may not succeed.'; - -export default async function () { - const { stdout: bad } = await ng( - 'add', - assetDir('add-collection-peer-bad'), - '--skip-confirmation', - ); - assert.match(bad, new RegExp(warning), 'peer warning not shown on bad package'); - - const { stdout: base } = await ng('add', assetDir('add-collection'), '--skip-confirmation'); - assert.doesNotMatch(base, new RegExp(warning), 'peer warning shown on base package'); - - const { stdout: good } = await ng( - 'add', - assetDir('add-collection-peer-good'), - '--skip-confirmation', - ); - assert.doesNotMatch(good, new RegExp(warning), 'peer warning shown on good package'); -} diff --git a/tests/legacy-cli/e2e/tests/commands/add/secure-registry.ts b/tests/legacy-cli/e2e/tests/commands/add/secure-registry.ts deleted file mode 100644 index a27ba708637d..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/add/secure-registry.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { expectFileNotToExist, expectFileToExist } from '../../../utils/fs'; -import { getActivePackageManager, installWorkspacePackages } from '../../../utils/packages'; -import { git, ng } from '../../../utils/process'; -import { createNpmConfigForAuthentication } from '../../../utils/registry'; -import { expectToFail } from '../../../utils/utils'; - -export default async function () { - // The environment variable has priority over the .npmrc - delete process.env['NPM_CONFIG_REGISTRY']; - const isNpm = getActivePackageManager() === 'npm'; - - const command = ['add', '@angular/pwa', '--skip-confirmation']; - await expectFileNotToExist('public/manifest.webmanifest'); - - // Works with unscoped registry authentication details - if (!isNpm) { - // NPM no longer support unscoped. - await createNpmConfigForAuthentication(false); - await ng(...command); - await expectFileToExist('public/manifest.webmanifest'); - await git('clean', '-dxf'); - } - // Works with scoped registry authentication details - await expectFileNotToExist('public/manifest.webmanifest'); - - await createNpmConfigForAuthentication(true); - await ng(...command); - await expectFileToExist('public/manifest.webmanifest'); - - // Invalid authentication token - if (isNpm) { - // NPM no longer support unscoped. - await createNpmConfigForAuthentication(false, true); - await expectToFail(() => ng(...command)); - } - - await createNpmConfigForAuthentication(true, true); - await expectToFail(() => ng(...command)); - - await git('clean', '-dxf'); - await installWorkspacePackages(); -} diff --git a/tests/legacy-cli/e2e/tests/commands/e2e/e2e-and-serve.ts b/tests/legacy-cli/e2e/tests/commands/e2e/e2e-and-serve.ts deleted file mode 100644 index 7e70e885a929..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/e2e/e2e-and-serve.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { silentNg } from '../../../utils/process'; -import { ngServe } from '../../../utils/project'; - -export default async function () { - // Should run side-by-side with `ng serve` - await ngServe(); - await silentNg('e2e'); -} diff --git a/tests/legacy-cli/e2e/tests/commands/e2e/multiple-specs.ts b/tests/legacy-cli/e2e/tests/commands/e2e/multiple-specs.ts deleted file mode 100644 index c7da20adf900..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/e2e/multiple-specs.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { silentNg } from '../../../utils/process'; -import { moveFile, copyFile } from '../../../utils/fs'; - -export default async function () { - // Should accept different multiple spec files - await moveFile('./e2e/src/app.e2e-spec.ts', './e2e/src/renamed-app.e2e-spec.ts'); - await copyFile('./e2e/src/renamed-app.e2e-spec.ts', './e2e/src/another-app.e2e-spec.ts'); - - await silentNg( - 'e2e', - 'test-project', - '--specs', - './e2e/renamed-app.e2e-spec.ts', - '--specs', - './e2e/another-app.e2e-spec.ts', - ); -} diff --git a/tests/legacy-cli/e2e/tests/commands/e2e/protractor-config.ts b/tests/legacy-cli/e2e/tests/commands/e2e/protractor-config.ts deleted file mode 100644 index 52e9494e4062..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/e2e/protractor-config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { moveFile } from '../../../utils/fs'; -import { silentNg } from '../../../utils/process'; - -export default async function () { - // Should accept different config file - await moveFile('./e2e/protractor.conf.js', './e2e/renamed-protractor.conf.js'); - await silentNg('e2e', 'test-project', '--protractor-config=e2e/renamed-protractor.conf.js'); -} diff --git a/tests/legacy-cli/e2e/tests/commands/e2e/suite.ts b/tests/legacy-cli/e2e/tests/commands/e2e/suite.ts deleted file mode 100644 index 519ed63a71bb..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/e2e/suite.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { silentNg } from '../../../utils/process'; -import { replaceInFile } from '../../../utils/fs'; - -export default async function () { - // Suites block need to be added in the protractor.conf.js file to test suites - await replaceInFile( - 'e2e/protractor.conf.js', - `allScriptsTimeout: 11000,`, - `allScriptsTimeout: 11000, - suites: { - app: './e2e/src/app.e2e-spec.ts' - }, - `, - ); - await silentNg('e2e', 'test-project', '--suite=app'); -} diff --git a/tests/legacy-cli/e2e/tests/commands/serve/ssr-http-requests-assets.ts b/tests/legacy-cli/e2e/tests/commands/serve/ssr-http-requests-assets.ts deleted file mode 100644 index 78c5b4b94995..000000000000 --- a/tests/legacy-cli/e2e/tests/commands/serve/ssr-http-requests-assets.ts +++ /dev/null @@ -1,89 +0,0 @@ -import assert from 'node:assert'; - -import { killAllProcesses, ng } from '../../../utils/process'; -import { rimraf, writeMultipleFiles } from '../../../utils/fs'; -import { installWorkspacePackages } from '../../../utils/packages'; -import { ngServe, useSha } from '../../../utils/project'; -import { getGlobalVariable } from '../../../utils/env'; - -export default async function () { - const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; - - // Forcibly remove in case another test doesn't clean itself up. - await rimraf('node_modules/@angular/ssr'); - if (useWebpackBuilder) { - // `--server-routing` not supported in `browser` builder. - await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); - } else { - await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); - } - - await useSha(); - await installWorkspacePackages(); - - await writeMultipleFiles({ - // Add http client and route - 'src/app/app.config.ts': ` - import { ApplicationConfig } from '@angular/core'; - import { provideRouter } from '@angular/router'; - - import { Home } from './home/home'; - import { provideClientHydration } from '@angular/platform-browser'; - import { provideHttpClient, withFetch } from '@angular/common/http'; - - export const appConfig: ApplicationConfig = { - providers: [ - provideRouter([{ - path: '', - component: Home, - }]), - provideClientHydration(), - provideHttpClient(withFetch()), - ], - }; - `, - // Add asset - 'public/media.json': JSON.stringify({ dataFromAssets: true }), - // Update component to do an HTTP call to asset. - 'src/app/app.ts': ` - import { Component, inject } from '@angular/core'; - import { CommonModule } from '@angular/common'; - import { RouterOutlet } from '@angular/router'; - import { HttpClient } from '@angular/common/http'; - - @Component({ - selector: 'app-root', - standalone: true, - imports: [CommonModule, RouterOutlet], - template: \` -

{{ data | json }}

- - \`, - }) - export class App { - data: any; - constructor() { - const http = inject(HttpClient); - http.get('/media.json').toPromise().then((d) => { - this.data = d; - }); - } - } - `, - }); - - await ng('generate', 'component', 'home'); - const match = /

{[\S\s]*"dataFromAssets":[\s\S]*true[\S\s]*}<\/p>/; - const port = await ngServe('--no-ssl'); - assert.match(await (await fetch(`http://localhost:${port}/`)).text(), match); - - await killAllProcesses(); - - try { - process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; - const sslPort = await ngServe('--ssl'); - assert.match(await (await fetch(`https://localhost:${sslPort}/`)).text(), match); - } finally { - process.env.NODE_TLS_REJECT_UNAUTHORIZED = '1'; - } -} diff --git a/tests/legacy-cli/e2e/tests/generate/application/application-basic.ts b/tests/legacy-cli/e2e/tests/generate/application/application-basic.ts deleted file mode 100644 index 615e08426c2b..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/application/application-basic.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { expectFileToMatch } from '../../../utils/fs'; -import { ng } from '../../../utils/process'; -import { useCIChrome } from '../../../utils/project'; - -export default function () { - return ng('generate', 'application', 'app2') - .then(() => expectFileToMatch('angular.json', /\"app2\":/)) - .then(() => useCIChrome('app2', 'projects/app2')) - .then(() => ng('test', 'app2', '--watch=false')); -} diff --git a/tests/legacy-cli/e2e/tests/generate/application/application-zoneless.ts b/tests/legacy-cli/e2e/tests/generate/application/application-zoneless.ts deleted file mode 100644 index b7ceaddf3cb1..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/application/application-zoneless.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { ng } from '../../../utils/process'; -import { useCIChrome } from '../../../utils/project'; - -export default async function () { - await ng('generate', 'app', 'standalone', '--zoneless', '--standalone'); - await useCIChrome('standalone', 'projects/standalone'); - await ng('test', 'standalone', '--watch=false'); - await ng('build', 'standalone'); - - await ng('generate', 'app', 'ngmodules', '--zoneless', '--no-standalone', '--skip-install'); - await useCIChrome('ngmodules', 'projects/ngmodules'); - await ng('test', 'ngmodules', '--watch=false'); - await ng('build', 'ngmodules'); -} diff --git a/tests/legacy-cli/e2e/tests/generate/class.ts b/tests/legacy-cli/e2e/tests/generate/class.ts deleted file mode 100644 index e1b21f28982a..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/class.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { join } from 'node:path'; -import { ng } from '../../utils/process'; -import { expectFileToExist } from '../../utils/fs'; - -export default function () { - const projectDir = join('src', 'app'); - - return ( - ng('generate', 'class', 'test-class') - .then(() => expectFileToExist(projectDir)) - .then(() => expectFileToExist(join(projectDir, 'test-class.ts'))) - .then(() => expectFileToExist(join(projectDir, 'test-class.spec.ts'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')) - ); -} diff --git a/tests/legacy-cli/e2e/tests/generate/interface.ts b/tests/legacy-cli/e2e/tests/generate/interface.ts deleted file mode 100644 index d58248d27ac4..000000000000 --- a/tests/legacy-cli/e2e/tests/generate/interface.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { join } from 'node:path'; -import { ng } from '../../utils/process'; -import { expectFileToExist } from '../../utils/fs'; - -export default function () { - const interfaceDir = join('src', 'app'); - - return ( - ng('generate', 'interface', 'test-interface', 'model') - .then(() => expectFileToExist(interfaceDir)) - .then(() => expectFileToExist(join(interfaceDir, 'test-interface.model.ts'))) - - // Try to run the unit tests. - .then(() => ng('test', '--watch=false')) - ); -} diff --git a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es2015-e2e.ts b/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es2015-e2e.ts deleted file mode 100644 index 3fe337c4c90f..000000000000 --- a/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es2015-e2e.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { getGlobalVariable } from '../../utils/env'; -import { ng } from '../../utils/process'; -import { langTranslations, setupI18nConfig } from './setup'; - -export default async function () { - // Setup i18n tests and config. - await setupI18nConfig(); - - for (const { lang } of langTranslations) { - // Execute Application E2E tests with dev server - await ng('e2e', `--configuration=${lang}`, '--port=0'); - } -} diff --git a/tests/legacy-cli/e2e/tests/test/test-environment.ts b/tests/legacy-cli/e2e/tests/test/test-environment.ts deleted file mode 100644 index 1a4dadaa4317..000000000000 --- a/tests/legacy-cli/e2e/tests/test/test-environment.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { ng } from '../../utils/process'; -import { writeFile, writeMultipleFiles } from '../../utils/fs'; -import { updateJsonFile } from '../../utils/project'; - -export default function () { - // Tests run in 'dev' environment by default. - return ( - writeMultipleFiles({ - 'src/environment.prod.ts': ` - export const environment = { - production: true - };`, - 'src/environment.ts': ` - export const environment = { - production: false - }; - `, - 'src/app/environment.spec.ts': ` - import { environment } from '../environment'; - - describe('Test environment', () => { - it('should have production disabled', () => { - expect(environment.production).toBe(false); - }); - }); - `, - }) - .then(() => ng('test', '--watch=false')) - .then(() => - updateJsonFile('angular.json', (configJson) => { - const appArchitect = configJson.projects['test-project'].architect; - appArchitect.test.configurations = { - production: { - fileReplacements: [ - { - replace: 'src/environment.ts', - with: 'src/environment.prod.ts', - }, - ], - }, - }; - }), - ) - - // Tests can run in different environment. - .then(() => - writeFile( - 'src/app/environment.spec.ts', - ` - import { environment } from '../environment'; - - describe('Test environment', () => { - it('should have production enabled', () => { - expect(environment.production).toBe(true); - }); - }); - `, - ), - ) - .then(() => ng('test', '--configuration=production', '--watch=false')) - ); -} diff --git a/tests/legacy-cli/e2e/utils/network.ts b/tests/legacy-cli/e2e/utils/network.ts deleted file mode 100644 index a869d9289ad2..000000000000 --- a/tests/legacy-cli/e2e/utils/network.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { AddressInfo, createServer } from 'node:net'; - -export function findFreePort(): Promise { - return new Promise((resolve, reject) => { - const srv = createServer(); - srv.once('listening', () => { - const port = (srv.address() as AddressInfo).port; - srv.close((e) => (e ? reject(e) : resolve(port))); - }); - srv.once('error', (e) => srv.close(() => reject(e))); - srv.listen(); - }); -} diff --git a/tests/package.json b/tests/package.json index 4aec9553824b..17660ff2192e 100644 --- a/tests/package.json +++ b/tests/package.json @@ -1,7 +1,8 @@ { "devDependencies": { + "@types/tar-stream": "3.1.4", "@angular-devkit/schematics": "workspace:*", - "rxjs": "7.8.2", + "tar-stream": "3.1.7", "tree-kill": "1.2.2" } } diff --git a/tests/legacy-cli/rollup.config.mjs b/tests/rollup.config.mjs similarity index 87% rename from tests/legacy-cli/rollup.config.mjs rename to tests/rollup.config.mjs index 0fc2768c5057..c48299094fef 100644 --- a/tests/legacy-cli/rollup.config.mjs +++ b/tests/rollup.config.mjs @@ -25,7 +25,7 @@ for (const file of testFiles) { export default { input: chunks, - external: [], + external: ['undici', 'puppeteer'], // This cannot be bundled as `node:sqlite` is experimental in node.js 22. Remove once this feature is no longer behind a flag plugins: [ nodeResolve({ preferBuiltins: true, diff --git a/tests/legacy-cli/tsconfig.json b/tests/tsconfig.json similarity index 64% rename from tests/legacy-cli/tsconfig.json rename to tests/tsconfig.json index 235d85b0bb7c..5070cc5b6927 100644 --- a/tests/legacy-cli/tsconfig.json +++ b/tests/tsconfig.json @@ -1,5 +1,5 @@ { - "extends": "../../tsconfig-test.json", + "extends": "../tsconfig-test.json", "compilerOptions": { "paths": {} }, "exclude": ["e2e/assets/**"] } diff --git a/tests/legacy-cli/verdaccio.yaml b/tests/verdaccio.yaml similarity index 100% rename from tests/legacy-cli/verdaccio.yaml rename to tests/verdaccio.yaml diff --git a/tests/legacy-cli/verdaccio_auth.yaml b/tests/verdaccio_auth.yaml similarity index 100% rename from tests/legacy-cli/verdaccio_auth.yaml rename to tests/verdaccio_auth.yaml diff --git a/tools/BUILD.bazel b/tools/BUILD.bazel index 65954dc5e6bc..4804a9ee59a6 100644 --- a/tools/BUILD.bazel +++ b/tools/BUILD.bazel @@ -30,11 +30,3 @@ js_binary( ], entry_point = "quicktype_runner.js", ) - -js_binary( - name = "ng_example_db", - data = [ - "example_db_generator.js", - ], - entry_point = "example_db_generator.js", -) diff --git a/tools/baseline_browserslist/BUILD.bazel b/tools/baseline_browserslist/BUILD.bazel deleted file mode 100644 index 7680d4e021d0..000000000000 --- a/tools/baseline_browserslist/BUILD.bazel +++ /dev/null @@ -1,52 +0,0 @@ -load("@aspect_rules_js//js:defs.bzl", "js_binary") -load("@aspect_rules_ts//ts:defs.bzl", "ts_config") -load("@npm//:defs.bzl", "npm_link_all_packages") -load("//tools:defaults.bzl", "jasmine_test", "ts_project") - -npm_link_all_packages() - -js_binary( - name = "baseline_browserslist", - data = [":baseline_browserslist_lib"], - entry_point = "index.mjs", - visibility = ["//:__subpackages__"], -) - -ts_project( - name = "baseline_browserslist_lib", - srcs = [ - "generate_browserslist.mts", - "index.mts", - ], - source_map = True, - tsconfig = ":build_tsconfig", - deps = [":node_modules/baseline-browser-mapping"], -) - -ts_project( - name = "baseline_browserslist_test_lib", - testonly = True, - srcs = ["generate_browserslist_spec.mts"], - tsconfig = ":test_tsconfig", - deps = [":baseline_browserslist_lib"], -) - -jasmine_test( - name = "test", - data = [":baseline_browserslist_test_lib"], -) - -ts_config( - name = "build_tsconfig", - src = "tsconfig-build.json", - deps = [ - "//:build-tsconfig-esm", - "//:node_modules/@types/node", - ], -) - -ts_config( - name = "test_tsconfig", - src = "tsconfig-test.json", - deps = ["//:test-tsconfig-esm"], -) diff --git a/tools/baseline_browserslist/baseline_browserslist.bzl b/tools/baseline_browserslist/baseline_browserslist.bzl deleted file mode 100644 index 144b33153828..000000000000 --- a/tools/baseline_browserslist/baseline_browserslist.bzl +++ /dev/null @@ -1,26 +0,0 @@ -"""Generates a `browserslist` configuration from a Baseline date.""" - -load("@aspect_rules_js//js:defs.bzl", "js_run_binary") - -def baseline_browserslist(name, baseline, out, **kwargs): - """Generates a `browserslist` configuration from a Baseline date. - - Args: - name: Name of this target. - baseline: A string date in "YYYY-MM-DD" format of the Baseline widely - available browser set to use in the generated `browserslist`. - out: Name of the output browserslist file. Prefer using `.browserslistrc` - for the output as the `browserslist` package seems to not like files - with a different name, even when explicitly provided. - - See: https://web.dev/baseline - """ - - js_run_binary( - name = name, - srcs = [], - tool = Label(":baseline_browserslist"), - stdout = out, - args = [baseline], - **kwargs - ) diff --git a/tools/baseline_browserslist/generate_browserslist.mts b/tools/baseline_browserslist/generate_browserslist.mts deleted file mode 100644 index 68dc8d7e2c5b..000000000000 --- a/tools/baseline_browserslist/generate_browserslist.mts +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.dev/license - */ - -import { getCompatibleVersions } from 'baseline-browser-mapping'; - -// Map `baseline-browser-mapping` browsers to `browserslist` browsers. -const browsers: Record = { - chrome: 'Chrome', - chrome_android: 'ChromeAndroid', - edge: 'Edge', - firefox: 'Firefox', - firefox_android: 'FirefoxAndroid', - safari: 'Safari', - safari_ios: 'iOS', -}; - -/** - * Generates the `browserslist` configuration for the given Baseline date. - * - * @param date The Baseline "widely available" date to generate a `browserslist` - * configuration for. Uses `YYYY-MM-DD` format. - * @returns The `browserslist` configuration file content. - */ -export function generateBrowserslist(date: string): string { - // Generate a `browserslist` configuration. - return getCompatibleVersions({ - widelyAvailableOnDate: date, - includeDownstreamBrowsers: false, - }) - .filter(({ browser }) => browsers[browser]) - .map(({ browser, version }) => `${browsers[browser]} >= ${version}`) - .join('\n'); -} diff --git a/tools/baseline_browserslist/generate_browserslist_spec.mts b/tools/baseline_browserslist/generate_browserslist_spec.mts deleted file mode 100644 index bbf5b529149b..000000000000 --- a/tools/baseline_browserslist/generate_browserslist_spec.mts +++ /dev/null @@ -1,27 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.dev/license - */ - -import { generateBrowserslist } from './generate_browserslist.mjs'; - -describe('generate_browserslist', () => { - describe('generateBrowserslist', () => { - it('generates a `browserslist` file', () => { - expect(generateBrowserslist('2025-03-31').trim()).toBe( - ` -Chrome >= 105 -ChromeAndroid >= 105 -Edge >= 105 -Firefox >= 104 -FirefoxAndroid >= 104 -Safari >= 16 -iOS >= 16 - `.trim(), - ); - }); - }); -}); diff --git a/tools/baseline_browserslist/index.mts b/tools/baseline_browserslist/index.mts deleted file mode 100644 index 78d5aec5e3d5..000000000000 --- a/tools/baseline_browserslist/index.mts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.dev/license - */ - -import { generateBrowserslist } from './generate_browserslist.mjs'; - -const [baselineDate] = process.argv.slice(2); -const browserslist = generateBrowserslist(baselineDate); - -// eslint-disable-next-line no-console -console.log(browserslist); diff --git a/tools/baseline_browserslist/package.json b/tools/baseline_browserslist/package.json deleted file mode 100644 index b4eebd84e3dc..000000000000 --- a/tools/baseline_browserslist/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "type": "module", - "devDependencies": { - "baseline-browser-mapping": "2.6.3" - } -} diff --git a/tools/baseline_browserslist/tsconfig-build.json b/tools/baseline_browserslist/tsconfig-build.json deleted file mode 100644 index acbbe1ae9949..000000000000 --- a/tools/baseline_browserslist/tsconfig-build.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig-build-esm.json", - "include": ["**.mts"], - "exclude": ["**_spec.mts"], - "compilerOptions": { - "types": ["node"] - } -} diff --git a/tools/baseline_browserslist/tsconfig-test.json b/tools/baseline_browserslist/tsconfig-test.json deleted file mode 100644 index 48ba7db3fd84..000000000000 --- a/tools/baseline_browserslist/tsconfig-test.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "../../tsconfig-test-esm.json", - "include": ["**_spec.mts"] -} diff --git a/tools/baseline_browserslist/tsconfig.json b/tools/baseline_browserslist/tsconfig.json deleted file mode 100644 index 53c965a91293..000000000000 --- a/tools/baseline_browserslist/tsconfig.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "files": [], - "references": ["./tsconfig-build.json", "./tsconfig-test.json"] -} diff --git a/tools/bazel/npm_package.bzl b/tools/bazel/npm_package.bzl index 0a76bfe1bb73..c6ce650d3971 100644 --- a/tools/bazel/npm_package.bzl +++ b/tools/bazel/npm_package.bzl @@ -45,7 +45,7 @@ def npm_package( pkg_label = to_label(pkg_dep) if pkg_label.name != "package.json": fail("ERROR: only package.json files allowed in pkg_deps of pkg_npm macro") - pkg_deps_copies.append("@%s//%s:package_json_copy" % (pkg_label.workspace_name, pkg_label.package)) + pkg_deps_copies.append("@@%s//%s:package_json_copy" % (pkg_label.repo_name, pkg_label.package)) # Substitute dependencies on other packages in this repo with tarballs. link_package_json_to_tarballs( @@ -119,6 +119,7 @@ def npm_package( name = "npm_package_archive", srcs = [":pkg"], extension = "tgz", - strip_prefix = "./npm_package", + # should not be built unless it is a dependency of another rule + tags = ["manual"], visibility = visibility, ) diff --git a/tools/defaults.bzl b/tools/defaults.bzl index cde6f8c43dd6..d301591a32ba 100644 --- a/tools/defaults.bzl +++ b/tools/defaults.bzl @@ -2,6 +2,7 @@ load("@aspect_bazel_lib//lib:copy_to_bin.bzl", _copy_to_bin = "copy_to_bin") load("@aspect_rules_jasmine//jasmine:defs.bzl", _jasmine_test = "jasmine_test") load("@aspect_rules_js//js:defs.bzl", _js_binary = "js_binary") load("@devinfra//bazel/ts_project:index.bzl", "strict_deps_test") +load("@rules_angular//src/ng_examples_db:index.bzl", _ng_examples_db = "ng_examples_db") load("@rules_angular//src/ng_package:index.bzl", _ng_package = "ng_package") load("@rules_angular//src/ts_project:index.bzl", _ts_project = "ts_project") load("//tools:substitutions.bzl", "substitutions") @@ -12,8 +13,8 @@ def ts_project( deps = [], tsconfig = None, testonly = False, + source_map = True, visibility = None, - ignore_strict_deps = False, **kwargs): if tsconfig == None: tsconfig = "//:test-tsconfig" if testonly else "//:build-tsconfig" @@ -22,18 +23,19 @@ def ts_project( name = name, testonly = testonly, declaration = True, + source_map = source_map, tsconfig = tsconfig, visibility = visibility, deps = deps, **kwargs ) - if not ignore_strict_deps: - strict_deps_test( - name = "%s_strict_deps_test" % name, - srcs = kwargs.get("srcs", []), - deps = deps, - ) + strict_deps_test( + name = "%s_strict_deps_test" % name, + srcs = kwargs.get("srcs", []), + tsconfig = tsconfig, + deps = deps, + ) def npm_package(**kwargs): _npm_package(**kwargs) @@ -44,13 +46,16 @@ def copy_to_bin(**kwargs): def js_binary(**kwargs): _js_binary(**kwargs) -def ng_package(deps = [], **kwargs): +def ng_package(deps = [], extra_substitutions = {}, **kwargs): + nostamp_subs = dict(substitutions["nostamp"], **extra_substitutions) + stamp_subs = dict(substitutions["stamp"], **extra_substitutions) + _ng_package( deps = deps, license = "//:LICENSE", substitutions = select({ - "//:stamp": substitutions["stamp"], - "//conditions:default": substitutions["nostamp"], + "//:stamp": stamp_subs, + "//conditions:default": nostamp_subs, }), **kwargs ) @@ -73,3 +78,6 @@ def jasmine_test(data = [], args = [], **kwargs): data = data + ["//:node_modules/source-map-support"], **kwargs ) + +def ng_examples_db(**kwargs): + _ng_examples_db(**kwargs) diff --git a/tools/example_db_generator.bzl b/tools/example_db_generator.bzl deleted file mode 100644 index 7a899e3d8de4..000000000000 --- a/tools/example_db_generator.bzl +++ /dev/null @@ -1,12 +0,0 @@ -load("@aspect_rules_js//js:defs.bzl", "js_run_binary") - -def cli_example_db(name, srcs, path, out, data = []): - js_run_binary( - name = name, - outs = [out], - srcs = srcs + data, - tool = "//tools:ng_example_db", - progress_message = "Generating code example database from %s" % path, - mnemonic = "NgExampleSqliteDb", - args = [path, "$(rootpath %s)" % out], - ) diff --git a/tools/example_db_generator.js b/tools/example_db_generator.js deleted file mode 100644 index f55303ce6d46..000000000000 --- a/tools/example_db_generator.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.dev/license - */ - -const { readdirSync, readFileSync, mkdirSync, existsSync, rmSync } = require('node:fs'); -const { resolve, dirname } = require('node:path'); -const { DatabaseSync } = require('node:sqlite'); - -function generate(inPath, outPath) { - const examples = []; - - const entries = readdirSync(resolve(inPath), { withFileTypes: true }); - for (const entry of entries) { - if (!entry.isFile()) { - continue; - } - - examples.push(readFileSync(resolve(inPath, entry.name), 'utf-8')); - } - - const dbPath = outPath; - mkdirSync(dirname(outPath), { recursive: true }); - - if (existsSync(dbPath)) { - rmSync(dbPath); - } - const db = new DatabaseSync(dbPath); - - db.exec(`CREATE VIRTUAL TABLE examples USING fts5(content, tokenize = 'porter ascii');`); - - const insertStatement = db.prepare('INSERT INTO examples(content) VALUES(?);'); - - db.exec('BEGIN TRANSACTION'); - for (const example of examples) { - insertStatement.run(example); - } - db.exec('END TRANSACTION'); - - db.close(); -} - -if (require.main === module) { - const argv = process.argv.slice(2); - if (argv.length !== 2) { - console.error('Must include 2 arguments.'); - process.exit(1); - } - - const [inPath, outPath] = argv; - - try { - generate(inPath, outPath); - } catch (error) { - console.error('An error happened:'); - console.error(error); - process.exit(127); - } -} - -exports.generate = generate; diff --git a/tools/link_package_json_to_tarballs.bzl b/tools/link_package_json_to_tarballs.bzl index 38172e53acc9..b01d64669834 100644 --- a/tools/link_package_json_to_tarballs.bzl +++ b/tools/link_package_json_to_tarballs.bzl @@ -1,4 +1,4 @@ -# Copyright Google Inc. All Rights Reserved. +# Copyright Google LLC. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license @@ -41,7 +41,7 @@ def link_package_json_to_tarballs(name, src, pkg_deps, out): # for the tar for this package as that would create a circular dependency. pkg_label = to_label(pkg_dep) if pkg_label.package != src_pkg: - pkg_tar = "@%s//%s:npm_package_archive.tgz" % (pkg_label.workspace_name, pkg_label.package) + pkg_tar = "@@%s//%s:npm_package_archive.tgz" % (pkg_label.repo_name, pkg_label.package) srcs.append(pkg_tar) # Deriving the absolute path to the tar in the execroot requries different diff --git a/tools/ng_cli_schema_generator.bzl b/tools/ng_cli_schema_generator.bzl index 9bcc4d287a6a..86d9552dd70c 100644 --- a/tools/ng_cli_schema_generator.bzl +++ b/tools/ng_cli_schema_generator.bzl @@ -4,6 +4,7 @@ def cli_json_schema(name, src, out, data = []): js_run_binary( name = name, outs = [out], + tags = ["schema"], srcs = [src] + data, tool = "//tools:ng_cli_schema", progress_message = "Generating CLI interface from %s" % src, diff --git a/tools/package_json_release_filter.jq b/tools/package_json_release_filter.jq index 4b5a0eb20c62..8fdae0df46c5 100644 --- a/tools/package_json_release_filter.jq +++ b/tools/package_json_release_filter.jq @@ -1,4 +1,4 @@ -# Copyright Google Inc. All Rights Reserved. +# Copyright Google LLC. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license diff --git a/tools/snapshot_repo_filter.bzl b/tools/snapshot_repo_filter.bzl index a648e8e300a7..fbd9672c07a9 100644 --- a/tools/snapshot_repo_filter.bzl +++ b/tools/snapshot_repo_filter.bzl @@ -1,4 +1,4 @@ -# Copyright Google Inc. All Rights Reserved. +# Copyright Google LLC. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license diff --git a/tools/substitutions.bzl b/tools/substitutions.bzl index b2e3877138cd..dc40701971ff 100644 --- a/tools/substitutions.bzl +++ b/tools/substitutions.bzl @@ -1,4 +1,14 @@ -load("//:constants.bzl", "ANGULAR_FW_PEER_DEP", "ANGULAR_FW_VERSION", "NG_PACKAGR_PEER_DEP", "NG_PACKAGR_VERSION", "RELEASE_ENGINES_NODE", "RELEASE_ENGINES_NPM", "RELEASE_ENGINES_YARN") +load( + "//:constants.bzl", + "ANGULAR_FW_PEER_DEP", + "ANGULAR_FW_VERSION", + "BASELINE_DATE", + "NG_PACKAGR_PEER_DEP", + "NG_PACKAGR_VERSION", + "RELEASE_ENGINES_NODE", + "RELEASE_ENGINES_NPM", + "RELEASE_ENGINES_YARN", +) _stamp_substitutions = { # Version of the local package being built, generated via the `--workspace_status_command` flag. @@ -6,6 +16,7 @@ _stamp_substitutions = { "0.0.0-EXPERIMENTAL-PLACEHOLDER": "{{STABLE_PROJECT_EXPERIMENTAL_VERSION}}", # --- "BUILD_SCM_HASH-PLACEHOLDER": "{{BUILD_SCM_ABBREV_HASH}}", + "BASELINE-DATE-PLACEHOLDER": BASELINE_DATE, "0.0.0-ENGINES-NODE": RELEASE_ENGINES_NODE, "0.0.0-ENGINES-NPM": RELEASE_ENGINES_NPM, "0.0.0-ENGINES-YARN": RELEASE_ENGINES_YARN, @@ -13,8 +24,6 @@ _stamp_substitutions = { "0.0.0-NG-PACKAGR-PEER-DEP": NG_PACKAGR_PEER_DEP, "0.0.0-ANGULAR-FW-VERSION": ANGULAR_FW_VERSION, "0.0.0-ANGULAR-FW-PEER-DEP": ANGULAR_FW_PEER_DEP, - # The below is needed for @angular/ssr FESM file. - "\\./(.+)/packages/angular/ssr/third_party/beasties": "../third_party/beasties/index.js", } _no_stamp_substitutions = dict(_stamp_substitutions, **{ diff --git a/tools/test/BUILD.bazel b/tools/test/BUILD.bazel index 2e651ae3e654..5d210ff7ac50 100644 --- a/tools/test/BUILD.bazel +++ b/tools/test/BUILD.bazel @@ -1,5 +1,5 @@ -load("@bazel_skylib//rules:diff_test.bzl", "diff_test") load("@aspect_bazel_lib//lib:jq.bzl", "jq") +load("@bazel_skylib//rules:diff_test.bzl", "diff_test") jq( name = "final_package_json", diff --git a/tools/test/expected_package.json b/tools/test/expected_package.json index a456312e8903..6630c9062f8a 100644 --- a/tools/test/expected_package.json +++ b/tools/test/expected_package.json @@ -35,8 +35,8 @@ } }, "engines": { - "node": "^16.14.0 || >=18.10.0", - "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", - "yarn": ">= 1.13.0" + "node": "0.0.0-ENGINES-NODE", + "npm": "0.0.0-ENGINES-NPM", + "yarn": "0.0.0-ENGINES-YARN" } } diff --git a/tools/toolchains/BUILD.bazel b/tools/toolchains/BUILD.bazel new file mode 100644 index 000000000000..1abb54e5faa7 --- /dev/null +++ b/tools/toolchains/BUILD.bazel @@ -0,0 +1,44 @@ +load("@rules_cc//cc:defs.bzl", "cc_toolchain") +load(":dummy_cc_toolchain.bzl", "dummy_cc_toolchain_config") + +# This is needed following https://github.com/bazel-contrib/rules_nodejs/pull/3859 +toolchain( + name = "node22_windows_no_exec_toolchain", + exec_compatible_with = [], + target_compatible_with = [ + "@platforms//os:windows", + "@platforms//cpu:x86_64", + ], + toolchain = "@node22_windows_amd64//:toolchain", + toolchain_type = "@rules_nodejs//nodejs:toolchain_type", +) + +# This defines a dummy C++ toolchain for Windows. +# Without this, the build fails with "Unable to find a CC toolchain using toolchain resolution". +dummy_cc_toolchain_config(name = "dummy_cc_toolchain_config") + +filegroup(name = "empty") + +cc_toolchain( + name = "dummy_cc_toolchain", + all_files = ":empty", + compiler_files = ":empty", + dwp_files = ":empty", + linker_files = ":empty", + objcopy_files = ":empty", + strip_files = ":empty", + supports_param_files = 0, + toolchain_config = ":dummy_cc_toolchain_config", + toolchain_identifier = "dummy_cc_toolchain", +) + +toolchain( + name = "dummy_cc_windows_no_exec_toolchain", + exec_compatible_with = [], + target_compatible_with = [ + "@platforms//os:windows", + "@platforms//cpu:x86_64", + ], + toolchain = ":dummy_cc_toolchain", + toolchain_type = "@rules_cc//cc:toolchain_type", +) diff --git a/tools/toolchains/dummy_cc_toolchain.bzl b/tools/toolchains/dummy_cc_toolchain.bzl new file mode 100644 index 000000000000..a18a9c780915 --- /dev/null +++ b/tools/toolchains/dummy_cc_toolchain.bzl @@ -0,0 +1,28 @@ +""" +This file defines a dummy C++ toolchain for Windows. +It is needed to satisfy Bazel's toolchain resolution when cross-compiling for Windows on Linux. +Some rules (e.g. rules_nodejs, js_test) or their dependencies may trigger C++ toolchain resolution +even if no actual C++ compilation is performed for the target platform. +Without this, the build fails with "Unable to find a CC toolchain using toolchain resolution". +""" + +load("@rules_cc//cc:defs.bzl", "cc_common") + +def _impl(ctx): + return cc_common.create_cc_toolchain_config_info( + ctx = ctx, + toolchain_identifier = "dummy-toolchain", + host_system_name = "local", + target_system_name = "local", + target_cpu = "x64_windows", + target_libc = "unknown", + compiler = "dummy", + abi_version = "unknown", + abi_libc_version = "unknown", + ) + +dummy_cc_toolchain_config = rule( + implementation = _impl, + attrs = {}, + provides = [CcToolchainConfigInfo], +) diff --git a/tools/ts_json_schema.bzl b/tools/ts_json_schema.bzl index deb34c0af597..dab651d0d7e0 100644 --- a/tools/ts_json_schema.bzl +++ b/tools/ts_json_schema.bzl @@ -12,6 +12,7 @@ def ts_json_schema(name, src, data = []): name = name + ".interface", outs = [out], srcs = [src] + data, + tags = ["schema"], tool = "//tools:quicktype_runner", progress_message = "Generating TS interface for %s" % src, mnemonic = "TsJsonSchema", diff --git a/tsconfig-build-esm.json b/tsconfig-build-esm.json index 5a548be0a88f..8682ad1fbdc5 100644 --- a/tsconfig-build-esm.json +++ b/tsconfig-build-esm.json @@ -8,7 +8,7 @@ "compilerOptions": { "module": "esnext", "target": "es2022", - "lib": ["es2020"], + "lib": ["es2022"], // don't auto-discover @types/node, it results in a ///