A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Share a town: a picture card, and a link that opens it running
Claudea1b74301ffc0
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.mdindex 4f32cfb..c194176 100644--- a/DEVELOPMENT.md+++ b/DEVELOPMENT.md@@ -160,6 +160,10 @@ That is how the README's screenshots of grown towns were made.- `src/asset-lab/town-props.ts`: parks (ground and furnishings, drawn cell by cell), stone paving and ruins.- `src/asset-lab/services.ts`: grain hoist, fish racks, watch tower, herbs,medical signs, street noticeboard and builder's equipment.+- `src/share/`: sharing a town: the card it is shared as (`card.ts`), the format and limits the page and the+ server agree on (`format.ts`), and the page's side: uploading, fetching, and the device's share sheet (`client.ts`).+- `src/server/`: the only server code: the routes behind shared towns (`handler.ts`), the Cloudflare Worker that+ runs them (`worker.ts`), and the same routes under `pnpm dev`, over a bucket in memory (`dev.ts`).- `src/asset-lab/appearance.ts`: material state metadata for catalogue presets.Wear, neighbourhood, hazards and winter are per-instance attributes in thelive renderer. A state change does not change the geometry cache key.@@ -246,6 +250,34 @@ pnpm balance -- --seeds 1 --verbose --every 1 # minute by minutepnpm balance -- --snapshot 40 # save each seed's town at minute 40 (see above)```+## Sharing a town++**share** (bottom right, and on the reckoning) draws the town as the camera+sees it into a 1200 × 630 card (at 2×), with the term's state and numbers on a+strip of paper. **Save the picture** downloads it; on a phone it goes to the+share sheet instead. **Make a link** uploads the town (its save file, gzipped,+with the camera) and a JPEG of the card; `/t/<id>` then opens the game on that+town, running, with the building tools put away until the visitor chooses+**Play from here** (the town becomes theirs and autosaves) or founds their own.+A shared town loads through `loadText` in `src/save.ts`, so it is checked and+carried forward between save versions exactly as a save is.++The server (`src/server/handler.ts`) keeps each share as two files in an R2+bucket, `towns/<id>.json.gz` (its preview's title and description as metadata)+and `towns/<id>.picture`:++| route | does |+|---|---|+| `POST /api/towns` | checks the town is gzip under 400 KB, the picture a JPEG/PNG/WebP under 600 KB, and the lines short and plain; keeps them under a new id |+| `GET /api/towns/<id>` and `/picture` | the files as kept, cached for a year (shares never change) |+| `GET /t/<id>` | the game's `index.html` with the share's Open Graph and Twitter tags written in, so links unfurl to the card |++The Worker runs only for `/t/*` and `/api/*`; everything else is a static+file, served free and unmetered. Shares are deleted after 180 days by a+lifecycle rule on the bucket. Under `pnpm dev` the same routes run in Vite+over a bucket in memory (shares last until the server stops), so sharing+works locally and `pnpm check:browser` checks it end to end.+## TestingThe simulation has no renderer in it: it runs headless (`src/sim/headless.ts`),@@ -270,6 +302,10 @@ breaks a rule. A second property checks that the same charter and commandsalways make the same town. `RUNS=200 pnpm test` searches harder;`SEED=…` replays.+`test/share.test.ts` checks the server's routes and what they refuse, and+carries a real town through them into another headless town, which must+then play on step for step the same as the original.+`pnpm check` puts the real simulation into each way a term can end(complete, bankrupt, revolt, abandoned, dismissed, run out), checks an unansweredcrown request, and checks that a town saved mid-term loads back the same. It@@ -284,9 +320,11 @@ mends falls down while one by a builder's yard is kept.## Releasing to CloudflareThe game is deployed with [Alchemy](https://alchemy.run/) as a Cloudflare-Worker serving the Vite build. The separate `deploy/` package keeps its-dependencies out of the game, and Cloudflare stores the deployment state.-Saves stay in the player's browser.+Worker serving the Vite build, with an R2 bucket (`Shares`) for shared+towns. The separate `deploy/` package keeps its dependencies out of the game,+and Cloudflare stores the deployment state. Saves stay in the player's+browser; only towns a player shares go to the bucket. R2 needs a payment+method on the account even within its free tier.```shpnpm install --frozen-lockfile@@ -299,8 +337,8 @@ Release from an up-to-date `main`. The release command checks the game'stypes and simulation and the deployment config, then Alchemy builds anddeploys the game to <https://inkline.typeonce.dev>. Alchemy attaches thatcustom domain to the `prod` Worker and creates its DNS record and certificate-in the `typeonce.dev` Cloudflare zone. Check that the game opens and save/load-works there after each release.+in the `typeonce.dev` Cloudflare zone. Check that the game opens, save/load+works, and a shared link opens and unfurls there after each release.`admin` is the existing local Alchemy Cloudflare profile. On anothermachine, use your own logged-in profile or set `CLOUDFLARE_ACCOUNT_ID` anddiff --git a/README.md b/README.mdindex 4338988..4c5ec37 100644--- a/README.md+++ b/README.md@@ -127,7 +127,8 @@ different on every cell.## PlayInkline Town runs in the browser. Saves stay in your browser, and the town-autosaves every two minutes of play.+autosaves every two minutes of play. Share a picture of your town, or a link+that opens it running for anyone, who can then play on from where you left it.```shpnpm installdiff --git a/deploy/alchemy.run.ts b/deploy/alchemy.run.tsindex ad7ace5..a2ee785 100644--- a/deploy/alchemy.run.ts+++ b/deploy/alchemy.run.ts@@ -10,6 +10,9 @@ const rootDir = fileURLToPath(new URL("..", import.meta.url))// Only production claims the custom domain; previews stay on workers.dev.const productionDomain = "inkline.typeonce.dev"+/** Shared towns are kept this long, so the bucket stays within the free 10 GB. */+const SHARE_DAYS = 180+export default Alchemy.Stack("inkline-town",{@@ -19,8 +22,22 @@ export default Alchemy.Stack(},Effect.gen(function* () {const stage = yield* Alchemy.Stage+ // Shared towns: each a gzipped save and its picture (see src/server/handler.ts).+ const shares = yield* Cloudflare.R2.Bucket("Shares", {+ lifecycleRules: [+ {+ id: "forget-old-shares",+ prefix: "towns/",+ deleteObjectsTransition: { condition: { type: "Age", maxAge: 60 * 60 * 24 * SHARE_DAYS } }+ }+ ]+ })const game = yield* Cloudflare.Website.Vite("Game", {rootDir,+ // The Worker answers only shared towns; every other path is a static file, served without it.+ main: "src/server/worker.ts",+ env: { SHARES: shares },+ assets: { runWorkerFirst: ["/t/*", "/api/*"] },...(stage === "prod" ? { domain: productionDomain } : {})})return { url: game.url }diff --git a/docs/how-to-play.md b/docs/how-to-play.mdindex 87432c4..d7d0bb4 100644--- a/docs/how-to-play.md+++ b/docs/how-to-play.md@@ -31,6 +31,13 @@ Save, load, and new town sit in the bottom right. The town also autosavesevery two minutes of game time, and **load** takes whichever save is newer.New town and load ask before they replace the town you have.+**share** makes a picture of the town as you see it, with how it stands, to+save or post anywhere (on a phone it opens the share sheet). **Make a link**+there gives a link anyone can open to watch your town running, from where+you were looking; **Play from here** makes it theirs to carry on, in their+own browser. The end of a term has a share button too. Shared links last+six months.+## A term in office- **The charter**: a new town is founded on land you choose: its sizediff --git a/scripts/check-browser.ts b/scripts/check-browser.tsindex 5e35a79..1024788 100644--- a/scripts/check-browser.ts+++ b/scripts/check-browser.ts@@ -183,6 +183,36 @@ try {await page.getByRole("button",{name:"Found a new town",exact:true}).waitFor({state:"visible"})assert.equal(await page.evaluate(()=>window.town.ui.stats!.fate.state),"over")facts.reckoning=true+ // Sharing: the card, then a link that opens the town in another browser (a phone), which can play on from there.+ await page.getByRole("button",{name:"Share the town",exact:true}).click()+ const card=page.locator(".dialog.share img.card-preview")+ await card.waitFor({state:"visible"})+ assert.deepEqual(await card.evaluate(async(img:HTMLImageElement)=>{await img.decode();return [img.naturalWidth,img.naturalHeight]}),[2400,1260])+ await page.getByRole("button",{name:"Make a link",exact:true}).click()+ const link=page.locator(".dialog.share .link-row input")+ await link.waitFor({state:"visible"})+ const url=await link.inputValue()+ assert.match(url,/\/t\/[a-z2-9]{8}$/)+ const unfurl=await (await fetch(url)).text()+ assert.ok(unfurl.includes(`<meta property="og:image" content="${new URL(url).origin}/api/towns/`),"A shared link unfurls to its picture")+ const picture=await fetch(unfurl.match(/property="og:image" content="([^"]+)"/)![1]!)+ assert.equal(picture.headers.get("content-type"),"image/jpeg")+ const sharedWorld=await snapshot()+ const visitor=await browser.newPage({viewport:{width:390,height:844},deviceScaleFactor:1,hasTouch:true,isMobile:true})+ visitor.on("pageerror",e=>errors.push(`visitor: ${e.message}`))+ await visitor.goto(url)+ await visitor.waitForFunction(()=>document.body.classList.contains("visiting"),undefined,{timeout:60000})+ const visited=await visitor.evaluate(()=>window.town.runtime.snapshot())+ assert.deepEqual(visited.entities,sharedWorld.entities,"The visitor sees the town as it was shared")+ assert.deepEqual(visited.resources,sharedWorld.resources)+ assert.ok(await visitor.locator(".toolbar").isHidden(),"A visitor's building tools are put away")+ await visitor.getByRole("button",{name:"Look at the town",exact:true}).click()+ await visitor.getByRole("button",{name:"Play from here",exact:true}).click()+ assert.equal(new URL(visitor.url()).pathname,"/")+ assert.ok(await visitor.locator(".toolbar").isVisible(),"Playing on brings the tools back")+ await visitor.screenshot({path:`${output}/shared-visitor.png`})+ await visitor.close()+ facts.sharedLink=urlassert.deepEqual(errors,[])await writeFile(`${output}/results.json`,JSON.stringify(facts,null,2))console.log(JSON.stringify(facts,null,2))diff --git a/src/factory.css b/src/factory.cssindex e688947..f4a4da8 100644--- a/src/factory.css+++ b/src/factory.css@@ -251,6 +251,38 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.dialog .sheet { padding: 16px; }}+/* ── Sharing: the card, and the link once it is made ── */+.dialog.share .sheet { width: 680px; }+.dialog .card-preview { display: block; width: 100%; aspect-ratio: 1200 / 630; margin: 8px 0 12px; border: 1px solid #c9cec4; border-radius: 4px; background: #e2e9e6; }+.dialog .frame { display: inline-flex; align-items: center; gap: 7px; text-decoration: none; color: inherit; }+.dialog .frame.primary .glyph { background: #f7f8f4; border-radius: 3px; padding: 1px; margin: -1px; }+.dialog .frame:disabled { opacity: 0.6; cursor: progress; }+.dialog .link-row { display: none; gap: 8px; margin-top: 12px; }+.dialog .link-row.show { display: flex; }+.dialog .link-row input { flex: 1; min-width: 0; font: inherit; font-size: 13px; color: #3d4943; background: #f7f8f4; border: 1px solid #c9cec4; border-radius: 2px; padding: 6px 10px; -webkit-user-select: text; user-select: text; }++/* ── Visiting a shared town: the banner, and the tools put away ── */+.visit {+ position: fixed; left: 50%; bottom: calc(14px + env(safe-area-inset-bottom)); transform: translateX(-50%); display: none; z-index: 4;+ max-width: calc(100vw - 32px); box-sizing: border-box; font-size: 12px;+}+.visit.show { display: flex; }+.visit .stack { display: flex; flex-direction: column; line-height: 1.25; }+.visit .stack b { font-size: 14px; }+.visit .stack small { color: #77817a; white-space: normal; }+.visit .cell { white-space: normal; }+.visit button { font: inherit; color: inherit; cursor: pointer; border: 1px solid #3d4943; border-radius: 2px; padding: 7px 12px; background: transparent; white-space: nowrap; }+.visit button:hover { background: #e6e9e2; }+.visit button.primary { background: #3d4943; color: #f7f8f4; }+.visiting .toolbar, .visiting .system, .visiting .views { display: none; }+@media (max-width: 600px) {+ .visit { flex-direction: column; align-items: stretch; width: calc(100vw - 32px); }+ .visit .cell + .cell { border-left: 0; border-top: 1px solid #e0e3db; }+ .visit .cell:last-child button { flex: 1; }+ .dialog .link-row { flex-wrap: wrap; }+ .dialog .link-row input { flex-basis: 100%; }+}+.result {position: fixed; top: 12px; left: 50%; transform: translateX(-50%); display: none; font: inherit; font-size: 12px; padding: 7px 12px; z-index: 5;background: #3d4943; color: #f7f8f4; border: 0; border-radius: 4px; cursor: pointer; box-shadow: 0 2px 0 #c9cec4;diff --git a/src/host.ts b/src/host.tsindex dcebcc7..0bcb8b1 100644--- a/src/host.ts+++ b/src/host.ts@@ -54,7 +54,10 @@ import { generate } from "./mapgen.ts"import { askOf, priceOf } from "./sim/index.ts"import type { Line, Stats, Tool, TradeMode, UiValue, View } from "./ui.ts"import { emptyPreview } from "./ui.ts"-import { GameScene } from "./render3d/scene.ts"+import { GameScene, type CameraView } from "./render3d/scene.ts"+import { blobOf, cardFacts, drawCard, metaOf, scaled, verdictOf } from "./share/card.ts"+import { handheld, offerLink, offerPicture, upload } from "./share/client.ts"+import { PICTURE_HEIGHT, PICTURE_WIDTH } from "./share/format.ts"import { MapInput } from "./render3d/input.ts"const el = <K extends keyof HTMLElementTagNameMap>(tag: K, className: string, text = "") => {@@ -111,9 +114,12 @@ const signed = (n: number) => `${n > 0 ? "+" : n < 0 ? "−" : ""}${Math.abs(n)}export interface Persistence {readonly save: () => string | nullreadonly load: () => string | null+ /** The town as a save file (as text), with where the camera stands, to share. */+ readonly shareFile: (camera: CameraView) => string}-export const createHost = async (mount: HTMLElement, persistence: () => Persistence) => {+/** `shared`: the page opened on a shared town's link, so it loads that rather than asking for a charter. */+export const createHost = async (mount: HTMLElement, persistence: () => Persistence, options: { readonly shared?: boolean } = {}) => {const app = new Application()// Pixi remains an offscreen thumbnail renderer for the unchanged menus.await app.init({ width: 64, height: 64, antialias: true, resolution: 2, autoStart: false, backgroundAlpha: 0 })@@ -216,12 +222,14 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst dialog = el("div", "dialog")const confirmBox = el("div", "dialog")const reckoning = el("div", "dialog")+ const shareBox = el("div", "dialog share")+ const visitBar = el("div", "card visit")const result = el("button", "result", "")result.onclick = () => showReckoning(true)// Map views, and the legend of the one shown.const views = el("div", "views")const legend = el("div", "card legend")- document.body.append(hud, people, tooltip, toastBox, toolbar, system, panel, result, dialog, confirmBox, reckoning, views, legend)+ document.body.append(hud, people, tooltip, toastBox, toolbar, system, panel, result, dialog, confirmBox, reckoning, shareBox, visitBar, views, legend)let toastTimer = 0const ui: UiValue = {@@ -353,6 +361,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistebutton.onclick = runsystem.append(button)}+ action("share", "share", "Share a picture of the town, or a link anyone can open to watch it and play on", () => void openShare())action("save", "save", "Save the town in this browser (it also autosaves every two minutes)", () =>ui.toast(persistence().save() ?? "Saved"))@@ -443,7 +452,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteif (event.target instanceof HTMLElement && event.target.closest("input,select,textarea,[contenteditable=true]")) returnif (event.key === " " && event.target instanceof HTMLButtonElement) returnif (confirmBox.classList.contains("open") && event.key === "Escape") confirmBox.querySelector<HTMLButtonElement>(".primary")?.click()- if (ui.founding || reckoning.classList.contains("open") || confirmBox.classList.contains("open")) return+ if (shareBox.classList.contains("open") && event.key === "Escape") closeShare()+ if (ui.founding || reckoning.classList.contains("open") || confirmBox.classList.contains("open") || shareBox.classList.contains("open") || visiting) returnif (event.key === " ") {event.preventDefault()setSpeed(ui.speed === 0 ? lastSpeed : 0)@@ -1279,6 +1289,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst actions = el("div", "actions")const found = el("button", "frame primary", "Found the town")found.onclick = () => {+ if (visiting) endVisit()ui.edits.push({ type: "newTown", charter: { ...choice } })history.length = 0ui.selected = null@@ -1302,7 +1313,131 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteui.founding = falsedialog.classList.remove("open")}- openCharter(false)+ if (!options.shared) openCharter(false)++ // ── Sharing ──+ // A picture of the town (the card), to post anywhere; and, on asking, a link+ // that opens the town itself, running, for anyone to watch and play on.+ let shareSpeed = 1+ const closeShare = () => {+ if (!shareBox.classList.contains("open")) return+ shareBox.classList.remove("open")+ for (const img of shareBox.querySelectorAll("img")) URL.revokeObjectURL(img.src)+ if (!visiting) setSpeed(shareSpeed)+ }+ shareBox.onclick = (event) => {+ if (event.target === shareBox) closeShare()+ }+ const openShare = async () => {+ const s = ui.stats+ if (!s || shareBox.classList.contains("open")) return+ shareSpeed = ui.speed+ setSpeed(0)+ const facts = cardFacts(s)+ let card: HTMLCanvasElement, png: Blob+ try {+ card = await drawCard(stage.picture(PICTURE_WIDTH, PICTURE_HEIGHT, 2), facts, location.host)+ png = await blobOf(card, "image/png")+ } catch (error) {+ setSpeed(shareSpeed)+ return ui.toast(error instanceof Error ? error.message : "The picture could not be made")+ }+ const name = `inkline-town-${s.fate.state === "playing" ? `year-${s.season.year}` : s.fate.state === "won" ? "complete" : "reckoning"}.png`+ const caption = `${metaOf(facts).title} · ${metaOf(facts).description}`+ shareBox.replaceChildren()+ const sheet = el("div", "sheet")+ sheet.append(el("h2", "", "share the town"))+ const preview = document.createElement("img")+ preview.className = "card-preview"+ preview.alt = caption+ preview.src = URL.createObjectURL(png)+ sheet.append(preview)+ sheet.append(el("p", "sub", "Post the picture anywhere, or make a link: whoever opens it sees this town running, from where you look at it now, and can play on from here."))+ const actions = el("div", "actions")+ const picture = el("button", "frame primary", "")+ picture.append(iconEl("picture", 15), document.createTextNode(handheld() ? "Share the picture" : "Save the picture"))+ picture.onclick = async () => ui.toast(await offerPicture(png, name, caption))+ const link = el("button", "frame", "")+ link.append(iconEl("link", 15), document.createTextNode("Make a link"))+ const linkRow = el("div", "link-row")+ link.onclick = async () => {+ link.disabled = true+ link.lastChild!.textContent = "Making a link…"+ try {+ const small = await blobOf(scaled(card, PICTURE_WIDTH, PICTURE_HEIGHT), "image/jpeg", 0.86)+ const made = await upload(persistence().shareFile(stage.view()), small, metaOf(facts))+ link.remove()+ const field = document.createElement("input")+ field.readOnly = true+ field.value = made.url+ field.onfocus = () => field.select()+ const copy = el("button", "frame primary", handheld() ? "Share the link" : "Copy the link")+ copy.onclick = async () => ui.toast(await offerLink(made.url, metaOf(facts).title))+ const open = el("a", "frame", "Open")+ open.setAttribute("href", made.url)+ open.setAttribute("target", "_blank")+ open.setAttribute("rel", "noopener")+ linkRow.replaceChildren(field, copy, open)+ linkRow.classList.add("show")+ copy.focus()+ } catch (error) {+ link.disabled = false+ link.lastChild!.textContent = "Try the link again"+ ui.toast(error instanceof Error ? error.message : "Could not share the town")+ }+ }+ const close = el("button", "frame", "Close")+ close.onclick = () => closeShare()+ actions.append(picture, link, close)+ sheet.append(actions, linkRow)+ shareBox.append(sheet)+ shareBox.classList.add("open")+ picture.focus()+ }++ // ── Visiting a shared town ──+ // The town runs as its mayor left it, with the building tools put away,+ // until the visitor plays on from here (it becomes theirs, and autosaves)+ // or founds a town of their own.+ let visiting = false+ const endVisit = () => {+ visiting = false+ document.body.classList.remove("visiting")+ visitBar.classList.remove("show")+ window.history.replaceState(null, "", "/")+ }+ /** The shared town is loaded: show it running. */+ const visit = (title: string) => {+ visiting = true+ closeCharter()+ resetPage()+ document.body.classList.add("visiting")+ visitBar.replaceChildren()+ const text = el("div", "cell")+ text.append(iconEl("town", 18))+ const words = el("span", "stack")+ words.append(el("b", "", "a shared town"), el("small", "", title))+ text.append(words)+ const play = el("button", "frame primary", "Play from here")+ play.title = "Make this town yours: build, govern, and it autosaves in this browser"+ play.onclick = () => {+ endVisit()+ ui.toast("The town is yours: it autosaves as you play")+ }+ const own = el("button", "frame", "Found your own")+ own.onclick = () => openCharter(true)+ const buttons = el("div", "cell")+ buttons.append(play, own)+ visitBar.append(text, buttons)+ visitBar.classList.add("show")+ setSpeed(1)+ }+ /** The shared town could not be opened: say why, and found a town instead. */+ const visitFailed = (message: string) => {+ window.history.replaceState(null, "", "/")+ openCharter(false)+ ui.toast(message)+ }// ── The end of the term ──/** Lines of residents, coins, and approval over the term, on the term's own time axis. */@@ -1330,15 +1465,6 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste}).join("")return `<svg viewBox="0 0 ${w} ${h}" preserveAspectRatio="none">${winters}<line x1="0" x2="${w}" y1="${goal}" y2="${goal}" stroke="#77817a" stroke-dasharray="3 3" vector-effect="non-scaling-stroke"/>${line(coinsLine, Math.min(0, ...coinsLine), Math.max(1, ...coinsLine), "#d6ae2e")}${line(approvalLine, -100, 100, "#3d6db5", "4 3")}${line(residents, 0, top, "#3d4943")}</svg>`}- /** What became of a town whose term ran out. */- const verdictOf = (s: Stats): string => {- if (s.fate.governing) return "complete"- const residents = s.settlers + s.citizens- if (s.fate.peak < 40) return "the town never took root"- if (residents >= sizes[s.charter.size].goal.residents * 0.75) return "flourishing"- if (residents >= s.fate.peak * 0.7) return "holding on"- return "declining"- }let reckoned = ""let reckoningOpen = falseconst showReckoning = (open: boolean) => {@@ -1408,7 +1534,10 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste}const look = el("button", "frame", "Look at the town")look.onclick = () => showReckoning(false)- actions.append(again, look)+ const share = el("button", "frame", "Share the town")+ share.title = "A picture of the town and its verdict, or a link anyone can open"+ share.onclick = () => void openShare()+ actions.append(again, look, share)card.append(actions)reckoning.append(card)showReckoning(true)@@ -1568,5 +1697,5 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste} else tooltip.style.display = "none"}- return { app, stage, ui, syncPage, resetPage, input }+ return { app, stage, ui, syncPage, resetPage, input, visit, visitFailed, visiting: () => visiting }}diff --git a/src/icons.ts b/src/icons.tsindex 6292d1c..02a74b3 100644--- a/src/icons.ts+++ b/src/icons.ts@@ -59,6 +59,9 @@ const paths: Record<string, string> = {load: `<path d="M2 4.5h4.5l1.5 1.5h6v7.5H2z" fill="#f3dca6"/><path d="M8 7v5M5.8 10L8 12.2 10.2 10" fill="none"/>`,newTown: `<path d="M4 14.5V2" fill="none"/><path d="M4 2.5h8.5l-2 3 2 3H4z" fill="#a6c48a"/><path d="M9.5 11.5h4M11.5 9.5v4" fill="none"/>`,close: `<path d="M4 4l8 8M12 4l-8 8" fill="none"/>`,+ share: `<path d="M3 8.5v5.5h10V8.5" fill="#f7f8f4"/><path d="M8 10.5V2.5M5.3 5.2L8 2.5l2.7 2.7" fill="none"/>`,+ picture: `<path d="M2 3.5h12v9H2z" fill="#f7f8f4"/><path d="M2.5 12l4-4.5 3 3 1.5-1.5 2.5 3" fill="#cfe5b8"/><circle cx="11" cy="6" r="1.2" fill="#f0d98a"/>`,+ link: `<path d="M7 9a2.5 2.5 0 0 0 3.5 0l2.5-2.5a2.5 2.5 0 0 0-3.5-3.5L8.5 4M9 7a2.5 2.5 0 0 0-3.5 0L3 9.5A2.5 2.5 0 0 0 6.5 13l1-1" fill="none"/>`,info: `<circle cx="8" cy="8" r="6" fill="#f7f8f4" stroke-width="1"/><path d="M8 7v4.5" fill="none" stroke-width="1.4"/><circle cx="8" cy="4.9" r=".9" fill="${ink}" stroke="none"/>`,upkeep: `<path d="M8 2.5v11M5 11l3 3 3-3" fill="none" stroke="#b04a39"/>`,burghers: `<circle cx="8" cy="5.5" r="2.3" fill="#f5f6f2"/><path d="M5.5 3.2h5V1.5h-5z" fill="${ink}"/><path d="M3.5 14c0-3.5 2-5.5 4.5-5.5s4.5 2 4.5 5.5z" fill="#8a58a8"/>`,diff --git a/src/main.ts b/src/main.tsindex f892ac8..449893a 100644--- a/src/main.ts+++ b/src/main.ts@@ -12,7 +12,9 @@ import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView,import { lands, sizes, STEP_SECONDS } from "./content.ts"import { createHost, type Persistence } from "./host.ts"import { present } from "./present.ts"-import { browserStorage, describe, loadLatest, save, Storage, World } from "./save.ts"+import { browserStorage, describe, fileOf, loadLatest, loadText, save, Storage, World } from "./save.ts"+import type { CameraView } from "./render3d/scene.ts"+import { download, sharedId } from "./share/client.ts"import { BuildingNodes, Clock, FieldNodes, Game, Rules, HouseNodes, RockNodes, RuinNodes, StageService, TreeNodes, Ui, WalkerNodes } from "./schema.ts"import { blankResources, simulate } from "./sim/index.ts"@@ -21,8 +23,16 @@ const AUTOSAVE_MINUTES = 2const start = async () => {const mount = document.getElementById("app")!- let persistence: Persistence = { save: () => "Not ready", load: () => "Not ready" }- const { stage, ui, syncPage, resetPage } = await createHost(mount, () => persistence)+ let persistence: Persistence = { save: () => "Not ready", load: () => "Not ready", shareFile: () => "" }+ // A shared town's link (`/t/<id>`): fetch it while the page starts, and load it once the town is up.+ const shared = sharedId(location.pathname)+ let arriving: string | null = null+ const { stage, ui, syncPage, resetPage, visit, visitFailed, visiting } = await createHost(mount, () => persistence, { shared: shared !== null })+ if (shared)+ download(shared).then(+ (text) => (arriving = text),+ (error: unknown) => visitFailed(error instanceof Error ? error.message : "Could not open that town")+ )const clock = { deltaSeconds: STEP_SECONDS, elapsed: 0 }const buildingNodes = stage.registry<BuildingView>(),@@ -96,13 +106,27 @@ const start = async () => {const loaded = run(loadLatest)if (loaded._tag === "Failure") return describe(loaded.failure)return loaded.success.slot === "auto" ? `Loaded the autosave: ${loaded.success.title}` : `Loaded ${loaded.success.title}`+ },+ shareFile: (camera) => {+ const file = run(fileOf("manual"))+ if (file._tag === "Failure") throw new Error("The town could not be packed up")+ return JSON.stringify({ ...file.success, camera })}}+ /** Loads the shared town that arrived, once the town the page started with has been founded. */+ const arrive = (text: string) => {+ const loaded = run(loadText(text))+ if (loaded._tag === "Failure") return visitFailed(describe(loaded.failure))+ const camera = (JSON.parse(text) as { camera?: CameraView }).camera+ if (camera) stage.setView(camera)+ else stage.resetCamera()+ visit(loaded.success.title)+ }/** The page autosaves every `AUTOSAVE_MINUTES` of game time while a term runs. */let autosaved = 0const autosave = () => {const s = ui.stats- if (!s || s.fate.state !== "playing" || ui.founding) return+ if (!s || s.fate.state !== "playing" || ui.founding || visiting()) returnif (s.minute < autosaved) autosaved = 0if (s.minute < autosaved + AUTOSAVE_MINUTES) returnautosaved = Math.floor(s.minute / AUTOSAVE_MINUTES) * AUTOSAVE_MINUTES@@ -119,6 +143,11 @@ const start = async () => {// new-town dialog is open, and once the term has ended (an edit, such as// founding a new town, still gets its step).update: () => {+ if (arriving !== null && ui.edits.length === 0) {+ const text = arriving+ arriving = null+ arrive(text)+ }if (ui.edits.some((edit) => edit.type === "newTown")) {resetPresentation()stage.resetCamera()diff --git a/src/render3d/scene.ts b/src/render3d/scene.tsindex 0938c77..c63f7b9 100644--- a/src/render3d/scene.ts+++ b/src/render3d/scene.ts@@ -13,6 +13,15 @@ import { groundAsset, landAsset, overlayAsset, previewAsset, type OverlayCell }import { parkAsset } from "../asset-lab/town-props.ts"import type { ParkCell } from "../appeal.ts"+/** Where the camera stands: the grid cell it looks at, its zoom, and its angles. */+export interface CameraView {+ readonly x: number+ readonly y: number+ readonly zoom: number+ readonly heading: number+ readonly elevation: number+}+export interface SceneNode {readonly group: THREE.Grouporient(): void@@ -302,6 +311,50 @@ export class GameScene {capture() {return this.canvas.toDataURL("image/webp", 0.94)}+ /** Where the camera looks from, to share along with the town. */+ view(): CameraView {+ return { x: this.target.x / floorScale, y: this.target.z / floorScale, zoom: this.camera.zoom, heading: this.heading, elevation: this.elevation }+ }+ /** Looks from a shared view, kept within the limits the controls keep to. */+ setView(view: CameraView) {+ const finite = (n: number, fallback: number) => (Number.isFinite(n) ? n : fallback)+ this.target.set(THREE.MathUtils.clamp(finite(view.x, GRID / 2), 0, GRID) * floorScale, 0, THREE.MathUtils.clamp(finite(view.y, GRID / 2), 0, GRID) * floorScale)+ this.camera.zoom = THREE.MathUtils.clamp(finite(view.zoom, 1), 0.35, 4)+ this.heading = finite(view.heading, Math.PI / 4)+ this.elevation = THREE.MathUtils.clamp(finite(view.elevation, Math.PI / 6), Math.PI / 12, (Math.PI / 180) * 65)+ this.camera.updateProjectionMatrix()+ this.placeCamera()+ }+ /**+ * The town as the camera sees it, drawn afresh at `width` × `height`+ * (times `scale`) into a canvas of its own. The view is widened or+ * narrowed so all of what the mayor sees on screen fits the picture.+ * The drawing buffer is read right after the render, so this works+ * without keeping the buffer between frames.+ */+ picture(width: number, height: number, scale = 2): HTMLCanvasElement {+ const ratio = this.renderer.getPixelRatio(),+ zoom = this.camera.zoom,+ fit = Math.min(width / this.width, height / this.height)+ this.renderer.setPixelRatio(scale)+ this.renderer.setSize(width, height, false)+ this.camera.left = -width / 2+ this.camera.right = width / 2+ this.camera.top = height / 2+ this.camera.bottom = -height / 2+ this.camera.zoom = Math.max(0.3, zoom * fit)+ this.camera.updateProjectionMatrix()+ this.renderer.render(this.scene, this.camera)+ const out = document.createElement("canvas")+ out.width = width * scale+ out.height = height * scale+ out.getContext("2d")!.drawImage(this.canvas, 0, 0, out.width, out.height)+ this.camera.zoom = zoom+ this.renderer.setPixelRatio(ratio)+ this.resize()+ this.renderer.render(this.scene, this.camera)+ return out+ }dispose() {this.renderer.setAnimationLoop(null)this.observer.disconnect()diff --git a/src/save.ts b/src/save.tsindex 7b131b6..d7673a5 100644--- a/src/save.ts+++ b/src/save.ts@@ -124,10 +124,9 @@ export const memoryStorage = (files = new Map<string, string>()): Storage["Servi// ── Saving and loading ────────────────────────────────────────────────────-/** Writes the town to a slot. */-export const save = (slot: Slot) =>+/** The town as a save file, written nowhere: what a slot keeps, and what a shared town carries. */+export const fileOf = (slot: Slot) =>Effect.gen(function* () {- const storage = yield* Storageconst world = yield* Worldconst file: SaveFile = {format: SAVE_FORMAT,@@ -137,6 +136,14 @@ export const save = (slot: Slot) =>title: world.title(),world: world.snapshot()}+ return file+ })++/** Writes the town to a slot. */+export const save = (slot: Slot) =>+ Effect.gen(function* () {+ const storage = yield* Storage+ const file = yield* fileOf(slot)yield* Effect.try({try: () => storage.set(keyOf(slot), JSON.stringify(file)),catch: (cause) => new StorageFailed({ slot, reason: cause instanceof Error ? cause.message : String(cause) })@@ -186,3 +193,10 @@ export const loadLatest = Effect.gen(function* () {.sort((a, b) => b.savedAt - a.savedAt)[0]return yield* load(newest?.slot ?? "manual")})++/**+ * Loads a save file handed over as text (a shared town), checked and+ * carried forward as a load from a slot is, without touching the slots.+ */+export const loadText = (text: string) =>+ load("manual").pipe(Effect.provideService(Storage, memoryStorage(new Map([[keyOf("manual"), text]]))))diff --git a/src/server/dev.ts b/src/server/dev.tsnew file mode 100644index 0000000..392c9e4--- /dev/null+++ b/src/server/dev.ts@@ -0,0 +1,54 @@+/**+ * Shared towns under `pnpm dev`: the same handler the Worker runs, over a+ * bucket in memory, so sharing works (and is checked) without Cloudflare.+ * Shares last until the dev server stops.+ */+import { readFile } from "node:fs/promises"+import type { IncomingMessage, ServerResponse } from "node:http"+import type { Plugin, ViteDevServer } from "vite"++import { handle, memoryBucket } from "./handler.ts"++const bodyOf = async (req: IncomingMessage): Promise<Uint8Array<ArrayBuffer> | undefined> => {+ if (req.method === "GET" || req.method === "HEAD") return undefined+ const chunks: Array<Uint8Array> = []+ for await (const chunk of req) chunks.push(chunk as Uint8Array)+ return new Uint8Array(Buffer.concat(chunks))+}++const requestOf = async (req: IncomingMessage): Promise<Request> => {+ const headers = new Headers()+ for (const [name, value] of Object.entries(req.headers)) {+ if (typeof value === "string") headers.set(name, value)+ else if (Array.isArray(value)) for (const v of value) headers.append(name, v)+ }+ const body = await bodyOf(req)+ return new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, { method: req.method ?? "GET", headers, ...(body ? { body } : {}) })+}++const send = async (res: ServerResponse, response: Response) => {+ res.statusCode = response.status+ response.headers.forEach((value, name) => res.setHeader(name, value))+ res.end(Buffer.from(await response.arrayBuffer()))+}++export const sharesInDev = (): Plugin => ({+ name: "inkline-town:shares",+ apply: "serve",+ configureServer(server: ViteDevServer) {+ const bucket = memoryBucket()+ const assets = {+ fetch: async (request: Request) => {+ const html = await server.transformIndexHtml(new URL(request.url).pathname, await readFile("index.html", "utf8"))+ return new Response(html, { headers: { "content-type": "text/html" } })+ }+ }+ server.middlewares.use((req, res, next) => {+ if (!req.url?.startsWith("/api/") && !req.url?.startsWith("/t/")) return next()+ requestOf(req)+ .then((request) => handle(request, { bucket, assets }))+ .then((response) => (response ? send(res, response) : next()))+ .catch(next)+ })+ }+})diff --git a/src/server/handler.ts b/src/server/handler.tsnew file mode 100644index 0000000..56df10c--- /dev/null+++ b/src/server/handler.ts@@ -0,0 +1,176 @@+/**+ * The server behind shared towns: three routes over a bucket of files.+ *+ * - `POST /api/towns` takes a town (gzipped), its picture, and its lines,+ * keeps them under a new id, and answers with the link.+ * - `GET /api/towns/:id` and `/api/towns/:id/picture` give them back.+ * - `GET /t/:id` is the game's own page, with the town's picture and lines+ * written into it for link previews; the page loads the town itself.+ *+ * It is written against the few bucket and asset calls it uses, so the same+ * code runs on Cloudflare (an R2 bucket and the site's assets), under the+ * dev server, and in tests (both in memory).+ */+import { checkMeta, isGzip, newId, ID_PATTERN, PICTURE_LIMIT, pictureType, picturePath, sharePath, TOWN_LIMIT, type ShareMeta } from "../share/format.ts"++/** What the handler needs of an R2 bucket. */+export interface Bucket {+ head(key: string): Promise<{ readonly customMetadata?: Record<string, string> } | null>+ get(key: string): Promise<{ readonly body: ReadableStream; readonly httpMetadata?: { readonly contentType?: string } } | null>+ put(+ key: string,+ value: ArrayBuffer | Uint8Array,+ options: { readonly httpMetadata: { readonly contentType: string }; readonly customMetadata?: Record<string, string> }+ ): Promise<unknown>+}++export interface Env {+ readonly bucket: Bucket+ /** The site's static files: here, its `index.html`. */+ readonly assets: { fetch(request: Request): Promise<Response> }+}++const townKey = (id: string) => `towns/${id}.json.gz`+const pictureKey = (id: string) => `towns/${id}.picture`++/** Shares never change once made, so anything may keep them. */+const FOREVER = "public, max-age=31536000, immutable"++const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } })+const fail = (status: number, error: string) => json({ error }, status)++const escapeAttr = (text: string) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """)++/** The tags a link preview reads, for a share. */+export const previewTags = (origin: string, id: string, meta: ShareMeta) => {+ const picture = `${origin}${picturePath(id)}`,+ url = `${origin}${sharePath(id)}`+ return [+ ["og:type", "website"],+ ["og:site_name", "Inkline Town"],+ ["og:url", url],+ ["og:title", meta.title],+ ["og:description", meta.description],+ ["og:image", picture],+ ["og:image:width", "1200"],+ ["og:image:height", "630"],+ ["og:image:alt", `${meta.title}: ${meta.description}`],+ ["twitter:card", "summary_large_image"],+ ["twitter:title", meta.title],+ ["twitter:description", meta.description],+ ["twitter:image", picture]+ ]+ .map(([key, value]) => `<meta ${key!.startsWith("og:") ? "property" : "name"}="${key}" content="${escapeAttr(value!)}" />`)+ .concat(`<meta name="description" content="${escapeAttr(meta.description)}" />`)+ .join("\n ")+}++/** The game's page with a share's preview written into its head (and its title). */+const sharePage = async (request: Request, env: Env, id: string) => {+ const origin = new URL(request.url).origin+ const page = await env.assets.fetch(new Request(`${origin}/`, { headers: { accept: "text/html" } }))+ if (!page.ok) return page+ const html = await page.text()+ const head = await env.bucket.head(townKey(id))+ const meta = head ? checkMeta(head.customMetadata ?? {}) : null+ const written = meta+ ? html+ .replace(/<title>[^<]*<\/title>/, `<title>${escapeAttr(meta.title)}</title>`)+ .replace("</head>", ` ${previewTags(origin, id, meta)}\n </head>`)+ : html+ return new Response(written, {+ status: head ? 200 : 404,+ headers: { "content-type": "text/html; charset=utf-8", "cache-control": "public, max-age=300" }+ })+}++const bytesOf = async (value: FormDataEntryValue | null): Promise<Uint8Array | null> =>+ value !== null && typeof value !== "string" ? new Uint8Array(await value.arrayBuffer()) : null++/** Keeps a new share and answers with its id and link. */+const create = async (request: Request, env: Env) => {+ const length = Number(request.headers.get("content-length") ?? "0")+ if (length > TOWN_LIMIT + PICTURE_LIMIT + 10_000) return fail(413, "That town is too large to share")+ let form: FormData+ try {+ form = await request.formData()+ } catch {+ return fail(400, "Expected a town, a picture, and its lines")+ }+ const town = await bytesOf(form.get("town")),+ picture = await bytesOf(form.get("picture"))+ let meta: ShareMeta | null = null+ try {+ meta = checkMeta(JSON.parse(String(form.get("meta") ?? "")))+ } catch {}+ if (!town || !isGzip(town)) return fail(400, "The town must be gzipped")+ if (town.byteLength > TOWN_LIMIT) return fail(413, "That town is too large to share")+ const type = picture ? pictureType(picture) : null+ if (!picture || !type) return fail(400, "The picture must be a JPEG, PNG, or WebP")+ if (picture.byteLength > PICTURE_LIMIT) return fail(413, "That picture is too large to share")+ if (!meta) return fail(400, "The share's lines are missing or too long")+ // Eight characters from thirty-two: a clash is rare, but look before writing over one.+ let id = newId()+ for (let tries = 0; (await env.bucket.head(townKey(id))) !== null; tries++) {+ if (tries > 4) return fail(500, "Could not find a free id")+ id = newId()+ }+ await env.bucket.put(pictureKey(id), picture, { httpMetadata: { contentType: type } })+ await env.bucket.put(townKey(id), town, {+ httpMetadata: { contentType: "application/gzip" },+ customMetadata: { title: meta.title, description: meta.description }+ })+ const origin = new URL(request.url).origin+ return json({ id, url: `${origin}${sharePath(id)}` }, 201)+}++/** A share's file from the bucket, as it was kept. */+const serve = async (env: Env, key: string, fallbackType: string) => {+ const object = await env.bucket.get(key)+ if (!object) return fail(404, "No town is shared under that link")+ return new Response(object.body, {+ headers: { "content-type": object.httpMetadata?.contentType ?? fallbackType, "cache-control": FOREVER }+ })+}++/** Answers a request for a share, or null when it is not one (the site's files answer those). */+export const handle = async (request: Request, env: Env): Promise<Response | null> => {+ const { pathname } = new URL(request.url)+ if (pathname === "/api/towns" || pathname === "/api/towns/") {+ return request.method === "POST" ? create(request, env) : fail(405, "Share a town with POST")+ }+ const parts = pathname.split("/").filter(Boolean)+ if (parts[0] === "t" && parts.length === 2) {+ if (!ID_PATTERN.test(parts[1]!)) return null+ return request.method === "GET" || request.method === "HEAD" ? sharePage(request, env, parts[1]!) : fail(405, "Read only")+ }+ if (parts[0] === "api" && parts[1] === "towns" && parts.length >= 3) {+ const id = parts[2]!+ if (!ID_PATTERN.test(id)) return fail(404, "No town is shared under that link")+ if (request.method !== "GET" && request.method !== "HEAD") return fail(405, "Read only")+ if (parts.length === 3) return serve(env, townKey(id), "application/gzip")+ if (parts.length === 4 && parts[3] === "picture") return serve(env, pictureKey(id), "image/jpeg")+ return fail(404, "Not found")+ }+ return null+}++/** A bucket in memory, for the dev server and tests. */+export const memoryBucket = (): Bucket & { readonly files: Map<string, { bytes: Uint8Array; type: string; meta: Record<string, string> }> } => {+ const files = new Map<string, { bytes: Uint8Array; type: string; meta: Record<string, string> }>()+ return {+ files,+ head: async (key) => {+ const file = files.get(key)+ return file ? { customMetadata: file.meta } : null+ },+ get: async (key) => {+ const file = files.get(key)+ return file ? { body: new Response(file.bytes.slice()).body!, httpMetadata: { contentType: file.type } } : null+ },+ put: async (key, value, options) => {+ files.set(key, { bytes: new Uint8Array(value).slice(), type: options.httpMetadata.contentType, meta: { ...options.customMetadata } })+ }+ }+}diff --git a/src/server/worker.ts b/src/server/worker.tsnew file mode 100644index 0000000..4654010--- /dev/null+++ b/src/server/worker.ts@@ -0,0 +1,18 @@+/**+ * The Cloudflare Worker in front of the game. Only shared towns reach it+ * (`/t/*` and `/api/*`, see `deploy/alchemy.run.ts`); every other request is+ * a static file Cloudflare serves without running it.+ */+import { handle, type Bucket } from "./handler.ts"++interface WorkerEnv {+ readonly SHARES: Bucket+ readonly ASSETS: { fetch(request: Request): Promise<Response> }+}++export default {+ async fetch(request: Request, env: WorkerEnv): Promise<Response> {+ const response = await handle(request, { bucket: env.SHARES, assets: env.ASSETS })+ return response ?? env.ASSETS.fetch(request)+ }+}diff --git a/src/share/card.ts b/src/share/card.tsnew file mode 100644index 0000000..26111f5--- /dev/null+++ b/src/share/card.ts@@ -0,0 +1,174 @@+/**+ * The picture a town is shared as: the town as the camera sees it, with a+ * strip of paper along the bottom saying what it is and how it stands (its+ * verdict once the term is over), drawn in the page's ink and type.+ */+import { lands, sizes } from "../content.ts"+import { icon, type IconName } from "../icons.ts"+import type { Stats } from "../ui.ts"+import { PICTURE_HEIGHT, PICTURE_WIDTH, type ShareMeta } from "./format.ts"++const INK = "#3d4943",+ MUTED = "#77817a",+ PAPER = "#f7f8f4",+ RULE = "#c9cec4",+ FONT = `ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace`++/** What became of a town whose term ran out. */+export const verdictOf = (s: Stats): string => {+ if (s.fate.governing) return "complete"+ const residents = s.settlers + s.citizens+ if (s.fate.peak < 40) return "the town never took root"+ if (residents >= sizes[s.charter.size].goal.residents * 0.75) return "flourishing"+ if (residents >= s.fate.peak * 0.7) return "holding on"+ return "declining"+}++/** What a card says. */+export interface CardFacts {+ readonly headline: string+ readonly land: string+ readonly numbers: ReadonlyArray<{ readonly icon: IconName; readonly value: string; readonly label: string }>+}++const capital = (text: string) => text.charAt(0).toUpperCase() + text.slice(1)+const signed = (n: number) => `${n > 0 ? "+" : n < 0 ? "−" : ""}${Math.abs(n)}`++export const cardFacts = (s: Stats): CardFacts => {+ const headline =+ s.fate.state === "won"+ ? "The town is complete"+ : s.fate.state === "lost"+ ? capital(s.fate.reason.split(":")[0]!.toLowerCase())+ : s.fate.state === "over"+ ? `The term is over: ${verdictOf(s)}`+ : `Year ${s.season.year} · ${Math.floor(s.minute)} min in`+ return {+ headline,+ land: `${capital(sizes[s.charter.size].title)}, ${lands[s.charter.land].title} land · ${s.charter.term}-minute term`,+ numbers: [+ { icon: "people", value: `${s.settlers + s.citizens}`, label: "residents" },+ { icon: "citizens", value: `${s.citizens}`, label: "citizens" },+ { icon: "coins", value: `${s.coins}`, label: "coins" },+ { icon: "approval", value: signed(s.mood.approval), label: "approval" }+ ]+ }+}++/** A card's lines for a link preview. */+export const metaOf = (facts: CardFacts): ShareMeta => ({+ title: `Inkline Town · ${facts.headline}`,+ description: `${facts.land} · ${facts.numbers.map((n) => `${n.value} ${n.label}`).join(" · ")}`+})++const iconImage = (name: IconName, size: number) =>+ new Promise<HTMLImageElement>((resolve, reject) => {+ const image = new Image(size, size)+ image.onload = () => resolve(image)+ image.onerror = () => reject(new Error(`icon ${name} did not load`))+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(icon(name, size).replace("<svg ", `<svg xmlns="http://www.w3.org/2000/svg" `))}`+ })++/** Shrinks a line's type until it fits `width`. */+const fit = (g: CanvasRenderingContext2D, text: string, weight: string, size: number, width: number) => {+ let s = size+ for (; s > 12; s--) {+ g.font = `${weight} ${s}px ${FONT}`+ if (g.measureText(text).width <= width) break+ }+ return s+}++/**+ * The card: `picture` (the town drawn at the card's size, at any scale)+ * under the strip of paper. `site` is the address printed in the corner.+ */+export const drawCard = async (picture: HTMLCanvasElement, facts: CardFacts, site: string): Promise<HTMLCanvasElement> => {+ const W = PICTURE_WIDTH,+ H = PICTURE_HEIGHT,+ scale = picture.width / W+ const canvas = document.createElement("canvas")+ canvas.width = Math.round(W * scale)+ canvas.height = Math.round(H * scale)+ const g = canvas.getContext("2d")!+ g.scale(scale, scale)+ g.drawImage(picture, 0, 0, W, H)+ g.textBaseline = "alphabetic"++ // The address, in a tab at the top right.+ g.font = `600 15px ${FONT}`+ const tab = g.measureText(site).width + 28+ g.fillStyle = PAPER+ g.strokeStyle = RULE+ g.lineWidth = 1+ g.beginPath()+ g.roundRect(W - tab - 20, 20, tab, 34, 8)+ g.fill()+ g.stroke()+ g.fillStyle = INK+ g.fillText(site, W - tab - 6, 42)++ // The strip.+ const strip = 128,+ top = H - strip+ g.fillStyle = PAPER+ g.fillRect(0, top, W, strip)+ g.fillStyle = INK+ g.fillRect(0, top, W, 1.5)+ g.fillStyle = "#dfe2db"+ g.fillRect(0, top + 1.5, W, 3)++ // The name and the headline, on the left.+ const mark = await iconImage("town", 40)+ g.drawImage(mark, 32, top + 26, 40, 40)+ g.fillStyle = MUTED+ g.font = `700 13px ${FONT}`+ g.letterSpacing = "3px"+ g.fillText("INKLINE TOWN", 86, top + 40)+ g.letterSpacing = "0px"+ const numbersWidth = 4 * 128+ const textWidth = W - numbersWidth - 86 - 56+ g.fillStyle = INK+ fit(g, facts.headline, "700", 28, textWidth)+ g.fillText(facts.headline, 86, top + 72)+ g.fillStyle = MUTED+ fit(g, facts.land, "400", 15, textWidth)+ g.fillText(facts.land, 86, top + 100)++ // The numbers, on the right, each in a column of its own.+ const left = W - numbersWidth - 24+ for (const [i, n] of facts.numbers.entries()) {+ const x = left + i * 128+ if (i > 0) {+ g.fillStyle = "#e0e3db"+ g.fillRect(x, top + 28, 1, strip - 52)+ }+ const glyph = await iconImage(n.icon, 22)+ g.drawImage(glyph, x + 18, top + 34, 22, 22)+ g.fillStyle = INK+ fit(g, n.value, "700", 26, 128 - 54)+ g.fillText(n.value, x + 46, top + 56)+ g.fillStyle = MUTED+ g.font = `400 13px ${FONT}`+ g.fillText(n.label, x + 18, top + 88)+ }+ // A thin frame of ink around it all, as the page's cards have.+ g.strokeStyle = INK+ g.lineWidth = 2+ g.strokeRect(1, 1, W - 2, H - 2)+ return canvas+}++export const blobOf = (canvas: HTMLCanvasElement, type: string, quality?: number) =>+ new Promise<Blob>((resolve, reject) => canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error("The picture could not be made"))), type, quality))++/** A smaller copy of a canvas, for the picture a link previews. */+export const scaled = (canvas: HTMLCanvasElement, width: number, height: number) => {+ const out = document.createElement("canvas")+ out.width = width+ out.height = height+ const g = out.getContext("2d")!+ g.imageSmoothingQuality = "high"+ g.drawImage(canvas, 0, 0, width, height)+ return out+}diff --git a/src/share/client.ts b/src/share/client.tsnew file mode 100644index 0000000..0169686--- /dev/null+++ b/src/share/client.ts@@ -0,0 +1,96 @@+/**+ * The page's side of sharing: packing a town up and sending it, fetching a+ * shared one back, and handing a picture or a link to the device (its share+ * sheet on a phone; a download or the clipboard on a computer).+ */+import { ID_PATTERN, townPath, type ShareMeta } from "./format.ts"++const pipe = async (bytes: Uint8Array, stream: CompressionStream | DecompressionStream) =>+ new Uint8Array(await new Response(new Blob([bytes as BlobPart]).stream().pipeThrough(stream)).arrayBuffer())++export const gzipText = (text: string) => pipe(new TextEncoder().encode(text), new CompressionStream("gzip"))+export const gunzipText = async (bytes: Uint8Array) => new TextDecoder().decode(await pipe(bytes, new DecompressionStream("gzip")))++/** The shared town a page's address names, if it names one. */+export const sharedId = (pathname: string): string | null => {+ const match = /^\/t\/([^/]+)\/?$/.exec(pathname)+ return match && ID_PATTERN.test(match[1]!) ? match[1]! : null+}++/** What the server said went wrong, or what did. */+const reason = async (response: Response) => {+ try {+ const body = (await response.json()) as { error?: unknown }+ if (typeof body.error === "string") return body.error+ } catch {}+ return `the server answered ${response.status}`+}++/** Sends a town (its save file, as text) with its picture and lines; answers with its link. */+export const upload = async (file: string, picture: Blob, meta: ShareMeta): Promise<{ readonly id: string; readonly url: string }> => {+ const form = new FormData()+ form.append("town", new Blob([(await gzipText(file)) as BlobPart], { type: "application/gzip" }), "town.json.gz")+ form.append("picture", picture, "picture")+ form.append("meta", JSON.stringify(meta))+ let response: Response+ try {+ response = await fetch("/api/towns", { method: "POST", body: form })+ } catch {+ throw new Error("Could not reach the server to share the town")+ }+ if (!response.ok) throw new Error(`Could not share the town: ${await reason(response)}`)+ return (await response.json()) as { id: string; url: string }+}++/** A shared town's save file, as text. */+export const download = async (id: string): Promise<string> => {+ let response: Response+ try {+ response = await fetch(townPath(id))+ } catch {+ throw new Error("Could not reach the server for that town")+ }+ if (response.status === 404) throw new Error("No town is shared under that link (shares are kept for six months)")+ if (!response.ok) throw new Error(`Could not open that town: ${await reason(response)}`)+ return gunzipText(new Uint8Array(await response.arrayBuffer()))+}++/** A phone or a tablet: where the system's share sheet is the way to share. */+export const handheld = () => typeof navigator.share === "function" && matchMedia("(pointer: coarse)").matches++/** Hands a picture to the share sheet, or saves it. Answers what happened, for a toast. */+export const offerPicture = async (picture: Blob, name: string, text: string): Promise<string> => {+ const file = new File([picture], name, { type: picture.type })+ if (handheld() && navigator.canShare?.({ files: [file] })) {+ try {+ await navigator.share({ files: [file], text })+ return "Shared"+ } catch (error) {+ if (error instanceof DOMException && error.name === "AbortError") return "Not shared"+ }+ }+ const link = document.createElement("a")+ link.href = URL.createObjectURL(picture)+ link.download = name+ link.click()+ setTimeout(() => URL.revokeObjectURL(link.href), 10_000)+ return `Saved the picture as ${name}`+}++/** Hands a link to the share sheet, or copies it. */+export const offerLink = async (url: string, title: string): Promise<string> => {+ if (handheld()) {+ try {+ await navigator.share({ url, title })+ return "Shared"+ } catch (error) {+ if (error instanceof DOMException && error.name === "AbortError") return "Not shared"+ }+ }+ try {+ await navigator.clipboard.writeText(url)+ return "Link copied"+ } catch {+ return url+ }+}diff --git a/src/share/format.ts b/src/share/format.tsnew file mode 100644index 0000000..00492dd--- /dev/null+++ b/src/share/format.ts@@ -0,0 +1,63 @@+/**+ * What a shared town is, as both the page and the server see it. A share is+ * three things kept under one id: the town (a save file, gzipped, with the+ * camera the mayor looked from), its picture (the card a link unfurls to),+ * and a few lines about it for the link's preview. The server keeps them as+ * they come and checks only what it must: sizes, kinds, and the lines it+ * writes into a page. The town itself is checked when it is loaded, by the+ * same code that loads a save.+ */++/** Ids are eight letters and digits: short enough to read out, too many to guess. */+export const ID_LENGTH = 8+const ID_ALPHABET = "abcdefghijkmnpqrstuvwxyz23456789"+export const ID_PATTERN = /^[a-z2-9]{8}$/++export const newId = (random: (bytes: Uint8Array<ArrayBuffer>) => Uint8Array = (b) => crypto.getRandomValues(b)): string =>+ [...random(new Uint8Array(ID_LENGTH))].map((n) => ID_ALPHABET[n % ID_ALPHABET.length]).join("")++/** Where a shared town opens, and where its parts are fetched from. */+export const sharePath = (id: string) => `/t/${id}`+export const townPath = (id: string) => `/api/towns/${id}`+export const picturePath = (id: string) => `/api/towns/${id}/picture`++/** The largest town and picture the server takes: a full large town gzips to a tenth of this. */+export const TOWN_LIMIT = 400_000+export const PICTURE_LIMIT = 600_000+/** The picture's size: what link previews expect. */+export const PICTURE_WIDTH = 1200+export const PICTURE_HEIGHT = 630++/** The lines about a share, shown in its link's preview. */+export interface ShareMeta {+ /** "Inkline Town · the town is complete" */+ readonly title: string+ /** "Large, fair land · year 5 · 581 residents · 352 citizens · 9000 coins" */+ readonly description: string+}++const LINE_LIMIT = 200+/** Plain lines only: no control characters, and not too long. */+const line = (value: unknown): string | null =>+ typeof value === "string" && value.length > 0 && value.length <= LINE_LIMIT && !/[\u0000-\u001f\u007f]/.test(value) ? value : null++/** A share's lines, or null when they are not lines this server writes into a page. */+export const checkMeta = (value: unknown): ShareMeta | null => {+ if (typeof value !== "object" || value === null) return null+ const v = value as Record<string, unknown>+ const title = line(v.title),+ description = line(v.description)+ return title && description ? { title, description } : null+}++/** gzip starts with 1f 8b. */+export const isGzip = (bytes: Uint8Array) => bytes.length > 2 && bytes[0] === 0x1f && bytes[1] === 0x8b+/** The picture formats a share keeps: JPEG, PNG, or WebP. */+export const pictureType = (bytes: Uint8Array): string | null => {+ if (bytes.length < 12) return null+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "image/jpeg"+ if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return "image/png"+ const ascii = (from: number, to: number) => String.fromCharCode(...bytes.subarray(from, to))+ if (ascii(0, 4) === "RIFF" && ascii(8, 12) === "WEBP") return "image/webp"+ return null+}diff --git a/test/share.test.ts b/test/share.test.tsnew file mode 100644index 0000000..42c75f2--- /dev/null+++ b/test/share.test.ts@@ -0,0 +1,164 @@+/**+ * Shared towns: the server's routes (`src/server/handler.ts`) over a bucket+ * in memory, and a town carried all the way through them, from one headless+ * town into another, as the page sends and loads it.+ */+import assert from "node:assert/strict"+import { test } from "node:test"+import { gunzipSync, gzipSync } from "node:zlib"++import { Effect } from "effect"++import { fileOf, loadText, memoryStorage, Storage, World } from "../src/save.ts"+import { handle, memoryBucket, type Env } from "../src/server/handler.ts"+import { checkMeta, ID_PATTERN, newId, pictureType, TOWN_LIMIT } from "../src/share/format.ts"+import { headless, type Headless } from "../src/sim/headless.ts"++const PAGE = `<!doctype html><html><head><title>Inkline Town</title></head><body><div id="app"></div></body></html>`+const ORIGIN = "https://inkline.test"++const setup = () => {+ const bucket = memoryBucket()+ const env: Env = { bucket, assets: { fetch: async () => new Response(PAGE, { headers: { "content-type": "text/html" } }) } }+ const call = async (path: string, init?: RequestInit) => {+ const response = await handle(new Request(`${ORIGIN}${path}`, init), env)+ assert.ok(response, `${path} is a share route`)+ return response+ }+ return { bucket, call }+}++/** A JPEG's first bytes, then anything. */+const jpeg = () => new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0, 0x10, 0x4a, 0x46, 0x49, 0x46, 0, 1, 2, 3])+const meta = { title: "Inkline Town · The town is complete", description: "Large, fair land · 60-minute term · 581 residents" }++const form = (parts: { town?: Uint8Array; picture?: Uint8Array; meta?: unknown }) => {+ const body = new FormData()+ if (parts.town) body.append("town", new Blob([parts.town as BlobPart]), "town.json.gz")+ if (parts.picture) body.append("picture", new Blob([parts.picture as BlobPart]), "picture")+ if (parts.meta !== undefined) body.append("meta", JSON.stringify(parts.meta))+ return { method: "POST", body }+}++test("a town shared is given back as it was sent, with its picture", async () => {+ const { call } = setup()+ const town = gzipSync(JSON.stringify({ hello: "town" }))+ const made = await call("/api/towns", form({ town, picture: jpeg(), meta }))+ assert.equal(made.status, 201)+ const { id, url } = (await made.json()) as { id: string; url: string }+ assert.match(id, ID_PATTERN)+ assert.equal(url, `${ORIGIN}/t/${id}`)++ const back = await call(`/api/towns/${id}`)+ assert.equal(back.status, 200)+ assert.match(back.headers.get("cache-control")!, /immutable/)+ assert.deepEqual(JSON.parse(gunzipSync(new Uint8Array(await back.arrayBuffer())).toString()), { hello: "town" })++ const picture = await call(`/api/towns/${id}/picture`)+ assert.equal(picture.headers.get("content-type"), "image/jpeg")+ assert.deepEqual(new Uint8Array(await picture.arrayBuffer()), jpeg())+})++test("a shared town's page carries its preview, escaped", async () => {+ const { call } = setup()+ const lines = { title: `Inkline Town · "<b>bold</b>" & co`, description: "Small, rich land" }+ const made = await call("/api/towns", form({ town: gzipSync("{}"), picture: jpeg(), meta: lines }))+ const { id } = (await made.json()) as { id: string }+ const page = await call(`/t/${id}`)+ assert.equal(page.status, 200)+ const html = await page.text()+ assert.match(html, /<title>Inkline Town · "<b>bold<\/b>" & co<\/title>/)+ assert.ok(html.includes(`<meta property="og:image" content="${ORIGIN}/api/towns/${id}/picture" />`))+ assert.ok(html.includes(`<meta name="twitter:card" content="summary_large_image" />`))+ assert.ok(!html.includes("<b>bold</b>"))+ assert.ok(html.includes(`<div id="app"></div>`), "the game's own page, which loads the town")+})++test("what the server will not keep", async () => {+ const { call, bucket } = setup()+ const refused = async (init: RequestInit, status: number) => assert.equal((await call("/api/towns", init)).status, status)+ await refused(form({ town: new TextEncoder().encode("{}"), picture: jpeg(), meta }), 400) // not gzipped+ await refused(form({ town: gzipSync("{}"), picture: new TextEncoder().encode("<svg onload=alert(1)>"), meta }), 400) // not a picture+ await refused(form({ town: gzipSync("{}"), picture: jpeg(), meta: { title: "a\nb", description: "c" } }), 400) // not a line+ await refused(form({ town: gzipSync("{}"), picture: jpeg(), meta: { title: "x".repeat(201), description: "c" } }), 400)+ await refused(form({ town: gzipSync("{}"), picture: jpeg() }), 400)+ const huge = new Uint8Array(TOWN_LIMIT + 1)+ huge.set([0x1f, 0x8b])+ await refused(form({ town: huge, picture: jpeg(), meta }), 413)+ await refused({ method: "GET" }, 405)+ assert.equal(bucket.files.size, 0)+})++test("unknown and malformed links", async () => {+ const { call } = setup()+ assert.equal((await call("/api/towns/abcdefgh")).status, 404)+ assert.equal((await call("/api/towns/..%2F..%2Fetc")).status, 404)+ assert.equal((await call("/api/towns/abcdefgh/picture")).status, 404)+ assert.equal((await call("/t/abcdefgh")).status, 404)+ assert.equal((await call("/api/towns/abcdefgh", { method: "DELETE" })).status, 405)+ const env: Env = { bucket: memoryBucket(), assets: { fetch: async () => new Response("") } }+ assert.equal(await handle(new Request(`${ORIGIN}/`), env), null, "the site's own files are not the server's")+ assert.equal(await handle(new Request(`${ORIGIN}/t/NOT-AN-ID`), env), null)+})++test("ids, lines, and picture kinds", () => {+ for (let i = 0; i < 200; i++) assert.match(newId(), ID_PATTERN)+ assert.equal(new Set(Array.from({ length: 1000 }, () => newId())).size, 1000)+ assert.deepEqual(checkMeta(meta), meta)+ assert.equal(checkMeta({ title: "", description: "x" }), null)+ assert.equal(checkMeta("nope"), null)+ assert.equal(pictureType(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0])), "image/png")+ assert.equal(pictureType(new TextEncoder().encode("RIFF\0\0\0\0WEBPVP8 ")), "image/webp")+ assert.equal(pictureType(new TextEncoder().encode("GIF89a........")), null)+})++const worldOf = (town: Headless): World["Service"] => ({+ snapshot: () => town.snapshot(),+ restore: (data) => {+ try {+ town.restore(data as never)+ return null+ } catch (cause) {+ return cause instanceof Error ? cause.message : String(cause)+ }+ },+ title: () => "medium, fair land · year 1 · 3 min in"+})+const runOn = <A, E>(town: Headless, program: Effect.Effect<A, E, Storage | World>) =>+ Effect.runSync(Effect.result(program.pipe(Effect.provideService(Storage, memoryStorage()), Effect.provideService(World, worldOf(town)))))+/** The world as it plays (see save.test.ts on `nextEntity`). */+const playing = (town: Headless) => {+ const { nextEntity: _, ...world } = town.snapshot()+ return JSON.stringify(world)+}++test("a town shared from one page plays on, the same, in another", async () => {+ const { call } = setup()+ const mine = headless({ size: "medium", term: 60, land: "fair", seed: 77 })+ mine.run(180)+ const file = runOn(mine, fileOf("manual"))+ assert.equal(file._tag, "Success")+ const camera = { x: 30, y: 31, zoom: 1.4, heading: 1, elevation: 0.6 }+ const text = JSON.stringify({ ...(file as { success: object }).success, camera })+ const made = await call("/api/towns", form({ town: gzipSync(text), picture: jpeg(), meta }))+ const { id } = (await made.json()) as { id: string }++ const back = gunzipSync(new Uint8Array(await (await call(`/api/towns/${id}`)).arrayBuffer())).toString()+ const theirs = headless({ size: "small", term: 45, land: "rich", seed: 1 })+ const loaded = runOn(theirs, loadText(back))+ assert.equal(loaded._tag, "Success")+ assert.deepEqual(JSON.parse(back).camera, camera)+ assert.equal(playing(theirs), playing(mine))+ mine.run(60)+ theirs.run(60)+ assert.equal(playing(theirs), playing(mine), "the shared town runs on exactly as the original")+})++test("a shared file that is not a town is refused, and the town is left alone", () => {+ const town = headless({ size: "small", term: 45, land: "fair", seed: 3 })+ const before = playing(town)+ const refused = runOn(town, loadText(JSON.stringify({ format: "inkline-town/save", version: 6, slot: "manual", savedAt: 0, title: "x", world: { entities: "no" } })))+ assert.equal(refused._tag, "Failure")+ assert.equal(runOn(town, loadText("not json"))._tag, "Failure")+ assert.equal(playing(town), before)+})diff --git a/vite.config.ts b/vite.config.tsindex 581efd7..1b2c8d2 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -1,16 +1,24 @@import { defineConfig } from "vite"+import { sharesInDev } from "./src/server/dev.ts"+export default defineConfig({- build: {- rolldownOptions: {- input: {- game: "index.html",- gallery: "gallery.html",- assets: "asset-lab.html",- map: "map-lab.html",- models: "model-review.html",- effects: "effects-lab.html",- parks: "park-lab.html"+ plugins: [sharesInDev()],+ environments: {+ // The pages are the client's alone: on deploy, the Worker (src/server/worker.ts) builds as an environment of its own.+ client: {+ build: {+ rolldownOptions: {+ input: {+ game: "index.html",+ gallery: "gallery.html",+ assets: "asset-lab.html",+ map: "map-lab.html",+ models: "model-review.html",+ effects: "effects-lab.html",+ parks: "park-lab.html"+ }+ }}}}