Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bcae35b63e | |||
| a93c0d57c8 | |||
| 77cb04bb8c | |||
| 271586625c | |||
| be13248bdd | |||
| 7ef3e0ccc6 | |||
| 7a51d8f6d4 |
@@ -26,3 +26,7 @@ simulator/static/review_audio.html
|
||||
|
||||
# Editor annotation/comment-thread metadata (not project content)
|
||||
.threads/
|
||||
|
||||
# Static build outputs (tools/build_static.py)
|
||||
/dist/
|
||||
/dist-media/
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# Deploying to benstull.art — Cloudflare Pages + R2
|
||||
|
||||
Publishes the simulator as a fully-static site: the frontend on **Cloudflare
|
||||
Pages** (`benstull.art`, app at `/human-experience-simulator`, apex redirects to
|
||||
it) and the video/audio on **R2** behind `static.benstull.art`. No origin server.
|
||||
|
||||
Design: `docs/superpowers/specs/2026-06-30-cloudflare-static-publish-design.md`.
|
||||
Plan: `docs/superpowers/plans/2026-06-30-cloudflare-static-publish.md`.
|
||||
|
||||
This project is **exempt from the flotilla/PPE/§9 pipeline** (operator-set) — it
|
||||
deploys directly to Cloudflare. Safety/hygiene rules still hold.
|
||||
|
||||
## Prerequisites (operator gestures — need Cloudflare auth)
|
||||
|
||||
`wrangler` is not installed in the dev box; the deploy runs from a machine with
|
||||
Cloudflare credentials.
|
||||
|
||||
```bash
|
||||
npm i -g wrangler
|
||||
wrangler login
|
||||
```
|
||||
|
||||
`benstull.art` is already a Cloudflare zone (no nameserver migration).
|
||||
|
||||
## 1. Build the artifacts
|
||||
|
||||
From the repo root (run as a MODULE — `tools/http.py` shadows stdlib `http` if run
|
||||
as a script):
|
||||
|
||||
```bash
|
||||
.venv/bin/python -m tools.build_static
|
||||
```
|
||||
|
||||
Produces:
|
||||
- `dist/` — Pages output: `dist/human-experience-simulator/` (frontend + baked
|
||||
`clips.json`/`ring.json`/`media-versions.json` + generated `config.js`) and a
|
||||
root `dist/_redirects` (apex → app path, and no-slash → slashed).
|
||||
- `dist-media/` — R2 upload tree, ~2.3 GB / 604 files, manifest-referenced only
|
||||
(clip bases + 154 transition morphs + 5 per-scale audio). No master/mezzanine
|
||||
sources.
|
||||
|
||||
## 2. R2 — bucket, CORS, custom domain, media
|
||||
|
||||
```bash
|
||||
wrangler r2 bucket create hef-media
|
||||
wrangler r2 bucket cors put hef-media --rules deploy/cloudflare/r2-cors.json
|
||||
wrangler r2 bucket sync ./dist-media r2://hef-media
|
||||
```
|
||||
|
||||
Then in the dashboard (R2 → `hef-media` → Settings):
|
||||
- **Custom domain:** add `static.benstull.art` (this is the `mediaBase` baked into
|
||||
`config.js`).
|
||||
- **CORS is load-bearing** — the WebGL dream shader taints without it. The policy
|
||||
in `r2-cors.json` allows `https://benstull.art` + `Range` (video scrubbing).
|
||||
- **Caching:** the media URLs are content-hash-versioned (`?v=<hash>`), so set the
|
||||
objects `Cache-Control: public, max-age=31536000, immutable` (a re-baked clip
|
||||
gets a new hash → new URL → cache busts cleanly).
|
||||
|
||||
If you change the media base, rebuild with `--media-base https://<host>/` so
|
||||
`config.js` matches.
|
||||
|
||||
## 3. Pages — deploy + domain + redirect
|
||||
|
||||
```bash
|
||||
wrangler pages project create human-experience-simulator
|
||||
wrangler pages deploy dist --project-name human-experience-simulator
|
||||
```
|
||||
|
||||
Then in the dashboard (Pages → project → Custom domains):
|
||||
- Bind **`benstull.art`** to the project.
|
||||
- The app serves at `benstull.art/human-experience-simulator/`; the generated
|
||||
`dist/_redirects` sends `/` and the no-slash form to it. (Alternatively, a
|
||||
zone-level **Redirect Rule** `benstull.art/` → `/human-experience-simulator`
|
||||
is the authoritative equivalent if you prefer not to ship `_redirects`.)
|
||||
|
||||
## 4. Verify before/after going live
|
||||
|
||||
```bash
|
||||
# CORS + Range on the media origin (after step 2)
|
||||
curl -sI -H "Origin: https://benstull.art" -H "Range: bytes=0-1" \
|
||||
https://static.benstull.art/<some>/base.mp4 | grep -iE "access-control-allow-origin|content-range|accept-ranges"
|
||||
```
|
||||
|
||||
Open `https://benstull.art/` → should redirect to
|
||||
`https://benstull.art/human-experience-simulator/`. Turn the **Feel** knob to max
|
||||
and confirm the dream effect renders (no `SecurityError` in the console — that
|
||||
would mean CORS is misconfigured and the GL texture is tainted). The local
|
||||
static-build E2E (`simulator/e2e/tests/static-build.spec.ts`) exercises this same
|
||||
cross-origin path before you ship.
|
||||
@@ -0,0 +1,9 @@
|
||||
[
|
||||
{
|
||||
"AllowedOrigins": ["https://benstull.art"],
|
||||
"AllowedMethods": ["GET", "HEAD"],
|
||||
"AllowedHeaders": ["Range", "Content-Type"],
|
||||
"ExposeHeaders": ["Content-Length", "Content-Range", "ETag", "Accept-Ranges"],
|
||||
"MaxAgeSeconds": 86400
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,706 @@
|
||||
# Cloudflare Static Publish — Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Publish the simulator as a fully-static site (no origin server) to `benstull.art/human-experience-simulator` on Cloudflare Pages, with media on R2.
|
||||
|
||||
**Architecture:** Port the only live server logic (`/api/alteration`, the delta=0 random pick) to client JS; serve the read-APIs as baked JSON; point media at a configurable R2 base with CORS; keep the existing graduated prefetch. A Python build script emits `dist/` (Pages) + a media sync tree (R2). The dev FastAPI server stays for localhost/authoring.
|
||||
|
||||
**Tech Stack:** Vanilla JS (UMD modules, `node --test`), Python 3 build script (imports existing `simulator`/`player` builders), Playwright E2E, `wrangler` (Pages + R2), Cloudflare redirect rule.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- **Path:** app served at `/human-experience-simulator`; apex `benstull.art` **redirects** there.
|
||||
- **Media base:** `https://static.benstull.art/` (R2 custom domain), public bucket.
|
||||
- **CORS is load-bearing:** R2 must send `Access-Control-Allow-Origin: https://benstull.art`; `<video>`/`<audio>` carry `crossOrigin="anonymous"` — else the WebGL dream shader taints.
|
||||
- **Served media = manifest-referenced only:** `base.mp4` clip bases + 154 transition morphs + 10 `.mp3`. NEVER sync `master.mp4`/`mezzanine.mp4`.
|
||||
- **Versioning preserved:** keep the `?v=<hash>` query; set those objects `Cache-Control: public, max-age=31536000, immutable` on the CDN.
|
||||
- **No new runtime:** no Pages Functions / Worker; no Service Worker.
|
||||
- **Project is exempt from flotilla/PPE/§9** (operator-set) — deploy directly to Cloudflare. Safety/hygiene rules (git-ssh, branch→PR, secrets) still hold.
|
||||
- **Module idiom:** UMD — `(function(root,factory){ if (module?.exports) module.exports=factory(); else root.HEFx=factory(); })(...)` — matching `simulator/static/scrub.js`.
|
||||
- **JS tests run:** `node --test simulator/unit`. **Python tests run:** `.venv/bin/python -m pytest`.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Client-side alteration engine (`HEFAlteration`)
|
||||
|
||||
Port `player/alteration.py::plan_alteration` (+ `render_plan_to_dict`) and `player/audio.py::resolve_visual`/`resolve_audio` to a pure UMD JS module, producing byte-for-byte the same shape `/api/alteration` returns. Calibration is always unity (`DEFAULT_CALIBRATION`; the client never sends one — `app.js:619`).
|
||||
|
||||
**Files:**
|
||||
- Create: `simulator/static/alteration.js`
|
||||
- Test: `simulator/unit/alteration.test.js`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces (browser global `HEFAlteration`, also `module.exports`):
|
||||
- `plan(controls)` → `{ grade:{tone}, overlay:{level,intensity}, affect:{strength,intensity}, dream:{strength,intensity}, is_identity }`
|
||||
- `renderAudio(source, scaleAudio, mediaBase)` → `{ source, url, altitude_coupled }`
|
||||
- `alteration(controls, scaleAudio, mediaBase)` → `{ plan, render:{ video:{shown}, audio:{source,url,altitude_coupled} } }` (the `/api/alteration` response)
|
||||
- `controls` shape (from `app.js:595` `controls()`): `{ visual:"on"|"off", audio:"soundtrack"|"off", left:int, right:int, dark:int, light:int }`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```js
|
||||
// simulator/unit/alteration.test.js
|
||||
"use strict";
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const A = require("../static/alteration.js");
|
||||
|
||||
const c = (o) => ({ visual: "on", audio: "off", left: 0, right: 0, dark: 0, light: 0, ...o });
|
||||
|
||||
test("identity at zero knobs", () => {
|
||||
const p = A.plan(c({}));
|
||||
assert.equal(p.grade.tone, 0);
|
||||
assert.equal(p.overlay.level, 0);
|
||||
assert.equal(p.dream.strength, 0);
|
||||
assert.equal(p.is_identity, true);
|
||||
});
|
||||
|
||||
test("mood tone is signed (light - dark)/KNOB_MAX, clamped", () => {
|
||||
assert.equal(A.plan(c({ light: 4 })).grade.tone, 1); // full light
|
||||
assert.equal(A.plan(c({ dark: 4 })).grade.tone, -1); // full dark
|
||||
assert.equal(A.plan(c({ light: 2 })).grade.tone, 0.5);
|
||||
});
|
||||
|
||||
test("left drives overlay level + intensity; right drives dream + affect", () => {
|
||||
const p = A.plan(c({ left: 2, right: 4 }));
|
||||
assert.equal(p.overlay.level, 2);
|
||||
assert.equal(p.overlay.intensity, 0.5);
|
||||
assert.equal(p.dream.strength, 4);
|
||||
assert.equal(p.dream.intensity, 1);
|
||||
assert.equal(p.affect.strength, 4);
|
||||
assert.equal(p.affect.intensity, 1);
|
||||
assert.equal(p.is_identity, false);
|
||||
});
|
||||
|
||||
test("renderAudio: off → null, no coupling", () => {
|
||||
assert.deepEqual(A.renderAudio("off", "cosmos.mp3", "https://x/"),
|
||||
{ source: "off", url: null, altitude_coupled: false });
|
||||
});
|
||||
|
||||
test("renderAudio: soundtrack → mediaBase audio url, coupled", () => {
|
||||
assert.deepEqual(A.renderAudio("soundtrack", "cosmos.mp3", "https://x/"),
|
||||
{ source: "soundtrack", url: "https://x/audio/cosmos.mp3", altitude_coupled: true });
|
||||
// no scale audio → null url but still coupled
|
||||
assert.deepEqual(A.renderAudio("soundtrack", "", "https://x/"),
|
||||
{ source: "soundtrack", url: null, altitude_coupled: true });
|
||||
});
|
||||
|
||||
test("alteration() composes plan + render with video.shown from visual", () => {
|
||||
const r = A.alteration(c({ visual: "off", audio: "soundtrack", left: 1 }), "reef.mp3", "https://x/");
|
||||
assert.equal(r.render.video.shown, false);
|
||||
assert.equal(r.render.audio.url, "https://x/audio/reef.mp3");
|
||||
assert.equal(r.plan.overlay.level, 1);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `node --test simulator/unit/alteration.test.js`
|
||||
Expected: FAIL — `Cannot find module '../static/alteration.js'`.
|
||||
|
||||
- [ ] **Step 3: Write the implementation**
|
||||
|
||||
```js
|
||||
// simulator/static/alteration.js
|
||||
// Client-side port of player/alteration.py + player/audio.py (the alteration
|
||||
// engine). Replaces the live POST /api/alteration in the static build — pure math,
|
||||
// unity calibration. UMD so the browser gets `HEFAlteration` and node --test can
|
||||
// require() it. Keep IN SYNC with the Python (guarded by parity tests there).
|
||||
(function (root, factory) {
|
||||
const api = factory();
|
||||
if (typeof module !== "undefined" && module.exports) module.exports = api;
|
||||
else root.HEFAlteration = api;
|
||||
})(typeof self !== "undefined" ? self : this, function () {
|
||||
"use strict";
|
||||
const KNOB_MAX = 4; // player/alteration.py:25
|
||||
const clamp = (x, lo, hi) => Math.max(lo, Math.min(hi, x));
|
||||
|
||||
function plan(c) {
|
||||
const tone = clamp((c.light - c.dark) / KNOB_MAX, -1, 1);
|
||||
const overlayIntensity = clamp(c.left / KNOB_MAX, 0, 1);
|
||||
const dreamIntensity = clamp(c.right / KNOB_MAX, 0, 1);
|
||||
const affectIntensity = clamp(c.right / KNOB_MAX, 0, 1); // affect uses overlay_gain too
|
||||
const is_identity = tone === 0 && c.left === 0 && c.right === 0;
|
||||
return {
|
||||
grade: { tone },
|
||||
overlay: { level: c.left, intensity: overlayIntensity },
|
||||
affect: { strength: c.right, intensity: affectIntensity },
|
||||
dream: { strength: c.right, intensity: dreamIntensity },
|
||||
is_identity,
|
||||
};
|
||||
}
|
||||
|
||||
function renderAudio(source, scaleAudio, mediaBase) {
|
||||
if (source === "off") return { source: "off", url: null, altitude_coupled: false };
|
||||
// soundtrack — couple to the current altitude's asset
|
||||
const url = scaleAudio ? mediaBase + "audio/" + scaleAudio : null;
|
||||
return { source: "soundtrack", url, altitude_coupled: true };
|
||||
}
|
||||
|
||||
function alteration(controls, scaleAudio, mediaBase) {
|
||||
return {
|
||||
plan: plan(controls),
|
||||
render: {
|
||||
video: { shown: controls.visual === "on" },
|
||||
audio: renderAudio(controls.audio, scaleAudio, mediaBase),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return { plan, renderAudio, alteration, KNOB_MAX };
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run tests to verify they pass**
|
||||
|
||||
Run: `node --test simulator/unit/alteration.test.js`
|
||||
Expected: PASS (6 tests).
|
||||
|
||||
- [ ] **Step 5: Add a Python parity test (guards JS↔Python drift)**
|
||||
|
||||
Create `tests/test_alteration_js_parity.py`:
|
||||
|
||||
```python
|
||||
"""The static build reimplements plan_alteration/resolve_audio in JS
|
||||
(simulator/static/alteration.js). This pins the numeric contract so the Python
|
||||
and JS cannot silently diverge — if you change the engine, change both."""
|
||||
from hef.selection import Coordinate
|
||||
from player.alteration import plan_alteration, render_plan_to_dict
|
||||
from player.audio import resolve_audio, resolve_visual
|
||||
|
||||
|
||||
def test_engine_contract_matches_js_expectations():
|
||||
# mirrors the cases asserted in simulator/unit/alteration.test.js
|
||||
p = render_plan_to_dict(plan_alteration(Coordinate(left=2, right=4, dark=0, light=0)))
|
||||
assert p["overlay"] == {"level": 2, "intensity": 0.5}
|
||||
assert p["dream"] == {"strength": 4, "intensity": 1.0}
|
||||
assert p["affect"] == {"strength": 4, "intensity": 1.0}
|
||||
assert render_plan_to_dict(plan_alteration(Coordinate(0, 0, 0, 4)))["grade"]["tone"] == 1.0
|
||||
assert render_plan_to_dict(plan_alteration(Coordinate(0, 0, 4, 0)))["grade"]["tone"] == -1.0
|
||||
assert resolve_visual("off") is False
|
||||
a = resolve_audio("soundtrack", scale_audio="cosmos.mp3")
|
||||
assert a.url == "/media/audio/cosmos.mp3" and a.altitude_coupled is True
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Run + commit**
|
||||
|
||||
Run: `node --test simulator/unit/alteration.test.js && .venv/bin/python -m pytest tests/test_alteration_js_parity.py -q`
|
||||
Expected: all PASS.
|
||||
|
||||
```bash
|
||||
git add simulator/static/alteration.js simulator/unit/alteration.test.js tests/test_alteration_js_parity.py
|
||||
git commit -m "feat(static): client-side alteration engine (port of player.alteration/audio)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Static config + boot rewiring in `app.js`
|
||||
|
||||
Introduce a runtime config the build injects, then make `app.js` (a) read media from a configurable base, (b) boot from baked JSON in static mode, (c) pick pool members client-side, (d) compute alteration locally, (e) tag media elements with `crossOrigin`, (f) skip the dev-version poll in static mode. All changes degrade to today's behavior when config is absent (dev server unaffected).
|
||||
|
||||
**Files:**
|
||||
- Create: `simulator/static/config.js` (dev default; the build overwrites it in `dist/`)
|
||||
- Modify: `simulator/static/app.js` (boot `loadData` ~59, `pickRandomMember` ~87, `mediaNetUrl` ~123, alteration fetch ~617, dev poll ~1041, video/audio element creation)
|
||||
- Modify: `simulator/static/index.html:111` (load `config.js` before `app.js`)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `HEFAlteration` (Task 1).
|
||||
- Produces: global `HEF_CONFIG = { mediaBase: string, static: boolean }`. Dev default `{ mediaBase: "/media/", static: false }`.
|
||||
|
||||
- [ ] **Step 1: Create the dev-default config and load it**
|
||||
|
||||
`simulator/static/config.js`:
|
||||
```js
|
||||
// Runtime config. This dev default serves media from the local FastAPI /media
|
||||
// mount and uses the live API. The static build (tools/build_static.py) OVERWRITES
|
||||
// this file in dist/ with { mediaBase: "https://static.benstull.art/", static: true }.
|
||||
window.HEF_CONFIG = { mediaBase: "/media/", static: false };
|
||||
```
|
||||
|
||||
In `simulator/static/index.html`, add before `app.js` (line 111 area):
|
||||
```html
|
||||
<script src="/config.js"></script>
|
||||
```
|
||||
(Place it before `<script src="/app.js"></script>`.)
|
||||
|
||||
- [ ] **Step 2: Media base — modify `mediaNetUrl` (`app.js:123`)**
|
||||
|
||||
Replace:
|
||||
```js
|
||||
function mediaNetUrl(file) { const v = mediaVersions[file]; return "/media/" + file + (v ? "?v=" + v : ""); }
|
||||
```
|
||||
with:
|
||||
```js
|
||||
function mediaNetUrl(file) {
|
||||
const base = (window.HEF_CONFIG && window.HEF_CONFIG.mediaBase) || "/media/";
|
||||
const v = mediaVersions[file];
|
||||
return base + file + (v ? "?v=" + v : "");
|
||||
}
|
||||
```
|
||||
Note: audio-layer absolute urls already begin with the configured base — keep the existing `file.startsWith("/media/")` guard in `mediaUrl`, and ALSO short-circuit absolute `http` urls:
|
||||
```js
|
||||
function mediaUrl(file) {
|
||||
if (/^https?:\/\//.test(file) || file.startsWith("/media/")) return file;
|
||||
return mediaBlobs[file] || mediaNetUrl(file);
|
||||
}
|
||||
```
|
||||
And in `HEFAlteration.alteration(...)` we pass `mediaBase`, so the audio `url` it returns is already absolute (R2) in static mode and `/media/...` in dev.
|
||||
|
||||
- [ ] **Step 3: Boot from baked JSON — modify `loadData` (`app.js:59`)**
|
||||
|
||||
Replace the three `fetch("/api/...")` calls with a base that depends on mode:
|
||||
```js
|
||||
async function loadData() {
|
||||
const api = (window.HEF_CONFIG && window.HEF_CONFIG.static)
|
||||
? { clips: "./clips.json", versions: "./media-versions.json", ring: "./ring.json" }
|
||||
: { clips: "/api/clips", versions: "/api/media-versions", ring: "/api/ring" };
|
||||
const clips = (await (await fetch(api.clips)).json()).clips || [];
|
||||
clipsById = Object.fromEntries(clips.map((c) => [c.id, c]));
|
||||
try { mediaVersions = (await (await fetch(api.versions)).json()).versions || {}; }
|
||||
catch (_) { mediaVersions = {}; }
|
||||
const r = await fetch(api.ring);
|
||||
serverRing = r.ok;
|
||||
ring = r.ok ? await r.json() : null;
|
||||
// ...rest unchanged (fallback ring synth, morphByPair build, ringIndex = 0)
|
||||
}
|
||||
```
|
||||
(`clips.json` mirrors `{clips:[...]}`, `ring.json` mirrors `ring_to_dict(...)`, `media-versions.json` mirrors `{versions:{...}}` — Task 3 bakes them.)
|
||||
|
||||
- [ ] **Step 4: Client-side pick — modify `pickRandomMember` (`app.js:87`)**
|
||||
|
||||
The delta=0 server pick becomes a uniform client-side pool pick (matches `hef`'s `pick_clip_id`):
|
||||
```js
|
||||
async function pickRandomMember() {
|
||||
const scale = ring && ring.scales[ringIndex];
|
||||
if (!scale) return null;
|
||||
const pool = (scale.pool && scale.pool.length) ? scale.pool : [{ clip_id: scale.clip_id }];
|
||||
return pool[Math.floor(Math.random() * pool.length)].clip_id;
|
||||
}
|
||||
```
|
||||
(Drag/scroll navigation already resolves picks + morphs client-side via `scrub.js`; this removes the last `/api/ring/advance` dependency. `serverRing` stays as the "real ring vs synthesized" flag.)
|
||||
|
||||
- [ ] **Step 5: Local alteration — modify the fetch at `app.js:617`**
|
||||
|
||||
Replace:
|
||||
```js
|
||||
const resp = await fetch("/api/alteration", { /* ... */ body: JSON.stringify({ controls: controls(), altitude_index: ringIndex }) });
|
||||
const data = await resp.json();
|
||||
```
|
||||
with a mode-aware path that reuses the engine:
|
||||
```js
|
||||
let data;
|
||||
if (window.HEF_CONFIG && window.HEF_CONFIG.static) {
|
||||
const scale = ring && ring.scales[ringIndex];
|
||||
const scaleAudio = (scale && scale.audio) || "";
|
||||
const base = window.HEF_CONFIG.mediaBase;
|
||||
data = HEFAlteration.alteration(controls(), scaleAudio, base);
|
||||
} else {
|
||||
const resp = await fetch("/api/alteration", {
|
||||
method: "POST", headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ controls: controls(), altitude_index: ringIndex }),
|
||||
});
|
||||
data = await resp.json();
|
||||
}
|
||||
```
|
||||
**Prerequisite:** `ring.json` must expose each scale's `audio` field. Verify `ring_to_dict` includes it; if not, that is a Task 3 bake concern (add it). The rest of the function (`data.render`, `data.plan.*`) is unchanged.
|
||||
|
||||
- [ ] **Step 6: crossOrigin on media elements (CORS for WebGL)**
|
||||
|
||||
Find where `<video>` and `<audio>` elements are created/used in `app.js` (the double-buffered `#vid`/loop videos and the audio layer). Set `crossOrigin` BEFORE assigning `src`:
|
||||
```js
|
||||
videoEl.crossOrigin = "anonymous";
|
||||
```
|
||||
Apply to: the visible video, the preload/double-buffer video, and the `<audio>` element. (In dev, same-origin `/media/` ignores it; in static it prevents GL-texture taint and lets ranged `fetch()` succeed under CORS.) Also set `crossorigin="anonymous"` on any static `<video>`/`<audio>` in `index.html`.
|
||||
|
||||
- [ ] **Step 7: Skip the dev-version poll in static mode (`app.js:1041`)**
|
||||
|
||||
Wrap the `/dev/version` poller so it no-ops when `HEF_CONFIG.static` (there is no dev server):
|
||||
```js
|
||||
if (!(window.HEF_CONFIG && window.HEF_CONFIG.static)) {
|
||||
// existing setInterval(... fetch("/dev/version") ...) poll
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 8: Manual dev smoke (no regression)**
|
||||
|
||||
Run (this env has only `python3`):
|
||||
```bash
|
||||
.venv/bin/python -m uvicorn simulator.app:app --port 8000
|
||||
```
|
||||
Open `http://localhost:8000/`, confirm boot, altitude changes, dream/overlay still work (dev mode: `HEF_CONFIG.static=false`, behavior identical to before).
|
||||
|
||||
- [ ] **Step 9: Commit**
|
||||
|
||||
```bash
|
||||
git add simulator/static/config.js simulator/static/app.js simulator/static/index.html
|
||||
git commit -m "feat(static): config-driven media base, baked-JSON boot, client pick/alteration, crossOrigin"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Static build script → `dist/` + media sync tree
|
||||
|
||||
A Python script that produces the deployable `dist/` (frontend + baked JSON + static config) and a separate media sync tree containing ONLY manifest-referenced files. Reuses the live app's loaders so the baked JSON is identical to the API output.
|
||||
|
||||
**Files:**
|
||||
- Create: `tools/build_static.py`
|
||||
- Create: `tests/test_build_static.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `simulator.app.create_app` (to render the same JSON the API serves) OR the underlying loaders (`simulator.clips`/`build_pool_manifest` + `player`/`hef`). Prefer driving `create_app(manifest)` via `fastapi.testclient.TestClient` so the bake is byte-identical to the API.
|
||||
- Produces: `build_static(out_dir, media_out, *, media_base, app_path) -> dict` (counts), and a CLI.
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```python
|
||||
# tests/test_build_static.py
|
||||
import json
|
||||
from pathlib import Path
|
||||
from tools.build_static import build_static
|
||||
|
||||
def test_build_emits_frontend_baked_json_and_only_referenced_media(tmp_path):
|
||||
out = tmp_path / "dist"
|
||||
media = tmp_path / "media"
|
||||
result = build_static(out, media, media_base="https://static.benstull.art/",
|
||||
app_path="/human-experience-simulator")
|
||||
|
||||
# frontend present, dev/author surfaces excluded
|
||||
assert (out / "index.html").exists()
|
||||
assert (out / "app.js").exists()
|
||||
assert (out / "scrub.js").exists()
|
||||
assert (out / "alteration.js").exists()
|
||||
assert (out / "config.js").exists()
|
||||
assert not (out / "author.html").exists()
|
||||
assert not list(out.glob("review*.html"))
|
||||
|
||||
# baked JSON matches the API shape
|
||||
clips = json.loads((out / "clips.json").read_text())
|
||||
assert "clips" in clips and clips["clips"]
|
||||
ring = json.loads((out / "ring.json").read_text())
|
||||
assert "scales" in ring and "transitions" in ring
|
||||
assert all("audio" in s for s in ring["scales"]) # needed by client alteration
|
||||
versions = json.loads((out / "media-versions.json").read_text())
|
||||
assert "versions" in versions
|
||||
|
||||
# config.js points at R2 + static mode
|
||||
cfg = (out / "config.js").read_text()
|
||||
assert "https://static.benstull.art/" in cfg and "static: true" in cfg
|
||||
|
||||
# media tree holds ONLY referenced files — no masters/mezzanines
|
||||
synced = {p.name for p in media.rglob("*.mp4")}
|
||||
assert not any(n in ("master.mp4", "mezzanine.mp4") for n in synced)
|
||||
# every versions key exists in the media tree
|
||||
for f in versions["versions"]:
|
||||
assert (media / f).exists(), f"missing synced media: {f}"
|
||||
assert result["media_files"] == len(list(media.rglob("*")))
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails**
|
||||
|
||||
Run: `.venv/bin/python -m pytest tests/test_build_static.py -q`
|
||||
Expected: FAIL — `ModuleNotFoundError: tools.build_static`.
|
||||
|
||||
- [ ] **Step 3: Implement the build script**
|
||||
|
||||
```python
|
||||
# tools/build_static.py
|
||||
"""Build the fully-static deployable for Cloudflare (Pages + R2).
|
||||
|
||||
Emits `out_dir/` (frontend + baked API JSON + static config.js) and a `media_out/`
|
||||
sync tree containing ONLY the files the manifest references (clip bases + transition
|
||||
morphs + audio) — never the master/mezzanine pipeline sources. The baked JSON is
|
||||
produced through the real app (TestClient) so it is byte-identical to the API.
|
||||
|
||||
Cloudflare-side steps (R2 sync, Pages deploy, CORS, redirect) live in
|
||||
deploy/cloudflare/ — this script only produces artifacts.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from simulator.app import create_app, MEDIA_DIR
|
||||
|
||||
STATIC = Path(__file__).resolve().parent.parent / "simulator" / "static"
|
||||
# Frontend files that ship; everything else in static/ (author*, review*) is dev-only.
|
||||
PUBLIC_ASSETS = ["index.html", "app.js", "scrub.js", "i18n.js", "alteration.js", "style.css"]
|
||||
|
||||
|
||||
def _bake_api(out: Path) -> dict:
|
||||
app = create_app()
|
||||
client = TestClient(app)
|
||||
clips = client.get("/api/clips").json()
|
||||
ring = client.get("/api/ring").json()
|
||||
versions = client.get("/api/media-versions").json()
|
||||
(out / "clips.json").write_text(json.dumps(clips, ensure_ascii=False))
|
||||
(out / "ring.json").write_text(json.dumps(ring, ensure_ascii=False))
|
||||
(out / "media-versions.json").write_text(json.dumps(versions, ensure_ascii=False))
|
||||
return versions["versions"]
|
||||
|
||||
|
||||
def _write_config(out: Path, media_base: str) -> None:
|
||||
(out / "config.js").write_text(
|
||||
"// GENERATED by tools/build_static.py — do not edit in dist/.\n"
|
||||
f'window.HEF_CONFIG = {{ mediaBase: "{media_base}", static: true }};\n'
|
||||
)
|
||||
|
||||
|
||||
def build_static(out_dir, media_out, *, media_base: str, app_path: str) -> dict:
|
||||
out = Path(out_dir)
|
||||
media = Path(media_out)
|
||||
for d in (out, media):
|
||||
if d.exists():
|
||||
shutil.rmtree(d)
|
||||
d.mkdir(parents=True)
|
||||
|
||||
for name in PUBLIC_ASSETS:
|
||||
src = STATIC / name
|
||||
if src.exists():
|
||||
shutil.copy2(src, out / name)
|
||||
|
||||
versions = _bake_api(out)
|
||||
_write_config(out, media_base)
|
||||
|
||||
# Sync ONLY referenced media (versions covers bases + morphs); add audio explicitly.
|
||||
referenced = set(versions.keys())
|
||||
ring = json.loads((out / "ring.json").read_text())
|
||||
for s in ring.get("scales", []):
|
||||
if s.get("audio"):
|
||||
referenced.add(f"audio/{s['audio']}")
|
||||
n = 0
|
||||
for rel in sorted(referenced):
|
||||
src = MEDIA_DIR / rel
|
||||
if not src.exists():
|
||||
raise FileNotFoundError(f"referenced media missing on disk: {rel}")
|
||||
dst = media / rel
|
||||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(src, dst)
|
||||
n += 1
|
||||
|
||||
return {"out": str(out), "media": str(media), "media_files": n, "app_path": app_path}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--out", default="dist")
|
||||
ap.add_argument("--media-out", default="dist-media")
|
||||
ap.add_argument("--media-base", default="https://static.benstull.art/")
|
||||
ap.add_argument("--app-path", default="/human-experience-simulator")
|
||||
a = ap.parse_args()
|
||||
r = build_static(a.out, a.media_out, media_base=a.media_base, app_path=a.app_path)
|
||||
print(json.dumps(r, indent=2))
|
||||
```
|
||||
|
||||
**Verify before running the test:** confirm `simulator/app.py` exports `MEDIA_DIR` and that `ring_to_dict` includes `audio` per scale. If `audio` is absent from `ring.json`, add it to `ring_to_dict` (small change in `simulator/app.py` / the ring serializer) and add a Python test asserting `"audio" in scale dict`.
|
||||
|
||||
- [ ] **Step 4: Run the test to verify it passes**
|
||||
|
||||
Run: `.venv/bin/python -m pytest tests/test_build_static.py -q`
|
||||
Expected: PASS. (Test asserts media tree excludes masters and includes every versioned file + audio.)
|
||||
|
||||
- [ ] **Step 5: Real build smoke**
|
||||
|
||||
Run: `.venv/bin/python tools/build_static.py`
|
||||
Expected: prints counts; `dist/` has the frontend + 3 JSON + `config.js`; `dist-media/` ≈ ~2 GB, no `master.mp4`/`mezzanine.mp4`.
|
||||
|
||||
- [ ] **Step 6: Commit** (do NOT commit `dist/`/`dist-media/` — add to `.gitignore`)
|
||||
|
||||
```bash
|
||||
printf '\n/dist/\n/dist-media/\n' >> .gitignore
|
||||
git add tools/build_static.py tests/test_build_static.py .gitignore simulator/app.py
|
||||
git commit -m "feat(static): build script — dist/ + manifest-only media sync tree, baked API JSON"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Cloudflare config artifacts + deploy runbook
|
||||
|
||||
Produce the version-controlled Cloudflare config (CORS policy, redirect, deploy commands). The actual deploy needs operator Cloudflare auth (`wrangler login` / API token) — `wrangler` is NOT installed here, so this task delivers artifacts + exact commands and the operator runs the authenticated steps.
|
||||
|
||||
**Files:**
|
||||
- Create: `deploy/cloudflare/README.md` (runbook)
|
||||
- Create: `deploy/cloudflare/r2-cors.json` (bucket CORS policy)
|
||||
- Create: `deploy/cloudflare/_redirects` (copied into `dist/` for the apex/path redirect, or documented as a dashboard Redirect Rule)
|
||||
|
||||
**Interfaces:** none (ops artifacts).
|
||||
|
||||
- [ ] **Step 1: CORS policy**
|
||||
|
||||
`deploy/cloudflare/r2-cors.json`:
|
||||
```json
|
||||
[
|
||||
{
|
||||
"AllowedOrigins": ["https://benstull.art"],
|
||||
"AllowedMethods": ["GET", "HEAD"],
|
||||
"AllowedHeaders": ["Range", "Content-Type"],
|
||||
"ExposeHeaders": ["Content-Length", "Content-Range", "ETag", "Accept-Ranges"],
|
||||
"MaxAgeSeconds": 86400
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Redirect artifact**
|
||||
|
||||
`deploy/cloudflare/_redirects` (Pages `_redirects` form — apex/root to the app path):
|
||||
```
|
||||
/ /human-experience-simulator 308
|
||||
```
|
||||
(If the app is deployed as a Pages project bound to `benstull.art`, also document a dashboard **Redirect Rule**: `benstull.art/` → `/human-experience-simulator` as the authoritative alternative.)
|
||||
|
||||
- [ ] **Step 3: Runbook**
|
||||
|
||||
`deploy/cloudflare/README.md` — exact operator commands (run after `tools/build_static.py`):
|
||||
```bash
|
||||
npm i -g wrangler
|
||||
wrangler login
|
||||
|
||||
wrangler r2 bucket create hef-media
|
||||
wrangler r2 bucket cors put hef-media --rules deploy/cloudflare/r2-cors.json
|
||||
# bind custom domain static.benstull.art to the bucket (dashboard: R2 > bucket > Settings > Custom Domains)
|
||||
# upload media (preserves keys):
|
||||
wrangler r2 bucket sync ./dist-media r2://hef-media
|
||||
|
||||
cp deploy/cloudflare/_redirects dist/_redirects
|
||||
wrangler pages project create human-experience-simulator
|
||||
wrangler pages deploy dist --project-name human-experience-simulator
|
||||
# bind benstull.art to the Pages project; serve at /human-experience-simulator
|
||||
# add the apex Redirect Rule if not using _redirects
|
||||
```
|
||||
Document: set the media objects' `Cache-Control: public, max-age=31536000, immutable` (sync flag or bucket lifecycle), and verify `wrangler r2 bucket sync` excludes nothing unexpected (the tree is already filtered by the build).
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add deploy/cloudflare/
|
||||
git commit -m "chore(static): Cloudflare deploy artifacts — R2 CORS, apex redirect, runbook"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: E2E against the static build
|
||||
|
||||
Verify the built `dist/` boots with **no `/api/*` server**, the dream shader survives cross-origin media (CORS, no taint), and scrub/morph/audio work. Serve `dist/` and the media from **two different origins** to exercise CORS the way R2 will.
|
||||
|
||||
**Files:**
|
||||
- Create: `simulator/e2e/tests/static-build.spec.ts`
|
||||
- Create: `simulator/e2e/serve-static.mjs` (tiny dual static server: app on one port, media w/ CORS on another)
|
||||
|
||||
**Interfaces:** consumes the `dist/` + `dist-media/` produced by Task 3.
|
||||
|
||||
- [ ] **Step 1: Dual static server with CORS**
|
||||
|
||||
`simulator/e2e/serve-static.mjs`:
|
||||
```js
|
||||
// Serves dist/ (app) and dist-media/ (media w/ CORS + Range) on two ports — a
|
||||
// local stand-in for Pages + R2, so the static-build E2E exercises cross-origin
|
||||
// media exactly as production will.
|
||||
import http from "node:http";
|
||||
import { createReadStream, statSync } from "node:fs";
|
||||
import { join, extname } from "node:path";
|
||||
|
||||
const TYPES = { ".html":"text/html", ".js":"text/javascript", ".json":"application/json",
|
||||
".css":"text/css", ".mp4":"video/mp4", ".mp3":"audio/mpeg" };
|
||||
|
||||
function serve(rootEnv, port, cors) {
|
||||
const root = process.env[rootEnv];
|
||||
http.createServer((req, res) => {
|
||||
if (cors) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Accept-Ranges", "bytes"); }
|
||||
let p = decodeURIComponent(req.url.split("?")[0]);
|
||||
if (p === "/") p = "/index.html";
|
||||
const file = join(root, p);
|
||||
try {
|
||||
const st = statSync(file);
|
||||
res.setHeader("Content-Type", TYPES[extname(file)] || "application/octet-stream");
|
||||
const range = req.headers.range; // honor Range for video scrub
|
||||
if (range && /^bytes=/.test(range)) {
|
||||
const [s, e] = range.replace("bytes=", "").split("-");
|
||||
const start = +s, end = e ? +e : st.size - 1;
|
||||
res.writeHead(206, { "Content-Range": `bytes ${start}-${end}/${st.size}`,
|
||||
"Content-Length": end - start + 1 });
|
||||
createReadStream(file, { start, end }).pipe(res);
|
||||
} else { res.writeHead(200, { "Content-Length": st.size }); createReadStream(file).pipe(res); }
|
||||
} catch { res.writeHead(404); res.end("nf"); }
|
||||
}).listen(port);
|
||||
}
|
||||
serve("DIST_DIR", 8077, false);
|
||||
serve("MEDIA_DIR_E2E", 8078, true);
|
||||
console.log("static app :8077 media(cors) :8078");
|
||||
```
|
||||
|
||||
- [ ] **Step 2: The spec**
|
||||
|
||||
`simulator/e2e/tests/static-build.spec.ts`:
|
||||
```ts
|
||||
import { test, expect } from "@playwright/test";
|
||||
|
||||
// Built dist/ is served on :8077; media (CORS) on :8078. The build's config.js
|
||||
// must be overridden to point media at :8078 for this run (see Step 3).
|
||||
test.use({ baseURL: "http://localhost:8077" });
|
||||
|
||||
test("boots fully static — no /api calls, ring + clips load from JSON", async ({ page }) => {
|
||||
const apiCalls: string[] = [];
|
||||
page.on("request", (r) => { if (r.url().includes("/api/")) apiCalls.push(r.url()); });
|
||||
await page.goto("/");
|
||||
await expect(page.locator("#vid")).toBeVisible({ timeout: 30_000 });
|
||||
expect(apiCalls, "no /api/* in static mode").toEqual([]);
|
||||
});
|
||||
|
||||
test("dream shader runs on cross-origin media without tainting the GL texture", async ({ page }) => {
|
||||
const errors: string[] = [];
|
||||
page.on("pageerror", (e) => errors.push(String(e)));
|
||||
await page.goto("/");
|
||||
// crank Right to engage the dream, let a few frames render
|
||||
await page.evaluate(() => { const r = document.getElementById("right") as HTMLInputElement; r.value = "4"; r.dispatchEvent(new Event("input", { bubbles: true })); });
|
||||
await page.waitForTimeout(2000);
|
||||
// a tainted texture throws SecurityError on the GL draw; assert none surfaced
|
||||
expect(errors.filter((e) => /SecurityError|tainted|cross-origin/i.test(e))).toEqual([]);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Wire the run (build → point media → serve → test)**
|
||||
|
||||
Document in `simulator/e2e/README.md` and use a throwaway config for the run:
|
||||
```bash
|
||||
.venv/bin/python tools/build_static.py --media-base http://localhost:8078/
|
||||
DIST_DIR=$PWD/dist MEDIA_DIR_E2E=$PWD/dist-media node simulator/e2e/serve-static.mjs &
|
||||
cd simulator/e2e && npx playwright test static-build.spec.ts
|
||||
```
|
||||
(Building with `--media-base http://localhost:8078/` writes that base into `dist/config.js`, so the app fetches media cross-origin from the CORS server — the production CORS path, locally.)
|
||||
|
||||
- [ ] **Step 4: Run the E2E**
|
||||
|
||||
Expected: both tests PASS — zero `/api/*` requests; no `SecurityError` from the dream shader.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add simulator/e2e/serve-static.mjs simulator/e2e/tests/static-build.spec.ts simulator/e2e/README.md
|
||||
git commit -m "test(static): E2E — static boot with no API + dream shader survives cross-origin CORS"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
**Spec coverage:**
|
||||
- No-origin static frontend → Tasks 2, 3. ✅
|
||||
- Media on R2 + CORS + crossOrigin → Tasks 2 (crossOrigin), 4 (CORS policy). ✅
|
||||
- Bake read-APIs to JSON → Task 3. ✅
|
||||
- Random pick client-side → Task 2 Step 4. ✅
|
||||
- `/api/alteration` client-side → Tasks 1, 2 Step 5. ✅
|
||||
- Served = manifest-only (no masters) → Task 3 (test asserts). ✅
|
||||
- `?v=` versioning + immutable caching → Task 2 (preserved), Task 4 (cache header). ✅
|
||||
- Path `/human-experience-simulator` + apex redirect → Task 4. ✅
|
||||
- E2E against static build (no API, dream survives CORS) → Task 5. ✅
|
||||
- Prefetch unchanged → no task needed (only `mediaNetUrl` base changes, Task 2 Step 2). ✅
|
||||
|
||||
**Placeholder scan:** none — every code step has full content.
|
||||
|
||||
**Type consistency:** `HEF_CONFIG.{mediaBase,static}`, `HEFAlteration.{plan,renderAudio,alteration}`, `controls()` shape, and `build_static(out, media_out, *, media_base, app_path)` are used identically across tasks. ✅
|
||||
|
||||
**Open verify-at-execution items (flagged, not placeholders):** (a) confirm `ring_to_dict` emits per-scale `audio` — add it if missing (Task 3 Step 3); (b) confirm `simulator/app.py` exports `MEDIA_DIR` (used by the build); (c) locate the exact video/audio element creation sites for `crossOrigin` (Task 2 Step 6).
|
||||
@@ -0,0 +1,149 @@
|
||||
# Publish to benstull.art — Cloudflare Pages + R2 (fully static) — Design
|
||||
|
||||
**Status:** Approved (brainstormed 2026-06-30). Ready for writing-plans.
|
||||
|
||||
## Goal
|
||||
|
||||
Publish the Human Experience **Simulator** publicly at
|
||||
`benstull.art/human-experience-simulator`, hosted on Cloudflare, with the
|
||||
`benstull.art` apex **redirecting** to that path for now.
|
||||
|
||||
The simulator today is a FastAPI server (`simulator/app.py`) serving ~92 KB of
|
||||
static frontend plus video/audio from a local `/media/` mount. The public target
|
||||
has **no origin server**: the frontend is **fully static** on **Cloudflare Pages**,
|
||||
and the video/audio lives in a public **R2** bucket behind a custom domain. Nothing
|
||||
runs, nothing to patch, nothing to keep alive. The existing GCE/flotilla deployment
|
||||
stays as the dev/authoring surface — this is a *new, additional* public target, not
|
||||
a migration of the dev box.
|
||||
|
||||
## Why this shape (the constraint that forces it)
|
||||
|
||||
Cloudflare Pages has a **hard 25 MiB per-file limit** (and 20,000 files free /
|
||||
100,000 paid; no total-size cap). The repo carries **3.9 GB across 663 mp4 + 10
|
||||
mp3**, with individual files up to ~117 MB. Pages cannot host the video. R2 has no
|
||||
relevant per-file limit, **free egress**, and ~2 GB of served media sits inside its
|
||||
10 GB-month free tier (≈ free). So: **Pages for the ~92 KB frontend, R2 for the
|
||||
media.** (Verified against Cloudflare docs 2026-06-30.)
|
||||
|
||||
## Decisions (locked)
|
||||
|
||||
- **Path:** experience at `/human-experience-simulator`; **apex `benstull.art`
|
||||
redirects** there (302/308 redirect, not a rewrite).
|
||||
- **Fully static**, no Pages Functions / Worker — the dynamic logic is trivial
|
||||
client-side (see Component 2).
|
||||
- **Media on R2** at a custom domain `static.benstull.art` (public bucket binding).
|
||||
- **No cross-session cache** (no Service Worker) for now — the existing in-memory
|
||||
graduated prefetch is sufficient. Deferred, not rejected.
|
||||
- **benstull.art is already a Cloudflare zone** — no nameserver migration needed.
|
||||
- **Operates outside Wiggleverse deployment patterns (standing, operator-set):**
|
||||
this **entire project** is exempt from the typical Wiggleverse deployment
|
||||
conventions — `flotilla-only-provisioning`, the `ppe-before-prod` GCE pipeline,
|
||||
and the §9 prod-promotion gate do not bind it. It is a static public art target
|
||||
hosted directly on Cloudflare. (Safety/hygiene rules — `git-ssh`, the secrets
|
||||
rule, branch→PR — still apply; only the *deployment* machinery is out of scope.)
|
||||
|
||||
## Served media — what actually ships
|
||||
|
||||
The on-disk 3.9 GB is mostly **pipeline source**, not served bytes. The manifest
|
||||
(`simulator/sample_media/manifest.json`) references only **`base.mp4`** for clips —
|
||||
the `master.mp4` (20 files, incl. the 91–117 MB `coast_birdrock` set) and
|
||||
`mezzanine.mp4` proxies are build inputs that **never reach the browser**. The
|
||||
served set is:
|
||||
|
||||
- the `base.mp4` clip bases (one per pool member),
|
||||
- the **154 transition morphs** (`*__*.mp4` / `*.rev.mp4`, ~1.6 GB, each already
|
||||
kept < 25 MB),
|
||||
- the **10 audio `.mp3`** layers (~12 MB).
|
||||
|
||||
≈ **~2 GB** to R2. The build computes the exact set by walking the manifest — it
|
||||
**must not** blindly sync `sample_media/` (that would push the masters too).
|
||||
|
||||
## Components
|
||||
|
||||
### 1. Static build (`tools/` — new build script → `dist/`)
|
||||
|
||||
Replaces the server with baked artifacts:
|
||||
|
||||
- **Bake the read endpoints to static JSON** the page loads at boot, replacing the
|
||||
fetches to `/api/clips`, `/api/ring`, `/api/media-versions`:
|
||||
- `clips.json` ← `GET /api/clips`
|
||||
- `ring.json` ← `GET /api/ring`
|
||||
- `media-versions.json` ← `GET /api/media-versions` (file → content-hash)
|
||||
Generate these by importing the existing builders (`simulator/clips.py`,
|
||||
`build_pool_manifest.py`) directly — **single source of truth, no hand-copy**.
|
||||
- **Copy only manifest-referenced media** into the R2 sync tree (see Served media).
|
||||
- **Emit the public frontend** (`index.html`, `app.js`, `scrub.js`, `style.css`,
|
||||
`i18n.js`) into `dist/`, **excluding** author/review/dev surfaces
|
||||
(`author.*`, `review*.html`, `/api/author/*`).
|
||||
- Output is deterministic and re-runnable; checked by the integration test below.
|
||||
|
||||
### 2. Client-side dynamic logic (`simulator/static/app.js`)
|
||||
|
||||
The only server-computed behavior is the **random clip pick on landing**
|
||||
(`POST /api/ring/advance`). The scrub work (PR #28, spec 2026-06-27) **already
|
||||
moved the pick client-side** for drag/scroll gestures via the pool + `morphByPair`
|
||||
lookup — so the remaining task is to ensure **every** entry path (initial load, tap-
|
||||
label jumps) uses the client-side pick and that **no code path depends on a live
|
||||
`/api/*` call**. Boot loads the baked JSON instead of fetching the API.
|
||||
`/api/alteration` is verified client-resolvable or dropped from the public build.
|
||||
|
||||
### 3. Media URL base + CORS (`simulator/static/app.js`)
|
||||
|
||||
- `mediaNetUrl(file)` changes its base from `"/media/" + file` to a configurable
|
||||
**`MEDIA_BASE`** (`https://static.benstull.art/`), preserving the existing
|
||||
`?v=<hash>` content-hash versioning. A single const, fed from the baked config so
|
||||
localhost dev still works against the FastAPI `/media/` mount.
|
||||
- **CORS is load-bearing** because of the WebGL dream shader: `app.js` preloads each
|
||||
clip via `fetch()` (cross-origin → needs `Access-Control-Allow-Origin`) into a
|
||||
blob, and any clip that falls back to the *direct network* `<video>` path feeding
|
||||
WebGL **taints the GL texture** without CORS. So:
|
||||
- R2 bucket gets a **CORS policy** allowing `https://benstull.art`.
|
||||
- `<video>` elements carry **`crossOrigin="anonymous"`**.
|
||||
Without this, plain playback works but the *dream effect* throws a security error.
|
||||
|
||||
### 4. Prefetch (unchanged)
|
||||
|
||||
Keep the existing graduated strategy verbatim — `preloadList()` (all bases),
|
||||
`preloadOrder()` (current pool → neighbors outward → reachable morphs → sweep),
|
||||
`refreshReachablePreload()` (per-landing), `preloadAllMedia(concurrency=4)` behind
|
||||
the "Loading Universe…" bar. It improves on R2: Cloudflare edge-caches each object
|
||||
after first fetch; egress is free, so the background fill is free. No code change
|
||||
beyond the `MEDIA_BASE` swap (Component 3).
|
||||
|
||||
### 5. Caching headers
|
||||
|
||||
Server today sets `/media/` to `no-cache` (revalidate-always). On the CDN, set the
|
||||
versioned media objects to long-lived **`immutable`** — the `?v=<hash>` query already
|
||||
guarantees a new URL when bytes change, so a re-baked clip busts cache without a
|
||||
manual purge. Pages assets keep normal Cloudflare defaults.
|
||||
|
||||
### 6. Deploy & redirect
|
||||
|
||||
- **Pages:** deploy `dist/` (Pages Git integration or `wrangler pages deploy`).
|
||||
Serve the app under the `/human-experience-simulator` path.
|
||||
- **R2:** sync the media tree to the bucket (`wrangler r2` or rclone), bind
|
||||
`static.benstull.art` as the public custom domain, apply the CORS policy.
|
||||
- **Apex redirect:** `benstull.art/` → `/human-experience-simulator` via a
|
||||
Cloudflare redirect rule (or Pages `_redirects`).
|
||||
|
||||
## Testing
|
||||
|
||||
- **Build integration test:** run the build against the real manifest; assert
|
||||
`dist/` contains the expected static files, the three baked JSONs match the live
|
||||
API output, and the media sync tree contains **only** manifest-referenced files
|
||||
(no masters/mezzanines, nothing > some sanity bound).
|
||||
- **E2E (Playwright) against the static build:** point the existing suite at the
|
||||
built `dist/` + an R2-equivalent media origin and verify: boot with **no `/api/*`
|
||||
server**, the **dream/Kuwahara shader survives CORS** (texture not tainted),
|
||||
scrub-driven morphs stay smooth, audio crossfade works, language dropdown works.
|
||||
The E2E browser tier is required per the §9 pipeline (handbook).
|
||||
- **Pre-deploy check:** a smoke run confirming CORS headers + range requests on the
|
||||
R2 custom domain before flipping the apex redirect.
|
||||
|
||||
## Out of scope / deferred
|
||||
|
||||
- Service Worker / cross-session caching (deferred, not rejected).
|
||||
- Migrating the dev/authoring GCE deployment (stays as-is on flotilla).
|
||||
- Per-clip loop files for the reverse-landing frame jump (pre-existing residual,
|
||||
tracked elsewhere).
|
||||
- Cloudflare Stream (R2 is sufficient and cheaper for this payload).
|
||||
@@ -32,3 +32,24 @@ npm test
|
||||
|
||||
`playwright.config.ts` starts uvicorn on port 8099 automatically (`reuseExistingServer`
|
||||
locally) and points the tests at it.
|
||||
|
||||
## Static-build E2E (Cloudflare publish)
|
||||
|
||||
`tests/static-build.spec.ts` verifies the **built static site** (Cloudflare publish
|
||||
— see `deploy/cloudflare/README.md`): it boots with NO `/api/*` server (baked JSON),
|
||||
and the WebGL dream shader runs on **cross-origin** media without tainting the GL
|
||||
texture (the CORS path R2 will use in production).
|
||||
|
||||
It uses `playwright.static.config.ts` (no uvicorn `webServer`) and a dual static
|
||||
server, `serve-static.mjs`, that serves the built `dist/` (app, :8077) and
|
||||
`dist-media/` (media with CORS + Range, :8078):
|
||||
|
||||
```bash
|
||||
# from the repo root: build with the media base pointed at the local CORS server
|
||||
.venv/bin/python -m tools.build_static --media-base http://localhost:8078/
|
||||
|
||||
# from this directory (simulator/e2e): start the dual server, then run the spec
|
||||
DIST_DIR="$PWD/../../dist" MEDIA_DIR_E2E="$PWD/../../dist-media" node serve-static.mjs &
|
||||
npx playwright test --config playwright.static.config.ts
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from "@playwright/test";
|
||||
|
||||
// Static-build E2E: NO webServer — the built dist/ + dist-media/ are served by
|
||||
// serve-static.mjs (started manually, see README.md), so there is no uvicorn/API.
|
||||
// Run: npx playwright test --config playwright.static.config.ts
|
||||
export default defineConfig({
|
||||
testDir: "./tests",
|
||||
testMatch: /static-build\.spec\.ts/,
|
||||
timeout: 60_000,
|
||||
use: { actionTimeout: 10_000 },
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
// Serves the built dist/ (app) and dist-media/ (media, with CORS + Range) on two
|
||||
// ports — a local stand-in for Pages + R2, so the static-build E2E exercises the
|
||||
// cross-origin media path exactly as production will (CORS for the WebGL dream
|
||||
// shader, Range for video scrubbing).
|
||||
//
|
||||
// Env: DIST_DIR (app root), MEDIA_DIR_E2E (media root). Ports: app 8077, media 8078.
|
||||
import http from "node:http";
|
||||
import { createReadStream, statSync } from "node:fs";
|
||||
import { join, extname, normalize } from "node:path";
|
||||
|
||||
const TYPES = {
|
||||
".html": "text/html", ".js": "text/javascript", ".json": "application/json",
|
||||
".css": "text/css", ".mp4": "video/mp4", ".mp3": "audio/mpeg",
|
||||
};
|
||||
|
||||
function serve(root, port, cors, indexFallback) {
|
||||
http.createServer((req, res) => {
|
||||
if (cors) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Accept-Ranges", "bytes"); }
|
||||
let p = decodeURIComponent(req.url.split("?")[0]);
|
||||
if (p.endsWith("/")) p += "index.html";
|
||||
// contain to root (no path traversal)
|
||||
const file = normalize(join(root, p));
|
||||
if (!file.startsWith(normalize(root))) { res.writeHead(403); return res.end("forbidden"); }
|
||||
try {
|
||||
const st = statSync(file);
|
||||
res.setHeader("Content-Type", TYPES[extname(file)] || "application/octet-stream");
|
||||
const range = req.headers.range; // honor Range for video scrub
|
||||
if (range && /^bytes=/.test(range)) {
|
||||
const [s, e] = range.replace("bytes=", "").split("-");
|
||||
const start = +s, end = e ? +e : st.size - 1;
|
||||
res.writeHead(206, {
|
||||
"Content-Range": `bytes ${start}-${end}/${st.size}`,
|
||||
"Content-Length": end - start + 1,
|
||||
});
|
||||
createReadStream(file, { start, end }).pipe(res);
|
||||
} else {
|
||||
res.writeHead(200, { "Content-Length": st.size });
|
||||
createReadStream(file).pipe(res);
|
||||
}
|
||||
} catch {
|
||||
res.writeHead(404); res.end("not found");
|
||||
}
|
||||
}).listen(port);
|
||||
}
|
||||
|
||||
serve(process.env.DIST_DIR, 8077, false);
|
||||
serve(process.env.MEDIA_DIR_E2E, 8078, true);
|
||||
console.log("static app :8077 media(cors) :8078");
|
||||
@@ -0,0 +1,30 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
|
||||
// Runs against the BUILT static site: dist/ served on :8077, media (CORS) on :8078
|
||||
// by serve-static.mjs. Build with `--media-base http://localhost:8078/` so config.js
|
||||
// points media cross-origin — the production CORS path, locally. See README.md.
|
||||
const APP = "http://localhost:8077/human-experience-simulator/";
|
||||
|
||||
test("boots fully static — no /api calls, ring + clips load from baked JSON", async ({ page }) => {
|
||||
const apiCalls: string[] = [];
|
||||
page.on("request", (r) => { if (r.url().includes("/api/")) apiCalls.push(r.url()); });
|
||||
await page.goto(APP);
|
||||
await expect(page.locator("#vid")).toBeVisible({ timeout: 30_000 });
|
||||
expect(apiCalls, "static build must not call /api/*").toEqual([]);
|
||||
});
|
||||
|
||||
test("dream shader runs on cross-origin media without tainting the GL texture", async ({ page }) => {
|
||||
const errors: string[] = [];
|
||||
page.on("pageerror", (e) => errors.push(String(e)));
|
||||
await page.goto(APP);
|
||||
await expect(page.locator("#vid")).toBeVisible({ timeout: 30_000 });
|
||||
// crank the Feel (Right) knob to engage the dream, let a few frames render
|
||||
await page.evaluate(() => {
|
||||
const r = document.getElementById("right") as HTMLInputElement;
|
||||
r.value = "4";
|
||||
r.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
await page.waitForTimeout(2000);
|
||||
// a tainted GL texture throws SecurityError on draw; assert none surfaced
|
||||
expect(errors.filter((e) => /SecurityError|tainted|cross-origin/i.test(e))).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
// Client-side port of player/alteration.py + player/audio.py (the alteration
|
||||
// engine). Replaces the live POST /api/alteration in the static build — pure math,
|
||||
// unity calibration (the client never sends a calibration, so DEFAULT_CALIBRATION
|
||||
// = all gains 1.0 always applies). UMD so the browser gets `HEFAlteration` and
|
||||
// `node --test` can require() it. Keep IN SYNC with the Python — the numeric
|
||||
// contract is guarded by tests/test_alteration_js_parity.py.
|
||||
(function (root, factory) {
|
||||
const api = factory();
|
||||
if (typeof module !== "undefined" && module.exports) module.exports = api;
|
||||
else root.HEFAlteration = api;
|
||||
})(typeof self !== "undefined" ? self : this, function () {
|
||||
"use strict";
|
||||
const KNOB_MAX = 4; // player/alteration.py:25
|
||||
const clamp = (x, lo, hi) => Math.max(lo, Math.min(hi, x));
|
||||
|
||||
// Mirror of player/alteration.py::plan_alteration with DEFAULT_CALIBRATION (unity).
|
||||
function plan(c) {
|
||||
const tone = clamp((c.light - c.dark) / KNOB_MAX, -1, 1);
|
||||
const overlayIntensity = clamp(c.left / KNOB_MAX, 0, 1);
|
||||
const dreamIntensity = clamp(c.right / KNOB_MAX, 0, 1);
|
||||
const affectIntensity = clamp(c.right / KNOB_MAX, 0, 1); // affect uses overlay_gain too
|
||||
const is_identity = tone === 0 && c.left === 0 && c.right === 0;
|
||||
return {
|
||||
grade: { tone },
|
||||
overlay: { level: c.left, intensity: overlayIntensity },
|
||||
affect: { strength: c.right, intensity: affectIntensity },
|
||||
dream: { strength: c.right, intensity: dreamIntensity },
|
||||
is_identity,
|
||||
};
|
||||
}
|
||||
|
||||
// Mirror of player/audio.py::resolve_audio. `scaleAudio` is the current scale's
|
||||
// `audio` filename (relative to <mediaBase>audio/); off → silence.
|
||||
function renderAudio(source, scaleAudio, mediaBase) {
|
||||
if (source === "off") return { source: "off", url: null, altitude_coupled: false };
|
||||
const url = scaleAudio ? mediaBase + "audio/" + scaleAudio : null;
|
||||
return { source: "soundtrack", url, altitude_coupled: true };
|
||||
}
|
||||
|
||||
// The full /api/alteration response shape, computed locally.
|
||||
function alteration(controls, scaleAudio, mediaBase) {
|
||||
return {
|
||||
plan: plan(controls),
|
||||
render: {
|
||||
video: { shown: controls.visual === "on" }, // player/audio.py::resolve_visual
|
||||
audio: renderAudio(controls.audio, scaleAudio, mediaBase),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return { plan, renderAudio, alteration, KNOB_MAX };
|
||||
});
|
||||
+34
-21
@@ -57,14 +57,19 @@ let activeLang = "en"; // session-only; no persistence (resets to en each lo
|
||||
let lastAffect = null; // {strength, intensity, right} from the last renderAffect, for re-render on language switch
|
||||
|
||||
async function loadData() {
|
||||
const clips = (await (await fetch("/api/clips")).json()).clips || [];
|
||||
// Static build: boot from baked JSON (no server). Dev: the live API. The baked
|
||||
// files sit alongside index.html, so RELATIVE urls resolve under the deploy path.
|
||||
const api = (window.HEF_CONFIG && window.HEF_CONFIG.static)
|
||||
? { clips: "clips.json", versions: "media-versions.json", ring: "ring.json" }
|
||||
: { clips: "/api/clips", versions: "/api/media-versions", ring: "/api/ring" };
|
||||
const clips = (await (await fetch(api.clips)).json()).clips || [];
|
||||
clipsById = Object.fromEntries(clips.map((c) => [c.id, c]));
|
||||
// Per-file content-hash tokens → appended to /media URLs as ?v=<hash> so a
|
||||
// re-baked clip (new bytes, same path) gets a fresh URL the browser can't serve
|
||||
// stale. Best-effort: an empty map just yields un-versioned URLs.
|
||||
try { mediaVersions = (await (await fetch("/api/media-versions")).json()).versions || {}; }
|
||||
try { mediaVersions = (await (await fetch(api.versions)).json()).versions || {}; }
|
||||
catch (_) { mediaVersions = {}; }
|
||||
const r = await fetch("/api/ring");
|
||||
const r = await fetch(api.ring);
|
||||
serverRing = r.ok;
|
||||
ring = r.ok ? await r.json() : null;
|
||||
if (!ring && clips.length) {
|
||||
@@ -87,16 +92,12 @@ async function loadData() {
|
||||
async function pickRandomMember() {
|
||||
const scale = ring && ring.scales[ringIndex];
|
||||
if (!scale) return null;
|
||||
if (serverRing) {
|
||||
try {
|
||||
const resp = await fetch("/api/ring/advance", {
|
||||
method: "POST", headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ from_index: ringIndex, delta: 0 }),
|
||||
});
|
||||
if (resp.ok) return (await resp.json()).target_clip_id;
|
||||
} catch (_) { /* fall through to the primary member */ }
|
||||
}
|
||||
return scale.clip_id;
|
||||
// Uniform random pool member, client-side (mirrors hef.selection.pick_clip_id).
|
||||
// The drag/scroll navigation already resolves picks + morphs client-side via
|
||||
// scrub.js; this removes the last /api/ring/advance dependency so the build is
|
||||
// fully static. The synthesized fallback ring has a pool of one → returns it.
|
||||
const pool = (scale.pool && scale.pool.length) ? scale.pool : [{ clip_id: scale.clip_id }];
|
||||
return pool[Math.floor(Math.random() * pool.length)].clip_id;
|
||||
}
|
||||
|
||||
// Land on the current scale: pick a random pool member and force its media to load.
|
||||
@@ -118,9 +119,11 @@ let mediaVersions = {}; // file -> content-hash token (from /api/media-version
|
||||
// Network path for a media file, content-hash-versioned so a re-baked clip's URL
|
||||
// changes with its bytes (permanent cache-bust). The blob cache, when present,
|
||||
// wins — those bytes are already the current ones for this session.
|
||||
function mediaNetUrl(file) { const v = mediaVersions[file]; return "/media/" + file + (v ? "?v=" + v : ""); }
|
||||
function mediaBase() { return (window.HEF_CONFIG && window.HEF_CONFIG.mediaBase) || "/media/"; }
|
||||
function mediaNetUrl(file) { const v = mediaVersions[file]; return mediaBase() + file + (v ? "?v=" + v : ""); }
|
||||
function mediaUrl(file) {
|
||||
if (file.startsWith("/media/")) return file; // already a resolved absolute url (audio layer)
|
||||
// Already a resolved absolute url (audio layer, or R2 in static mode): pass through.
|
||||
if (/^https?:\/\//.test(file) || file.startsWith("/media/")) return file;
|
||||
return mediaBlobs[file] || mediaNetUrl(file);
|
||||
}
|
||||
|
||||
@@ -614,12 +617,21 @@ function controls() {
|
||||
let timer = null;
|
||||
async function update() {
|
||||
if (busy) return;
|
||||
const resp = await fetch("/api/alteration", {
|
||||
method: "POST", headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ controls: controls(), altitude_index: ringIndex }),
|
||||
});
|
||||
if (!resp.ok) { readout.textContent = "invalid: " + resp.status; return; }
|
||||
const data = await resp.json();
|
||||
let data;
|
||||
if (window.HEF_CONFIG && window.HEF_CONFIG.static) {
|
||||
// Static build: compute the alteration locally (HEFAlteration is the JS port of
|
||||
// player.alteration/audio). Audio couples to the current altitude's asset.
|
||||
const scale = ring && ring.scales[ringIndex];
|
||||
const scaleAudio = (scale && scale.audio) || "";
|
||||
data = HEFAlteration.alteration(controls(), scaleAudio, mediaBase());
|
||||
} else {
|
||||
const resp = await fetch("/api/alteration", {
|
||||
method: "POST", headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ controls: controls(), altitude_index: ringIndex }),
|
||||
});
|
||||
if (!resp.ok) { readout.textContent = "invalid: " + resp.status; return; }
|
||||
data = await resp.json();
|
||||
}
|
||||
readout.textContent = JSON.stringify(data, null, 2);
|
||||
// Tolerate a stale server that still returns {content:{video}} instead of the
|
||||
// {render:{video:{shown}}} (visual/audio-split) shape, so video works either way.
|
||||
@@ -1035,6 +1047,7 @@ async function reroll() {
|
||||
// from the live API and masks it otherwise). Reloads on my edits AND on a server
|
||||
// restart. Dev-only convenience; harmless if the endpoint is absent.
|
||||
function devLiveReload() {
|
||||
if (window.HEF_CONFIG && window.HEF_CONFIG.static) return; // no dev server in the static build
|
||||
let seen = null;
|
||||
setInterval(async () => {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// Runtime config. This dev default serves media from the local FastAPI /media
|
||||
// mount and uses the live API. The static build (tools/build_static.py) OVERWRITES
|
||||
// this file in dist/ with { mediaBase: "https://static.benstull.art/", static: true }.
|
||||
window.HEF_CONFIG = { mediaBase: "/media/", static: false };
|
||||
@@ -4,7 +4,7 @@
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>HEF — Alteration Simulator</title>
|
||||
<link rel="stylesheet" href="/style.css" />
|
||||
<link rel="stylesheet" href="style.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="loading">
|
||||
@@ -17,10 +17,10 @@
|
||||
<main>
|
||||
<section class="stage" id="stage">
|
||||
<div class="screen">
|
||||
<video id="vid" loop muted playsinline></video>
|
||||
<video id="vid-loop" loop muted playsinline></video>
|
||||
<audio id="aud" loop preload="auto"></audio>
|
||||
<audio id="aud-b" loop preload="auto"></audio>
|
||||
<video id="vid" loop muted playsinline crossorigin="anonymous"></video>
|
||||
<video id="vid-loop" loop muted playsinline crossorigin="anonymous"></video>
|
||||
<audio id="aud" loop preload="auto" crossorigin="anonymous"></audio>
|
||||
<audio id="aud-b" loop preload="auto" crossorigin="anonymous"></audio>
|
||||
<canvas id="paint"></canvas>
|
||||
<div id="tint"></div>
|
||||
<svg id="overlay" viewBox="0 0 100 100" preserveAspectRatio="none"></svg>
|
||||
@@ -107,8 +107,10 @@
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script src="/scrub.js"></script>
|
||||
<script src="/i18n.js"></script>
|
||||
<script src="/app.js"></script>
|
||||
<script src="config.js"></script>
|
||||
<script src="scrub.js"></script>
|
||||
<script src="alteration.js"></script>
|
||||
<script src="i18n.js"></script>
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"use strict";
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const A = require("../static/alteration.js");
|
||||
|
||||
const c = (o) => ({ visual: "on", audio: "off", left: 0, right: 0, dark: 0, light: 0, ...o });
|
||||
|
||||
test("identity at zero knobs", () => {
|
||||
const p = A.plan(c({}));
|
||||
assert.equal(p.grade.tone, 0);
|
||||
assert.equal(p.overlay.level, 0);
|
||||
assert.equal(p.dream.strength, 0);
|
||||
assert.equal(p.is_identity, true);
|
||||
});
|
||||
|
||||
test("mood tone is signed (light - dark)/KNOB_MAX, clamped", () => {
|
||||
assert.equal(A.plan(c({ light: 4 })).grade.tone, 1); // full light
|
||||
assert.equal(A.plan(c({ dark: 4 })).grade.tone, -1); // full dark
|
||||
assert.equal(A.plan(c({ light: 2 })).grade.tone, 0.5);
|
||||
});
|
||||
|
||||
test("left drives overlay level + intensity; right drives dream + affect", () => {
|
||||
const p = A.plan(c({ left: 2, right: 4 }));
|
||||
assert.equal(p.overlay.level, 2);
|
||||
assert.equal(p.overlay.intensity, 0.5);
|
||||
assert.equal(p.dream.strength, 4);
|
||||
assert.equal(p.dream.intensity, 1);
|
||||
assert.equal(p.affect.strength, 4);
|
||||
assert.equal(p.affect.intensity, 1);
|
||||
assert.equal(p.is_identity, false);
|
||||
});
|
||||
|
||||
test("renderAudio: off → null, no coupling", () => {
|
||||
assert.deepEqual(A.renderAudio("off", "cosmos.mp3", "https://x/"),
|
||||
{ source: "off", url: null, altitude_coupled: false });
|
||||
});
|
||||
|
||||
test("renderAudio: soundtrack → mediaBase audio url, coupled", () => {
|
||||
assert.deepEqual(A.renderAudio("soundtrack", "cosmos.mp3", "https://x/"),
|
||||
{ source: "soundtrack", url: "https://x/audio/cosmos.mp3", altitude_coupled: true });
|
||||
// no scale audio → null url but still coupled
|
||||
assert.deepEqual(A.renderAudio("soundtrack", "", "https://x/"),
|
||||
{ source: "soundtrack", url: null, altitude_coupled: true });
|
||||
});
|
||||
|
||||
test("alteration() composes plan + render with video.shown from visual", () => {
|
||||
const r = A.alteration(c({ visual: "off", audio: "soundtrack", left: 1 }), "reef.mp3", "https://x/");
|
||||
assert.equal(r.render.video.shown, false);
|
||||
assert.equal(r.render.audio.url, "https://x/audio/reef.mp3");
|
||||
assert.equal(r.plan.overlay.level, 1);
|
||||
});
|
||||
@@ -8,7 +8,7 @@ const I = require("../static/i18n.js");
|
||||
const html = fs.readFileSync(path.join(__dirname, "../static/index.html"), "utf8");
|
||||
|
||||
test("index.html includes the i18n script and a language select", () => {
|
||||
assert.match(html, /<script src="\/i18n\.js">/);
|
||||
assert.match(html, /<script src="i18n\.js">/); // relative: works at dev-root and under the deploy path prefix
|
||||
assert.match(html, /id="lang-select"/);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""The static build reimplements plan_alteration/resolve_audio in JS
|
||||
(simulator/static/alteration.js). This pins the numeric contract so the Python
|
||||
and JS cannot silently diverge — if you change the engine, change both (the
|
||||
mirrored JS cases live in simulator/unit/alteration.test.js)."""
|
||||
from hef.selection import Coordinate
|
||||
from player.alteration import plan_alteration, render_plan_to_dict
|
||||
from player.audio import resolve_audio, resolve_visual
|
||||
|
||||
|
||||
def test_engine_contract_matches_js_expectations():
|
||||
# mirrors the cases asserted in simulator/unit/alteration.test.js
|
||||
p = render_plan_to_dict(plan_alteration(Coordinate(left=2, right=4, dark=0, light=0)))
|
||||
assert p["overlay"] == {"level": 2, "intensity": 0.5}
|
||||
assert p["dream"] == {"strength": 4, "intensity": 1.0}
|
||||
assert p["affect"] == {"strength": 4, "intensity": 1.0}
|
||||
assert render_plan_to_dict(plan_alteration(Coordinate(0, 0, 0, 4)))["grade"]["tone"] == 1.0
|
||||
assert render_plan_to_dict(plan_alteration(Coordinate(0, 0, 4, 0)))["grade"]["tone"] == -1.0
|
||||
assert render_plan_to_dict(plan_alteration(Coordinate(0, 0, 0, 0)))["is_identity"] is True
|
||||
assert resolve_visual("off") is False
|
||||
a = resolve_audio("soundtrack", scale_audio="cosmos.mp3")
|
||||
assert a.url == "/media/audio/cosmos.mp3" and a.altitude_coupled is True
|
||||
@@ -0,0 +1,50 @@
|
||||
import json
|
||||
|
||||
from tools.build_static import build_static
|
||||
|
||||
|
||||
def test_build_emits_frontend_baked_json_and_only_referenced_media(tmp_path):
|
||||
out = tmp_path / "dist"
|
||||
media = tmp_path / "media"
|
||||
result = build_static(
|
||||
out, media,
|
||||
media_base="https://static.benstull.art/",
|
||||
app_path="/human-experience-simulator",
|
||||
)
|
||||
app_dir = out / "human-experience-simulator"
|
||||
|
||||
# frontend present under the app path; dev/author surfaces excluded
|
||||
assert (app_dir / "index.html").exists()
|
||||
assert (app_dir / "app.js").exists()
|
||||
assert (app_dir / "scrub.js").exists()
|
||||
assert (app_dir / "alteration.js").exists()
|
||||
assert (app_dir / "config.js").exists()
|
||||
assert not (app_dir / "author.html").exists()
|
||||
assert not list(app_dir.glob("review*.html"))
|
||||
|
||||
# apex + no-slash redirect rules
|
||||
redirects = (out / "_redirects").read_text()
|
||||
assert "/ /human-experience-simulator/ 308" in redirects
|
||||
assert "/human-experience-simulator /human-experience-simulator/ 308" in redirects
|
||||
|
||||
# baked JSON matches the API shape
|
||||
clips = json.loads((app_dir / "clips.json").read_text())
|
||||
assert "clips" in clips and clips["clips"]
|
||||
ring = json.loads((app_dir / "ring.json").read_text())
|
||||
assert "scales" in ring and "transitions" in ring
|
||||
assert all("audio" in s for s in ring["scales"]) # needed by client alteration
|
||||
versions = json.loads((app_dir / "media-versions.json").read_text())
|
||||
assert "versions" in versions
|
||||
|
||||
# config.js points at R2 + static mode
|
||||
cfg = (app_dir / "config.js").read_text()
|
||||
assert "https://static.benstull.art/" in cfg and "static: true" in cfg
|
||||
|
||||
# media tree holds ONLY referenced files — no masters/mezzanines
|
||||
synced = {p.name for p in media.rglob("*.mp4")}
|
||||
assert synced, "expected synced media"
|
||||
assert not any(n in ("master.mp4", "mezzanine.mp4") for n in synced)
|
||||
# every versioned file exists in the media tree
|
||||
for f in versions["versions"]:
|
||||
assert (media / f).exists(), f"missing synced media: {f}"
|
||||
assert result["media_files"] == sum(1 for _ in media.rglob("*") if _.is_file())
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Build the fully-static deployable for Cloudflare (Pages + R2).
|
||||
|
||||
Emits the Pages output tree and a separate R2 media sync tree:
|
||||
|
||||
out_dir/
|
||||
_redirects apex + no-slash → /<app>/ (308)
|
||||
<app>/ the app (served at benstull.art/<app>/)
|
||||
index.html app.js scrub.js i18n.js alteration.js style.css
|
||||
config.js GENERATED: { mediaBase, static: true }
|
||||
clips.json ring.json media-versions.json baked API responses
|
||||
media_out/ R2 upload tree — ONLY manifest-referenced files
|
||||
<clip base.mp4 / transition morphs / audio>
|
||||
|
||||
The app lives under a path segment (so apex can redirect to it) and uses RELATIVE
|
||||
asset urls, which resolve correctly under the `/<app>/` prefix. The baked JSON is
|
||||
produced through the real app (TestClient) so it is byte-identical to the API. The
|
||||
media tree contains ONLY referenced files — never the master/mezzanine pipeline
|
||||
sources. Cloudflare-side steps (R2 sync, Pages deploy, CORS, redirect) live in
|
||||
deploy/cloudflare/ — this script only produces artifacts.
|
||||
|
||||
Run as a MODULE so the repo root (not tools/) is on sys.path — otherwise the
|
||||
sibling tools/http.py shadows the stdlib `http` that fastapi/starlette import:
|
||||
|
||||
.venv/bin/python -m tools.build_static
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from simulator.app import MEDIA_DIR, create_app
|
||||
|
||||
STATIC = Path(__file__).resolve().parent.parent / "simulator" / "static"
|
||||
# Frontend files that ship; everything else in static/ (author*, review*) is dev-only.
|
||||
PUBLIC_ASSETS = ["index.html", "app.js", "scrub.js", "i18n.js", "alteration.js", "style.css"]
|
||||
|
||||
|
||||
def _bake_api(app_dir: Path) -> dict:
|
||||
app = create_app()
|
||||
client = TestClient(app)
|
||||
clips = client.get("/api/clips").json()
|
||||
ring = client.get("/api/ring").json()
|
||||
versions = client.get("/api/media-versions").json()
|
||||
(app_dir / "clips.json").write_text(json.dumps(clips, ensure_ascii=False))
|
||||
(app_dir / "ring.json").write_text(json.dumps(ring, ensure_ascii=False))
|
||||
(app_dir / "media-versions.json").write_text(json.dumps(versions, ensure_ascii=False))
|
||||
return versions["versions"]
|
||||
|
||||
|
||||
def _write_config(app_dir: Path, media_base: str) -> None:
|
||||
(app_dir / "config.js").write_text(
|
||||
"// GENERATED by tools/build_static.py — do not edit in dist/.\n"
|
||||
f'window.HEF_CONFIG = {{ mediaBase: "{media_base}", static: true }};\n'
|
||||
)
|
||||
|
||||
|
||||
def _write_redirects(out: Path, seg: str) -> None:
|
||||
# Apex → app path, and the no-trailing-slash form → slashed (so RELATIVE asset
|
||||
# urls resolve under the prefix). Cloudflare Pages `_redirects` syntax.
|
||||
(out / "_redirects").write_text(
|
||||
f"/ /{seg}/ 308\n"
|
||||
f"/{seg} /{seg}/ 308\n"
|
||||
)
|
||||
|
||||
|
||||
def build_static(out_dir, media_out, *, media_base: str, app_path: str) -> dict:
|
||||
out = Path(out_dir)
|
||||
media = Path(media_out)
|
||||
seg = app_path.strip("/")
|
||||
app_dir = out / seg
|
||||
for d in (out, media):
|
||||
if d.exists():
|
||||
shutil.rmtree(d)
|
||||
app_dir.mkdir(parents=True)
|
||||
media.mkdir(parents=True)
|
||||
|
||||
for name in PUBLIC_ASSETS:
|
||||
src = STATIC / name
|
||||
if src.exists():
|
||||
shutil.copy2(src, app_dir / name)
|
||||
|
||||
versions = _bake_api(app_dir)
|
||||
_write_config(app_dir, media_base)
|
||||
_write_redirects(out, seg)
|
||||
|
||||
# Sync ONLY referenced media: `versions` covers clip bases + transition morphs;
|
||||
# add each scale's audio explicitly. Never the master/mezzanine pipeline sources.
|
||||
referenced = set(versions.keys())
|
||||
ring = json.loads((app_dir / "ring.json").read_text())
|
||||
for s in ring.get("scales", []):
|
||||
if s.get("audio"):
|
||||
referenced.add(f"audio/{s['audio']}")
|
||||
n = 0
|
||||
for rel in sorted(referenced):
|
||||
src = MEDIA_DIR / rel
|
||||
if not src.exists():
|
||||
raise FileNotFoundError(f"referenced media missing on disk: {rel}")
|
||||
dst = media / rel
|
||||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(src, dst)
|
||||
n += 1
|
||||
|
||||
return {"out": str(out), "app_dir": str(app_dir), "media": str(media),
|
||||
"media_files": n, "app_path": app_path}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--out", default="dist")
|
||||
ap.add_argument("--media-out", default="dist-media")
|
||||
ap.add_argument("--media-base", default="https://static.benstull.art/")
|
||||
ap.add_argument("--app-path", default="/human-experience-simulator")
|
||||
a = ap.parse_args()
|
||||
r = build_static(a.out, a.media_out, media_base=a.media_base, app_path=a.app_path)
|
||||
print(json.dumps(r, indent=2))
|
||||
Reference in New Issue
Block a user