diff --git a/.github/workflows/deploy-dev.yml b/.github/workflows/deploy-dev.yml index bb9ec87..9518216 100644 --- a/.github/workflows/deploy-dev.yml +++ b/.github/workflows/deploy-dev.yml @@ -12,6 +12,8 @@ # # Secrets required (set in the "dev" GitHub Environment): # UNSPLASH_ACCESS_KEY — Unsplash API key for SSM +# SNS_FROM_NUMBER — SMS origination number (TF_VAR_sns_from_number) +# ALERT_EMAIL — owner email for the billing alarm + research-download notices # Secrets required at repo level: # SONAR_TOKEN — SonarCloud analysis token # @@ -226,6 +228,7 @@ jobs: TF_VAR_environment: ${{ env.ENVIRONMENT }} TF_VAR_unsplash_access_key: ${{ secrets.UNSPLASH_ACCESS_KEY }} TF_VAR_sns_from_number: ${{ secrets.SNS_FROM_NUMBER }} + TF_VAR_alert_email: ${{ secrets.ALERT_EMAIL }} run: | terraform apply -auto-approve \ -target=aws_ecr_repository.lambda \ @@ -253,6 +256,7 @@ jobs: TF_VAR_environment: ${{ env.ENVIRONMENT }} TF_VAR_unsplash_access_key: ${{ secrets.UNSPLASH_ACCESS_KEY }} TF_VAR_sns_from_number: ${{ secrets.SNS_FROM_NUMBER }} + TF_VAR_alert_email: ${{ secrets.ALERT_EMAIL }} run: terraform apply -auto-approve -target=aws_cloudfront_distribution.main - name: Terraform Apply working-directory: infra @@ -260,6 +264,7 @@ jobs: TF_VAR_environment: ${{ env.ENVIRONMENT }} TF_VAR_unsplash_access_key: ${{ secrets.UNSPLASH_ACCESS_KEY }} TF_VAR_sns_from_number: ${{ secrets.SNS_FROM_NUMBER }} + TF_VAR_alert_email: ${{ secrets.ALERT_EMAIL }} run: terraform apply -auto-approve - name: Read outputs id: tf-out diff --git a/.github/workflows/deploy-prod.yml b/.github/workflows/deploy-prod.yml index 9163a61..97f2553 100644 --- a/.github/workflows/deploy-prod.yml +++ b/.github/workflows/deploy-prod.yml @@ -68,6 +68,7 @@ jobs: TF_VAR_environment: ${{ env.ENVIRONMENT }} TF_VAR_unsplash_access_key: ${{ secrets.UNSPLASH_ACCESS_KEY }} TF_VAR_sns_from_number: ${{ secrets.SNS_FROM_NUMBER }} + TF_VAR_alert_email: ${{ secrets.ALERT_EMAIL }} run: | terraform apply -auto-approve \ -target=aws_ecr_repository.lambda \ @@ -95,6 +96,7 @@ jobs: TF_VAR_environment: ${{ env.ENVIRONMENT }} TF_VAR_unsplash_access_key: ${{ secrets.UNSPLASH_ACCESS_KEY }} TF_VAR_sns_from_number: ${{ secrets.SNS_FROM_NUMBER }} + TF_VAR_alert_email: ${{ secrets.ALERT_EMAIL }} run: terraform apply -auto-approve -target=aws_cloudfront_distribution.main - name: Terraform Apply working-directory: infra @@ -102,6 +104,7 @@ jobs: TF_VAR_environment: ${{ env.ENVIRONMENT }} TF_VAR_unsplash_access_key: ${{ secrets.UNSPLASH_ACCESS_KEY }} TF_VAR_sns_from_number: ${{ secrets.SNS_FROM_NUMBER }} + TF_VAR_alert_email: ${{ secrets.ALERT_EMAIL }} run: terraform apply -auto-approve - name: Read outputs id: tf-out diff --git a/.github/workflows/deploy-qa.yml b/.github/workflows/deploy-qa.yml index bd3f836..33c5d3c 100644 --- a/.github/workflows/deploy-qa.yml +++ b/.github/workflows/deploy-qa.yml @@ -206,6 +206,7 @@ jobs: TF_VAR_environment: ${{ env.ENVIRONMENT }} TF_VAR_unsplash_access_key: ${{ secrets.UNSPLASH_ACCESS_KEY }} TF_VAR_sns_from_number: ${{ secrets.SNS_FROM_NUMBER }} + TF_VAR_alert_email: ${{ secrets.ALERT_EMAIL }} run: | terraform apply -auto-approve \ -target=aws_ecr_repository.lambda \ @@ -233,6 +234,7 @@ jobs: TF_VAR_environment: ${{ env.ENVIRONMENT }} TF_VAR_unsplash_access_key: ${{ secrets.UNSPLASH_ACCESS_KEY }} TF_VAR_sns_from_number: ${{ secrets.SNS_FROM_NUMBER }} + TF_VAR_alert_email: ${{ secrets.ALERT_EMAIL }} run: terraform apply -auto-approve -target=aws_cloudfront_distribution.main - name: Terraform Apply working-directory: infra @@ -240,6 +242,7 @@ jobs: TF_VAR_environment: ${{ env.ENVIRONMENT }} TF_VAR_unsplash_access_key: ${{ secrets.UNSPLASH_ACCESS_KEY }} TF_VAR_sns_from_number: ${{ secrets.SNS_FROM_NUMBER }} + TF_VAR_alert_email: ${{ secrets.ALERT_EMAIL }} run: terraform apply -auto-approve - name: Read outputs id: tf-out diff --git a/.github/workflows/destroy.yml b/.github/workflows/destroy.yml index 7d84702..12e17a8 100644 --- a/.github/workflows/destroy.yml +++ b/.github/workflows/destroy.yml @@ -116,8 +116,10 @@ jobs: working-directory: infra env: TF_VAR_environment: ${{ inputs.environment }} # choice input; constrained to dev/qa/prod - # unsplash_access_key is required by the variable block even for destroy + # All three are required by the variable block even for destroy. TF_VAR_unsplash_access_key: ${{ secrets.UNSPLASH_ACCESS_KEY }} + TF_VAR_sns_from_number: ${{ secrets.SNS_FROM_NUMBER }} + TF_VAR_alert_email: ${{ secrets.ALERT_EMAIL }} run: | terraform destroy -auto-approve echo "Destroy complete for environment: $ENVIRONMENT" diff --git a/.gitignore b/.gitignore index 9695588..8057db5 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,11 @@ coverage/ .eslintcache .vite/ +# === Photo pool (generated; metadata JSON + image cache live in S3, not the repo) === +backend/photos.json +backend/photos-cache/ +backend/.photos-build.pid + # === Python (legacy/) === __pycache__/ *.py[cod] diff --git a/backend/.env.example b/backend/.env.example index a63af7d..b219c5b 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -22,4 +22,5 @@ COGNITO_CLIENT_ID= # --- Unsplash --- # Leave blank locally to use placeholder images instead of calling the API. +# REQUIRED to build the photo pool: `npm run build:photos` reads this from .env. UNSPLASH_ACCESS_KEY= diff --git a/backend/README.md b/backend/README.md index 8e2c5be..72c3983 100644 --- a/backend/README.md +++ b/backend/README.md @@ -21,12 +21,14 @@ src/ recommender.ts confidence/exploration, batch selection, novelty (the A/B loop) insights.ts taste→trait inference + "why this card?" reasons (A/B interpretation) dossier.ts per-user A/B state + applyInteraction orchestration (persistable) - signatures.ts per-country feature signatures (from the cached pool, else a seed) - photos.types.ts CachedPhoto type (kept apart from the generated data) - photos.data.ts generated per-country photo pool (empty until build:photos) + signatures.ts per-country feature signatures (primed from the pool, else a seed) + photos.types.ts CachedPhoto type (data lives in photos.json / S3, not the repo) + photos.curate.ts pure dedup + quality-gate + cities/landscapes balance (tested) + pool.ts loads the photo-pool metadata from S3 (cold start, cached) → primes signatures algorithm.ts preference-learning logic (ported from v1) db.ts DynamoDB data access (preferences + learnProgress) auth.ts Cognito token verification (+ local dev bypass) + ownerNotify.ts best-effort SES email to the owner (research-download notifications) images.ts weighted country selection + Unsplash client schema.ts Pothos GraphQL schema yoga.ts GraphQL Yoga server instance @@ -78,15 +80,50 @@ npm run dev # GraphQL at http://localhost:4000/graphql ## Scripts -| Command | Purpose | -| ------------------------- | -------------------------------------------------------------- | -| `npm run dev` | Local server with watch reload | -| `npm run build` | Bundle the Lambda handler with esbuild | -| `npm run typecheck` | `tsc --noEmit` | -| `npm test` | Run the Jest suites | -| `npm run lint` / `format` | ESLint + Prettier | -| `npm run printschema` | Regenerate `schema.graphql` | -| `npm run build:photos` | Regenerate the cached photo pool (needs `UNSPLASH_ACCESS_KEY`) | +| Command | Purpose | +| ------------------------- | ---------------------------------------------------------------------------------------------------- | +| `npm run dev` | Local server with watch reload | +| `npm run build` | Bundle the Lambda handler with esbuild | +| `npm run typecheck` | `tsc --noEmit` | +| `npm test` | Run the Jest suites | +| `npm run lint` / `format` | ESLint + Prettier | +| `npm run printschema` | Regenerate `schema.graphql` | +| `npm run build:photos` | Step A — fetch photo metadata → `photos.json` (needs `UNSPLASH_ACCESS_KEY`) | +| `npm run sync:photos` | Step B — download images + upload images & `photos.json` to S3 (needs `PHOTO_S3_BUCKET` + AWS creds) | + +## Travel photo pool + +The Travel feed serves from a pool the running app loads **from S3, not the code**, so +there are **zero Unsplash API calls at runtime** and the photo set can be regenerated +without a code deploy. The metadata (`photos.json`) and the image binaries both live in +the shared `bba-photos` bucket; the Lambda fetches `photos.json` once per cold start +(`pool.ts`, cached warm) and CloudFront serves the images at `/photos/*`. + +Building it is two steps (owner-run; nothing photo-related is committed): + +1. **`npm run build:photos`** (Step A, rate-limited, resumable). Two searches per + catalog country — a landscape/nature and a cityscape query — curated by + `photos.curate.ts` (dedup by id, min-likes gate, denylist for food/interiors/ + people/text, cities↔landscapes balance) down to `PHOTOS_PER_COUNTRY` (default 15), + then each kept photo is **enriched** via `GET /photos/:id` for its real `tags` + (search results carry none) plus `location` + camera `exif`. Writes `photos.json`. + Because every call (searches + enrichment) shares the **demo-mode 50/hr** budget, a + full 228-country run is **~2.5–3 days** — a single global gate spaces all calls, the + run checkpoints after every country (only committing a country once fully enriched), + and skips already-populated ones, so a background run resumes cleanly. Knobs: + `PHOTOS_PER_COUNTRY`, `PHOTOS_MAX_COUNTRIES`, `PHOTOS_MIN_LIKES`, `PHOTOS_THROTTLE_MS`, + `PHOTOS_ENRICH` (`0` to skip enrichment → no tags, much faster), `PHOTOS_RESET`. +2. **`PHOTO_S3_BUCKET=bba-photos npm run sync:photos`** (Step B, fast, ~15–30 min). + Downloads each image from the Unsplash CDN (a file fetch — not rate-limited) into + `photos-cache/` (gitignored, resumable), then uploads **both** the images + (`s3://bba-photos/photos/.jpg`) and `photos.json` (`s3://bba-photos/photos.json`). + Run **once** — the bucket is account-global, not per environment. + +`imageUrl` is a same-origin `/photos/.jpg` (`PHOTO_CDN_BASE`, default `/photos`) +served by CloudFront from `bba-photos`; local dev reads a local `photos.json` and falls +back to the retained Unsplash CDN url for images. Enrichment also captures +`locationName`/`lat`/`lng` when the photographer geotagged the shot, but **`country` +stays the search association** — the catalog key — not the geotag (see `photos.types.ts`). ## Deployment diff --git a/backend/package-lock.json b/backend/package-lock.json index 175bdcd..57f79f9 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -14,6 +14,7 @@ "@aws-sdk/client-dynamodb": "^3.1051.0", "@aws-sdk/client-kms": "^3.1056.0", "@aws-sdk/client-pinpoint-sms-voice-v2": "^3.1073.0", + "@aws-sdk/client-s3": "^3.1085.0", "@aws-sdk/client-ses": "^3.1073.0", "@aws-sdk/client-ssm": "^3.1056.0", "@aws-sdk/lib-dynamodb": "^3.1051.0", @@ -118,20 +119,6 @@ "tslib": "^2.2.0" } }, - "node_modules/@aws-crypto/crc32": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", - "integrity": "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==", - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/util": "^5.2.0", - "@aws-sdk/types": "^3.222.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, "node_modules/@aws-crypto/decrypt-node": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/@aws-crypto/decrypt-node/-/decrypt-node-5.0.0.tgz", @@ -353,6 +340,22 @@ "tslib": "^2.6.2" } }, + "node_modules/@aws-sdk/checksums": { + "version": "3.1000.16", + "resolved": "https://registry.npmjs.org/@aws-sdk/checksums/-/checksums-3.1000.16.tgz", + "integrity": "sha512-EKnvkXSmz3IpA99tCNuI+dLFXyZyClSm8zns9sB/elvkU+MTuomAs6toJMPMBf98/fICG/urXDkzGz0/c3yyAQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.975.1", + "@aws-sdk/types": "^3.974.0", + "@smithy/core": "^3.29.2", + "@smithy/types": "^4.16.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/@aws-sdk/client-cognito-identity-provider": { "version": "3.1051.0", "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity-provider/-/client-cognito-identity-provider-3.1051.0.tgz", @@ -439,6 +442,28 @@ "node": ">=20.0.0" } }, + "node_modules/@aws-sdk/client-s3": { + "version": "3.1085.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.1085.0.tgz", + "integrity": "sha512-O0xe8sR50AYkwxlvRRsV0qytEO2dtXQTQ1CF3YBBdE5xtVkbu27H0vGa1mjQi1/+fbYM80AWEIPai5jZmXyubw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/checksums": "^3.1000.16", + "@aws-sdk/core": "^3.975.1", + "@aws-sdk/credential-provider-node": "^3.972.66", + "@aws-sdk/middleware-sdk-s3": "^3.972.62", + "@aws-sdk/signature-v4-multi-region": "^3.996.39", + "@aws-sdk/types": "^3.974.0", + "@smithy/core": "^3.29.2", + "@smithy/fetch-http-handler": "^5.6.4", + "@smithy/node-http-handler": "^4.9.4", + "@smithy/types": "^4.16.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/@aws-sdk/client-ses": { "version": "3.1073.0", "resolved": "https://registry.npmjs.org/@aws-sdk/client-ses/-/client-ses-3.1073.0.tgz", @@ -482,17 +507,17 @@ } }, "node_modules/@aws-sdk/core": { - "version": "3.974.22", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.974.22.tgz", - "integrity": "sha512-YofH63shc6YRdXjz80BJkpJW+Bkn0Cuu2dn4Rv7s9G2Idt58tgtzQEWxrR2xVljlVfIBeUjPuULnSVYLke3sUQ==", + "version": "3.975.1", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.975.1.tgz", + "integrity": "sha512-8qh/6EYb7hl/ZwVfQufhbMEZs1gQIc7GbdrIf4eprQJ7cv042+74nE6l3YDfyWNzb9iPXb8fRyYSHkNIk5eE6Q==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "^3.973.13", - "@aws-sdk/xml-builder": "^3.972.30", - "@aws/lambda-invoke-store": "^0.2.2", - "@smithy/core": "^3.24.6", - "@smithy/signature-v4": "^5.4.6", - "@smithy/types": "^4.14.3", + "@aws-sdk/types": "^3.974.0", + "@aws-sdk/xml-builder": "^3.972.34", + "@aws/lambda-invoke-store": "^0.3.0", + "@smithy/core": "^3.29.2", + "@smithy/signature-v4": "^5.6.3", + "@smithy/types": "^4.16.0", "bowser": "^2.11.0", "tslib": "^2.6.2" }, @@ -501,15 +526,15 @@ } }, "node_modules/@aws-sdk/credential-provider-env": { - "version": "3.972.48", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.48.tgz", - "integrity": "sha512-h6FEC95fbexUd6zxm4PdgS82bTcI2PRtUb2ZwMipb/Xr8bPwtf0G8rBo2jp7NA24Mbx2JA8/WingiYpA9RCCyw==", + "version": "3.972.57", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.57.tgz", + "integrity": "sha512-1RfJaF7SW1TOnvNGU7kaYjwUf5H3sfm+synGH1bHhRlqcnxCt3szebH3dmKEyY4tuGcbQ6ffzUT89cRitBV8OQ==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.974.22", - "@aws-sdk/types": "^3.973.13", - "@smithy/core": "^3.24.6", - "@smithy/types": "^4.14.3", + "@aws-sdk/core": "^3.975.1", + "@aws-sdk/types": "^3.974.0", + "@smithy/core": "^3.29.2", + "@smithy/types": "^4.16.0", "tslib": "^2.6.2" }, "engines": { @@ -517,17 +542,17 @@ } }, "node_modules/@aws-sdk/credential-provider-http": { - "version": "3.972.50", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.50.tgz", - "integrity": "sha512-lJO3OLpjvz5m/RSBQmsG/CEUGsvCy5ruxKwPQaOCqxqCMuyYT2BZwQUTDZVVwqQ9LrZKuK24JSa6r31hL/tvkg==", + "version": "3.972.59", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.59.tgz", + "integrity": "sha512-sRCkpTiFnCdQvuaRVjQ6SVoHu6i7RUpurVo1c4F81HWhPvUJ7Wdp5MNtSdX1O29CNXc8em3O5m52hCjVtAD9SA==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.974.22", - "@aws-sdk/types": "^3.973.13", - "@smithy/core": "^3.24.6", - "@smithy/fetch-http-handler": "^5.4.6", - "@smithy/node-http-handler": "^4.7.6", - "@smithy/types": "^4.14.3", + "@aws-sdk/core": "^3.975.1", + "@aws-sdk/types": "^3.974.0", + "@smithy/core": "^3.29.2", + "@smithy/fetch-http-handler": "^5.6.4", + "@smithy/node-http-handler": "^4.9.4", + "@smithy/types": "^4.16.0", "tslib": "^2.6.2" }, "engines": { @@ -535,23 +560,23 @@ } }, "node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.972.55", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.972.55.tgz", - "integrity": "sha512-TBoF4buBGYhXjdZAryayY2TrkQj2B2KfE/msG4V53XCt+w0EhEwM2JRjx8p2grJ2C6gtH5++SAwEvGMRdi0yyw==", + "version": "3.973.1", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.1.tgz", + "integrity": "sha512-6d8H6ZAh3ZPKZ6fe1nG2OWeZEZPtt9ravoD1dezPdPtsSkJRoxGAnFSHwKT3E/Te6fHE30zRzjV6TD12rvF6yQ==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.974.22", - "@aws-sdk/credential-provider-env": "^3.972.48", - "@aws-sdk/credential-provider-http": "^3.972.50", - "@aws-sdk/credential-provider-login": "^3.972.54", - "@aws-sdk/credential-provider-process": "^3.972.48", - "@aws-sdk/credential-provider-sso": "^3.972.54", - "@aws-sdk/credential-provider-web-identity": "^3.972.54", - "@aws-sdk/nested-clients": "^3.997.22", - "@aws-sdk/types": "^3.973.13", - "@smithy/core": "^3.24.6", - "@smithy/credential-provider-imds": "^4.3.7", - "@smithy/types": "^4.14.3", + "@aws-sdk/core": "^3.975.1", + "@aws-sdk/credential-provider-env": "^3.972.57", + "@aws-sdk/credential-provider-http": "^3.972.59", + "@aws-sdk/credential-provider-login": "^3.972.63", + "@aws-sdk/credential-provider-process": "^3.972.57", + "@aws-sdk/credential-provider-sso": "^3.973.1", + "@aws-sdk/credential-provider-web-identity": "^3.972.63", + "@aws-sdk/nested-clients": "^3.997.31", + "@aws-sdk/types": "^3.974.0", + "@smithy/core": "^3.29.2", + "@smithy/credential-provider-imds": "^4.4.7", + "@smithy/types": "^4.16.0", "tslib": "^2.6.2" }, "engines": { @@ -559,16 +584,16 @@ } }, "node_modules/@aws-sdk/credential-provider-login": { - "version": "3.972.54", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.54.tgz", - "integrity": "sha512-hBWI3wZTdTGiuMfmPts6AWbAjFfRniOQnqx68tc2cQvRKWawFbN9wkLOVPWM1FAOyowZU73mC6Fi+rHSHNyLFw==", + "version": "3.972.63", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.63.tgz", + "integrity": "sha512-GREWRrMj0XnNKMaVa/Mauoaui26qBEHu71WWqXbwZOu/jFQOnPZjTf7u0KtGKC8VGa6VUs9kDWGgocrKNLS9vw==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.974.22", - "@aws-sdk/nested-clients": "^3.997.22", - "@aws-sdk/types": "^3.973.13", - "@smithy/core": "^3.24.6", - "@smithy/types": "^4.14.3", + "@aws-sdk/core": "^3.975.1", + "@aws-sdk/nested-clients": "^3.997.31", + "@aws-sdk/types": "^3.974.0", + "@smithy/core": "^3.29.2", + "@smithy/types": "^4.16.0", "tslib": "^2.6.2" }, "engines": { @@ -576,21 +601,21 @@ } }, "node_modules/@aws-sdk/credential-provider-node": { - "version": "3.972.57", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.57.tgz", - "integrity": "sha512-u6dClpzNdWf1HGWz4wwhdXi1wiOofCLniM9S4BQQGlLAN9TW7VB+ld5V533GdKrYMaFeBGFqKnj0JCYvynLqwQ==", + "version": "3.972.66", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.66.tgz", + "integrity": "sha512-f+qjRXZpz7sgzbc4QB+6nLKfyKFgRRXzWdXbsKPv/VhVRyHsDyq4yBWC/B75BAJpFIcUeI2XR/3gdWJ677zB4A==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/credential-provider-env": "^3.972.48", - "@aws-sdk/credential-provider-http": "^3.972.50", - "@aws-sdk/credential-provider-ini": "^3.972.55", - "@aws-sdk/credential-provider-process": "^3.972.48", - "@aws-sdk/credential-provider-sso": "^3.972.54", - "@aws-sdk/credential-provider-web-identity": "^3.972.54", - "@aws-sdk/types": "^3.973.13", - "@smithy/core": "^3.24.6", - "@smithy/credential-provider-imds": "^4.3.7", - "@smithy/types": "^4.14.3", + "@aws-sdk/credential-provider-env": "^3.972.57", + "@aws-sdk/credential-provider-http": "^3.972.59", + "@aws-sdk/credential-provider-ini": "^3.973.1", + "@aws-sdk/credential-provider-process": "^3.972.57", + "@aws-sdk/credential-provider-sso": "^3.973.1", + "@aws-sdk/credential-provider-web-identity": "^3.972.63", + "@aws-sdk/types": "^3.974.0", + "@smithy/core": "^3.29.2", + "@smithy/credential-provider-imds": "^4.4.7", + "@smithy/types": "^4.16.0", "tslib": "^2.6.2" }, "engines": { @@ -598,15 +623,15 @@ } }, "node_modules/@aws-sdk/credential-provider-process": { - "version": "3.972.48", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.48.tgz", - "integrity": "sha512-w6VZwojPt12WnEkAUy6Nu4K6sWCbBmR7QX390b0nE6vRvkXbrYr9Lq9VySGkfjiMjpUA87op+J4EgvRmtWIDoQ==", + "version": "3.972.57", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.57.tgz", + "integrity": "sha512-TiVQhuU0pbhIZAUZacbPHMyzrIdiH+lnx+PMY/Pu/b93dJrq3wdZwzUJ0TPpvNxaqbHsxJvQZW3/h/beLiKq7Q==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.974.22", - "@aws-sdk/types": "^3.973.13", - "@smithy/core": "^3.24.6", - "@smithy/types": "^4.14.3", + "@aws-sdk/core": "^3.975.1", + "@aws-sdk/types": "^3.974.0", + "@smithy/core": "^3.29.2", + "@smithy/types": "^4.16.0", "tslib": "^2.6.2" }, "engines": { @@ -614,17 +639,17 @@ } }, "node_modules/@aws-sdk/credential-provider-sso": { - "version": "3.972.54", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.972.54.tgz", - "integrity": "sha512-23uZpIpF2SIFDCa1fcWa202tK4gGeyvX6GIIAjiB8WBsvsVRBMnJ/7dCxHzxf7eZT7GToJg837LDIBnZsl/VUg==", + "version": "3.973.1", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.1.tgz", + "integrity": "sha512-3foTZUJ4821Ij60X7K3NJroygiZLnbBmarN+T//O2cjkISan90zElN3NBmgSlDrTQ7Gs6z/yO8V7h60QNcDZHQ==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.974.22", - "@aws-sdk/nested-clients": "^3.997.22", - "@aws-sdk/token-providers": "3.1071.0", - "@aws-sdk/types": "^3.973.13", - "@smithy/core": "^3.24.6", - "@smithy/types": "^4.14.3", + "@aws-sdk/core": "^3.975.1", + "@aws-sdk/nested-clients": "^3.997.31", + "@aws-sdk/token-providers": "3.1083.0", + "@aws-sdk/types": "^3.974.0", + "@smithy/core": "^3.29.2", + "@smithy/types": "^4.16.0", "tslib": "^2.6.2" }, "engines": { @@ -632,16 +657,16 @@ } }, "node_modules/@aws-sdk/credential-provider-web-identity": { - "version": "3.972.54", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.54.tgz", - "integrity": "sha512-0Iv5QttS6wcATlodYKgvQj6B9Db51rx7NU9fqu0PoLeS4BIgdYMc/QK4smwLwpm5RFrs02V/eLyEFp3FklvlNQ==", + "version": "3.972.63", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.63.tgz", + "integrity": "sha512-8qZLFhM69eKcS37m459ctPR05Qimycm/74OPVioe6wNZabMT54GYhwBju0+J656RkMasNSawWQu+c8CmBe3TUQ==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.974.22", - "@aws-sdk/nested-clients": "^3.997.22", - "@aws-sdk/types": "^3.973.13", - "@smithy/core": "^3.24.6", - "@smithy/types": "^4.14.3", + "@aws-sdk/core": "^3.975.1", + "@aws-sdk/nested-clients": "^3.997.31", + "@aws-sdk/types": "^3.974.0", + "@smithy/core": "^3.29.2", + "@smithy/types": "^4.16.0", "tslib": "^2.6.2" }, "engines": { @@ -711,21 +736,36 @@ "node": ">=20.0.0" } }, + "node_modules/@aws-sdk/middleware-sdk-s3": { + "version": "3.972.62", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.972.62.tgz", + "integrity": "sha512-k8JJwYXVYlOOjWnPZDThQS1xDFJgi5Dokt73qFlDtrZAbdcint5aIdjB9XgJAAQVP5OoqcefQmh1FYXiPpvsvw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.975.1", + "@aws-sdk/signature-v4-multi-region": "^3.996.39", + "@aws-sdk/types": "^3.974.0", + "@smithy/core": "^3.29.2", + "@smithy/types": "^4.16.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/@aws-sdk/nested-clients": { - "version": "3.997.22", - "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.22.tgz", - "integrity": "sha512-4IwtcYSxEIVw5hcp8ogq0CMbFNZFw7jJUetpfFUhFFeqsa1K8j2Ihg2hnxLyOp3stMZnXda6VzOmPi1AFZQXcg==", + "version": "3.997.31", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.31.tgz", + "integrity": "sha512-BDHTpwcsZHEBNEJzOg/B1BkFYJxAXY50dau/NyVWs3d51F0WgIUGSWZot/Os+N3KpDhXeaXnz37mWffAvduREw==", "license": "Apache-2.0", "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "^3.974.22", - "@aws-sdk/signature-v4-multi-region": "^3.996.35", - "@aws-sdk/types": "^3.973.13", - "@smithy/core": "^3.24.6", - "@smithy/fetch-http-handler": "^5.4.6", - "@smithy/node-http-handler": "^4.7.6", - "@smithy/types": "^4.14.3", + "@aws-sdk/core": "^3.975.1", + "@aws-sdk/signature-v4-multi-region": "^3.996.39", + "@aws-sdk/types": "^3.974.0", + "@smithy/core": "^3.29.2", + "@smithy/fetch-http-handler": "^5.6.4", + "@smithy/node-http-handler": "^4.9.4", + "@smithy/types": "^4.16.0", "tslib": "^2.6.2" }, "engines": { @@ -733,14 +773,14 @@ } }, "node_modules/@aws-sdk/signature-v4-multi-region": { - "version": "3.996.35", - "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.35.tgz", - "integrity": "sha512-6L/VWs+Wch2stHemCGTmUNqKLMzURxQDK5boNG3Jn3kAOp71meDUuS5sbObpEvFxHDq0uWeSLFDNSYsjNt+Dlg==", + "version": "3.996.39", + "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.39.tgz", + "integrity": "sha512-8+srXqYIF8KYMLC4FxMLEM5Ek7kUNibJu1R4m8/fUhhNYIZZz26oGtKkCr8I/HiG2fFQxBvaGgQZT4/mqRCSnA==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "^3.973.13", - "@smithy/signature-v4": "^5.4.6", - "@smithy/types": "^4.14.3", + "@aws-sdk/types": "^3.974.0", + "@smithy/signature-v4": "^5.6.3", + "@smithy/types": "^4.16.0", "tslib": "^2.6.2" }, "engines": { @@ -748,16 +788,16 @@ } }, "node_modules/@aws-sdk/token-providers": { - "version": "3.1071.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1071.0.tgz", - "integrity": "sha512-4LDW2Qob6LoLFuqYSYZq2AyTE9koSE9+i+n5UZcm10GpmQOK0zRD9L4uYlzItiTKksIWgC/qMFChAi3RvKYtMg==", + "version": "3.1083.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1083.0.tgz", + "integrity": "sha512-s0woKnxuHrExLc5L2ArIH5BMkbonHPtt+5hSBM8oknp9M6QTuUmmAmJ2E0EdzCGONrO+8+ADPqvv6UX0nNcc7A==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.974.22", - "@aws-sdk/nested-clients": "^3.997.22", - "@aws-sdk/types": "^3.973.13", - "@smithy/core": "^3.24.6", - "@smithy/types": "^4.14.3", + "@aws-sdk/core": "^3.975.1", + "@aws-sdk/nested-clients": "^3.997.31", + "@aws-sdk/types": "^3.974.0", + "@smithy/core": "^3.29.2", + "@smithy/types": "^4.16.0", "tslib": "^2.6.2" }, "engines": { @@ -765,12 +805,12 @@ } }, "node_modules/@aws-sdk/types": { - "version": "3.973.13", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.973.13.tgz", - "integrity": "sha512-pEHZqRkAlHfnfAU9tK+WpKv/gBNjGJrHMgA3A0iYRGyswBS2t0pfez+lWlwktb3Bqa0ovh7w/QJTFwp3fDxLNg==", + "version": "3.974.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.974.0.tgz", + "integrity": "sha512-QIBrw90CDm4O0UaIIzkU6DrFdeJzEb2Va5EPEVpyldj6sHJxB6cshhStJuhZxk3wR3PmjJlYsjPmY1kNb+KGBg==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.14.3", + "@smithy/types": "^4.16.0", "tslib": "^2.6.2" }, "engines": { @@ -805,13 +845,12 @@ } }, "node_modules/@aws-sdk/xml-builder": { - "version": "3.972.30", - "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.30.tgz", - "integrity": "sha512-StElZPEoBquWwNqw1AcfpzEyZqJvFxouG+mpDNYlcH6ZOrqd2CuIryv+8LV8gNHZUOyKyJF3Dq9vxaXEmDR9TQ==", + "version": "3.972.34", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.34.tgz", + "integrity": "sha512-wHhWL1y7sN3enBA8POrPpQM5jCcmu2ozyhbRei4c8OjVcEaEs6yLucLa/pla457ggS/ysuy7bosagz3HaJkZXA==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.14.3", - "fast-xml-parser": "5.7.3", + "@smithy/types": "^4.16.0", "tslib": "^2.6.2" }, "engines": { @@ -819,9 +858,9 @@ } }, "node_modules/@aws/lambda-invoke-store": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.2.4.tgz", - "integrity": "sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ==", + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz", + "integrity": "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==", "license": "Apache-2.0", "engines": { "node": ">=18.0.0" @@ -2798,18 +2837,6 @@ "@emnapi/runtime": "^1.7.1" } }, - "node_modules/@nodable/entities": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-2.2.0.tgz", - "integrity": "sha512-9uGyhaQavEUMC8AIddIjau4NsnsXhou+j5sBAGojCM1oxmQpVKTWR/9JxABD6UAv12vpIms55fPZKFQEhG6uBg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/nodable" - } - ], - "license": "MIT" - }, "node_modules/@pkgjs/parseargs": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", @@ -2877,13 +2904,12 @@ } }, "node_modules/@smithy/core": { - "version": "3.25.1", - "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.25.1.tgz", - "integrity": "sha512-zpDbpXBCBsxfLtG2GEUyfgvHvSFrw5CwDZSNzL0v52gx/c3oPlPbm+7W7num8xs6vyiUBn+bvYPHcQDOXZynCQ==", + "version": "3.29.3", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.29.3.tgz", + "integrity": "sha512-L+Ys6ecjk5vwPMAKHBpPKlJ3DkqwNcnfEISXBZIsVvWG/XKXfsAP8mwIYlTeLcd2ElHdesPI8OuOmJSFAPhm6A==", "license": "Apache-2.0", "dependencies": { - "@aws-crypto/crc32": "5.2.0", - "@smithy/types": "^4.15.0", + "@smithy/types": "^4.16.1", "tslib": "^2.6.2" }, "engines": { @@ -2891,13 +2917,13 @@ } }, "node_modules/@smithy/credential-provider-imds": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.4.1.tgz", - "integrity": "sha512-TSAF5NHgxEsllbErYWbK8aLnl5L601NGc5VYJlSPsKnf3YlkhdoBN+geGcaU00oiw2OK3QO5LA3QNXiiWhCidQ==", + "version": "4.4.8", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.4.8.tgz", + "integrity": "sha512-q9J7JTiXrAhB8sDp4px97uEPT7CwKH61Co78grdNQvU8QZAdiuaSRhP0tUVf2ogy36RZTrlMU1rBmDEH+cnkiA==", "license": "Apache-2.0", "dependencies": { - "@smithy/core": "^3.25.1", - "@smithy/types": "^4.15.0", + "@smithy/core": "^3.29.3", + "@smithy/types": "^4.16.1", "tslib": "^2.6.2" }, "engines": { @@ -2905,13 +2931,13 @@ } }, "node_modules/@smithy/fetch-http-handler": { - "version": "5.5.1", - "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.5.1.tgz", - "integrity": "sha512-96JrD1q71anokymx9Iblb+zKmNQYNstlV/25A9ZYIJ2A0rp1r7/GZAIm0bDWSmVvz3DpNOCZuabzsiL+w0UHhw==", + "version": "5.6.5", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.6.5.tgz", + "integrity": "sha512-SuqeisTyPoiIPtIYru/sGxGyXzmZ+8nnFOhC+qRPglt06Ebd1yH//CDltZB2J/3WBNVhwfUaZ0EtHB3cm2X32g==", "license": "Apache-2.0", "dependencies": { - "@smithy/core": "^3.25.1", - "@smithy/types": "^4.15.0", + "@smithy/core": "^3.29.3", + "@smithy/types": "^4.16.1", "tslib": "^2.6.2" }, "engines": { @@ -2931,13 +2957,13 @@ } }, "node_modules/@smithy/node-http-handler": { - "version": "4.8.1", - "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.8.1.tgz", - "integrity": "sha512-emtXvoky671puri18ETf64AFIQUGIEA093F2drXpBgB0OGnBLjcwNR3CA2mYu62IAqNsS56xa5lnTxAgPq7cjw==", + "version": "4.9.5", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.9.5.tgz", + "integrity": "sha512-bNqdxTQTxmLbomSmlkZFz8L6B/feQ2HHzw4L2zY7Ecp2XffYAZq2uzdWDdxJHJFbEvqd+SRuluJso0P8+xPdbw==", "license": "Apache-2.0", "dependencies": { - "@smithy/core": "^3.25.1", - "@smithy/types": "^4.15.0", + "@smithy/core": "^3.29.3", + "@smithy/types": "^4.16.1", "tslib": "^2.6.2" }, "engines": { @@ -2945,13 +2971,13 @@ } }, "node_modules/@smithy/signature-v4": { - "version": "5.5.1", - "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.5.1.tgz", - "integrity": "sha512-X9rVls3En0z3NtrmguTmpRM0/NqtWUxBjal6fcAkwtsub+gOdLZ6kD+V7xhUgFMGdG14bHbZ7M5QjaRI1+DatQ==", + "version": "5.6.4", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.6.4.tgz", + "integrity": "sha512-B89bpf2t/y/wia6LZ+4JfHXYQT9PnVftsH05rgJKKIStS7r/4XSs9HOjtPoLtgcA6HCW9jVqX5DBbq7E0PAkiQ==", "license": "Apache-2.0", "dependencies": { - "@smithy/core": "^3.25.1", - "@smithy/types": "^4.15.0", + "@smithy/core": "^3.29.3", + "@smithy/types": "^4.16.1", "tslib": "^2.6.2" }, "engines": { @@ -2959,9 +2985,9 @@ } }, "node_modules/@smithy/types": { - "version": "4.15.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.15.0.tgz", - "integrity": "sha512-Z5TAOxygoFvybJV3igo5SloFflSokHx2hu1eFA+DxDTcn+FtKxUSui+rbTRG1pAafMA888Z3MVvCWUuvCrTXjg==", + "version": "4.16.1", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.16.1.tgz", + "integrity": "sha512-0JFs3V2y2M9tKW5na/qxe69Zv+uxLMO7QBbhxF/FHu/Gp2NFZAAL9tWl9PU02xxo07pb3G9FTyjNc6D5uZrJIg==", "license": "Apache-2.0", "dependencies": { "tslib": "^2.6.2" @@ -3989,18 +4015,6 @@ "node": ">= 8" } }, - "node_modules/anynum": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/anynum/-/anynum-1.0.1.tgz", - "integrity": "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT" - }, "node_modules/arg": { "version": "4.1.3", "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", @@ -4996,43 +5010,6 @@ "dev": true, "license": "MIT" }, - "node_modules/fast-xml-builder": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.2.0.tgz", - "integrity": "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "dependencies": { - "path-expression-matcher": "^1.5.0", - "xml-naming": "^0.1.0" - } - }, - "node_modules/fast-xml-parser": { - "version": "5.7.3", - "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.7.3.tgz", - "integrity": "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "dependencies": { - "@nodable/entities": "^2.1.0", - "fast-xml-builder": "^1.1.7", - "path-expression-matcher": "^1.5.0", - "strnum": "^2.2.3" - }, - "bin": { - "fxparser": "src/cli/cli.js" - } - }, "node_modules/fb-watchman": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", @@ -6645,21 +6622,6 @@ "node": ">=8" } }, - "node_modules/path-expression-matcher": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.6.0.tgz", - "integrity": "sha512-e5y7RCLHKjemsgQ4eqGJtPyr10ILz25HO7flzxhTV8bgvd5yHx98DGtCAtbVW9f2TqnYI/gEVZd+vz7snrdPTw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, "node_modules/path-is-absolute": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", @@ -7270,21 +7232,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/strnum": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.4.1.tgz", - "integrity": "sha512-M9eUSMT2dCB2cTNPG7UYj6KuK7RJR2SN2+yCV/fTW3xzTCS6EaGZ5pSMgDIjB7r8zSfTGk+dvvn9rTjpVS9Mwg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "dependencies": { - "anynum": "^1.0.1" - } - }, "node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", @@ -7983,21 +7930,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/xml-naming": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.1.0.tgz", - "integrity": "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "engines": { - "node": ">=16.0.0" - } - }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/backend/package.json b/backend/package.json index 27c3748..17686ca 100644 --- a/backend/package.json +++ b/backend/package.json @@ -9,6 +9,8 @@ "build": "esbuild src/handler.ts --bundle --platform=node --target=node24 --outfile=dist/handler.js", "printschema": "tsx scripts/print-schema.ts", "build:photos": "tsx scripts/build-photo-pool.ts", + "photos:progress": "tsx scripts/photos-progress.ts", + "sync:photos": "tsx scripts/sync-photos-s3.ts", "typecheck": "tsc --noEmit", "test": "jest", "lint": "eslint . && node_modules/.bin/tsx node_modules/prettier/bin/prettier.cjs --check .", @@ -23,6 +25,7 @@ "@aws-sdk/client-dynamodb": "^3.1051.0", "@aws-sdk/client-kms": "^3.1056.0", "@aws-sdk/client-pinpoint-sms-voice-v2": "^3.1073.0", + "@aws-sdk/client-s3": "^3.1085.0", "@aws-sdk/client-ses": "^3.1073.0", "@aws-sdk/client-ssm": "^3.1056.0", "@aws-sdk/lib-dynamodb": "^3.1051.0", diff --git a/backend/prettier.config.ts b/backend/prettier.config.ts index f94a986..34ce975 100644 --- a/backend/prettier.config.ts +++ b/backend/prettier.config.ts @@ -27,6 +27,9 @@ const config: Config = { 'schema.graphql', '.env*', '.dockerignore', + // Generated photo pool (lives in S3, not the repo) + its runtime artifacts. + 'photos.json', + 'photos-cache/**', ], options: { parser: 'ignored' }, }, diff --git a/backend/schema.graphql b/backend/schema.graphql index 07c836b..e5517c0 100644 --- a/backend/schema.graphql +++ b/backend/schema.graphql @@ -33,12 +33,6 @@ type Dossier { totalRatings: Int! } -"""Which algorithm drives the feed: A (engagement) or B (user-first).""" -enum Driver { - A - B -} - """An illustrative trait Algorithm A infers — see Dossier.disclaimer.""" type InferredTrait { basis: String! @@ -97,6 +91,11 @@ type Mutation { """ mergeLearnProgress(progress: [LearnSectionProgressInput!]!): [LearnSectionProgress!]! + """ + Email the site owner that the authenticated user is downloading the research paper. Returns true ONLY if the email was sent — the client gates the download on this, so an unidentified user or a failed send blocks the download. + """ + notifyResearchDownload: Boolean! + """ Record that a Learn-page slide was viewed; returns the full updated progress. """ @@ -139,9 +138,9 @@ type Query { me: User """ - A batch of travel photos chosen by the given driver (A narrows toward the user's taste; B stays diverse). Defaults to B. + A batch of travel photos chosen user-first: diverse, weighted by the user's learned per-country preferences (Algorithm B). """ - travelImages(count: Int = 8, driver: Driver = B): [TravelImage!]! + travelImages(count: Int = 8): [TravelImage!]! } """One axis of the learned taste vector and its weight.""" diff --git a/backend/scripts/build-photo-pool.ts b/backend/scripts/build-photo-pool.ts index 76934cb..7dbddd6 100644 --- a/backend/scripts/build-photo-pool.ts +++ b/backend/scripts/build-photo-pool.ts @@ -1,104 +1,282 @@ /** - * @fileoverview Generates the cached photo pool (src/photos.data.ts). + * @fileoverview Generates the cached photo pool metadata (`backend/photos.json`) — Step A. * - * Fetches a batch of neutral, metadata-rich photos per catalog country from the - * Unsplash Search API, then writes them as `PHOTO_POOL`. Both the country signatures - * and the Travel feed serve from this committed pool, so the running app makes ~zero - * Unsplash calls (no rate-limit pressure). + * For each catalog country, runs TWO Unsplash searches — a landscape/nature query + * and a cityscape query — curates the candidates down to a unique, mixed set + * (see `photos.curate.ts`), then **enriches** each kept photo with a `GET /photos/:id` + * call for its real `tags` (search results carry none) plus `location` + `exif`. + * The metadata is written as `photos.json` (NOT committed); Step B uploads it to S3, + * and the Lambda loads it at runtime (`pool.ts`), so the running app makes ZERO + * Unsplash API calls. * - * Run once (and whenever the catalog changes), with a key configured: - * UNSPLASH_ACCESS_KEY=... npm run build:photos + * Country is a **search association**, not a verified geotag (see photos.types.ts). * - * Honors the rate limit by spacing requests; uses landscape orientation and the - * country's search term. Re-run sparingly. + * ── Rate limits & resumability ────────────────────────────────────────────── + * Every call (2 searches + up to PER_COUNTRY enrichment calls per country) shares the + * demo-mode budget of 50 req/hr, so a full 228-country run is ~2.5–3 days. A single + * global gate spaces ALL calls ≥ THROTTLE_MS apart. The run is **resumable**: it loads + * any existing `photos.json` and skips countries already populated, writing a country + * only after all its photos are enriched — so an interrupted background run picks up + * cleanly (at most one country of re-work). + * + * UNSPLASH_ACCESS_KEY=... npm run build:photos # full run (~2.5–3 days demo) + * PHOTOS_PER_COUNTRY=8 PHOTOS_MAX_COUNTRIES=10 \ + * UNSPLASH_ACCESS_KEY=... npm run build:photos # quick local sample + * PHOTOS_ENRICH=0 UNSPLASH_ACCESS_KEY=... npm run build:photos # skip enrichment (no tags) + * PHOTOS_RESET=1 UNSPLASH_ACCESS_KEY=... npm run build:photos # ignore existing, start fresh + * + * Image hosting (S3) is Step B — see `sync-photos-s3.ts`. `imageUrl` is written from + * PHOTO_CDN_BASE (default `/photos`) so photos load same-origin once synced; the + * original CDN url is retained in `unsplashImageUrl` as the sync source + local fallback. */ -import { writeFileSync } from 'node:fs'; +import 'dotenv/config'; // load UNSPLASH_ACCESS_KEY (and any PHOTOS_* knobs) from backend/.env +import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { COUNTRIES } from '../src/countries'; +import { COUNTRIES, type Country } from '../src/countries'; import { config } from '../src/config'; -import type { CachedPhoto } from '../src/photos.types'; - -// Env-configurable so a small pool can be built locally (demo mode, 50 req/hr) -// without burning quota, and the full pool built once for the live demo: -// PHOTOS_MAX_COUNTRIES=8 PHOTOS_PER_COUNTRY=6 npm run build:photos # local -// npm run build:photos # full -/** Photos to fetch per country (more = steadier signatures, more API calls). */ -const PER_COUNTRY = Number(process.env.PHOTOS_PER_COUNTRY ?? 12); -/** How many catalog countries to fetch (default: all). Each is one API call. */ +import { curatePhotos, isDenied, DEFAULT_DENY_TERMS } from '../src/photos.curate'; +import type { CachedPhoto, PhotoKind } from '../src/photos.types'; + +/** Photos kept per country after curation. */ +const PER_COUNTRY = Number(process.env.PHOTOS_PER_COUNTRY ?? 15); +/** How many catalog countries to process (default: all). */ const MAX_COUNTRIES = Number(process.env.PHOTOS_MAX_COUNTRIES ?? Number.MAX_SAFE_INTEGER); +/** Candidates requested per search (before curation). Max 30 per Unsplash. */ +const PER_PAGE = Number(process.env.PHOTOS_PER_PAGE ?? 25); +/** Minimum Unsplash likes to clear the quality gate. Default 0: a like gate starves + * the catalog's many niche countries (their Unsplash coverage is thin and low-liked), + * while popular countries fill up regardless because results come back in relevance + * order and we keep that order. content_filter=high + landscape orientation + the tag + * denylist do the quality work; raise PHOTOS_MIN_LIKES to bias popular countries harder. */ +const MIN_LIKES = Number(process.env.PHOTOS_MIN_LIKES ?? 0); /** Delay between API calls (ms). Demo mode (50/hr) needs ≥72000; production (5000/hr) ~800. */ -const THROTTLE_MS = Number(process.env.PHOTOS_THROTTLE_MS ?? 1500); +const THROTTLE_MS = Number(process.env.PHOTOS_THROTTLE_MS ?? 73000); +/** When set, ignore any existing pool and rebuild from scratch. */ +const RESET = Boolean(process.env.PHOTOS_RESET); +/** Enrich each kept photo (GET /photos/:id) for real tags + location + exif. On by + * default — search results carry no tags. Set PHOTOS_ENRICH=0 to skip (much faster, + * but photos will have empty tags). */ +const ENRICH = process.env.PHOTOS_ENRICH !== '0'; +/** Base for the same-origin image URL baked into the pool. */ +const CDN_BASE = (process.env.PHOTO_CDN_BASE ?? '/photos').replace(/\/$/, ''); +const OUTPUT_PATH = join(import.meta.dirname, '..', 'photos.json'); + +/** The subset of Unsplash `/search/photos` result fields we consume. */ interface SearchPhoto { + id: string; urls: { regular: string }; user: { name: string; links: { html: string } }; links: { html: string; download_location: string }; tags?: { title: string }[]; color?: string; + blur_hash?: string; + likes?: number; + width?: number; + height?: number; + description?: string; + alt_description?: string; +} + +/** Full photo fields we consume from the enrichment call (GET /photos/:id). */ +interface FullPhoto { + tags?: { title: string }[]; + location?: { + name?: string | null; + position?: { latitude?: number | null; longitude?: number | null }; + }; + exif?: { + make?: string | null; + model?: string | null; + focal_length?: string | null; + aperture?: string | null; + exposure_time?: string | null; + iso?: number | null; + }; } const sleep = (ms: number): Promise => new Promise((r) => setTimeout(r, ms)); -async function fetchCountry(searchTerm: string, key: string): Promise { +// A single global gate: every Unsplash call (search + enrichment) waits so that all +// requests are spaced ≥ THROTTLE_MS apart, keeping the whole run under the hourly cap. +let lastCallAt = 0; +async function gate(): Promise { + const wait = THROTTLE_MS - (Date.now() - lastCallAt); + if (wait > 0) await sleep(wait); + lastCallAt = Date.now(); +} + +/** Rate-limited GET. On a rate-limit 403 (hourly quota exhausted) it waits for the + * window to reset and retries, so a multi-day run survives quota blips unattended + * instead of stopping. Real (non-rate) errors fall through to the caller. */ +async function unsplash(url: URL | string, key: string): Promise { + for (;;) { + await gate(); + const res = await fetch(url, { headers: { Authorization: `Client-ID ${key}` } }); + if (res.status === 403 && res.headers.get('x-ratelimit-remaining') === '0') { + console.error(`${new Date().toISOString()} rate limit reached — waiting 1h for reset…`); + await sleep(60 * 60 * 1000 + 60_000); // 1h + buffer + continue; + } + return res; + } +} + +/** One Unsplash search. Throws on a non-OK response so the caller can react to 403s. */ +async function search(query: string, key: string): Promise { const url = new URL('https://api.unsplash.com/search/photos'); - url.searchParams.set('query', searchTerm); + url.searchParams.set('query', query); url.searchParams.set('orientation', 'landscape'); url.searchParams.set('content_filter', 'high'); - url.searchParams.set('per_page', String(PER_COUNTRY)); - const res = await fetch(url, { headers: { Authorization: `Client-ID ${key}` } }); - if (!res.ok) - throw new Error(`Unsplash search failed (${String(res.status)}) for "${searchTerm}"`); + url.searchParams.set('per_page', String(PER_PAGE)); + const res = await unsplash(url, key); + if (!res.ok) throw new Error(`Unsplash search failed (${String(res.status)}) for "${query}"`); const body = (await res.json()) as { results: SearchPhoto[] }; return body.results; } +/** Enrich a photo in place with its real tags + location + exif (GET /photos/:id). */ +async function enrich(photo: CachedPhoto, key: string): Promise { + const res = await unsplash(`https://api.unsplash.com/photos/${photo.id}`, key); + if (!res.ok) throw new Error(`Unsplash enrich failed (${String(res.status)}) for ${photo.id}`); + const full = (await res.json()) as FullPhoto; + + const tags = full.tags?.map((t) => t.title).filter(Boolean) ?? []; + if (tags.length > 0) photo.tags = tags; + + const name = full.location?.name; + if (name) photo.locationName = name; + const lat = full.location?.position?.latitude; + const lng = full.location?.position?.longitude; + if (typeof lat === 'number') photo.lat = lat; + if (typeof lng === 'number') photo.lng = lng; + + const e = full.exif; + if (e) { + const exif: NonNullable = {}; + if (e.make) exif.make = e.make; + if (e.model) exif.model = e.model; + if (e.focal_length) exif.focalLength = e.focal_length; + if (e.aperture) exif.aperture = e.aperture; + if (e.exposure_time) exif.exposureTime = e.exposure_time; + if (typeof e.iso === 'number') exif.iso = e.iso; + if (Object.keys(exif).length > 0) photo.exif = exif; + } +} + +/** Map a raw search result to a CachedPhoto for the given country + kind. */ +function toCachedPhoto(p: SearchPhoto, country: Country, kind: PhotoKind): CachedPhoto { + const photo: CachedPhoto = { + id: p.id, + country: country.code, + kind, + imageUrl: `${CDN_BASE}/${p.id}.jpg`, + unsplashImageUrl: p.urls.regular, + attribution: `Photo by ${p.user.name} on Unsplash`, + photographerName: p.user.name, + photographerUrl: p.user.links.html, + unsplashUrl: p.links.html, + tags: p.tags?.map((t) => t.title).filter(Boolean) ?? [], + likes: p.likes ?? 0, + width: p.width ?? 0, + height: p.height ?? 0, + downloadLocation: p.links.download_location, + }; + if (p.color) photo.color = p.color; + if (p.blur_hash) photo.blurHash = p.blur_hash; + const desc = p.description ?? p.alt_description; + if (desc) photo.description = desc; + return photo; +} + +/** A city-focused query companion to the catalog's landscape `searchTerm`. Short, for + * the same recall reason (see countries.ts) — " city skyline cityscape" starves + * niche countries; " city" returns far more. */ +function cityTerm(country: Country): string { + return `${country.name} city`; +} + +/** Load an existing pool (for resumable runs); {} on any miss. */ +function loadExistingPool(): Record { + if (RESET) return {}; + try { + return JSON.parse(readFileSync(OUTPUT_PATH, 'utf8')) as Record; + } catch { + return {}; + } +} + +function writePool(pool: Record): void { + writeFileSync(OUTPUT_PATH, `${JSON.stringify(pool, null, 2)}\n`); +} + async function main(): Promise { const key = config.unsplashAccessKey; if (!key) throw new Error('UNSPLASH_ACCESS_KEY is required to build the photo pool.'); + const pool = loadExistingPool(); + const seenIds = new Set( + Object.values(pool) + .flat() + .map((p) => p.id), + ); + const targets = COUNTRIES.slice(0, MAX_COUNTRIES); - const pool: Record = {}; + let processed = 0; for (const country of targets) { + // Resume: skip countries already populated by an earlier run. + if (!RESET && (pool[country.code]?.length ?? 0) > 0) { + console.log(`${country.code}: skip (already ${String(pool[country.code]?.length)})`); + continue; + } + try { - const results = await fetchCountry(country.searchTerm, key); - pool[country.code] = results.map((p) => ({ - country: country.code, - imageUrl: p.urls.regular, - attribution: `Photo by ${p.user.name} on Unsplash`, - photographerName: p.user.name, - photographerUrl: p.user.links.html, - unsplashUrl: p.links.html, - tags: p.tags?.map((t) => t.title).filter(Boolean) ?? [], - color: p.color, - downloadLocation: p.links.download_location, - })); - console.log(`${country.code}: ${String(pool[country.code]?.length ?? 0)} photos`); + const landscape = await search(country.searchTerm, key); + const city = await search(cityTerm(country), key); + + const candidates = [ + ...landscape.map((p) => toCachedPhoto(p, country, 'landscape')), + ...city.map((p) => toCachedPhoto(p, country, 'city')), + ]; + const kept = curatePhotos(candidates, { + perCountry: PER_COUNTRY, + minLikes: MIN_LIKES, + seenIds, + }); + + // Enrich each kept photo with real tags + location + exif. Done before the + // country is committed to `pool`, so an interrupt leaves no half-enriched country. + if (ENRICH) { + for (const photo of kept) await enrich(photo, key); + } + + // Real tags only exist after enrichment, so re-apply the denylist here — this is + // what catches people/portrait shots that had bland descriptions at curation time. + const clean = ENRICH ? kept.filter((p) => !isDenied(p, DEFAULT_DENY_TERMS)) : kept; + + pool[country.code] = clean; + processed++; + writePool(pool); // checkpoint after every country so a long run is resumable + const dropped = kept.length - clean.length; + console.log( + `${country.code}: ${String(clean.length)} kept` + + (dropped > 0 ? ` (${String(dropped)} dropped on real tags)` : ''), + ); } catch (err) { const msg = (err as Error).message; console.error(`${country.code}: ${msg}`); - // Rate limit reached — stop and write what we have rather than 403-looping. if (msg.includes('403')) { - console.error('Rate limit reached — stopping early; writing the partial pool.'); + console.error('Rate limit reached — progress saved; re-run to resume this country.'); + writePool(pool); break; } - pool[country.code] = []; } - await sleep(THROTTLE_MS); } - const header = - '/**\n' + - ' * @fileoverview Precomputed per-country photo pool — GENERATED by\n' + - ' * `npm run build:photos`. Do not edit by hand.\n' + - ' */\n\n' + - "import type { CachedPhoto } from './photos.types';\n\n" + - 'export const PHOTO_POOL: Record = '; - const out = `${header}${JSON.stringify(pool, null, 2)};\n`; - const outputPath = join(import.meta.dirname, '..', 'src', 'photos.data.ts'); - writeFileSync(outputPath, out); const total = Object.values(pool).reduce((n, ps) => n + ps.length, 0); console.log( - `Wrote ${outputPath} — ${String(total)} photos across ${String(COUNTRIES.length)} countries`, + `Wrote ${OUTPUT_PATH} — ${String(total)} photos across ` + + `${String(Object.keys(pool).length)} countries (${String(processed)} processed this run).`, ); } diff --git a/backend/scripts/photos-progress.ts b/backend/scripts/photos-progress.ts new file mode 100644 index 0000000..b7a87cc --- /dev/null +++ b/backend/scripts/photos-progress.ts @@ -0,0 +1,71 @@ +/** + * @fileoverview At-a-glance progress for a running `build:photos` job (Step A). + * + * Reads the checkpointed `photos.json` (written after every country) and reports how + * far through the 228-country catalog the run is, how many photos/tags landed, whether + * the background job is still alive, and the last few log lines. + * + * npm run photos:progress + */ +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { COUNTRIES } from '../src/countries'; +import type { CachedPhoto } from '../src/photos.types'; + +const cwd = process.cwd(); +const POOL = join(cwd, 'photos.json'); +const LOG = join(cwd, 'photos-build.log'); +const PID = join(cwd, '.photos-build.pid'); + +function readPool(): Record { + if (!existsSync(POOL)) return {}; + try { + return JSON.parse(readFileSync(POOL, 'utf8')) as Record; + } catch { + return {}; + } +} + +function isRunning(): boolean { + if (!existsSync(PID)) return false; + const pid = Number(readFileSync(PID, 'utf8').trim()); + try { + process.kill(pid, 0); // signal 0 = existence check, doesn't kill + return true; + } catch { + return false; + } +} + +const pool = readPool(); +const done = Object.keys(pool).length; +const total = COUNTRIES.length; +const photos = Object.values(pool).flat(); +const tagged = photos.filter((p) => p.tags.length > 0).length; +const geotagged = photos.filter((p) => p.locationName).length; +const pct = total > 0 ? Math.round((done / total) * 100) : 0; +const remaining = total - done; +const etaHrs = ((remaining * 20) / 60).toFixed(1); // ~20 min/country + +console.log(`\n Photo pool build — ${isRunning() ? '🟢 running' : '⚪️ not running'}`); +console.log(` ${'─'.repeat(46)}`); +console.log(` Countries : ${String(done)} / ${String(total)} (${String(pct)}%)`); +console.log( + ` Photos : ${String(photos.length)} (${String(tagged)} tagged, ${String(geotagged)} geotagged)`, +); +if (remaining > 0 && isRunning()) + console.log(` ETA : ~${etaHrs} h for the remaining ${String(remaining)}`); +if (!existsSync(POOL)) + console.log(` (photos.json not written yet — first country still enriching)`); + +if (existsSync(LOG)) { + const lines = readFileSync(LOG, 'utf8') + .split('\n') + .filter((l) => /kept|Rate limit|Wrote|failed/.test(l)) + .slice(-5); + if (lines.length > 0) { + console.log(`\n Recent:`); + for (const l of lines) console.log(` ${l}`); + } +} +console.log(''); diff --git a/backend/scripts/sync-photos-s3.ts b/backend/scripts/sync-photos-s3.ts new file mode 100644 index 0000000..2b13117 --- /dev/null +++ b/backend/scripts/sync-photos-s3.ts @@ -0,0 +1,136 @@ +/** + * @fileoverview Publishes the photo pool to S3 — Step B. + * + * Reads the generated `photos.json`, downloads each photo from Unsplash's image CDN + * (a plain file fetch — NOT the rate-limited API), then uploads BOTH the image + * binaries (`photos/.jpg`) AND the metadata (`photos.json`) to the shared photos + * bucket via `aws s3`. Fast and bandwidth-bound (~15–30 min), not the ~9 h Step A takes. + * + * The Lambda loads `photos.json` from this bucket at runtime (`pool.ts`), so the + * metadata is never bundled into the code — regenerate + re-sync, no code deploy. + * + * Downloads are **resumable**: files already in the local cache are skipped, so an + * interrupted run just re-runs. Uploading uses the AWS CLI (already required for + * deploys) so the Lambda bundle gains no new SDK dependency. + * + * PHOTO_S3_BUCKET=bba-photos npm run sync:photos # download + upload (images + json) + * npm run sync:photos # download only; prints the upload cmds + * + * Runtime ToS: we do NOT trigger Unsplash download pings here — that happens at + * runtime (`trackPhotoUse`) when a user actually likes a photo. + * + * NB: this script intentionally does NOT load `.env` — the `aws` CLI resolves its own + * credentials (profile / SSO / real env vars), and `backend/.env` holds dummy + * DynamoDB-Local creds that would break a real S3 upload. Pass `PHOTO_S3_BUCKET` inline. + */ +import { execFileSync } from 'node:child_process'; +import { createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs'; +import { Readable } from 'node:stream'; +import { pipeline } from 'node:stream/promises'; +import { join } from 'node:path'; +import type { CachedPhoto } from '../src/photos.types'; + +const POOL_PATH = join(import.meta.dirname, '..', 'photos.json'); +const CACHE_DIR = join(import.meta.dirname, '..', 'photos-cache'); +const BUCKET = process.env.PHOTO_S3_BUCKET; + +/** Load the generated metadata; {} if Step A has not run. */ +function loadPool(): Record { + try { + return JSON.parse(readFileSync(POOL_PATH, 'utf8')) as Record; + } catch { + return {}; + } +} +/** Concurrent downloads — the CDN is happy with a modest fan-out. */ +const CONCURRENCY = Number(process.env.PHOTO_SYNC_CONCURRENCY ?? 12); + +/** Download one photo to the cache, skipping if already present (resumable). */ +async function download(photo: CachedPhoto): Promise<'downloaded' | 'skipped' | 'failed'> { + const dest = join(CACHE_DIR, `${photo.id}.jpg`); + if (existsSync(dest)) return 'skipped'; + try { + const res = await fetch(photo.unsplashImageUrl); + if (!res.ok || !res.body) throw new Error(`HTTP ${String(res.status)}`); + await pipeline( + Readable.fromWeb(res.body as Parameters[0]), + createWriteStream(dest), + ); + return 'downloaded'; + } catch (err) { + console.error(`${photo.id}: download failed — ${(err as Error).message}`); + return 'failed'; + } +} + +/** Run tasks with a bounded worker pool. */ +async function pool( + items: T[], + limit: number, + worker: (item: T) => Promise, +): Promise { + let idx = 0; + const runners = Array.from({ length: Math.min(limit, items.length) }, async () => { + while (idx < items.length) { + const item = items[idx++]; + if (item !== undefined) await worker(item); + } + }); + await Promise.all(runners); +} + +async function main(): Promise { + const photos = Object.values(loadPool()).flat(); + if (photos.length === 0) { + console.error('photos.json is empty/missing — run `npm run build:photos` (Step A) first.'); + process.exit(1); + } + + mkdirSync(CACHE_DIR, { recursive: true }); + const counts = { downloaded: 0, skipped: 0, failed: 0 }; + await pool(photos, CONCURRENCY, async (photo) => { + counts[await download(photo)]++; + }); + const onDisk = readdirSync(CACHE_DIR).filter((f) => f.endsWith('.jpg')).length; + console.log( + `Downloaded ${String(counts.downloaded)}, skipped ${String(counts.skipped)}, ` + + `failed ${String(counts.failed)} — ${String(onDisk)} files in ${CACHE_DIR}`, + ); + + const bucket = BUCKET ?? ''; + // Images: immutable, id-addressed → cache hard. Metadata: mutable → no long cache. + const imagesArgs = [ + 's3', + 'sync', + CACHE_DIR, + `s3://${bucket}/photos/`, + '--content-type', + 'image/jpeg', + '--cache-control', + 'public,max-age=31536000,immutable', + ]; + const jsonArgs = [ + 's3', + 'cp', + POOL_PATH, + `s3://${bucket}/photos.json`, + '--content-type', + 'application/json', + '--cache-control', + 'no-cache', + ]; + if (!BUCKET) { + console.log( + `\nTo upload, set PHOTO_S3_BUCKET and re-run, or run:\n` + + ` aws ${imagesArgs.join(' ')}\n aws ${jsonArgs.join(' ')}`, + ); + return; + } + console.log(`\nUploading images to s3://${BUCKET}/photos/ …`); + execFileSync('aws', imagesArgs, { stdio: 'inherit' }); + console.log(`Uploading metadata to s3://${BUCKET}/photos.json …`); + execFileSync('aws', jsonArgs, { stdio: 'inherit' }); + console.log('Done.'); +} + +void main(); diff --git a/backend/src/config.ts b/backend/src/config.ts index 089a718..1d44a74 100644 --- a/backend/src/config.ts +++ b/backend/src/config.ts @@ -19,6 +19,12 @@ export interface Config { cognitoClientId?: string; /** Unsplash access key; when absent, images.ts falls back to placeholders. */ unsplashAccessKey?: string; + /** Shared S3 bucket holding the Travel photo pool (metadata JSON + image binaries). */ + photosBucket: string; + /** Key of the metadata JSON within `photosBucket`. */ + photosKey: string; + /** Owner address that receives research-download notifications (empty disables them). */ + ownerEmail: string; /** Local dev HTTP port. */ port: number; } @@ -39,6 +45,9 @@ export function loadConfig(): Config { cognitoUserPoolId: process.env.COGNITO_USER_POOL_ID, cognitoClientId: process.env.COGNITO_CLIENT_ID, unsplashAccessKey: process.env.UNSPLASH_ACCESS_KEY, + photosBucket: process.env.PHOTOS_BUCKET ?? 'bba-photos', + photosKey: process.env.PHOTOS_KEY ?? 'photos.json', + ownerEmail: process.env.OWNER_EMAIL ?? '', port: Number(process.env.PORT ?? 4000), }; } diff --git a/backend/src/countries.ts b/backend/src/countries.ts index fdd23dd..5843699 100644 --- a/backend/src/countries.ts +++ b/backend/src/countries.ts @@ -2,10 +2,11 @@ * @fileoverview The country catalog — static server-side config. * * Each country has a stable `code` (ISO 3166-1 alpha-2), a display `name`, and a - * neutral Unsplash `searchTerm`. Search terms are **templated and landmark-free** - * (`" landscape nature scenery"`) on purpose: the demo infers preference from - * abstract scenery, not from recognizable landmarks (see TravelPage/plan §1b). Weak - * results for obscure entries are dropped by the photo-pool quality guardrail. + * neutral Unsplash `searchTerm`. Search terms are **templated, short, and landmark-free** + * (`" landscape"`) on purpose: the demo infers preference from abstract scenery, + * not from recognizable landmarks (see TravelPage/plan §1b), and a short query keeps + * recall high on Unsplash's keyword-restrictive search. Weak results for obscure entries + * are dropped by the photo-pool quality guardrail. * * This is just data — per-user preferences key off `code`, so reordering or extending * never breaks stored data. Covers UN members + observers + common territories the @@ -21,8 +22,12 @@ export interface Country { searchTerm: string; } -/** Neutral, landmark-free search term for a place. */ -const term = (name: string): string => `${name} landscape nature scenery`; +/** Neutral, landmark-free search term for a place. Deliberately SHORT: Unsplash search + * is keyword-restrictive, so a long phrase like " landscape nature scenery" + * returns near-zero for niche countries (e.g. "Benin landscape nature scenery" → 0, + * while "Benin landscape" → 8 and "Benin" → 37). One scenery word keeps recall high + * without pulling in the people/art/food that a bare name would. */ +const term = (name: string): string => `${name} landscape`; // [code, name] tuples — grouped by region. searchTerm is templated from the name. const CATALOG: readonly [string, string][] = [ diff --git a/backend/src/images.ts b/backend/src/images.ts index 5adba28..44c0e36 100644 --- a/backend/src/images.ts +++ b/backend/src/images.ts @@ -9,7 +9,7 @@ import { COUNTRIES, type Country } from './countries'; import { NEUTRAL_PREFERENCE, type PreferenceMap } from './algorithm'; import { config } from './config'; -import { PHOTO_POOL } from './photos.data'; +import { ensurePool } from './pool'; import type { CachedPhoto } from './photos.types'; const COUNTRY_BY_CODE: Record = Object.fromEntries( @@ -142,7 +142,9 @@ function cachedToTravelImage(p: CachedPhoto): TravelImage | null { if (!country) return null; return { country, - imageUrl: p.imageUrl, + // Deployed, `/photos/.jpg` resolves same-origin via CloudFront. Local dev + // has no S3, so fall back to the Unsplash CDN url the sync source retains. + imageUrl: config.isLocal ? p.unsplashImageUrl : p.imageUrl, attribution: p.attribution, photographerName: p.photographerName, photographerUrl: p.photographerUrl, @@ -154,15 +156,16 @@ function cachedToTravelImage(p: CachedPhoto): TravelImage | null { } /** - * A neutral candidate pool for the driver to select from. Prefers the precomputed - * `PHOTO_POOL` (zero runtime Unsplash calls); falls back to a live neutral fetch + * A neutral candidate pool for the driver to select from. Prefers the cached pool + * loaded from S3 (zero runtime Unsplash calls); falls back to a live neutral fetch * until the pool is generated. */ export async function getImagePool( count: number, rng: () => number = Math.random, ): Promise { - const flat = Object.values(PHOTO_POOL) + const poolMap = await ensurePool(); + const flat = Object.values(poolMap) .flat() .map(cachedToTravelImage) .filter((x): x is TravelImage => x !== null); diff --git a/backend/src/ownerNotify.ts b/backend/src/ownerNotify.ts new file mode 100644 index 0000000..b77229b --- /dev/null +++ b/backend/src/ownerNotify.ts @@ -0,0 +1,49 @@ +/** + * @fileoverview Owner notifications via SES — currently just "someone downloaded the + * research paper." Uses the same verified sender as the Cognito email trigger. + * + * Best-effort: a send failure (SES sandbox, throttling, local dev with dummy creds) + * is logged and swallowed so it never breaks the caller's request. Sending to a fixed + * owner address means SES **sandbox** mode is fine as long as that address is a + * verified identity — no production access required. + */ +import { SESClient, SendEmailCommand } from '@aws-sdk/client-ses'; +import { config } from './config'; + +const ses = new SESClient({}); +const FROM = 'Building Better Algorithms '; + +/** + * Email the owner that a signed-in user downloaded the capstone research paper. + * Returns true ONLY if the notification was actually sent — the frontend gates the + * download on this, so a missing downloader email or a failed send blocks the download. + */ +export async function notifyResearchDownload(downloaderEmail: string): Promise { + const to = config.ownerEmail; + if (!to) return false; // notifications disabled (no OWNER_EMAIL configured) + if (!downloaderEmail) return false; // can't identify the user → block the download + + const when = new Date().toISOString(); + + try { + await ses.send( + new SendEmailCommand({ + Source: FROM, + Destination: { ToAddresses: [to] }, + Message: { + Subject: { Data: 'Someone downloaded your research paper', Charset: 'UTF-8' }, + Body: { + Text: { + Data: `${downloaderEmail} downloaded the Building Better Algorithms research paper.\n\nWhen: ${when}`, + Charset: 'UTF-8', + }, + }, + }, + }), + ); + return true; + } catch (err) { + console.error(`research-download notification failed: ${(err as Error).message}`); + return false; + } +} diff --git a/backend/src/photos.curate.ts b/backend/src/photos.curate.ts new file mode 100644 index 0000000..0c0ad16 --- /dev/null +++ b/backend/src/photos.curate.ts @@ -0,0 +1,168 @@ +/** + * @fileoverview Pure curation of raw Unsplash candidates into the cached pool. + * + * The generator fetches more candidates than it keeps (two queries per country — + * landscape + cityscape) and hands them here to be filtered and trimmed. Kept pure + * and deterministic so the guardrail is unit-testable without the network: + * + * 1. **Dedupe** by Unsplash id (also drops a photo already kept for another + * country — the id is globally unique). + * 2. **Quality gate** — drop anything below `minLikes`, or whose tags/description + * hit the denylist (food, interiors, people, text… the "photo of a table" + * problem), keeping the demo to cities and landscapes. + * 3. **Balance & cap** — interleave landscape/city so the per-country set is a mix, + * then cap at `perCountry`. + */ +import type { CachedPhoto, PhotoKind } from './photos.types'; + +/** Tags/description substrings that disqualify a photo (lowercased match). */ +export const DEFAULT_DENY_TERMS = [ + // People (whole-word matching means "man" no longer hits "Oman"/"Germany") + 'person', + 'people', + 'human', + 'man', + 'woman', + 'child', + 'kid', + 'boy', + 'girl', + 'crowd', + 'portrait', + 'face', + 'selfie', + 'model', + 'hair', + 'hand', + 'skin', + 'wedding', + 'bride', + 'groom', + 'fashion', + // Food & drink + 'food', + 'meal', + 'table', + 'restaurant', + 'drink', + 'coffee', + 'plate', + 'breakfast', + 'lunch', + 'dinner', + 'dish', + 'cuisine', + 'dessert', + 'cake', + 'fruit', + 'vegetable', + 'wine', + 'beer', + 'cocktail', + 'cafe', + 'kitchen', + 'cooking', + 'bakery', + 'pizza', + 'burger', + 'salad', + 'soup', + 'bread', + 'snack', + // Indoor / domestic + 'indoor', + 'interior', + 'room', + 'furniture', + 'bedroom', + 'bathroom', + 'desk', + 'sofa', + 'couch', + 'bed', + 'chair', + 'lamp', + // Pets / close-up animals + 'dog', + 'cat', + 'pet', + 'puppy', + 'kitten', + // Objects / products / graphics + 'text', + 'laptop', + 'computer', + 'smartphone', + 'phone', + 'product', + 'mockup', + 'logo', + 'poster', + 'book', + 'shoe', + 'clothing', + 'jewelry', + 'watch', + 'bottle', + 'toy', +] as const; + +export interface CurateOptions { + /** Max photos to keep per country. */ + perCountry: number; + /** Minimum Unsplash likes to clear the quality gate. */ + minLikes: number; + /** Lowercased substrings that disqualify a photo via its tags or description. */ + denyTerms?: readonly string[]; + /** Ids already committed elsewhere — excluded so the whole pool stays unique. */ + seenIds?: Set; +} + +/** True when a photo trips the denylist on any tag or its description. Matches whole + * WORDS, not substrings, so "table" no longer flags "vegetable", "bar" "harbor", or + * "text" "texture" — which lets the list grow without collateral damage. */ +export function isDenied(photo: CachedPhoto, denyTerms: readonly string[]): boolean { + const deny = new Set(denyTerms.map((t) => t.toLowerCase())); + const words = [...photo.tags, photo.description ?? ''] + .join(' ') + .toLowerCase() + .split(/[^a-z]+/) + .filter(Boolean); + return words.some((w) => deny.has(w)); +} + +/** Interleave two ordered lists (a, b, a, b, …), appending any remainder. */ +function interleave(a: T[], b: T[]): T[] { + const out: T[] = []; + const max = Math.max(a.length, b.length); + for (let i = 0; i < max; i++) { + if (i < a.length) out.push(a[i] as T); + if (i < b.length) out.push(b[i] as T); + } + return out; +} + +/** + * Filter and trim candidates for a single country. Mutates `seenIds` (adds the ids + * it keeps) so a caller looping over countries never repeats a photo across the pool. + */ +export function curatePhotos(candidates: CachedPhoto[], opts: CurateOptions): CachedPhoto[] { + const { perCountry, minLikes } = opts; + const denyTerms = opts.denyTerms ?? DEFAULT_DENY_TERMS; + const seenIds = opts.seenIds ?? new Set(); + + const eligible: Record = { landscape: [], city: [] }; + const localSeen = new Set(); + for (const photo of candidates) { + if (seenIds.has(photo.id) || localSeen.has(photo.id)) continue; + if (photo.likes < minLikes) continue; + if (isDenied(photo, denyTerms)) continue; + localSeen.add(photo.id); // dedupe within this batch before the cap + eligible[photo.kind].push(photo); + } + + // Only the photos that survive the cap are committed to the global seen set. + const kept = interleave(eligible.landscape, eligible.city).slice(0, perCountry); + for (const photo of kept) seenIds.add(photo.id); + return kept; +} diff --git a/backend/src/photos.data.ts b/backend/src/photos.data.ts deleted file mode 100644 index dfe702a..0000000 --- a/backend/src/photos.data.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * @fileoverview Precomputed per-country photo pool — the cached, metadata-enriched - * photos that feed both country signatures (`signatures.ts`) and the Travel feed - * (`images.ts`), so runtime Unsplash calls drop to ~zero (no rate-limit pressure). - * - * **Generated**, not hand-edited: run `npm run build:photos` (needs an Unsplash key) - * to fetch a batch per country and overwrite this file. Empty by default — until then - * the app falls back to live Unsplash fetches and seed signatures. - */ -import type { CachedPhoto } from './photos.types'; - -/** countryCode → its cached photos. Empty until generated. */ -export const PHOTO_POOL: Record = {}; diff --git a/backend/src/photos.types.ts b/backend/src/photos.types.ts index 7661dcb..be297bd 100644 --- a/backend/src/photos.types.ts +++ b/backend/src/photos.types.ts @@ -1,13 +1,49 @@ /** - * @fileoverview Type for the cached photo pool — kept separate from the generated - * `photos.data.ts` so regenerating the data never clobbers the type. + * @fileoverview Type for the cached photo pool. The data itself is not committed — it + * is generated as `photos.json` and loaded at runtime from S3 (see `pool.ts`). + * + * Honesty note (decision #2): every field here is either **measured** (returned by + * Unsplash) or **assigned by us** (`id`, `kind`, `imageUrl`). `tags`, `location*`, and + * `exif` come from the per-photo **enrichment** call (`GET /photos/:id`); the derived + * aesthetic axes the recommender reasons over (terrain / light / season) are computed + * in `features.ts` from `tags` and are never stored here as if measured. + * + * Country provenance: `country` is the **search association** — the catalog country + * whose query returned the photo. Enrichment now also captures `locationName`/`lat`/ + * `lng` **when the photographer geotagged the photo** (most don't); that is stored as + * real signal but `country` is left as the catalog key. `unsplashUrl` preserves full + * traceability to the source photo. */ -/** One cached photo: a hotlinked Unsplash URL plus the metadata we reason over. */ +/** Which search surfaced the photo — nature/landscape vs urban/cityscape. */ +export type PhotoKind = 'landscape' | 'city'; + +/** Camera EXIF from the enrichment call, when the photographer included it. */ +export interface PhotoExif { + make?: string; + model?: string; + focalLength?: string; + aperture?: string; + exposureTime?: string; + iso?: number; +} + +/** One cached photo: metadata plus a same-origin `imageUrl` we reason over. */ export interface CachedPhoto { - /** ISO 3166-1 alpha-2 country code (the catalog key). */ + /** Unsplash photo id — stable, globally unique; dedup key and S3 filename stem. */ + id: string; + /** ISO 3166-1 alpha-2 country code — the catalog key; a search association, not a verified geotag. */ country: string; + /** Which query surfaced it — powers the cities-vs-landscapes mix. */ + kind: PhotoKind; + /** + * Where the running app loads the image from. Written by the generator as + * `${PHOTO_CDN_BASE}/${id}.jpg` (defaults to `/photos/${id}.jpg` — same-origin S3 + * via CloudFront). Falls back to `unsplashImageUrl` when no CDN base is set. + */ imageUrl: string; + /** Original Unsplash CDN url — provenance + source for the S3 sync + local-dev fallback. */ + unsplashImageUrl: string; /** Display credit, e.g. "Photo by Annie Spratt on Unsplash". */ attribution: string; /** Photographer's full name (for the linked credit). */ @@ -16,8 +52,26 @@ export interface CachedPhoto { photographerUrl: string; /** The photo's Unsplash page URL (link target for "Unsplash"). */ unsplashUrl: string; + /** Unsplash keyword tags — the abstract signal the recommender reasons over. */ tags: string[]; + /** Dominant colour as a hex string. */ color?: string; - /** Unsplash download-tracking endpoint — pinged when the photo is used (ToS). */ + /** Low-res placeholder hash (BlurHash), for a smooth load-in. */ + blurHash?: string; + /** Community like count — used as a curation quality gate. */ + likes: number; + /** Native pixel dimensions. */ + width: number; + height: number; + /** Photographer-supplied description / alt text, when present. */ + description?: string; + /** Unsplash download-tracking endpoint — pinged at runtime when a photo is liked (ToS). */ downloadLocation?: string; + // ── From enrichment (GET /photos/:id) ────────────────────────────────────── + /** Human place string ("Kyoto, Japan"), when the photographer geotagged it. */ + locationName?: string; + lat?: number; + lng?: number; + /** Measured camera EXIF, when included. */ + exif?: PhotoExif; } diff --git a/backend/src/pool.ts b/backend/src/pool.ts new file mode 100644 index 0000000..07c1e3d --- /dev/null +++ b/backend/src/pool.ts @@ -0,0 +1,76 @@ +/** + * @fileoverview Runtime loader for the Travel photo pool metadata. + * + * The pool is NOT bundled into the Lambda — it lives as `photos.json` in the shared + * `bba-photos` S3 bucket (alongside the image binaries), so the photo set can be + * regenerated and re-synced without a code deploy. This module fetches it **once per + * cold start** and caches it in module scope (warm invocations reuse it); local dev + * reads a `backend/photos.json` file instead of hitting S3. + * + * Loading also primes the country signatures (`setCountrySignatures`) so the + * synchronous `getCountrySignatures()` used in resolvers returns photo-derived + * signatures. `ensurePool()` is awaited in the GraphQL context (yoga.ts) before any + * resolver runs. On any failure it degrades to an empty pool + the catalog seed — + * the app still works, just without cached photos. + */ +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3'; +import { config } from './config'; +import { setCountrySignatures, signaturesFromPool } from './signatures'; +import type { CachedPhoto } from './photos.types'; + +type Pool = Record; + +/** Dev-only path: `backend/photos.json` (generated by `npm run build:photos`; cwd is backend/). */ +const LOCAL_PATH = join(process.cwd(), 'photos.json'); + +let cache: Pool | null = null; +let inflight: Promise | null = null; + +function fromLocal(): Pool { + if (!existsSync(LOCAL_PATH)) return {}; + return JSON.parse(readFileSync(LOCAL_PATH, 'utf8')) as Pool; +} + +async function fromS3(): Promise { + const s3 = new S3Client({ region: config.awsRegion }); + const res = await s3.send( + new GetObjectCommand({ Bucket: config.photosBucket, Key: config.photosKey }), + ); + const body = await res.Body?.transformToString(); + return body ? (JSON.parse(body) as Pool) : {}; +} + +async function load(): Promise { + // Tests stay hermetic — never pick up a generated photos.json on disk. + if (process.env.NODE_ENV === 'test') return {}; + try { + const pool = config.isLocal ? fromLocal() : await fromS3(); + // Prime photo-derived signatures; leave the catalog seed if the pool is empty. + if (Object.keys(pool).length > 0) setCountrySignatures(signaturesFromPool(pool)); + return pool; + } catch (err) { + console.error(`photo pool load failed — degrading to seed: ${(err as Error).message}`); + return {}; + } +} + +/** Load the pool once (memoized) and prime signatures. Safe to call on every request. */ +export async function ensurePool(): Promise { + if (cache) return cache; + inflight ??= load(); + cache = await inflight; + return cache; +} + +/** The already-loaded pool, or `{}` if `ensurePool` has not resolved yet. */ +export function loadedPool(): Pool { + return cache ?? {}; +} + +/** Test hook — reset the module cache between cases. */ +export function resetPoolCache(): void { + cache = null; + inflight = null; +} diff --git a/backend/src/schema.ts b/backend/src/schema.ts index 6042427..09ef430 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -16,6 +16,7 @@ import { COUNTRIES, isValidCountryCode, type Country } from './countries'; import { NEUTRAL_PREFERENCE } from './algorithm'; import type { TravelImage } from './images'; import { getImagePool, triggerDownload } from './images'; +import { notifyResearchDownload } from './ownerNotify'; import { extractFeatures } from './features'; import { scoreCountries } from './scoring'; import { selectNext, explorationFraction } from './recommender'; @@ -193,11 +194,6 @@ const InteractionActionEnum = builder.enumType('InteractionAction', { values: ['like', 'dislike', 'skip'] as const, }); -const DriverEnum = builder.enumType('Driver', { - description: 'Which algorithm drives the feed: A (engagement) or B (user-first).', - values: ['A', 'B'] as const, -}); - const InteractionInputRef = builder.inputType('InteractionInput', { description: "One interaction with an image, echoed back with the image's tags/colour.", fields: (t) => ({ @@ -288,20 +284,18 @@ builder.queryType({ type: ['TravelImage'], nullable: false, description: - 'A batch of travel photos chosen by the given driver (A narrows toward the ' + - "user's taste; B stays diverse). Defaults to B.", + "A batch of travel photos chosen user-first: diverse, weighted by the user's " + + 'learned per-country preferences (Algorithm B).', args: { count: t.arg.int({ defaultValue: 8 }), - driver: t.arg({ type: DriverEnum, defaultValue: 'B' }), }, resolve: async (_root, args, ctx) => { const user = requireUser(ctx); const count = args.count ?? 8; - const driver = args.driver ?? 'B'; const dossier = await db.getDossier(user.id); // A neutral candidate pool larger than the batch (cached when available), - // then let the driver pick. + // then the user-first algorithm picks. const pool = await getImagePool(Math.min(count * 3, 30)); const candidates = pool.map((img, i) => ({ id: String(i), @@ -309,21 +303,12 @@ builder.queryType({ features: extractFeatures({ tags: img.tags, color: img.color }), })); - const picks = - driver === 'A' - ? selectNext({ - driver: 'A', - pool: candidates, - count, - taste: dossier?.a.taste ?? [], - exploration: explorationFraction(dossier?.a.confidence ?? 0), - }) - : selectNext({ - driver: 'B', - pool: candidates, - count, - countryScores: scoreCountries(dossier?.b.taste ?? [], getCountrySignatures()), - }); + const picks = selectNext({ + driver: 'B', + pool: candidates, + count, + countryScores: scoreCountries(dossier?.b.taste ?? [], getCountrySignatures()), + }); return picks.flatMap((p) => { const img = pool[Number(p.id)]; @@ -420,6 +405,19 @@ builder.mutationType({ }, }), + notifyResearchDownload: t.field({ + type: 'Boolean', + nullable: false, + description: + 'Email the site owner that the authenticated user is downloading the research ' + + 'paper. Returns true ONLY if the email was sent — the client gates the download ' + + 'on this, so an unidentified user or a failed send blocks the download.', + resolve: async (_root, _args, ctx) => { + const user = requireUser(ctx); + return notifyResearchDownload(user.email); + }, + }), + resetDossier: t.field({ type: 'Boolean', nullable: false, diff --git a/backend/src/signatures.ts b/backend/src/signatures.ts index cbb68e0..7392c4d 100644 --- a/backend/src/signatures.ts +++ b/backend/src/signatures.ts @@ -11,7 +11,6 @@ import { COUNTRIES } from './countries'; import { countrySignature } from './scoring'; import type { FeatureVector, ImageFeatureInput } from './features'; -import { PHOTO_POOL } from './photos.data'; let cache: Record | null = null; @@ -36,15 +35,16 @@ export function signaturesFromPool( } /** - * The current country→signature map. Prefers the precomputed photo pool (real, - * photo-derived signatures); falls back to the catalog seed until the pool exists. + * The current country→signature map. Photo-derived signatures are injected by + * `pool.ts` (`setCountrySignatures`) once the pool loads; until then — and when the + * pool is empty — this falls back to the catalog seed. */ export function getCountrySignatures(): Record { - cache ??= Object.keys(PHOTO_POOL).length > 0 ? signaturesFromPool(PHOTO_POOL) : seed(); + cache ??= seed(); return cache; } -/** Replace the signature map — used by step 3 to inject cached-pool signatures (and by tests). */ +/** Replace the signature map — pool.ts injects photo-derived signatures (and tests use it). */ export function setCountrySignatures(sigs: Record): void { cache = sigs; } diff --git a/backend/src/yoga.ts b/backend/src/yoga.ts index d004072..b42ee05 100644 --- a/backend/src/yoga.ts +++ b/backend/src/yoga.ts @@ -7,6 +7,7 @@ import { createYoga } from 'graphql-yoga'; import { schema, type GraphQLContext } from './schema'; import { authenticate } from './auth'; +import { ensurePool } from './pool'; import { config } from './config'; export const yoga = createYoga({ @@ -15,7 +16,10 @@ export const yoga = createYoga({ // Introspection UI is enabled only outside production. graphiql: config.isLocal, landingPage: false, - context: async ({ request }): Promise => ({ - user: await authenticate(request.headers), - }), + // Load the photo pool once (memoized) before resolvers run — this also primes the + // country signatures that the synchronous getCountrySignatures() reads. + context: async ({ request }): Promise => { + const [user] = await Promise.all([authenticate(request.headers), ensurePool()]); + return { user }; + }, }); diff --git a/backend/tests/photos.curate.test.ts b/backend/tests/photos.curate.test.ts new file mode 100644 index 0000000..9e15a6f --- /dev/null +++ b/backend/tests/photos.curate.test.ts @@ -0,0 +1,109 @@ +import { describe, it, expect } from '@jest/globals'; +import { curatePhotos, isDenied, DEFAULT_DENY_TERMS } from '../src/photos.curate'; +import type { CachedPhoto } from '../src/photos.types'; + +/** Minimal CachedPhoto factory for tests. */ +function photo(overrides: Partial & { id: string }): CachedPhoto { + return { + country: 'JP', + kind: 'landscape', + imageUrl: `/photos/${overrides.id}.jpg`, + unsplashImageUrl: `https://images.unsplash.com/${overrides.id}`, + attribution: 'Photo by Test on Unsplash', + photographerName: 'Test', + photographerUrl: 'https://unsplash.com/@test', + unsplashUrl: `https://unsplash.com/photos/${overrides.id}`, + tags: ['mountain', 'nature'], + likes: 100, + width: 4000, + height: 3000, + ...overrides, + }; +} + +describe('isDenied', () => { + it('flags a photo whose tag hits the denylist', () => { + expect(isDenied(photo({ id: 'a', tags: ['food', 'sunset'] }), DEFAULT_DENY_TERMS)).toBe(true); + }); + + it('flags a photo whose description hits the denylist', () => { + expect( + isDenied( + photo({ id: 'b', tags: ['city'], description: 'A cozy interior' }), + DEFAULT_DENY_TERMS, + ), + ).toBe(true); + }); + + it('passes a clean cities/landscapes photo', () => { + expect(isDenied(photo({ id: 'c', tags: ['mountain', 'lake'] }), DEFAULT_DENY_TERMS)).toBe( + false, + ); + }); +}); + +describe('curatePhotos', () => { + it('drops photos below the like threshold', () => { + const kept = curatePhotos([photo({ id: 'a', likes: 5 }), photo({ id: 'b', likes: 200 })], { + perCountry: 10, + minLikes: 50, + }); + expect(kept.map((p) => p.id)).toEqual(['b']); + }); + + it('drops denylisted photos', () => { + const kept = curatePhotos( + [photo({ id: 'a', tags: ['table', 'food'] }), photo({ id: 'b', tags: ['coast'] })], + { perCountry: 10, minLikes: 0 }, + ); + expect(kept.map((p) => p.id)).toEqual(['b']); + }); + + it('caps to perCountry', () => { + const many = Array.from({ length: 40 }, (_, i) => photo({ id: `p${String(i)}` })); + expect(curatePhotos(many, { perCountry: 15, minLikes: 0 })).toHaveLength(15); + }); + + it('interleaves landscape and city so the mix is balanced', () => { + const candidates = [ + photo({ id: 'l1', kind: 'landscape' }), + photo({ id: 'l2', kind: 'landscape' }), + photo({ id: 'l3', kind: 'landscape' }), + photo({ id: 'c1', kind: 'city' }), + photo({ id: 'c2', kind: 'city' }), + ]; + const kept = curatePhotos(candidates, { perCountry: 4, minLikes: 0 }); + // landscape/city alternate, so the top 4 include both kinds evenly. + expect(kept.map((p) => p.id)).toEqual(['l1', 'c1', 'l2', 'c2']); + }); + + it('dedupes within a batch by id', () => { + const kept = curatePhotos( + [photo({ id: 'dup' }), photo({ id: 'dup' }), photo({ id: 'other' })], + { perCountry: 10, minLikes: 0 }, + ); + expect(kept.map((p) => p.id).sort()).toEqual(['dup', 'other']); + }); + + it('excludes ids already seen across the whole pool and records kept ids', () => { + const seenIds = new Set(['already']); + const kept = curatePhotos([photo({ id: 'already' }), photo({ id: 'fresh' })], { + perCountry: 10, + minLikes: 0, + seenIds, + }); + expect(kept.map((p) => p.id)).toEqual(['fresh']); + expect(seenIds.has('fresh')).toBe(true); + }); + + it('does not mark capped-out photos as seen', () => { + const seenIds = new Set(); + curatePhotos([photo({ id: 'keep' }), photo({ id: 'drop' })], { + perCountry: 1, + minLikes: 0, + seenIds, + }); + expect(seenIds.has('keep')).toBe(true); + expect(seenIds.has('drop')).toBe(false); // still available for another country + }); +}); diff --git a/backend/tests/schema.test.ts b/backend/tests/schema.test.ts index 5231262..b1fe3e5 100644 --- a/backend/tests/schema.test.ts +++ b/backend/tests/schema.test.ts @@ -24,9 +24,10 @@ describe('GraphQL schema', () => { it('exposes the two-algorithm surface', () => { expect(sdl).toContain('type Dossier'); - expect(sdl).toContain('enum Driver'); expect(sdl).toContain('input InteractionInput'); - expect(sdl).toMatch(/travelImages\(count: Int = 8, driver: Driver = B\)/); + // The feed is user-first only — no driver arg / Driver enum on the public API. + expect(sdl).not.toContain('enum Driver'); + expect(sdl).toMatch(/travelImages\(count: Int = 8\)/); expect(sdl).toMatch(/submitFeedback\(interactions: \[InteractionInput!\]!\)/); expect(sdl).toMatch(/dossier: Dossier!/); expect(sdl).toMatch(/resetPreferences:/); diff --git a/frontend/README.md b/frontend/README.md index b15e080..78e4832 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -37,16 +37,19 @@ src/ hovered logo), AMA academic references (generated references.ts) + disclosure TravelPage/ full-viewport snap-scroll photo feed (4 cols × 2 rows per section). Each section fills the screen and snaps into place; scrolling advances one section - at a time. Row parallax: entering/exiting sections have rows at staggered - offsets that converge to zero when snapped. Click the RIGHT half of a photo - to like (♥, pink tint); click the LEFT half to dislike (✕, greyscale). Arrow - keys (←/→/Enter) also work. Hovering for 1 s marks a photo "engaged" and - boosts the dwell signal sent to the algorithm. Per-photo ℹ button (top-right, - appears on hover/reaction) opens an info panel with photographer name, country, - tags, and a link to Unsplash. Sections auto-submit when scrolled off the top - (no submit button); dossier stats refresh with a one-section lag. Fixed topbar - stays visible while scrolling (driver toggle + "See your data" dossier panel). - Unsplash-compliant: UTM attribution links + trackPhotoUse for liked photos. + at a time. Click the RIGHT half of a photo to like (♥, pink tint); click the + LEFT half to dislike (✕, greyscale). Arrow keys (←/→/Enter) also work. + Hovering for 1 s marks a photo "engaged" and boosts the dwell signal sent to + the algorithm. Per-photo ℹ button (top-right, appears on hover/reaction) opens + an info panel with photographer name, country, tags, and a link to Unsplash. + Sections auto-submit when scrolled off the top (no submit button). Fixed + "See your data" button (top-right) opens the "Same taps, two algorithms" + contrast: two ledgers from the same session's dossier — User-First (just the + explicit likes/dislikes it keeps) vs Engagement (impressions, dwell samples, + skips, inferred features/traits it would harvest), each with a data-points + tally and an "Nx the data" punchline. The feed is user-first only — no + display-swapping algorithm toggle. Unsplash-compliant: UTM attribution links + + trackPhotoUse for liked photos. DashboardPage/ react-simple-maps equirectangular world map (bundled world-atlas 50m TopoJSON, Antarctica filtered, full-viewport width) choropleth-shaded by preference score; hover readout is a cursor-following gooey "score chip" diff --git a/frontend/src/gql/gql.ts b/frontend/src/gql/gql.ts index 6492b4f..cdf717f 100644 --- a/frontend/src/gql/gql.ts +++ b/frontend/src/gql/gql.ts @@ -17,12 +17,14 @@ type Documents = { "\n mutation FindEmailByPhone($phone: String!) {\n findEmailByPhone(phone: $phone)\n }\n": typeof types.FindEmailByPhoneDocument, "\n query Countries {\n countries {\n code\n name\n }\n }\n": typeof types.CountriesDocument, "\n mutation DeleteAccount {\n deleteAccount\n }\n": typeof types.DeleteAccountDocument, + "\n mutation ResetDossier {\n resetDossier\n }\n": typeof types.ResetDossierDocument, + "\n mutation NotifyResearchDownload {\n notifyResearchDownload\n }\n": typeof types.NotifyResearchDownloadDocument, "\n query Preferences {\n me {\n id\n name\n preferences {\n value\n country {\n code\n name\n }\n }\n }\n }\n": typeof types.PreferencesDocument, "\n query LearnProgress {\n me {\n id\n learnProgress {\n sectionId\n viewedSlides\n }\n }\n }\n": typeof types.LearnProgressDocument, "\n mutation RecordSlideView($sectionId: ID!, $slideIndex: Int!) {\n recordSlideView(sectionId: $sectionId, slideIndex: $slideIndex) {\n sectionId\n viewedSlides\n }\n }\n": typeof types.RecordSlideViewDocument, "\n mutation MergeLearnProgress($progress: [LearnSectionProgressInput!]!) {\n mergeLearnProgress(progress: $progress) {\n sectionId\n viewedSlides\n }\n }\n": typeof types.MergeLearnProgressDocument, "\n mutation ResetLearnProgress {\n resetLearnProgress\n }\n": typeof types.ResetLearnProgressDocument, - "\n query TravelImages($count: Int!, $driver: Driver!) {\n travelImages(count: $count, driver: $driver) {\n imageUrl\n attribution\n photographerName\n photographerUrl\n unsplashUrl\n tags\n color\n downloadLocation\n country {\n code\n name\n }\n }\n }\n": typeof types.TravelImagesDocument, + "\n query TravelImages($count: Int!) {\n travelImages(count: $count) {\n imageUrl\n attribution\n photographerName\n photographerUrl\n unsplashUrl\n tags\n color\n downloadLocation\n country {\n code\n name\n }\n }\n }\n": typeof types.TravelImagesDocument, "\n mutation SubmitFeedback($interactions: [InteractionInput!]!) {\n submitFeedback(interactions: $interactions) {\n id\n }\n }\n": typeof types.SubmitFeedbackDocument, "\n mutation TrackPhotoUse($downloadLocation: String!) {\n trackPhotoUse(downloadLocation: $downloadLocation)\n }\n": typeof types.TrackPhotoUseDocument, "\n query Dossier {\n dossier {\n totalInteractions\n likes\n dislikes\n skips\n avgDwellMs\n confidence\n exploration\n disclaimer\n inferredTraits {\n trait\n confidence\n }\n topFeatures {\n key\n value\n }\n }\n }\n": typeof types.DossierDocument, @@ -31,12 +33,14 @@ const documents: Documents = { "\n mutation FindEmailByPhone($phone: String!) {\n findEmailByPhone(phone: $phone)\n }\n": types.FindEmailByPhoneDocument, "\n query Countries {\n countries {\n code\n name\n }\n }\n": types.CountriesDocument, "\n mutation DeleteAccount {\n deleteAccount\n }\n": types.DeleteAccountDocument, + "\n mutation ResetDossier {\n resetDossier\n }\n": types.ResetDossierDocument, + "\n mutation NotifyResearchDownload {\n notifyResearchDownload\n }\n": types.NotifyResearchDownloadDocument, "\n query Preferences {\n me {\n id\n name\n preferences {\n value\n country {\n code\n name\n }\n }\n }\n }\n": types.PreferencesDocument, "\n query LearnProgress {\n me {\n id\n learnProgress {\n sectionId\n viewedSlides\n }\n }\n }\n": types.LearnProgressDocument, "\n mutation RecordSlideView($sectionId: ID!, $slideIndex: Int!) {\n recordSlideView(sectionId: $sectionId, slideIndex: $slideIndex) {\n sectionId\n viewedSlides\n }\n }\n": types.RecordSlideViewDocument, "\n mutation MergeLearnProgress($progress: [LearnSectionProgressInput!]!) {\n mergeLearnProgress(progress: $progress) {\n sectionId\n viewedSlides\n }\n }\n": types.MergeLearnProgressDocument, "\n mutation ResetLearnProgress {\n resetLearnProgress\n }\n": types.ResetLearnProgressDocument, - "\n query TravelImages($count: Int!, $driver: Driver!) {\n travelImages(count: $count, driver: $driver) {\n imageUrl\n attribution\n photographerName\n photographerUrl\n unsplashUrl\n tags\n color\n downloadLocation\n country {\n code\n name\n }\n }\n }\n": types.TravelImagesDocument, + "\n query TravelImages($count: Int!) {\n travelImages(count: $count) {\n imageUrl\n attribution\n photographerName\n photographerUrl\n unsplashUrl\n tags\n color\n downloadLocation\n country {\n code\n name\n }\n }\n }\n": types.TravelImagesDocument, "\n mutation SubmitFeedback($interactions: [InteractionInput!]!) {\n submitFeedback(interactions: $interactions) {\n id\n }\n }\n": types.SubmitFeedbackDocument, "\n mutation TrackPhotoUse($downloadLocation: String!) {\n trackPhotoUse(downloadLocation: $downloadLocation)\n }\n": types.TrackPhotoUseDocument, "\n query Dossier {\n dossier {\n totalInteractions\n likes\n dislikes\n skips\n avgDwellMs\n confidence\n exploration\n disclaimer\n inferredTraits {\n trait\n confidence\n }\n topFeatures {\n key\n value\n }\n }\n }\n": types.DossierDocument, @@ -68,6 +72,14 @@ export function graphql(source: "\n query Countries {\n countries {\n c * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ export function graphql(source: "\n mutation DeleteAccount {\n deleteAccount\n }\n"): (typeof documents)["\n mutation DeleteAccount {\n deleteAccount\n }\n"]; +/** + * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. + */ +export function graphql(source: "\n mutation ResetDossier {\n resetDossier\n }\n"): (typeof documents)["\n mutation ResetDossier {\n resetDossier\n }\n"]; +/** + * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. + */ +export function graphql(source: "\n mutation NotifyResearchDownload {\n notifyResearchDownload\n }\n"): (typeof documents)["\n mutation NotifyResearchDownload {\n notifyResearchDownload\n }\n"]; /** * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ @@ -91,7 +103,7 @@ export function graphql(source: "\n mutation ResetLearnProgress {\n resetLea /** * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ -export function graphql(source: "\n query TravelImages($count: Int!, $driver: Driver!) {\n travelImages(count: $count, driver: $driver) {\n imageUrl\n attribution\n photographerName\n photographerUrl\n unsplashUrl\n tags\n color\n downloadLocation\n country {\n code\n name\n }\n }\n }\n"): (typeof documents)["\n query TravelImages($count: Int!, $driver: Driver!) {\n travelImages(count: $count, driver: $driver) {\n imageUrl\n attribution\n photographerName\n photographerUrl\n unsplashUrl\n tags\n color\n downloadLocation\n country {\n code\n name\n }\n }\n }\n"]; +export function graphql(source: "\n query TravelImages($count: Int!) {\n travelImages(count: $count) {\n imageUrl\n attribution\n photographerName\n photographerUrl\n unsplashUrl\n tags\n color\n downloadLocation\n country {\n code\n name\n }\n }\n }\n"): (typeof documents)["\n query TravelImages($count: Int!) {\n travelImages(count: $count) {\n imageUrl\n attribution\n photographerName\n photographerUrl\n unsplashUrl\n tags\n color\n downloadLocation\n country {\n code\n name\n }\n }\n }\n"]; /** * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ diff --git a/frontend/src/gql/graphql.ts b/frontend/src/gql/graphql.ts index fbf6cab..f9ea3e0 100644 --- a/frontend/src/gql/graphql.ts +++ b/frontend/src/gql/graphql.ts @@ -4,11 +4,6 @@ type Exact = { [K in keyof T]: T[K] }; /** Internal type. DO NOT USE DIRECTLY. */ export type Incremental = T | { [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never }; import type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core'; -/** Which algorithm drives the feed: A (engagement) or B (user-first). */ -export type Driver = - | 'A' - | 'B'; - /** What the user did with an image. */ export type InteractionAction = | 'dislike' @@ -51,6 +46,16 @@ export type DeleteAccountMutationVariables = Exact<{ [key: string]: never; }>; export type DeleteAccountMutation = { deleteAccount: boolean }; +export type ResetDossierMutationVariables = Exact<{ [key: string]: never; }>; + + +export type ResetDossierMutation = { resetDossier: boolean }; + +export type NotifyResearchDownloadMutationVariables = Exact<{ [key: string]: never; }>; + + +export type NotifyResearchDownloadMutation = { notifyResearchDownload: boolean }; + export type PreferencesQueryVariables = Exact<{ [key: string]: never; }>; @@ -83,7 +88,6 @@ export type ResetLearnProgressMutation = { resetLearnProgress: boolean }; export type TravelImagesQueryVariables = Exact<{ count: number; - driver: Driver; }>; @@ -112,12 +116,14 @@ export type DossierQuery = { dossier: { totalInteractions: number, likes: number export const FindEmailByPhoneDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"FindEmailByPhone"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"phone"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findEmailByPhone"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"phone"},"value":{"kind":"Variable","name":{"kind":"Name","value":"phone"}}}]}]}}]} as unknown as DocumentNode; export const CountriesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Countries"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"countries"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"code"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]} as unknown as DocumentNode; export const DeleteAccountDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteAccount"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteAccount"}}]}}]} as unknown as DocumentNode; +export const ResetDossierDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ResetDossier"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"resetDossier"}}]}}]} as unknown as DocumentNode; +export const NotifyResearchDownloadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"NotifyResearchDownload"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"notifyResearchDownload"}}]}}]} as unknown as DocumentNode; export const PreferencesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Preferences"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"me"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"preferences"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"value"}},{"kind":"Field","name":{"kind":"Name","value":"country"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"code"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]}}]}}]} as unknown as DocumentNode; export const LearnProgressDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"LearnProgress"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"me"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"learnProgress"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sectionId"}},{"kind":"Field","name":{"kind":"Name","value":"viewedSlides"}}]}}]}}]}}]} as unknown as DocumentNode; export const RecordSlideViewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RecordSlideView"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"sectionId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"slideIndex"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"recordSlideView"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"sectionId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"sectionId"}}},{"kind":"Argument","name":{"kind":"Name","value":"slideIndex"},"value":{"kind":"Variable","name":{"kind":"Name","value":"slideIndex"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sectionId"}},{"kind":"Field","name":{"kind":"Name","value":"viewedSlides"}}]}}]}}]} as unknown as DocumentNode; export const MergeLearnProgressDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"MergeLearnProgress"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"progress"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"LearnSectionProgressInput"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"mergeLearnProgress"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"progress"},"value":{"kind":"Variable","name":{"kind":"Name","value":"progress"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sectionId"}},{"kind":"Field","name":{"kind":"Name","value":"viewedSlides"}}]}}]}}]} as unknown as DocumentNode; export const ResetLearnProgressDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ResetLearnProgress"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"resetLearnProgress"}}]}}]} as unknown as DocumentNode; -export const TravelImagesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"TravelImages"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"count"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"driver"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Driver"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"travelImages"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"count"},"value":{"kind":"Variable","name":{"kind":"Name","value":"count"}}},{"kind":"Argument","name":{"kind":"Name","value":"driver"},"value":{"kind":"Variable","name":{"kind":"Name","value":"driver"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"imageUrl"}},{"kind":"Field","name":{"kind":"Name","value":"attribution"}},{"kind":"Field","name":{"kind":"Name","value":"photographerName"}},{"kind":"Field","name":{"kind":"Name","value":"photographerUrl"}},{"kind":"Field","name":{"kind":"Name","value":"unsplashUrl"}},{"kind":"Field","name":{"kind":"Name","value":"tags"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"downloadLocation"}},{"kind":"Field","name":{"kind":"Name","value":"country"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"code"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]}}]} as unknown as DocumentNode; +export const TravelImagesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"TravelImages"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"count"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"travelImages"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"count"},"value":{"kind":"Variable","name":{"kind":"Name","value":"count"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"imageUrl"}},{"kind":"Field","name":{"kind":"Name","value":"attribution"}},{"kind":"Field","name":{"kind":"Name","value":"photographerName"}},{"kind":"Field","name":{"kind":"Name","value":"photographerUrl"}},{"kind":"Field","name":{"kind":"Name","value":"unsplashUrl"}},{"kind":"Field","name":{"kind":"Name","value":"tags"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"downloadLocation"}},{"kind":"Field","name":{"kind":"Name","value":"country"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"code"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]}}]} as unknown as DocumentNode; export const SubmitFeedbackDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SubmitFeedback"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"interactions"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"InteractionInput"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"submitFeedback"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"interactions"},"value":{"kind":"Variable","name":{"kind":"Name","value":"interactions"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]} as unknown as DocumentNode; export const TrackPhotoUseDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"TrackPhotoUse"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"downloadLocation"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"trackPhotoUse"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"downloadLocation"},"value":{"kind":"Variable","name":{"kind":"Name","value":"downloadLocation"}}}]}]}}]} as unknown as DocumentNode; export const DossierDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Dossier"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"dossier"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"totalInteractions"}},{"kind":"Field","name":{"kind":"Name","value":"likes"}},{"kind":"Field","name":{"kind":"Name","value":"dislikes"}},{"kind":"Field","name":{"kind":"Name","value":"skips"}},{"kind":"Field","name":{"kind":"Name","value":"avgDwellMs"}},{"kind":"Field","name":{"kind":"Name","value":"confidence"}},{"kind":"Field","name":{"kind":"Name","value":"exploration"}},{"kind":"Field","name":{"kind":"Name","value":"disclaimer"}},{"kind":"Field","name":{"kind":"Name","value":"inferredTraits"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"trait"}},{"kind":"Field","name":{"kind":"Name","value":"confidence"}}]}},{"kind":"Field","name":{"kind":"Name","value":"topFeatures"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}}]}}]}}]} as unknown as DocumentNode; \ No newline at end of file diff --git a/frontend/src/pages/AccountPage/AccountPage.tsx b/frontend/src/pages/AccountPage/AccountPage.tsx index 2717b04..769657f 100644 --- a/frontend/src/pages/AccountPage/AccountPage.tsx +++ b/frontend/src/pages/AccountPage/AccountPage.tsx @@ -54,6 +54,20 @@ const DeleteAccountMutation = graphql(` } `); +// resetDossier (not resetPreferences) clears the live learned state — both the +// Algorithm-A dossier and the Algorithm-B taste that backs the Dashboard scores. +const ResetPreferencesMutation = graphql(` + mutation ResetDossier { + resetDossier + } +`); + +const NotifyResearchDownloadMutation = graphql(` + mutation NotifyResearchDownload { + notifyResearchDownload + } +`); + type Status = { tone: 'ok' | 'error'; message: string } | null; type Popup = | 'emailVerify' @@ -223,6 +237,8 @@ export function AccountPage(): ReactElement { const { status, user, reload, logout } = useAuth(); const navigate = useNavigate(); const [deletion, deleteAccount] = useMutation(DeleteAccountMutation); + const [clearing, resetPreferences] = useMutation(ResetPreferencesMutation); + const [notifying, notifyResearchDownload] = useMutation(NotifyResearchDownloadMutation); const { theme } = useTheme(); const canvasRef = useRef(null); useCanvasAnimation(canvasRef, theme); @@ -283,6 +299,8 @@ export function AccountPage(): ReactElement { // ── Delete ──────────────────────────────────────────────────────────────── const [deleteError, setDeleteError] = useState(null); + const [clearError, setClearError] = useState(null); + const [researchError, setResearchError] = useState(null); useEffect(() => { iconTimerRef.current = setTimeout(() => { @@ -520,6 +538,45 @@ export function AccountPage(): ReactElement { void navigate('/'); } + async function clearPreferences(): Promise { + setClearError(null); + // Invalidate cached User/CountryPreference so the Dashboard refetches the reset scores. + const result = await resetPreferences( + {}, + { additionalTypenames: ['User', 'CountryPreference', 'Dossier'] }, + ); + if (result.error) { + setClearError( + result.error.networkError ? 'Network error. Please try again.' : result.error.message, + ); + return; + } + setPopup(null); + } + + async function downloadResearch(): Promise { + setResearchError(null); + // Gate the download: only proceed if the owner-notification email actually sends + // (which also requires the backend to have identified the user's email). + const result = await notifyResearchDownload({}); + if (result.error || result.data?.notifyResearchDownload !== true) { + setResearchError( + result.error?.networkError + ? 'Network error. Please try again.' + : 'We could not complete your request right now. Please try again.', + ); + return; + } + // Confirmed — trigger the browser download (served same-origin at /research.pdf). + const a = document.createElement('a'); + a.href = '/research.pdf'; + a.download = 'Building-Better-Algorithms-Research.pdf'; + document.body.appendChild(a); + a.click(); + a.remove(); + setPopup(null); + } + // ── Render ───────────────────────────────────────────────────────────────── return ( @@ -859,6 +916,7 @@ export function AccountPage(): ReactElement { type="button" className="account-btn" onClick={() => { + setResearchError(null); setPopup('downloadResearch'); }} > @@ -886,6 +944,7 @@ export function AccountPage(): ReactElement { type="button" className="account-btn account-btn--danger" onClick={() => { + setClearError(null); setPopup('clearPreferences'); }} > @@ -1064,23 +1123,26 @@ export function AccountPage(): ReactElement { title="Clear preferences data?" hoverState="hover-trash" onClose={() => { + setClearError(null); setPopup(null); }} >

- This permanently removes all of your learned country preferences. Your account data - will be fully erased and this action cannot be undone. + This permanently removes all of your learned country preferences, resetting every + country to neutral. This action cannot be undone.

+ {clearError &&

{clearError}

}
)} @@ -1121,6 +1183,7 @@ export function AccountPage(): ReactElement { title="Download our research?" hoverState="hover-swipe" onClose={() => { + setResearchError(null); setPopup(null); }} > @@ -1134,12 +1197,14 @@ export function AccountPage(): ReactElement { + {researchError &&

{researchError}

} )} diff --git a/frontend/src/pages/TravelPage/TravelPage.css b/frontend/src/pages/TravelPage/TravelPage.css index 9fbffbe..90d806f 100644 --- a/frontend/src/pages/TravelPage/TravelPage.css +++ b/frontend/src/pages/TravelPage/TravelPage.css @@ -26,8 +26,8 @@ z-index: 50; display: flex; align-items: center; - justify-content: space-between; - pointer-events: none; /* let clicks pass through the gap between buttons */ + justify-content: flex-end; + pointer-events: none; /* let clicks pass through around the button */ } /* Re-enable clicks on the actual interactive children. */ @@ -35,45 +35,7 @@ pointer-events: auto; } -/* Algorithm toggle pill — matches .learn-progress-toggle glass style */ -.travel-driver { - display: inline-flex; - border: 1px solid rgba(255, 255, 255, 0.22); - border-radius: 100px; - overflow: hidden; - background: rgba(255, 255, 255, 0.14); - backdrop-filter: blur(18px) saturate(180%); - -webkit-backdrop-filter: blur(18px) saturate(180%); - box-shadow: 0 12px 40px rgba(0, 0, 0, 0.25); - transition: border-color 0.2s ease; -} - -.travel-driver:hover { - border-color: rgba(255, 255, 255, 0.36); -} - -[data-theme='light'] .travel-driver { - background: rgba(255, 255, 255, 0.55); - border-color: rgba(61, 82, 160, 0.2); - box-shadow: 0 12px 40px rgba(0, 0, 0, 0.1); -} - -.travel-driver-tab { - border: 0; - background: transparent; - color: var(--color-heading); - padding: 0.55rem 1.1rem; - font-size: var(--fs-sm); - font-weight: var(--fw-bold); - letter-spacing: 0.02em; - white-space: nowrap; -} - -.travel-driver-tab.is-active { - background: rgba(255, 255, 255, 0.18); -} - -/* "See your data" button — identical glass style */ +/* "See your data" button — frosted-glass pill */ .travel-dossier-toggle { border: 1px solid rgba(255, 255, 255, 0.22); border-radius: 100px; @@ -231,46 +193,135 @@ opacity: 0.65; } -/* ── Hold-to-zoom overlay ────────────────────────────────────────────────── */ +/* ── "Same taps, two algorithms" data-collected contrast ─────────────────── */ -.travel-zoom-overlay { - position: fixed; - inset: 0; - z-index: 200; +/* Wider card to fit the two ledgers side by side. */ +.travel-dossier-card--contrast { + max-width: 46rem; +} + +.travel-dossier-sub { + margin: 0.4rem 0 0; + text-align: center; + font-size: var(--fs-sm); + font-weight: var(--fw-semibold); + color: var(--color-text); + opacity: 0.8; +} + +.travel-contrast { + display: flex; + gap: 1rem; + margin-top: 1.5rem; +} + +.travel-contrast-col { + flex: 1; display: flex; flex-direction: column; - align-items: center; - justify-content: center; - padding: 2rem; - background: rgba(0, 0, 0, 0.88); - cursor: zoom-out; - animation: travel-fade-in 180ms ease both; + border: 1px solid var(--color-border); + border-radius: 16px; + padding: 1.1rem 1.2rem 1.25rem; + background: rgba(255, 255, 255, 0.04); } -.travel-zoom-img { - max-width: min(92vw, 128vh); - max-height: 82vh; - border-radius: 12px; - object-fit: contain; - cursor: default; - animation: travel-zoom-bounce 360ms cubic-bezier(0.34, 1.56, 0.64, 1) both; +/* User-first: calm/positive; Engagement: alarming. */ +.travel-contrast-col--b { + border-color: color-mix(in srgb, var(--color-accent) 45%, transparent); + background: color-mix(in srgb, var(--color-accent) 8%, transparent); } -.travel-zoom-credit { - margin-top: 0.75rem; - color: var(--color-text-muted); +.travel-contrast-col--a { + border-color: rgba(224, 36, 94, 0.45); + background: rgba(224, 36, 94, 0.07); +} + +.travel-contrast-title { + margin: 0 0 0.6rem; font-size: var(--fs-sm); - pointer-events: none; + font-weight: var(--fw-extrabold); + letter-spacing: 0.02em; + color: var(--color-heading); } -@keyframes travel-zoom-bounce { - from { - opacity: 0; - transform: scale(0.72); - } - to { - opacity: 1; - transform: scale(1); +.travel-contrast-title span { + display: block; + font-size: var(--fs-xs); + font-weight: var(--fw-semibold); + letter-spacing: 0.06em; + text-transform: uppercase; + opacity: 0.55; +} + +.travel-contrast-list { + list-style: none; + margin: 0; + padding: 0; + font-size: var(--fs-sm); + line-height: 1.85; + color: var(--color-text); +} + +.travel-contrast-list b { + display: inline-block; + min-width: 1.6em; + font-weight: var(--fw-extrabold); + color: var(--color-heading); +} + +.travel-contrast-note { + margin: 0.7rem 0 0; + font-size: var(--fs-xs); + font-style: italic; + line-height: 1.5; + opacity: 0.7; +} + +.travel-contrast-note--a { + color: #e0245e; + opacity: 0.85; +} + +/* Push the tally to the bottom so both columns' numbers line up. */ +.travel-contrast-tally { + margin-top: auto; + padding-top: 0.9rem; + font-size: var(--fs-xs); + font-weight: var(--fw-bold); + text-transform: uppercase; + letter-spacing: 0.06em; + opacity: 0.7; +} + +.travel-contrast-num { + display: block; + font-size: var(--fs-2xl); + font-weight: var(--fw-extrabold); + letter-spacing: 0; + color: var(--color-accent); +} + +.travel-contrast-tally--a .travel-contrast-num { + color: #e0245e; +} + +.travel-dossier-footer { + margin: 1.4rem 0 0; + text-align: center; + font-size: var(--fs-sm); + font-weight: var(--fw-semibold); + line-height: 1.6; + color: var(--color-text); +} + +.travel-dossier-footer strong { + color: #e0245e; +} + +/* Stack the two ledgers on narrow screens. */ +@media (max-width: 560px) { + .travel-contrast { + flex-direction: column; } } @@ -341,12 +392,9 @@ -webkit-user-drag: none; outline: none; z-index: 1; - /* `scale` is an individual CSS transform property — composes with the - JS-driven `translate` (column parallax) without overwriting it. */ transition: scale 300ms cubic-bezier(0.34, 1.56, 0.64, 1), filter 300ms ease; - will-change: translate; } /* Dim all non-hovered cells when any cell in the section is hovered. */ diff --git a/frontend/src/pages/TravelPage/TravelPage.test.tsx b/frontend/src/pages/TravelPage/TravelPage.test.tsx index ff9c822..b21a794 100644 --- a/frontend/src/pages/TravelPage/TravelPage.test.tsx +++ b/frontend/src/pages/TravelPage/TravelPage.test.tsx @@ -50,10 +50,11 @@ async function renderAndLoad() { } describe('TravelPage', () => { - it('shows the driver toggle tabs after load', async () => { + it('shows the "See your data" button after load, not a driver toggle', async () => { await renderAndLoad(); - expect(screen.getByRole('tab', { name: 'Engagement' })).toBeInTheDocument(); - expect(screen.getByRole('tab', { name: 'User-First' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /see your data/i })).toBeInTheDocument(); + expect(screen.queryByRole('tab', { name: 'Engagement' })).not.toBeInTheDocument(); + expect(screen.queryByRole('tab', { name: 'User-First' })).not.toBeInTheDocument(); }); it('renders 16 photo cells across 2 sections', async () => { diff --git a/frontend/src/pages/TravelPage/TravelPage.tsx b/frontend/src/pages/TravelPage/TravelPage.tsx index 34455f2..e0c33de 100644 --- a/frontend/src/pages/TravelPage/TravelPage.tsx +++ b/frontend/src/pages/TravelPage/TravelPage.tsx @@ -6,12 +6,9 @@ * Click the LEFT half of a photo to dislike (✕, greyscale). * Hover for 1 s counts as "engaged" and boosts the dwell signal. * - * Row parallax: entering and exiting sections have rows at staggered offsets that - * converge to zero when the section is fully snapped (centred in the feed). - * - * Sections auto-submit when scrolled off the top — no submit button. The top bar - * (algorithm toggle + dossier) stays fixed. A per-photo info button (top-right ℹ) - * reveals photographer details. + * Sections auto-submit when scrolled off the top — no submit button. The fixed + * "See your data" button opens the data-collected contrast. A per-photo info + * button (top-right ℹ) reveals photographer details. * * Unsplash compliance: `trackPhotoUse` pings the download endpoint for liked * photos; attribution links carry UTM params. @@ -31,15 +28,14 @@ const COLS = 4; const ROWS = 2; const SECTION_SIZE = COLS * ROWS; // 8 photos per section const INITIAL_SECTIONS = 2; -const PARALLAX_PX = 160; // max row offset in px when adjacent section is fully off-screen const HOVER_DWELL_MS = 1000; // hover duration before counting as "engaged" const APP_NAME = 'Building Better Algorithms'; // ── GraphQL ─────────────────────────────────────────────────────────────────── const TravelImagesQuery = graphql(` - query TravelImages($count: Int!, $driver: Driver!) { - travelImages(count: $count, driver: $driver) { + query TravelImages($count: Int!) { + travelImages(count: $count) { imageUrl attribution photographerName @@ -95,7 +91,6 @@ const DossierQuery = graphql(` // ── Types ───────────────────────────────────────────────────────────────────── -type Driver = 'A' | 'B'; type PhotoReaction = 'like' | 'dislike' | null; interface FeedPhoto { @@ -129,17 +124,69 @@ function photoKey(sectionId: number, photoIdx: number): string { return `${sectionId}-${photoIdx}`; } +interface ContrastRow { + n: number; + label: string; +} + +interface DataContrast { + total: number; + bTotal: number; + aTotal: number; + ratio: number | null; + bRows: ContrastRow[]; + aRows: ContrastRow[]; + traits: string[]; +} + +/** + * Split the same session's dossier into two ledgers: what the **user-first** algorithm + * keeps (only the explicit reactions) vs. what an **engagement** algorithm would harvest + * from the identical taps (every impression, dwell sample, skip, and inference). Both + * are derived from the one `dossier` query — the contrast is the lesson. + */ +function computeContrast(d: { + totalInteractions: number; + likes: number; + dislikes: number; + skips: number; + topFeatures: { key: string }[]; + inferredTraits: { trait: string }[]; +}): DataContrast { + const total = d.totalInteractions; + const bRows: ContrastRow[] = [ + { n: d.likes, label: 'likes' }, + { n: d.dislikes, label: 'dislikes' }, + ]; + const aRows: ContrastRow[] = [ + { n: total, label: 'impressions logged' }, + { n: total, label: 'dwell-time samples' }, + { n: d.likes + d.dislikes, label: 'reactions' }, + { n: d.skips, label: 'skips' }, + { n: d.topFeatures.length, label: 'inferred taste features' }, + { n: d.inferredTraits.length, label: 'inferred traits' }, + { n: 2, label: 'derived scores' }, + ]; + const bTotal = bRows.reduce((s, r) => s + r.n, 0); + const aTotal = aRows.reduce((s, r) => s + r.n, 0); + return { + total, + bTotal, + aTotal, + ratio: bTotal > 0 ? Math.round(aTotal / bTotal) : null, + bRows, + aRows, + traits: d.inferredTraits.map((t) => t.trait), + }; +} + // ── Component ───────────────────────────────────────────────────────────────── export function TravelPage(): ReactElement { - const [driver, setDriver] = useState('B'); const [sections, setSections] = useState([]); const [isLoading, setIsLoading] = useState(false); const [showDossier, setShowDossier] = useState(false); const [infoOpen, setInfoOpen] = useState(null); - const [zoomedPhoto, setZoomedPhoto] = useState<{ sectionId: number; photoIdx: number } | null>( - null, - ); const sectionEls = useRef<(HTMLElement | null)[]>([]); const sectionIdCounter = useRef(0); @@ -148,8 +195,6 @@ export function TravelPage(): ReactElement { const pendingDossierRefresh = useRef(false); const feedRef = useRef(null); const hoverTimers = useRef>>(new Map()); - const holdTimerRef = useRef | null>(null); - const holdFiredRef = useRef(false); const client = useClient(); const [dossier, refetchDossier] = useQuery({ query: DossierQuery }); @@ -177,7 +222,7 @@ export function TravelPage(): ReactElement { const result = await client .query( TravelImagesQuery, - { count: count * SECTION_SIZE, driver }, + { count: count * SECTION_SIZE }, { requestPolicy: 'network-only' }, ) .toPromise(); @@ -222,7 +267,7 @@ export function TravelPage(): ReactElement { setIsLoading(false); } }, - [client, driver], + [client], ); useEffect(() => { @@ -231,45 +276,11 @@ export function TravelPage(): ReactElement { // ── Interaction ──────────────────────────────────────────────────────────── - // ── Hold-to-zoom ────────────────────────────────────────────────────────── - - function handlePhotoPointerDown(sectionId: number, photoIdx: number): void { - holdFiredRef.current = false; - holdTimerRef.current = setTimeout(() => { - holdFiredRef.current = true; - setZoomedPhoto({ sectionId, photoIdx }); - }, 400); - } - - function handlePhotoPointerUp(): void { - if (holdTimerRef.current !== null) { - clearTimeout(holdTimerRef.current); - holdTimerRef.current = null; - } - } - - // Close zoom on Escape. - useEffect(() => { - if (!zoomedPhoto) return; - function handleEsc(e: globalThis.KeyboardEvent): void { - if (e.key === 'Escape') setZoomedPhoto(null); - } - window.addEventListener('keydown', handleEsc); - return () => { - window.removeEventListener('keydown', handleEsc); - }; - }, [zoomedPhoto]); - function handlePhotoClick( e: MouseEvent, sectionId: number, photoIdx: number, ): void { - // If a hold just fired, swallow the synthetic click — don't react. - if (holdFiredRef.current) { - holdFiredRef.current = false; - return; - } // A tap anywhere on the cell closes an open info panel first (no reaction change). if (infoOpen !== null) { setInfoOpen(null); @@ -463,77 +474,17 @@ export function TravelPage(): ReactElement { }; }, [sections.length, refetchDossier]); - // ── Row parallax (on the feed scroll container) ──────────────────────────── - - useEffect(() => { - const feedEl = feedRef.current; - if (!feedEl) return; - - // Each column has its own speed multiplier; both rows in the same column - // share that speed so rows stay level with each other. - const COL_SPEEDS = [0.5, 1.4, 0.8, 1.2]; - - function handleScroll(): void { - if (!feedEl) return; - const feedH = feedEl.clientHeight; - if (feedH === 0) return; - - for (const el of sectionEls.current) { - if (!el) continue; - const progress = (el.offsetTop - feedEl.scrollTop) / feedH; - const cells = el.querySelectorAll('.travel-cell'); - cells.forEach((cell, idx) => { - const colIdx = idx % COLS; - const speed = COL_SPEEDS[colIdx] ?? 1; - cell.style.translate = `0 ${progress * speed * PARALLAX_PX}px`; - }); - } - } - - feedEl.addEventListener('scroll', handleScroll, { passive: true }); - return () => { - feedEl.removeEventListener('scroll', handleScroll); - }; - }, [sections.length]); - - // ── Driver switch ────────────────────────────────────────────────────────── - - function switchDriver(next: Driver): void { - if (next === driver) return; - setDriver(next); - } - // ── Render ───────────────────────────────────────────────────────────────── if (isLoading && sections.length === 0) return ; const d = dossier.data?.dossier; - - // Resolve the currently zoomed photo for the overlay. - const zoomedSection = zoomedPhoto - ? sections.find((s) => s.id === zoomedPhoto.sectionId) - : undefined; - const zoomedImg = zoomedSection?.photos[zoomedPhoto?.photoIdx ?? -1]; + const contrast = d ? computeContrast(d) : null; return (
{/* Controls overlay — floats over the photos, no background bar */}
-
- {(['A', 'B'] as Driver[]).map((drvr) => ( - { - switchDriver(drvr); - }} - > - {drvr === 'A' ? 'Engagement' : 'User-First'} - - ))} -
{ @@ -544,8 +495,8 @@ export function TravelPage(): ReactElement {
- {/* Dossier modal — same structure and classes as SecurityInfo */} - {showDossier && d && ( + {/* "See your data" — the same taps, seen by two algorithms */} + {showDossier && d && contrast && (
{ @@ -553,14 +504,14 @@ export function TravelPage(): ReactElement { }} role="dialog" aria-modal="true" - aria-label="What the algorithm has on you" + aria-label="What each algorithm collects from you" >
{ e.stopPropagation(); }} > - +
)} - {/* Hold-to-zoom overlay — appears when user presses and holds a photo */} - {zoomedImg && ( -
{ - setZoomedPhoto(null); - }} - role="dialog" - aria-modal="true" - aria-label="Zoomed photo" - > - {`${zoomedImg.country.name} { - e.stopPropagation(); - }} - /> -

- {zoomedImg.photographerName} · {zoomedImg.country.name} -

-
- )} - {/* Snap-scroll feed */}
{ - handlePhotoPointerDown(section.id, photoIdx); - }} - onPointerUp={handlePhotoPointerUp} - onPointerCancel={handlePhotoPointerUp} onClick={(e) => { handlePhotoClick(e, section.id, photoIdx); }} diff --git a/frontend/src/pages/TravelPage/plan/REDESIGN.md b/frontend/src/pages/TravelPage/plan/REDESIGN.md new file mode 100644 index 0000000..b2b5bf0 --- /dev/null +++ b/frontend/src/pages/TravelPage/plan/REDESIGN.md @@ -0,0 +1,169 @@ +# Travel Page — Redesign Plan + +> **Supersedes** the maximalist parts of [DEVELOPMENT-PLAN.md](./DEVELOPMENT-PLAN.md). +> Goal: cut the Travel page's complexity by **subtraction and repurposing**, not a +> rebuild. Most of what this plan needs already exists in the codebase — it is just +> wired together in the most complex possible way. + +## Why the page exploded + +The page was quietly doing three jobs; only one is the demo Learn §08 actually calls +for: + +1. **The planned demo** — explicit like/dislike → visible score movement; minimal, + legible, nothing inferred. +2. **A surveillance simulator** — a `driver` A/B toggle that swaps the _entire live + feed_, plus a hidden "dossier" of inferred traits, confidence, dwell tracking. +3. **Production polish** — column parallax, hold-to-zoom, `useRef` choreography around + auto-submit. + +Jobs 2 and 3 are the whole complexity budget, and job 2 (dwell + inferred dossier) +_contradicts_ §08's thesis (explicit-only, nothing inferred). The fix is to stop +doing the two expensive things the page was never asked to do, and to **reframe** the +already-computed A/B data as the lesson. + +## What already exists (reused, not rebuilt) + +- **Static photo pool, zero external calls** — `backend/src/photos.data.ts` + + `scripts/build-photo-pool.ts` cache metadata-rich photos so the running app makes + ~0 Unsplash calls. Currently near-empty (4 entries) and still hotlinks Unsplash + URLs. +- **Rich metadata type** — `CachedPhoto` (country, tags, color, photographer, + downloadLocation), ready to expand. +- **A-vs-B data already computed** — `dossier.ts` computes both an engagement taste + (A) and a user-first taste (B) from the _same_ interactions; `insights.ts` already + does `inferTraits` with an "illustrative, not a diagnosis" disclaimer. + +## Confirmed decisions + +1. **Images self-hosted in S3** (not hotlinked). Fine under the Unsplash License; + keep attribution + download-trigger. Matches the "no live external calls" goal. +2. **Metadata honesty** — Unsplash reliably gives tags/color/location; EXIF/GPS is + spotty and season/terrain/light are _derived_. Label derived fields as inferred, + never as precise measured EXIF. +3. **Feed selection stays on the backend** — `travelImages` already serves the static + pool with zero external calls; keeps "the algorithm chose these for you" real. + +## The interaction (unchanged) + +Keep the current **click-halves snap feed**: left half = dislike (✕), right half = +like (♥), keyboard support, snap-scroll sections, infinite preload, info button + +credit, auto-submit when a section scrolls off the top. + +--- + +## Phase 1 — Strip the feed down (subtraction) + +`TravelPage.tsx` (~793 → ~450 lines) and `TravelPage.css` trims. + +- **Delete** column parallax: the feed `scroll` handler, `COL_SPEEDS`, per-cell + `translate`, and the `PARALLAX_PX` constant. +- **Delete** hold-to-zoom: `holdTimerRef`, `holdFiredRef`, `zoomedPhoto` state, the + zoom overlay JSX, the pointer-down/up handlers, and the Escape effect for zoom. +- **Delete** the display-driving `driver` state and the two-tab toggle; the feed + becomes a single user-first / preference-weighted stream. +- **Keep**: click-halves like/dislike, keyboard, snap-scroll, infinite preload, info + panel + credit, auto-submit-on-scroll-off, dwell/hover recording (now feeds the + contrast, see Phase 3). + +## Phase 2 — Static photo dataset in S3 (data + metadata) + +**Sizing (confirmed):** catalog is **228 countries** (not 35), **~15 photos/country ≈ +3,400 total**, ~850 MB (≈17% of the 5 GB S3 free tier). Density is nearly free on both +storage and API calls (one search returns 30). Unsplash **demo mode (50/hr)**. + +**Metadata via enrichment (confirmed).** Unsplash **search returns no `tags`** (verified) +— they require a per-photo `GET /photos/:id`, which also yields `location` + camera +`exif`. Since the recommender needs tags, each kept photo is enriched. That pushes the +full demo-mode run to **~2.5–3 days** (all calls share the 50/hr budget; resumable). +`country` stays the search association (catalog key); geotags are stored when present +but don't override it. + +**Code — done (`develop`):** + +- **Metadata schema** — `photos.types.ts` `CachedPhoto` (id, kind, likes, dimensions, + blurHash, description, `unsplashImageUrl`, same-origin `imageUrl`, + enrichment: tags, + `locationName`/`lat`/`lng`, `exif`). Only measured or self-assigned fields. +- **Curation** — `photos.curate.ts` (pure, tested): dedup by id, min-likes gate, + food/interior/people/text denylist, cities↔landscapes interleave, per-country cap. +- **Step A generator** — `build-photo-pool.ts`: two searches/country + per-photo + **enrichment** (real tags + location + exif); global rate gate; resumable + + checkpointed; curated to 15/country. Verified live (tags/location/exif land). +- **Step B sync** — `sync-photos-s3.ts`: resumable CDN download → uploads **both** + images (`photos/.jpg`) and metadata (`photos.json`) to the bucket. `photos-cache/` + - `photos.json` gitignored. +- **Metadata in S3, not the code** — the pool is **not** bundled into the Lambda. It's + `photos.json` in `bba-photos`, loaded once per cold start by `pool.ts` (cached warm), + which also primes the country signatures. `images.ts` selects from it; local dev reads + a local `photos.json`. Lambda gets `s3:GetObject` on `bba-photos/photos.json`. + +**Data run — pending (owner-run; nothing photo-related is committed):** + +- `UNSPLASH_ACCESS_KEY=… npm run build:photos` (~2.5–3 days background, resumable; incl. + enrichment) → writes `photos.json` (gitignored). +- `PHOTO_S3_BUCKET=bba-photos npm run sync:photos` (once — shared bucket; after + `bootstrap/` applied) → images + `photos.json` to S3. + +## Phase 3 — Repurpose the dossier into the "data collected" contrast + +**Done (`develop`):** the old "What the algorithm has on you" modal is now the +**"Same taps. Two algorithms."** contrast — two ledgers (`computeContrast` in +`TravelPage.tsx`) split from the one `dossier` query: User-First keeps only +likes+dislikes; Engagement itemizes impressions, dwell samples, skips, inferred +features/traits, with per-column data-point tallies and an "Nx the data" line. Pure +reframing — no schema change, no photos needed. Format/lint/40 tests green. + +Replace the "What the algorithm has on you" dossier modal with a single **"See your +data"** button that opens a two-column contrast for _this session_: + +| Algorithm B — User-First (what we collected) | Algorithm A — Engagement (same session) | +| -------------------------------------------- | ---------------------------------------------------------- | +| N likes, M dislikes → explicit signals only | + every scroll, hover-dwell (ms/photo), skip, time-on-card | +| "Two numbers per country you rated." | + metadata inferences from the rich photo fields | +| Nothing else left your browser. | + confidence %, inferred traits _(illustrative)_ | +| **~5 data points** | **~80 data points** | + +Punchline: **same taps, ~15× the footprint.** Honest by construction — the feed still +records dwell/hover, but that tracking now visibly powers the lesson instead of a +hidden profile. Powered by the existing `dossier` (both tastes) + `insights` +(`inferTraits`), reframed from "your profile" to "the gap between two algorithms." + +Add a concrete **data-points tally**: + +- **B**: likes + dislikes (explicit events). +- **A**: likes + dislikes + skips + per-photo dwell samples + hover events + scroll + depth + N inferred features + N inferred traits → one headline number ~10–20× B. + +## Phase 4 — Backend trims + +**Done (`develop`):** + +- Dropped the `driver` arg **and** the `Driver` enum from the public schema — + `travelImages(count)` now always selects user-first (Algorithm B). Regenerated + `schema.graphql` + frontend codegen; removed `FEED_DRIVER`/`Driver` from + `TravelPage.tsx`. The recommender's internal `driver: 'B'` selection stays. +- **Kept** `dossier.ts` / `insights.ts` / `recommender.ts` / `features.ts` — the A/B + machinery still powers the "data collected" contrast (Phase 3), just not a public + display toggle. +- Photo metadata is loaded from S3 at runtime (`pool.ts`), not committed — see Phase 2. +- Backend 115 tests + frontend 40 tests green. + +## Phase 5 — Infra + +- **Done (`develop`):** single shared **`bba-photos`** bucket created in + `bootstrap/main.tf` (private, OAC, SSE; policy trusts any CloudFront distribution in + the account via `AWS:SourceAccount`, so all envs read it — photos are identical, so + we never triplicate them). `infra/photos.tf` looks it up; `frontend.tf` wires the + `s3-photos` origin + `/photos/*` behavior (long TTL, security headers). + `terraform validate` passes. +- **Pending:** `terraform apply -f bootstrap` (creates the bucket), then per-env + `terraform apply`, then run Step B sync **once** against `bba-photos`. + +--- + +## After-change checklist (per CLAUDE.md) + +After each phase touching code: update the relevant README(s), then +`npm run format` → `npm run lint` → `npm test` in the affected workspace(s). Re-run +GraphQL Code Generator after any schema change (`travelImages` arg / `TravelImage` +fields). Do not commit — the owner makes all commits. diff --git a/infra/README.md b/infra/README.md index e3b3c1c..2581565 100644 --- a/infra/README.md +++ b/infra/README.md @@ -34,14 +34,15 @@ Production additionally creates an ACM certificate and Route 53 A records for | File | Purpose | |---|---| -| `bootstrap/main.tf` | One-time account setup (state bucket, OIDC provider) | +| `bootstrap/main.tf` | One-time account setup (state bucket, OIDC provider, shared `bba-photos` bucket) | | `main.tf` | Terraform settings, S3 backend, provider, account data sources | | `variables.tf` | Input variables (`environment`, `unsplash_access_key`, `alert_email`) | | `locals.tf` | Naming prefix, environment flags, shared tags | | `data.tf` | DynamoDB `bba--prefs` table | | `auth.tf` | Cognito user pool (TOTP MFA) + app client | -| `frontend.tf` | S3 bucket, CloudFront distribution, OAC, ACM cert + R53 (prod only) | -| `backend.tf` | ECR, Lambda, IAM execution role, CloudWatch log group, API Gateway HTTP API | +| `frontend.tf` | S3 bucket, CloudFront distribution (`/*`, `/photos/*`, `/graphql`), OAC, ACM cert + R53 (prod only) | +| `photos.tf` | Data lookup of the shared `bba-photos` bucket (created in `bootstrap/`), wired as the `/photos/*` + `/research.pdf` CloudFront origin | +| `backend.tf` | ECR, Lambda (reads `bba-photos/photos.json` via IAM), execution role, log group, API Gateway HTTP API | | `secrets.tf` | SSM Parameter Store — Unsplash key, Cognito IDs | | `security.tf` | CloudFront response-headers policy, CloudTrail, billing alarm (prod) | | `cicd.tf` | GitHub Actions OIDC deploy role (one per environment) | diff --git a/infra/backend.tf b/infra/backend.tf index 6b091b4..d7a7d6d 100644 --- a/infra/backend.tf +++ b/infra/backend.tf @@ -82,6 +82,23 @@ resource "aws_iam_role_policy" "lambda_dynamodb" { }) } +# S3 — read the shared Travel photo-pool metadata (created in bootstrap/). +resource "aws_iam_role_policy" "lambda_photos" { + name = "photos" + role = aws_iam_role.lambda.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = ["s3:GetObject"] + Resource = "arn:aws:s3:::bba-photos-${local.account_id}/photos.json" + }, + ] + }) +} + # SSM — read parameters scoped to this environment resource "aws_iam_role_policy" "lambda_ssm" { name = "ssm" @@ -116,7 +133,13 @@ resource "aws_iam_role_policy" "lambda_kms" { }) } -# SES — send transactional emails for the custom email sender trigger +# SES — send transactional emails for the custom email sender trigger. +# Resource is scoped to all SES identities in this account/region (identity/*), +# not just the From domain. While the account is in the SES sandbox, SES checks +# ses:SendEmail against the *recipient's* verified identity as well as the From +# identity — so a domain-only grant gets AccessDenied on every send to a verified +# recipient address (e.g. the email-OTP MFA code). identity/* covers both the +# noreply@${domain} sender and any sandbox-verified recipient. resource "aws_iam_role_policy" "lambda_ses" { name = "ses" role = aws_iam_role.lambda.id @@ -126,7 +149,7 @@ resource "aws_iam_role_policy" "lambda_ses" { Statement = [{ Effect = "Allow" Action = ["ses:SendEmail"] - Resource = local.ses_identity_arn + Resource = "arn:aws:ses:${local.region}:${local.account_id}:identity/*" }] }) } @@ -211,6 +234,8 @@ resource "aws_lambda_function" "graphql" { COGNITO_CLIENT_ID = aws_cognito_user_pool_client.main.id COGNITO_REGION = local.region DYNAMODB_TABLE = aws_dynamodb_table.prefs.name + PHOTOS_BUCKET = "bba-photos-${local.account_id}" + OWNER_EMAIL = var.alert_email SSM_PREFIX = "/bba/${local.env}" COGNITO_SMS_KEY_ARN = local.cognito_sms_key_arn # Passed directly — Lambda env vars are KMS-encrypted at rest. SSM is the diff --git a/infra/bootstrap/main.tf b/infra/bootstrap/main.tf index 1de41e8..fba1164 100644 --- a/infra/bootstrap/main.tf +++ b/infra/bootstrap/main.tf @@ -29,6 +29,8 @@ provider "aws" { region = "us-east-1" } +data "aws_caller_identity" "current" {} + # --------------------------------------------------------------------------- # Terraform remote state bucket # --------------------------------------------------------------------------- @@ -88,6 +90,60 @@ resource "aws_dynamodb_table" "tf_state_lock" { # nosemgrep: terraform.aws.secur } } +# --------------------------------------------------------------------------- +# Shared Travel photo pool bucket (account-global — one set of photos for ALL +# environments; they are identical, so we never triplicate them). Private; read +# only by CloudFront via OAC. Populated out-of-band by `backend: npm run sync:photos`. +# +# The policy trusts any CloudFront distribution in THIS account (AWS:SourceAccount) +# rather than a specific distribution ARN, so every env's distribution (dev/qa/prod) +# can read it without this bootstrap stack knowing their ARNs. +# --------------------------------------------------------------------------- + +resource "aws_s3_bucket" "photos" { + # Account-ID suffixed for global S3 uniqueness (same pattern as the state bucket). + bucket = "bba-photos-${data.aws_caller_identity.current.account_id}" +} + +resource "aws_s3_bucket_public_access_block" "photos" { + bucket = aws_s3_bucket.photos.id + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} + +resource "aws_s3_bucket_server_side_encryption_configuration" "photos" { + bucket = aws_s3_bucket.photos.id + rule { + apply_server_side_encryption_by_default { + sse_algorithm = "AES256" + } + } +} + +resource "aws_s3_bucket_policy" "photos" { + bucket = aws_s3_bucket.photos.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "AllowCloudFrontServicePrincipalReadOnly" + Effect = "Allow" + Principal = { Service = "cloudfront.amazonaws.com" } + Action = "s3:GetObject" + Resource = "${aws_s3_bucket.photos.arn}/*" + Condition = { + StringEquals = { + "AWS:SourceAccount" = data.aws_caller_identity.current.account_id + } + } + }, + ] + }) +} + # --------------------------------------------------------------------------- # GitHub Actions OIDC identity provider (one per AWS account) # --------------------------------------------------------------------------- @@ -118,3 +174,7 @@ output "state_lock_table" { output "github_oidc_arn" { value = aws_iam_openid_connect_provider.github.arn } + +output "photos_bucket" { + value = aws_s3_bucket.photos.bucket +} diff --git a/infra/envs/dev.tfvars.example b/infra/envs/dev.tfvars.example index d20a8d4..c4d312d 100644 --- a/infra/envs/dev.tfvars.example +++ b/infra/envs/dev.tfvars.example @@ -7,4 +7,4 @@ environment = "dev" unsplash_access_key = "YOUR_UNSPLASH_ACCESS_KEY" -alert_email = "collinm.streitman@gmail.com" +alert_email = "you@example.com" diff --git a/infra/envs/prod.tfvars.example b/infra/envs/prod.tfvars.example index f293d96..75f7399 100644 --- a/infra/envs/prod.tfvars.example +++ b/infra/envs/prod.tfvars.example @@ -3,4 +3,4 @@ environment = "prod" unsplash_access_key = "YOUR_UNSPLASH_ACCESS_KEY" -alert_email = "collinm.streitman@gmail.com" +alert_email = "you@example.com" diff --git a/infra/envs/qa.tfvars.example b/infra/envs/qa.tfvars.example index d49d6e1..697bc36 100644 --- a/infra/envs/qa.tfvars.example +++ b/infra/envs/qa.tfvars.example @@ -3,4 +3,4 @@ environment = "qa" unsplash_access_key = "YOUR_UNSPLASH_ACCESS_KEY" -alert_email = "collinm.streitman@gmail.com" +alert_email = "you@example.com" diff --git a/infra/frontend.tf b/infra/frontend.tf index 8edfc63..e6ae419 100644 --- a/infra/frontend.tf +++ b/infra/frontend.tf @@ -150,7 +150,16 @@ resource "aws_cloudfront_distribution" "main" { # nosemgrep: terraform.aws.secur origin_access_control_id = aws_cloudfront_origin_access_control.frontend.id } - # Origin 2: API Gateway HTTP API (GraphQL). API Gateway is publicly reachable + # Origin 2: S3 (shared Travel photo pool, created in bootstrap/) — served + # same-origin at /photos/*. OAC read is authorised by the bucket policy's + # AWS:SourceAccount condition, so no per-distribution ARN wiring is needed. + origin { + domain_name = data.aws_s3_bucket.photos.bucket_regional_domain_name + origin_id = "s3-photos" + origin_access_control_id = aws_cloudfront_origin_access_control.frontend.id + } + + # Origin 3: API Gateway HTTP API (GraphQL). API Gateway is publicly reachable # and CloudFront proxies the request unchanged — no signing required. origin { domain_name = "${aws_apigatewayv2_api.graphql.id}.execute-api.${local.region}.amazonaws.com" @@ -186,6 +195,54 @@ resource "aws_cloudfront_distribution" "main" { # nosemgrep: terraform.aws.secur max_ttl = 86400 } + # /photos/* behaviour: serve immutable image binaries from the photos bucket, + # cached hard (they never change — id-addressed). + ordered_cache_behavior { + path_pattern = "/photos/*" + target_origin_id = "s3-photos" + viewer_protocol_policy = "redirect-to-https" + allowed_methods = ["GET", "HEAD", "OPTIONS"] + cached_methods = ["GET", "HEAD"] + compress = true + + forwarded_values { + query_string = false + cookies { + forward = "none" + } + } + + response_headers_policy_id = aws_cloudfront_response_headers_policy.security.id + + min_ttl = 0 + default_ttl = 86400 + max_ttl = 31536000 + } + + # /research.pdf: the capstone paper, served from the shared photos bucket (uploaded + # out-of-band, never committed to the repo). Same origin so the download button works. + ordered_cache_behavior { + path_pattern = "/research.pdf" + target_origin_id = "s3-photos" + viewer_protocol_policy = "redirect-to-https" + allowed_methods = ["GET", "HEAD", "OPTIONS"] + cached_methods = ["GET", "HEAD"] + compress = true + + forwarded_values { + query_string = false + cookies { + forward = "none" + } + } + + response_headers_policy_id = aws_cloudfront_response_headers_policy.security.id + + min_ttl = 0 + default_ttl = 3600 + max_ttl = 86400 + } + # /graphql behaviour: proxy to API Gateway; no caching. ordered_cache_behavior { path_pattern = "/graphql" diff --git a/infra/photos.tf b/infra/photos.tf new file mode 100644 index 0000000..ad89be9 --- /dev/null +++ b/infra/photos.tf @@ -0,0 +1,11 @@ +# --------------------------------------------------------------------------- +# Travel photo pool — SHARED, account-global bucket. +# The bucket itself (and its policy) is created once in `bootstrap/`; the photos +# are identical across environments, so we never triplicate them. Here we only +# look it up, to wire it as a CloudFront origin (see frontend.tf, `/photos/*`). +# Populated out-of-band by `backend: PHOTO_S3_BUCKET=bba-photos npm run sync:photos`. +# --------------------------------------------------------------------------- + +data "aws_s3_bucket" "photos" { + bucket = "bba-photos-${local.account_id}" +} diff --git a/infra/variables.tf b/infra/variables.tf index 1f182d9..8b9b4ef 100644 --- a/infra/variables.tf +++ b/infra/variables.tf @@ -20,7 +20,6 @@ variable "sns_from_number" { } variable "alert_email" { - description = "Email address for the monthly billing alarm. Defaults to the owner address." + description = "Owner email for the billing alarm and research-download notifications. Set per environment in the gitignored envs/.tfvars — no default so a real address is never committed." type = string - default = "collinm.streitman@gmail.com" }