diff --git a/.github/actions/builder-e2e-build/action.yml b/.github/actions/builder-e2e-build/action.yml new file mode 100644 index 0000000000..08868bcb78 --- /dev/null +++ b/.github/actions/builder-e2e-build/action.yml @@ -0,0 +1,54 @@ +name: Build Builder E2E prerequisites + +description: Build the Builder and package its E2E schema and dependencies. + +inputs: + submodules-ssh-key: + description: SSH key for private E2E dependencies. + required: false + +outputs: + shards: + description: Filename-derived E2E shard matrix. + value: ${{ steps.shards.outputs.value }} + +runs: + using: composite + steps: + - uses: ./.github/actions/submodules-checkout + with: + submodules-ssh-key: ${{ inputs.submodules-ssh-key }} + + - uses: ./.github/actions/ci-setup + with: + run-scripts: "true" + + - name: Discover shards + id: shards + shell: bash + run: | + shards=$(pnpm --dir apps/builder exec tsx ./e2e/print-shards.ts) + echo "value=$shards" >> "$GITHUB_OUTPUT" + + - name: Build Builder + shell: bash + run: pnpm --filter @webstudio-is/builder build + + - name: Build generated React Router components + shell: bash + run: pnpm --filter @webstudio-is/sdk-components-react-router build + + - name: Generate schema snapshot + shell: bash + run: pnpm --filter @webstudio-is/builder e2e:schema-cache + + - name: Upload prerequisites + uses: actions/upload-artifact@v6 + with: + name: builder-e2e-build + retention-days: 7 + path: | + apps/builder/build/server + apps/builder/build/client/assets + packages/*/lib + .cache/builder-e2e/schema-*.sql diff --git a/.github/actions/builder-e2e-shard/action.yml b/.github/actions/builder-e2e-shard/action.yml new file mode 100644 index 0000000000..742e748445 --- /dev/null +++ b/.github/actions/builder-e2e-shard/action.yml @@ -0,0 +1,72 @@ +name: Run Builder E2E shard + +description: Run one Builder E2E shard and preserve diagnostics on failure. + +inputs: + submodules-ssh-key: + description: SSH key for private E2E dependencies. + required: false + shard: + description: Filename-derived shard name. + required: true + partition: + description: Optional Playwright partition within the selected files. + required: false + +runs: + using: composite + steps: + - uses: ./.github/actions/submodules-checkout + with: + submodules-ssh-key: ${{ inputs.submodules-ssh-key }} + + - uses: ./.github/actions/ci-setup + with: + run-scripts: "true" + + - name: Cache Playwright Chromium + uses: actions/cache@v5 + with: + path: | + ~/.cache/ms-playwright/chromium-* + ~/.cache/ms-playwright/chromium_headless_shell-* + ~/.cache/ms-playwright/ffmpeg-* + key: playwright-chromium-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }} + + - name: Download Builder E2E build + uses: actions/download-artifact@v7 + with: + name: builder-e2e-build + path: . + + - name: Run Builder E2E + shell: bash + env: + E2E_TEST_SHARD: ${{ inputs.shard }} + E2E_TEST_PARTITION: ${{ inputs.partition }} + run: | + args=(--workers=2) + if [ -n "$E2E_TEST_PARTITION" ]; then + args+=(--shard="$E2E_TEST_PARTITION") + fi + pnpm --filter @webstudio-is/builder e2e:ci:shard -- "${args[@]}" + + - name: Upload report + if: failure() + uses: actions/upload-artifact@v6 + with: + name: builder-e2e-report-${{ inputs.shard }} + retention-days: 7 + path: | + apps/builder/playwright-report + apps/builder/test-results/e2e + + - name: Print service logs + if: failure() + shell: bash + run: bash apps/builder/backend/run.sh snapshot logs + + - name: Stop services + if: always() + shell: bash + run: bash apps/builder/backend/run.sh snapshot down --volumes --remove-orphans diff --git a/.github/actions/test-suite/action.yml b/.github/actions/test-suite/action.yml new file mode 100644 index 0000000000..47b28a10b9 --- /dev/null +++ b/.github/actions/test-suite/action.yml @@ -0,0 +1,55 @@ +name: Test suite + +description: Prepare browsers and run one repository test script. + +inputs: + submodules-ssh-key: + description: SSH key for private test dependencies. + required: false + script: + description: Root package script to run. + required: true + browsers: + description: Browsers required by the test script. + default: none + required: false + +runs: + using: composite + steps: + - uses: ./.github/actions/submodules-checkout + with: + submodules-ssh-key: ${{ inputs.submodules-ssh-key }} + + - uses: ./.github/actions/ci-setup + + - name: Cache Playwright Chromium + if: inputs.browsers != 'none' + uses: actions/cache@v5 + with: + path: | + ~/.cache/ms-playwright/chromium-* + ~/.cache/ms-playwright/chromium_headless_shell-* + ~/.cache/ms-playwright/ffmpeg-* + key: playwright-chromium-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }} + + - name: Cache Playwright Firefox + if: inputs.browsers == 'chromium-firefox' + uses: actions/cache@v5 + with: + path: ~/.cache/ms-playwright/firefox-* + key: playwright-firefox-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }} + + - name: Install package test browsers + if: inputs.browsers == 'chromium-firefox' + shell: bash + run: pnpm --filter @webstudio-is/sdk-components-animation exec playwright install chromium firefox + + - name: Install Builder test browser + if: inputs.browsers == 'chromium' + shell: bash + run: pnpm --filter @webstudio-is/builder exec playwright install chromium + + - name: Run test suite + shell: bash + run: pnpm run "${{ inputs.script }}" diff --git a/.github/actions/vercel/action.yaml b/.github/actions/vercel/action.yaml index 07f0be0b44..8a3de7fc04 100644 --- a/.github/actions/vercel/action.yaml +++ b/.github/actions/vercel/action.yaml @@ -134,6 +134,13 @@ runs: shell: bash + - name: Verify published CLI contract against staged Builder + if: ${{ inputs.production-staged == 'true' }} + run: pnpm --filter webstudio check:published-cli-contract + shell: bash + env: + WEBSTUDIO_CLI_CONTRACT_BUILDER_ORIGIN: ${{ steps.deploy.outputs.domain }} + - name: Set Alias id: alias run: | diff --git a/.github/workflows/approved-fork-workflows.yml b/.github/workflows/approved-fork-workflows.yml new file mode 100644 index 0000000000..e2ef617117 --- /dev/null +++ b/.github/workflows/approved-fork-workflows.yml @@ -0,0 +1,13 @@ +name: Approved fork workflows + +on: + workflow_call: + +jobs: + main: + uses: ./.github/workflows/main.yml + secrets: inherit + + vercel-deploy-staging: + uses: ./.github/workflows/vercel-deploy-staging.yml + secrets: inherit diff --git a/.github/workflows/cli-r2.yaml b/.github/workflows/cli-r2.yaml index fcd945c718..36762d5699 100644 --- a/.github/workflows/cli-r2.yaml +++ b/.github/workflows/cli-r2.yaml @@ -16,11 +16,11 @@ permissions: packages: write deployments: write +env: + COMPATIBILITY_DATE: "2024-04-10" + jobs: build: - env: - COMPATIBILITY_DATE: 2024-04-10 - environment: name: "staging" @@ -124,7 +124,7 @@ jobs: run: | NODE_ENV=production pnpm wrangler deploy \ --name build \ - --compatibility-date '${COMPATIBILITY_DATE}' \ + --compatibility-date "${COMPATIBILITY_DATE}" \ --minify true \ --logpush true \ --dry-run \ diff --git a/.github/workflows/fixtures-test.yml b/.github/workflows/fixtures-test.yml index b855621718..95c30afb21 100644 --- a/.github/workflows/fixtures-test.yml +++ b/.github/workflows/fixtures-test.yml @@ -38,6 +38,7 @@ jobs: - uses: actions/checkout@v5 with: ref: ${{ github.event.pull_request.head.sha || github.sha }} + allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }} # Test that everything is working with submodules - uses: ./.github/actions/submodules-checkout with: @@ -57,7 +58,8 @@ jobs: shell: bash run: | set +e - pnpm --filter='./fixtures/*' --sequential run fixtures:sync 2>&1 | tee fixtures-sync.log + # Build webstudio-features from its checked-in snapshot; its remote data is mutable. + pnpm --filter='./fixtures/*' --filter='!./fixtures/webstudio-features' --sequential run fixtures:sync 2>&1 | tee fixtures-sync.log sync_status=${PIPESTATUS[0]} if [ "$sync_status" -ne 0 ]; then message=$(tail -n 40 fixtures-sync.log | sed -e 's/%/%25/g' -e 's/\r/%0D/g' -e 's/$/%0A/' | tr -d '\n') @@ -74,12 +76,16 @@ jobs: find . -type f -path "./fixtures/*/.webstudio/data.json" -exec sed -i 's|"origin": ".*"|"origin": "https://main.development.webstudio.is"|g' {} + - name: Test git diff - # This command will fail if there are uncommitted changes, i.e something has broken - run: git diff --name-only HEAD --exit-code + # Submodule checkout can move the pinned commit to its current branch. + run: | + git diff --name-only HEAD --exit-code -- . ':(exclude)packages/sdk-components-animation/private-src' + git -C packages/sdk-components-animation/private-src diff --name-only HEAD --exit-code - name: Show changed files and diff if: ${{ failure() }} run: | echo "Changed files are:" - git diff --name-only HEAD - git diff HEAD | head -n 1000 + git diff --name-only HEAD -- . ':(exclude)packages/sdk-components-animation/private-src' + git -C packages/sdk-components-animation/private-src diff --name-only HEAD + git diff HEAD -- . ':(exclude)packages/sdk-components-animation/private-src' | head -n 1000 + git -C packages/sdk-components-animation/private-src diff HEAD | head -n 1000 diff --git a/.github/workflows/main-safe-to-deploy.yml b/.github/workflows/main-safe-to-deploy.yml new file mode 100644 index 0000000000..b9a9da59de --- /dev/null +++ b/.github/workflows/main-safe-to-deploy.yml @@ -0,0 +1,19 @@ +name: Workflows for approved forks + +on: + pull_request_target: + types: [labeled] + +permissions: + contents: read + deployments: write + pull-requests: write + statuses: write + +jobs: + approved-fork-workflows: + # GitHub cannot filter labeled events by label name. Gate one workflow call + # instead of adding skipped copies of every Main and Vercel workflow job. + if: github.event.label.name == 'safe-to-deploy' + uses: ./.github/workflows/approved-fork-workflows.yml + secrets: inherit diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index fb6873cae4..11923be42b 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -5,12 +5,10 @@ on: branches: - main pull_request: - pull_request_target: - types: [labeled] + workflow_call: -# cancel in-progress runs on new commits to same PR (gitub.event.number) concurrency: - group: ${{ github.workflow }}-${{ github.event.number || github.sha }} + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.number || github.sha }} cancel-in-progress: true permissions: @@ -19,11 +17,7 @@ permissions: jobs: ssg-artifact: name: Packaged SSG Assets build - if: | - github.event_name == 'push' || - github.event_name == 'pull_request' || - (github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy') - timeout-minutes: 20 + timeout-minutes: 7 runs-on: ubuntu-24.04-arm environment: name: development @@ -32,7 +26,7 @@ jobs: - uses: actions/checkout@v5 with: ref: ${{ github.event.pull_request.head.sha || github.sha }} - allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy' }} + allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }} - uses: ./.github/actions/submodules-checkout with: @@ -43,23 +37,52 @@ jobs: - name: Build packaged SSG fixture run: pnpm --filter webstudio test:ssg-package - checks: - # Run on push, regular PR (for repo branches), or labeled PR with safe-to-deploy (for forks) - if: | - github.event_name == 'push' || - github.event_name == 'pull_request' || - (github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy') - - timeout-minutes: 20 - + tests: + name: tests (${{ matrix.environment }}, ${{ matrix.suite.name }}) + timeout-minutes: ${{ (matrix.suite.name == 'builder-app' || matrix.suite.name == 'packages') && 12 || 7 }} + runs-on: ubuntu-24.04 strategy: + fail-fast: false matrix: environment: - empty - development - + suite: + - name: packages + script: test:packages + browsers: chromium-firefox + - name: cli + script: test:cli + browsers: none + - name: builder-core + script: test:builder:core + browsers: chromium + - name: builder-app + script: test:builder:app + browsers: chromium environment: name: ${{ matrix.environment }} + env: + DATABASE_URL: postgres:// + AUTH_SECRET: test + + steps: + - uses: actions/checkout@v5 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }} + + - uses: ./.github/actions/test-suite + with: + submodules-ssh-key: ${{ secrets.PRIVATE_GITHUB_DEPLOY_TOKEN }} + script: ${{ matrix.suite.script }} + browsers: ${{ matrix.suite.browsers }} + + checks: + timeout-minutes: 7 + + environment: + name: empty env: DATABASE_URL: postgres:// @@ -71,12 +94,7 @@ jobs: - uses: actions/checkout@v5 with: ref: ${{ github.event.pull_request.head.sha || github.sha }} - allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy' }} - - # Will not checkout submodules on empty environment, and will on development - - uses: ./.github/actions/submodules-checkout - with: - submodules-ssh-key: ${{ secrets.PRIVATE_GITHUB_DEPLOY_TOKEN }} + allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }} - uses: pnpm/action-setup@v6 @@ -89,8 +107,6 @@ jobs: run: | pnpm install - - run: echo ===SHA USED=== ${{ github.event.pull_request.head.sha || github.sha }} # todo: remove after check whats happening on main - - run: | pnpm oxfmt --check @@ -110,33 +126,12 @@ jobs: run: | pnpm check:generated-docs - - name: Cache Playwright browsers - uses: actions/cache@v5 - with: - path: ~/.cache/ms-playwright - key: playwright-${{ runner.os }}-${{ hashFiles('**/package-lock.json') }} - restore-keys: | - playwright-${{ runner.os }}- - - - name: Playwright init - run: | - pnpm playwright install - working-directory: packages/sdk-components-animation - - - name: Test - run: | - pnpm -r test - - name: Typecheck run: | pnpm -r typecheck check-size: - # Run on push, regular PR (for repo branches), or labeled PR with safe-to-deploy (for forks) - if: | - github.event_name == 'push' || - github.event_name == 'pull_request' || - (github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy') + timeout-minutes: 7 runs-on: ubuntu-24.04-arm @@ -147,7 +142,7 @@ jobs: - uses: actions/checkout@v5 with: ref: ${{ github.event.pull_request.head.sha || github.sha }} - allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy' }} + allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }} - uses: ./.github/actions/submodules-checkout with: @@ -157,54 +152,11 @@ jobs: - run: pnpm --filter "{./fixtures/*}..." build - - uses: actions/github-script@v8 - with: - script: | - const assertSize = async (directory, maxSize) => { - let result = '' - await exec.exec('du', ['-sk', directory], { - silent: true, - listeners: { - stdout: (data) => { - result += data.toString() - } - } - }) - const size = Number.parseInt(result, 10) - return { - passed: size <= maxSize, - size, - diff: size - maxSize, - directory, - } - } - const results = [ - await assertSize('./fixtures/ssg-cloudflare-pages/dist/client', 356), - await assertSize('./fixtures/react-router-netlify/build/client', 376), - await assertSize('./fixtures/webstudio-features/build/client', 3684), - ] - for (const result of results) { - if (result.passed) { - console.info(`${result.directory}: ${result.size}kB (${result.diff}kB)`) - } else { - console.info('') - console.error(`${result.directory}: ${result.size}kB (+${result.diff}kB)`) - } - } - if (results.some(result => result.passed === false)) { - console.error('Some fixtures exceeded limits') - process.exit(1) - } + - run: pnpm check:fixture-sizes builder-e2e-build: name: builder-e2e build - # Run on push, regular PR (for repo branches), or labeled PR with safe-to-deploy (for forks) - if: | - github.event_name == 'push' || - github.event_name == 'pull_request' || - (github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy') - - timeout-minutes: 20 + timeout-minutes: 7 runs-on: ubuntu-24.04 @@ -212,54 +164,42 @@ jobs: name: development outputs: - shards: ${{ steps.shards.outputs.value }} + shards: ${{ steps.build.outputs.shards }} steps: - uses: actions/checkout@v5 with: ref: ${{ github.event.pull_request.head.sha || github.sha }} - allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy' }} + allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }} - - uses: ./.github/actions/submodules-checkout + - id: build + uses: ./.github/actions/builder-e2e-build with: submodules-ssh-key: ${{ secrets.PRIVATE_GITHUB_DEPLOY_TOKEN }} + supabase-migrations: + name: Supabase migrations + timeout-minutes: 7 + runs-on: ubuntu-24.04 + environment: + name: empty + + steps: + - uses: actions/checkout@v5 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }} + - uses: ./.github/actions/ci-setup with: run-scripts: "true" - - name: Discover builder e2e shards - id: shards - run: echo "value=$(pnpm --dir apps/builder exec tsx ./e2e/print-shards.ts)" >> "$GITHUB_OUTPUT" - - - name: Build builder and generated preview dependencies - run: pnpm e2e:builder:build - - # Generate this from the current migrations for this workflow run only. - # Shards consume the snapshot as a fast, disposable schema cache. - - name: Generate builder e2e schema snapshot - run: pnpm e2e:builder:refresh-schema-cache - - - name: Upload builder e2e prerequisites - uses: actions/upload-artifact@v6 - with: - name: builder-e2e-build - retention-days: 7 - path: | - apps/builder/build/server - apps/builder/build/client/assets - packages/*/lib - .cache/builder-e2e/schema-*.sql + - name: Apply migrations to Supabase PostgreSQL + run: pnpm --filter @webstudio-is/builder e2e:supabase-migrations builder-e2e: name: builder-e2e (${{ matrix.shard }}) - # Run on push, regular PR (for repo branches), or labeled PR with safe-to-deploy (for forks) - if: | - github.event_name == 'push' || - github.event_name == 'pull_request' || - (github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy') - - timeout-minutes: 40 + timeout-minutes: 12 needs: builder-e2e-build @@ -267,62 +207,19 @@ jobs: strategy: fail-fast: false matrix: - shard: ${{ fromJSON(needs.builder-e2e-build.outputs.shards) }} + include: ${{ fromJSON(needs.builder-e2e-build.outputs.shards) }} environment: name: development - env: - BUILDER_E2E_COMPOSE_ARGS: "--env-file apps/builder/.env -f apps/builder/docker-compose.yaml -f apps/builder/docker-compose.e2e.yaml" - steps: - uses: actions/checkout@v5 with: ref: ${{ github.event.pull_request.head.sha || github.sha }} - allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy' }} + allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }} - - uses: ./.github/actions/submodules-checkout + - uses: ./.github/actions/builder-e2e-shard with: submodules-ssh-key: ${{ secrets.PRIVATE_GITHUB_DEPLOY_TOKEN }} - - - uses: ./.github/actions/ci-setup - with: - run-scripts: "true" - - - name: Cache Playwright browsers - uses: actions/cache@v5 - with: - path: ~/.cache/ms-playwright - key: builder-e2e-playwright-${{ runner.os }}-${{ hashFiles('apps/builder/package.json', 'pnpm-lock.yaml') }} - - - name: Download builder e2e build - uses: actions/download-artifact@v7 - with: - name: builder-e2e-build - path: . - - - name: Run builder e2e - env: - E2E_SKIP_BUILDER_BUILD: true - E2E_TEST_SHARD: ${{ matrix.shard }} - run: | - run_builder_e2e() { - E2E_TEST_COMMAND_TIMEOUT_SECONDS=300 pnpm e2e:builder - } - - run_builder_e2e_keep_logs() { - E2E_SKIP_CLEANUP=true E2E_TEST_COMMAND_TIMEOUT_SECONDS=300 pnpm e2e:builder - } - - run_builder_e2e || { - echo "::warning::Builder e2e shard ${E2E_TEST_SHARD} failed; retrying once" - run_builder_e2e_keep_logs - } - - - name: Print e2e service logs - if: failure() - run: docker compose $BUILDER_E2E_COMPOSE_ARGS logs - - - name: Stop e2e services - if: always() - run: docker compose $BUILDER_E2E_COMPOSE_ARGS down --volumes --remove-orphans + shard: ${{ matrix.shard }} + partition: ${{ matrix.partition }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 71d9ef216b..1bb4a41a65 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -61,6 +61,9 @@ jobs: publish: runs-on: ubuntu-latest + outputs: + registry_baseline: ${{ steps.registry-baseline.outputs.value }} + version: ${{ steps.version.outputs.value }} permissions: contents: write environment: @@ -119,15 +122,32 @@ jobs: echo "Exact registry artifact webstudio@$VERSION was not observable with integrity metadata." >&2 exit 1 - - name: Gate exact published CLI against baseline + release-smoke: + needs: publish + timeout-minutes: 20 + runs-on: ubuntu-24.04 + permissions: + contents: read + environment: + name: development + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.ref }} # tag name + - uses: ./.github/actions/submodules-checkout + with: + submodules-ssh-key: ${{ secrets.PRIVATE_GITHUB_DEPLOY_TOKEN }} + - uses: ./.github/actions/ci-setup + + - name: Verify exact published CLI against baseline id: registry-smoke env: DATABASE_URL: postgres:// AUTH_SECRET: test WEBSTUDIO_RELEASE_SMOKE_TOKEN_BUDGET: 6000 - WEBSTUDIO_RELEASE_SMOKE_CANDIDATE: webstudio@${{ steps.version.outputs.value }} - WEBSTUDIO_RELEASE_SMOKE_BASELINE: webstudio@${{ steps.registry-baseline.outputs.value }} - WEBSTUDIO_RELEASE_SMOKE_EXPECT_REGISTRY_VERSION: ${{ steps.version.outputs.value }} + WEBSTUDIO_RELEASE_SMOKE_CANDIDATE: webstudio@${{ needs.publish.outputs.version }} + WEBSTUDIO_RELEASE_SMOKE_BASELINE: webstudio@${{ needs.publish.outputs.registry_baseline }} + WEBSTUDIO_RELEASE_SMOKE_EXPECT_REGISTRY_VERSION: ${{ needs.publish.outputs.version }} WEBSTUDIO_RELEASE_SMOKE_REPORT: ${{ github.workspace }}/artifacts/cli-release-smoke.json run: pnpm --filter webstudio test:release-smoke:registry @@ -135,7 +155,7 @@ jobs: if: ${{ always() && (steps.registry-smoke.outcome == 'success' || steps.registry-smoke.outcome == 'failure') }} uses: actions/upload-artifact@v4 with: - name: cli-release-smoke-${{ steps.version.outputs.value }} + name: cli-release-smoke-${{ needs.publish.outputs.version }} path: artifacts/cli-release-smoke.json if-no-files-found: error diff --git a/.github/workflows/remove-pr-approvals.yml b/.github/workflows/remove-pr-approvals.yml new file mode 100644 index 0000000000..e117ace16a --- /dev/null +++ b/.github/workflows/remove-pr-approvals.yml @@ -0,0 +1,37 @@ +name: Remove PR approvals + +# Keep synchronization-only housekeeping out of label-triggered workflows. +on: + pull_request_target: + types: [synchronize] + +concurrency: + group: ${{ github.workflow }}-${{ github.event.number }} + cancel-in-progress: true + +permissions: + contents: read + pull-requests: write + +jobs: + remove-approvals: + runs-on: ubuntu-latest + steps: + - name: Remove revision-specific approval labels + uses: actions/github-script@v8 + with: + script: | + const labels = new Set( + context.payload.pull_request.labels.map(({ name }) => name) + ); + for (const name of ['safe-to-deploy', 'visual-change-approved']) { + if (labels.has(name) === false) { + continue; + } + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + name, + }); + } diff --git a/.github/workflows/vercel-deploy-staging.yml b/.github/workflows/vercel-deploy-staging.yml index 84852255a4..b69aa441fe 100644 --- a/.github/workflows/vercel-deploy-staging.yml +++ b/.github/workflows/vercel-deploy-staging.yml @@ -2,8 +2,7 @@ name: Vercel Deploy Staging on: push: - pull_request_target: - types: [labeled, synchronize] + workflow_call: # cancel in-progress runs on new commits to same PR (gitub.event.number) concurrency: @@ -17,29 +16,7 @@ permissions: pull-requests: write # needed to remove labels and comment jobs: - # Remove the safe-to-deploy label when new commits are pushed to a PR (requires re-review) - remove-label-on-update: - if: github.event_name == 'pull_request_target' && github.event.action == 'synchronize' - runs-on: ubuntu-latest - steps: - - name: Remove safe-to-deploy label - uses: actions/github-script@v8 - with: - script: | - await github.rest.issues.removeLabel({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: context.issue.number, - name: 'safe-to-deploy' - }).catch(() => {}); - console.log('Removed safe-to-deploy label due to new commits. Re-review required.'); - deployment: - # Run on push (for repo branches) OR on labeled event with safe-to-deploy label (for fork PRs) - if: | - github.event_name == 'push' || - (github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy') - # Execute development and staging on staging branches # Execute only development on all other branches strategy: @@ -125,11 +102,6 @@ jobs: builder-host: "${{ steps.vercel.outputs.alias }}.${{ matrix.environment }}.webstudio.is" deployment-host: - # Run on push (for repo branches) OR on labeled event with safe-to-deploy label (for fork PRs) - if: | - github.event_name == 'push' || - (github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy') - runs-on: ubuntu-latest outputs: development-builder-host: ${{ steps.host.outputs.value }} diff --git a/.github/workflows/visual-regression.yml b/.github/workflows/visual-regression.yml index 6f169794ff..17ce068c4b 100644 --- a/.github/workflows/visual-regression.yml +++ b/.github/workflows/visual-regression.yml @@ -7,11 +7,11 @@ on: pull_request: types: [opened, synchronize, reopened, labeled] pull_request_target: - types: [labeled, synchronize] + types: [opened, synchronize, reopened, labeled] concurrency: # A synchronize action emits both pull_request and pull_request_target. Keep - # their runs separate so approval cleanup cannot cancel the visual check. + # same-repository and fork runs separate. group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.number || github.sha }} cancel-in-progress: true @@ -19,28 +19,9 @@ permissions: contents: read jobs: - remove-approval: - if: github.event_name == 'pull_request_target' && github.event.action == 'synchronize' - permissions: - contents: read - pull-requests: write - runs-on: ubuntu-latest - steps: - - name: Remove visual change approval - uses: actions/github-script@v8 - with: - script: | - const labels = context.payload.pull_request.labels.map(({ name }) => name); - if (labels.includes('visual-change-approved')) { - await github.rest.issues.removeLabel({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: context.issue.number, - name: 'visual-change-approved', - }); - } - visual-regression: + # Same-repository PRs use the unprivileged event. Organization members' + # fork PRs are trusted; every other fork revision needs safe-to-deploy. if: | github.event_name == 'push' || ( @@ -53,18 +34,29 @@ jobs: ) || ( github.event_name == 'pull_request_target' && - github.event.action == 'labeled' && + github.event.pull_request.head.repo.full_name != github.repository && ( - github.event.label.name == 'safe-to-deploy' || ( - github.event.label.name == 'visual-change-approved' && - github.event.pull_request.head.repo.full_name != github.repository && - contains(github.event.pull_request.labels.*.name, 'safe-to-deploy') + contains(fromJSON('["OWNER", "MEMBER"]'), github.event.pull_request.author_association) && + ( + github.event.action != 'labeled' || + github.event.label.name == 'visual-change-approved' + ) + ) || + ( + github.event.action == 'labeled' && + ( + github.event.label.name == 'safe-to-deploy' || + ( + github.event.label.name == 'visual-change-approved' && + contains(github.event.pull_request.labels.*.name, 'safe-to-deploy') + ) + ) ) ) ) - timeout-minutes: 30 - runs-on: ubuntu-latest + timeout-minutes: 7 + runs-on: ubuntu-24.04 environment: name: development steps: @@ -72,6 +64,7 @@ jobs: with: fetch-depth: 0 ref: ${{ github.event.pull_request.head.sha || github.sha }} + allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' }} - uses: ./.github/actions/submodules-checkout with: @@ -79,11 +72,14 @@ jobs: - uses: ./.github/actions/ci-setup - - name: Cache pinned visual browser + - name: Cache Playwright Chromium uses: actions/cache@v5 with: - path: ~/.cache/ms-playwright - key: visual-playwright-${{ runner.os }}-${{ hashFiles('packages/sdk-components-animation/package.json', 'pnpm-lock.yaml') }} + path: | + ~/.cache/ms-playwright/chromium-* + ~/.cache/ms-playwright/chromium_headless_shell-* + ~/.cache/ms-playwright/ffmpeg-* + key: playwright-chromium-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }} - name: Install pinned visual browser run: | diff --git a/.gitignore b/.gitignore index df2fd3a014..92f9c3edb9 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,8 @@ yarn.lock # testing coverage +playwright-report +test-results # remix build @@ -70,3 +72,7 @@ packages/prisma-client/src/__generated__ # copilot instructions .github/instructions + +# local agent instructions +AGENTS.md +agents.md diff --git a/.storybook/main.ts b/.storybook/main.ts index 7a5aecb14f..a0dd4eadea 100644 --- a/.storybook/main.ts +++ b/.storybook/main.ts @@ -16,6 +16,7 @@ export default { "@storybook/addon-controls", "@storybook/addon-actions", "@storybook/addon-backgrounds", + "@storybook/addon-toolbars", ], async viteFinal(config) { return { diff --git a/.storybook/preview.tsx b/.storybook/preview.tsx index 77e6f9d5e5..48cf868a8f 100644 --- a/.storybook/preview.tsx +++ b/.storybook/preview.tsx @@ -1,15 +1,128 @@ +import "./request-fixtures"; +import { updateCsrfToken } from "../apps/builder/app/shared/csrf.client"; + +// Use a synthetic CSRF value in the isolated Storybook environment. +updateCsrfToken("storybook-fixture"); import type { Preview } from "@storybook/react"; import * as React from "react"; -import { useEffect } from "react"; +import { useEffect, useLayoutEffect, type ReactNode } from "react"; import { TooltipProvider } from "@radix-ui/react-tooltip"; import { setEnv } from "../packages/feature-flags/src/index"; -import { theme, globalCss } from "../packages/design-system/src/index"; -import { color } from "../packages/design-system/src/design-tokens"; +import { + cssVar, + type ThemeVariableName, +} from "../packages/design-system/src/index"; -// this adds `; - highlightCode( - code, - parser.parse(code), - solarizedLight, - (text, classes) => { - if (classes) { - highlightedCode += `${text}`; - } else { - highlightedCode += text; - } - }, - () => { - highlightedCode += "\n"; - } - ); - return highlightedCode; -}; diff --git a/apps/builder/app/shared/collection-equality.test.ts b/apps/builder/app/shared/collection-equality.test.ts new file mode 100644 index 0000000000..8e993c289d --- /dev/null +++ b/apps/builder/app/shared/collection-equality.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, test } from "vitest"; +import { areMapsShallowEqual, areSetsEqual } from "./collection-equality"; + +describe("collection equality", () => { + test("compares map entries without relying on insertion order", () => { + const value = {}; + expect( + areMapsShallowEqual( + new Map([ + ["first", value], + ["second", 1], + ]), + new Map([ + ["second", 1], + ["first", value], + ]) + ) + ).toBe(true); + expect( + areMapsShallowEqual(new Map([["first", value]]), new Map([["first", {}]])) + ).toBe(false); + }); + + test("compares set members without relying on insertion order", () => { + expect(areSetsEqual(new Set([1, 2]), new Set([2, 1]))).toBe(true); + expect(areSetsEqual(new Set([1, 2]), new Set([1, 3]))).toBe(false); + }); +}); diff --git a/apps/builder/app/shared/collection-equality.ts b/apps/builder/app/shared/collection-equality.ts new file mode 100644 index 0000000000..185d47087d --- /dev/null +++ b/apps/builder/app/shared/collection-equality.ts @@ -0,0 +1,25 @@ +export const areMapsShallowEqual = ( + left: ReadonlyMap | undefined, + right: ReadonlyMap | undefined +) => { + if (left === right) { + return true; + } + if (left === undefined || right === undefined || left.size !== right.size) { + return false; + } + for (const [key, value] of left) { + if ( + right.has(key) === false || + Object.is(right.get(key), value) === false + ) { + return false; + } + } + return true; +}; + +export const areSetsEqual = ( + left: ReadonlySet, + right: ReadonlySet +) => left.size === right.size && [...left].every((value) => right.has(value)); diff --git a/apps/builder/app/shared/color-scheme-controller.tsx b/apps/builder/app/shared/color-scheme-controller.tsx new file mode 100644 index 0000000000..13364b028f --- /dev/null +++ b/apps/builder/app/shared/color-scheme-controller.tsx @@ -0,0 +1,66 @@ +import { useStore } from "@nanostores/react"; +import { useEffect } from "react"; +import { + $settings, + synchronizeColorScheme, +} from "~/builder/shared/client-settings"; +import { getAuthorizationServerOrigin } from "./router-utils/origins"; +import { + applyColorScheme, + colorSchemeMediaQuery, + serializeColorSchemeCookie, +} from "./color-scheme"; + +export const ColorSchemeController = () => { + const { colorScheme: preference } = useStore($settings); + + useEffect(() => { + const mediaQuery = window.matchMedia(colorSchemeMediaQuery); + const cookieDomain = new URL( + getAuthorizationServerOrigin(window.location.origin) + ).hostname; + const updateColorScheme = () => { + applyColorScheme({ + preference, + prefersDark: mediaQuery.matches, + root: document.documentElement, + }); + }; + + document.cookie = serializeColorSchemeCookie({ + preference, + domain: cookieDomain, + secure: window.location.protocol === "https:", + }); + updateColorScheme(); + + if (preference !== "system") { + return; + } + + mediaQuery.addEventListener("change", updateColorScheme); + return () => { + mediaQuery.removeEventListener("change", updateColorScheme); + }; + }, [preference]); + + useEffect(() => { + const synchronizeVisibleDocument = () => { + if (document.visibilityState === "visible") { + synchronizeColorScheme(); + } + }; + + window.addEventListener("focus", synchronizeColorScheme); + document.addEventListener("visibilitychange", synchronizeVisibleDocument); + return () => { + window.removeEventListener("focus", synchronizeColorScheme); + document.removeEventListener( + "visibilitychange", + synchronizeVisibleDocument + ); + }; + }, []); + + return null; +}; diff --git a/apps/builder/app/shared/color-scheme-menu.tsx b/apps/builder/app/shared/color-scheme-menu.tsx new file mode 100644 index 0000000000..467fdf2b9b --- /dev/null +++ b/apps/builder/app/shared/color-scheme-menu.tsx @@ -0,0 +1,53 @@ +import { useStore } from "@nanostores/react"; +import { + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + MenuCheckedIcon, +} from "@webstudio-is/design-system"; +import { $settings, setSetting } from "~/builder/shared/client-settings"; + +const colorSchemeOptions = [ + { value: "system", label: "System" }, + { value: "light", label: "Light" }, + { value: "dark", label: "Dark" }, +] as const; + +export const ColorSchemeMenu = ({ + withIndicator = false, +}: { + withIndicator?: boolean; +}) => { + const { colorScheme } = useStore($settings); + + return ( + + + Theme + + + { + setSetting( + "colorScheme", + value as (typeof colorSchemeOptions)[number]["value"] + ); + }} + > + {colorSchemeOptions.map(({ value, label }) => ( + } + > + {label} + + ))} + + + + ); +}; diff --git a/apps/builder/app/shared/color-scheme.test.ts b/apps/builder/app/shared/color-scheme.test.ts new file mode 100644 index 0000000000..7169cf1bf8 --- /dev/null +++ b/apps/builder/app/shared/color-scheme.test.ts @@ -0,0 +1,163 @@ +import { describe, expect, test, vi } from "vitest"; +import { + applyColorScheme, + colorSchemeCookieName, + createColorSchemeBootstrapScript, + clientSettingsStorageKey, + initializeStoredColorScheme, + parseColorSchemeCookie, + serializeColorSchemeCookie, +} from "./color-scheme"; + +describe("applyColorScheme", () => { + test.each([ + { preference: "light", prefersDark: false, expected: "light" }, + { preference: "light", prefersDark: true, expected: "light" }, + { preference: "dark", prefersDark: false, expected: "dark" }, + { preference: "dark", prefersDark: true, expected: "dark" }, + { preference: "system", prefersDark: false, expected: "light" }, + { preference: "system", prefersDark: true, expected: "dark" }, + ] as const)( + "applies $expected for $preference when prefersDark is $prefersDark", + ({ preference, prefersDark, expected }) => { + const root = document.createElement("html"); + + applyColorScheme({ preference, prefersDark, root }); + + expect(root.dataset.colorScheme).toBe(expected); + } + ); +}); + +describe("initializeStoredColorScheme", () => { + test("prefers the shared cookie over origin-local settings", () => { + const root = document.createElement("html"); + const storage = { + getItem: vi.fn(() => JSON.stringify({ colorScheme: "light" })), + }; + + initializeStoredColorScheme({ + root, + storage, + storageKey: clientSettingsStorageKey, + storedPreference: "dark", + prefersDark: false, + }); + + expect(root.dataset.colorScheme).toBe("dark"); + }); + + test("applies the stored preference before the application renders", () => { + const root = document.createElement("html"); + const storage = { + getItem: vi.fn(() => JSON.stringify({ colorScheme: "dark" })), + }; + + initializeStoredColorScheme({ + root, + storage, + storageKey: clientSettingsStorageKey, + prefersDark: false, + }); + + expect(root.dataset.colorScheme).toBe("dark"); + }); + + test("falls back to the system scheme when storage is unavailable or invalid", () => { + const unavailableRoot = document.createElement("html"); + const unavailableStorage = { + getItem: vi.fn(() => { + throw new Error("Storage unavailable"); + }), + }; + + initializeStoredColorScheme({ + root: unavailableRoot, + storage: unavailableStorage, + storageKey: clientSettingsStorageKey, + prefersDark: true, + }); + + expect(unavailableRoot.dataset.colorScheme).toBe("dark"); + + const invalidRoot = document.createElement("html"); + const invalidStorage = { + getItem: vi.fn(() => JSON.stringify({ colorScheme: "sepia" })), + }; + + initializeStoredColorScheme({ + root: invalidRoot, + storage: invalidStorage, + storageKey: clientSettingsStorageKey, + prefersDark: true, + }); + + expect(invalidRoot.dataset.colorScheme).toBe("dark"); + }); + + test("resolves a stored system preference from the operating system", () => { + const root = document.createElement("html"); + const storage = { + getItem: vi.fn(() => JSON.stringify({ colorScheme: "system" })), + }; + + initializeStoredColorScheme({ + root, + storage, + storageKey: clientSettingsStorageKey, + prefersDark: true, + }); + + expect(root.dataset.colorScheme).toBe("dark"); + }); + + test("the document bootstrap applies the shared scheme synchronously", () => { + localStorage.setItem( + clientSettingsStorageKey, + JSON.stringify({ colorScheme: "light" }) + ); + const originalMatchMedia = window.matchMedia; + const mediaQueryList = { + matches: true, + media: "(prefers-color-scheme: dark)", + onchange: null, + addListener: vi.fn(), + removeListener: vi.fn(), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn(), + } satisfies MediaQueryList; + window.matchMedia = vi.fn(() => mediaQueryList); + + Function(createColorSchemeBootstrapScript("dark"))(); + + expect(document.documentElement.dataset.colorScheme).toBe("dark"); + + window.matchMedia = originalMatchMedia; + localStorage.clear(); + delete document.documentElement.dataset.colorScheme; + }); +}); + +describe("shared color scheme cookie", () => { + test("round-trips a preference across subdomains", () => { + const serialized = serializeColorSchemeCookie({ + preference: "dark", + domain: "apps.webstudio.is", + secure: true, + }); + + expect(serialized).toContain(`${colorSchemeCookieName}=dark`); + expect(serialized).toContain("Domain=apps.webstudio.is"); + expect(serialized).toContain("Path=/"); + expect(serialized).toContain("Secure"); + expect(parseColorSchemeCookie(serialized)).toBe("dark"); + }); + + test("ignores missing and invalid preferences", () => { + expect(parseColorSchemeCookie(undefined)).toBeUndefined(); + expect( + parseColorSchemeCookie(`${colorSchemeCookieName}=sepia`) + ).toBeUndefined(); + }); +}); diff --git a/apps/builder/app/shared/color-scheme.ts b/apps/builder/app/shared/color-scheme.ts new file mode 100644 index 0000000000..44982950b3 --- /dev/null +++ b/apps/builder/app/shared/color-scheme.ts @@ -0,0 +1,116 @@ +import { parse, serialize } from "cookie"; + +export const colorSchemePreferences = ["system", "light", "dark"] as const; + +export type ColorSchemePreference = (typeof colorSchemePreferences)[number]; +export type ColorScheme = Exclude; + +export const colorSchemeMediaQuery = "(prefers-color-scheme: dark)"; +export const clientSettingsStorageKey = "__webstudio_user_settings__"; +export const colorSchemeCookieName = "__webstudio_color_scheme__"; + +const isColorSchemePreference = ( + value: unknown +): value is ColorSchemePreference => + value === "system" || value === "light" || value === "dark"; + +export const parseColorSchemeCookie = (cookie: string | null | undefined) => { + if (cookie === null || cookie === undefined) { + return; + } + const preference = parse(cookie)[colorSchemeCookieName]; + return isColorSchemePreference(preference) ? preference : undefined; +}; + +export const serializeColorSchemeCookie = ({ + preference, + domain, + secure, +}: { + preference: ColorSchemePreference; + domain: string; + secure: boolean; +}) => + serialize(colorSchemeCookieName, preference, { + domain, + maxAge: 60 * 60 * 24 * 365, + path: "/", + sameSite: "lax", + secure, + }); + +export const applyColorScheme = ({ + preference, + prefersDark, + root, +}: { + preference: ColorSchemePreference; + prefersDark: boolean; + root: HTMLElement; +}) => { + const colorScheme: ColorScheme = + preference === "system" ? (prefersDark ? "dark" : "light") : preference; + + root.dataset.colorScheme = colorScheme; +}; + +export const initializeStoredColorScheme = ({ + root, + storage, + storageKey, + storedPreference, + prefersDark, +}: { + root: HTMLElement; + storage: Pick; + storageKey: string; + storedPreference?: unknown; + prefersDark: boolean; +}) => { + const hasStoredPreference = + storedPreference === "system" || + storedPreference === "light" || + storedPreference === "dark"; + let preference: ColorSchemePreference = hasStoredPreference + ? storedPreference + : "system"; + + if (hasStoredPreference === false) { + try { + const storedSettings = JSON.parse( + storage.getItem(storageKey) ?? "{}" + ) as { + colorScheme?: unknown; + }; + + if ( + storedSettings.colorScheme === "system" || + storedSettings.colorScheme === "light" || + storedSettings.colorScheme === "dark" + ) { + preference = storedSettings.colorScheme; + } + } catch { + // Invalid or unavailable storage leaves the interface on the system scheme. + } + } + + const colorScheme: ColorScheme = + preference === "system" ? (prefersDark ? "dark" : "light") : preference; + + root.dataset.colorScheme = colorScheme; +}; + +export const createColorSchemeBootstrapScript = ( + storedPreference?: ColorSchemePreference +) => `try { (${initializeStoredColorScheme.toString()})({ + root: document.documentElement, + storage: window.localStorage, + storageKey: ${JSON.stringify(clientSettingsStorageKey)}, + storedPreference: ${JSON.stringify(storedPreference)}, + prefersDark: window.matchMedia(${JSON.stringify(colorSchemeMediaQuery)}).matches +}); } catch { + document.documentElement.dataset.colorScheme = window.matchMedia(${JSON.stringify( + colorSchemeMediaQuery + )}).matches ? "dark" : "light"; +}`; diff --git a/apps/builder/app/shared/commands-emitter.ts b/apps/builder/app/shared/commands-emitter.ts index fb47a2c657..f6777a9796 100644 --- a/apps/builder/app/shared/commands-emitter.ts +++ b/apps/builder/app/shared/commands-emitter.ts @@ -16,8 +16,8 @@ export type CommandMeta = { /** listen hotkeys only locally without sharing with other apps */ disableHotkeyOutsideApp?: boolean; /** - * input, select and textarea, content editable and role=option used in Radix will not invoke command when hotkey is hit - * with the exception when default event behavior is prevented + * Inputs, text editors (including read-only ones), and Radix options + * will not invoke the command when its hotkey is pressed. **/ disableOnInputLikeControls?: boolean; /** @@ -176,6 +176,7 @@ export const createCommandsEmitter = ({ element.tagName.toLowerCase() ) || element.isContentEditable || + element.closest('[role="textbox"]') !== null || // Detect Radix select, dropdown and co. element.getAttribute("role") === "option"); diff --git a/apps/builder/app/shared/conflict-resolution-dialog.tsx b/apps/builder/app/shared/conflict-resolution-dialog.tsx index 316988f320..662499845b 100644 --- a/apps/builder/app/shared/conflict-resolution-dialog.tsx +++ b/apps/builder/app/shared/conflict-resolution-dialog.tsx @@ -1,5 +1,6 @@ import type { ReactNode } from "react"; import { + PanelContent, Button, Dialog, DialogActions, @@ -8,7 +9,6 @@ import { DialogTitle, Flex, Text, - theme, } from "@webstudio-is/design-system"; import { DialogRadioOptions } from "./dialog-radio-options"; @@ -47,7 +47,7 @@ export const ConflictResolutionDialog = ({ > {title} - + {description} @@ -62,9 +62,9 @@ export const ConflictResolutionDialog = ({ {details} - + - ); expect(toCss(fragment)).toMatchInlineSnapshot(` "@media all { input { @@ -1889,7 +1911,7 @@ test("FormTextInput", async () => { equalFragment( fragment, - <$.Input + { }, }); - equalFragment(fragment, <$.Label htmlFor="email">Email Address); + equalFragment(fragment, ); expect(toCss(fragment)).toMatchInlineSnapshot(` "@media all { label { @@ -2030,7 +2052,7 @@ test("FormTextarea", async () => { equalFragment( fragment, - <$.Textarea + `; + + expect(resolveHtmlEmbedAssetUrls(code, assetUrlsByPath)).toBe(code); +}); + +test("leaves unrelated and missing asset references unchanged", () => { + const code = `
`; + expect(resolveHtmlEmbedAssetUrls(code, assetUrlsByPath)).toBe(code); + expect(resolveHtmlEmbedAssetUrls(code, undefined)).toBe(code); +}); + +test("decodes character references and canonicalizes asset paths", () => { + const code = ` + +`; + + expect(resolveHtmlEmbedAssetUrls(code, assetUrlsByPath)).toBe( + ` + +` + ); +}); + +test("rewrites responsive image candidates", () => { + const code = ` + + +`; + + expect(resolveHtmlEmbedAssetUrls(code, assetUrlsByPath)).toBe(` + + +`); +}); + +test("preserves data URLs and resolves descriptorless and malformed srcset candidates", () => { + const code = + ``; + + expect(resolveHtmlEmbedAssetUrls(code, assetUrlsByPath)).toBe( + `` + ); +}); diff --git a/packages/sdk-components-react/src/html-embed-assets.ts b/packages/sdk-components-react/src/html-embed-assets.ts new file mode 100644 index 0000000000..314966f9a3 --- /dev/null +++ b/packages/sdk-components-react/src/html-embed-assets.ts @@ -0,0 +1,355 @@ +import { decodeNamedCharacterReference } from "decode-named-character-reference"; + +const assetAttributes = new Map>([ + ["audio", new Set(["src"])], + ["embed", new Set(["src"])], + ["img", new Set(["src", "srcset"])], + ["input", new Set(["src"])], + ["link", new Set(["href"])], + ["object", new Set(["data"])], + ["script", new Set(["src"])], + ["source", new Set(["src", "srcset"])], + ["track", new Set(["src"])], + ["video", new Set(["src", "poster"])], +]); + +const rawTextElements = new Set([ + "iframe", + "noembed", + "noframes", + "noscript", + "plaintext", + "script", + "style", + "textarea", + "title", + "xmp", +]); + +const isWhitespace = (character: string | undefined) => + character !== undefined && /\s/.test(character); +const isTagNameCharacter = (character: string | undefined) => + character !== undefined && /[A-Za-z0-9:-]/.test(character); + +const decodeHtmlCharacterReferences = (value: string) => + value + .replace( + /&(#(?:\d+|x[\da-f]+)|[a-z][\da-z]+);/gi, + (reference, name: string) => { + if (name[0] !== "#") { + return decodeNamedCharacterReference(name) || reference; + } + const isHex = name[1]?.toLowerCase() === "x"; + const radix = isHex ? 16 : 10; + const codePoint = Number.parseInt(name.slice(isHex ? 2 : 1), radix); + if ( + Number.isNaN(codePoint) || + codePoint === 0 || + codePoint > 0x10ffff || + (codePoint >= 0xd800 && codePoint <= 0xdfff) + ) { + return "�"; + } + return String.fromCodePoint(codePoint); + } + ) + // `amp` is one of the legacy named references HTML permits without a + // semicolon, except before an alphanumeric character or equals sign. + .replace(/&(?=$|[^=\da-z])/gi, "&"); + +const encodeAssetPathSegment = (segment: string) => { + const encoded = encodeURIComponent(segment); + if (encoded === ".") { + return "%2E"; + } + if (encoded === "..") { + return "%2E%2E"; + } + return encoded; +}; + +const normalizeAssetPath = (path: string) => + path + .split("/") + .map((segment) => { + try { + return encodeAssetPathSegment(decodeURIComponent(segment)); + } catch { + return encodeAssetPathSegment(segment); + } + }) + .join("/"); + +const resolveAssetUrl = ( + value: string, + assetUrlsByPath: Readonly> +) => { + value = decodeHtmlCharacterReferences(value); + if (value.startsWith("/") === false || value.startsWith("//")) { + return; + } + + const base = "https://webstudio.invalid"; + const hashIndex = value.indexOf("#"); + const beforeHash = hashIndex === -1 ? value : value.slice(0, hashIndex); + const hash = hashIndex === -1 ? "" : value.slice(hashIndex); + const searchIndex = beforeHash.indexOf("?"); + const pathname = + searchIndex === -1 ? beforeHash : beforeHash.slice(0, searchIndex); + const search = searchIndex === -1 ? "" : beforeHash.slice(searchIndex); + const assetUrl = assetUrlsByPath[normalizeAssetPath(pathname)]; + if (assetUrl === undefined) { + return; + } + + const isAbsolute = URL.canParse(assetUrl); + const resolved = new URL(assetUrl, base); + for (const [name, value] of new URLSearchParams(search)) { + resolved.searchParams.append(name, value); + } + if (hash !== "") { + resolved.hash = hash; + } + return isAbsolute + ? resolved.href + : `${resolved.pathname}${resolved.search}${resolved.hash}`; +}; + +const resolveSrcset = ( + value: string, + assetUrlsByPath: Readonly> +) => { + const replacements: Replacement[] = []; + let index = 0; + while (index < value.length) { + while ( + index < value.length && + (isWhitespace(value[index]) || value[index] === ",") + ) { + index += 1; + } + const urlStart = index; + while (index < value.length && isWhitespace(value[index]) === false) { + index += 1; + } + let urlEnd = index; + while (urlEnd > urlStart && value[urlEnd - 1] === ",") { + urlEnd -= 1; + } + const hasTrailingComma = urlEnd < index; + const resolved = resolveAssetUrl( + value.slice(urlStart, urlEnd), + assetUrlsByPath + ); + if (resolved !== undefined) { + replacements.push({ start: urlStart, end: urlEnd, value: resolved }); + } + if (hasTrailingComma) { + continue; + } + while (index < value.length && value[index] !== ",") { + index += 1; + } + } + if (replacements.length === 0) { + return; + } + let resolved = value; + for (const replacement of replacements.toReversed()) { + resolved = `${resolved.slice(0, replacement.start)}${replacement.value}${resolved.slice(replacement.end)}`; + } + return resolved; +}; + +type Replacement = { start: number; end: number; value: string }; + +const findTagEnd = (code: string, start: number) => { + let quote = ""; + for (let index = start; index < code.length; index += 1) { + const character = code[index]; + if (quote !== "") { + if (character === quote) { + quote = ""; + } + continue; + } + if (character === '"' || character === "'") { + quote = character; + continue; + } + if (character === ">") { + return index; + } + } + return code.length; +}; + +const collectAttributeReplacements = ({ + code, + start, + end, + attributeNames, + assetUrlsByPath, +}: { + code: string; + start: number; + end: number; + attributeNames: ReadonlySet; + assetUrlsByPath: Readonly>; +}) => { + const replacements: Replacement[] = []; + let index = start; + while (index < end) { + while (index < end && (isWhitespace(code[index]) || code[index] === "/")) { + index += 1; + } + const nameStart = index; + while ( + index < end && + isWhitespace(code[index]) === false && + code[index] !== "=" && + code[index] !== "/" && + code[index] !== ">" + ) { + index += 1; + } + if (index === nameStart) { + index += 1; + continue; + } + const name = code.slice(nameStart, index).toLowerCase(); + while (index < end && isWhitespace(code[index])) { + index += 1; + } + if (code[index] !== "=") { + continue; + } + index += 1; + while (index < end && isWhitespace(code[index])) { + index += 1; + } + const quote = code[index] === '"' || code[index] === "'" ? code[index] : ""; + if (quote !== "") { + index += 1; + } + const valueStart = index; + if (quote === "") { + while ( + index < end && + isWhitespace(code[index]) === false && + code[index] !== ">" + ) { + index += 1; + } + } else { + while (index < end && code[index] !== quote) { + index += 1; + } + } + const valueEnd = index; + if (quote !== "" && code[index] === quote) { + index += 1; + } + if (attributeNames.has(name)) { + const attributeValue = code.slice(valueStart, valueEnd); + const value = + name === "srcset" + ? resolveSrcset(attributeValue, assetUrlsByPath) + : resolveAssetUrl(attributeValue, assetUrlsByPath); + if (value !== undefined) { + replacements.push({ start: valueStart, end: valueEnd, value }); + } + } + } + return replacements; +}; + +const findRawTextEnd = (code: string, tagName: string, start: number) => { + if (tagName === "plaintext") { + return code.length; + } + const lowerCode = code.toLowerCase(); + let index = start; + while (index < code.length) { + const closingTag = lowerCode.indexOf(`" || afterName === "/" || isWhitespace(afterName)) { + return closingTag; + } + index = closingTag + tagName.length + 2; + } + return code.length; +}; + +export const resolveHtmlEmbedAssetUrls = ( + code: string, + assetUrlsByPath: Readonly> | undefined +) => { + if ( + assetUrlsByPath === undefined || + Object.keys(assetUrlsByPath).length === 0 + ) { + return code; + } + + const replacements: Replacement[] = []; + let index = 0; + while (index < code.length) { + const tagStart = code.indexOf("<", index); + if (tagStart === -1) { + break; + } + if (code.startsWith("", tagStart + 4); + index = commentEnd === -1 ? code.length : commentEnd + 3; + continue; + } + const nameStart = tagStart + 1; + if ( + code[nameStart] === "/" || + code[nameStart] === "!" || + code[nameStart] === "?" + ) { + index = findTagEnd(code, nameStart) + 1; + continue; + } + let nameEnd = nameStart; + while (isTagNameCharacter(code[nameEnd])) { + nameEnd += 1; + } + if (nameEnd === nameStart) { + index = tagStart + 1; + continue; + } + const tagName = code.slice(nameStart, nameEnd).toLowerCase(); + const tagEnd = findTagEnd(code, nameEnd); + const attributeNames = assetAttributes.get(tagName); + if (attributeNames !== undefined) { + replacements.push( + ...collectAttributeReplacements({ + code, + start: nameEnd, + end: tagEnd, + attributeNames, + assetUrlsByPath, + }) + ); + } + index = tagEnd + 1; + if (rawTextElements.has(tagName)) { + index = findRawTextEnd(code, tagName, index); + } + } + + if (replacements.length === 0) { + return code; + } + let resolved = code; + for (const replacement of replacements.toReversed()) { + resolved = `${resolved.slice(0, replacement.start)}${replacement.value}${resolved.slice(replacement.end)}`; + } + return resolved; +}; diff --git a/packages/sdk-components-react/src/html-embed.test.tsx b/packages/sdk-components-react/src/html-embed.browser.test.tsx similarity index 82% rename from packages/sdk-components-react/src/html-embed.test.tsx rename to packages/sdk-components-react/src/html-embed.browser.test.tsx index f450f10b4e..30d07981a3 100644 --- a/packages/sdk-components-react/src/html-embed.test.tsx +++ b/packages/sdk-components-react/src/html-embed.browser.test.tsx @@ -1,6 +1,3 @@ -/** - * @vitest-environment jsdom - */ import * as React from "react"; import ReactDOMServer from "react-dom/server"; import { test, expect, describe, beforeEach } from "vitest"; @@ -19,11 +16,16 @@ const App = (props: { clientOnly?: boolean; renderer?: "canvas" | "preview"; executeScriptOnCanvas?: boolean; + $ws$executeScripts?: boolean; + assetUrlsByPath?: Record; + code?: string; }) => { const [page, switchPage] = React.useReducer((n) => (n + 1) % 2, 0); const [refresh, setRefresh] = React.useReducer((n) => n + 1, 0); - const code = ` + const code = + props.code ?? + `
hello
`; @@ -32,6 +34,7 @@ const App = (props: { "", renderer: props.renderer, resources: {}, @@ -44,6 +47,7 @@ const App = (props: { code={code} clientOnly={props.clientOnly} executeScriptOnCanvas={props.executeScriptOnCanvas} + $ws$executeScripts={props.$ws$executeScripts} /> + + + ); + }); + await act(async () => container.querySelector("button")?.click()); + expect(onManagedSubmit).toHaveBeenCalledOnce(); + expect(onResultChange).toHaveBeenCalledOnce(); + expect(container.querySelector("form")?.dataset.state).toBe("success"); + } finally { + await act(async () => root.unmount()); + container.remove(); + } +}); + +test.each([true, false])( + "a visible Form resets edited fields only after success: %s", + async (success) => { + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + const onManagedSubmit = vi.fn(async () => ({ + success, + status: success ? 200 : 422, + results: [], + errors: success ? [] : [{ status: 422, body: null, message: "Failed" }], + })); + try { + await act(async () => { + root.render( + + + +