Compare commits

...

5 commits

Author SHA1 Message Date
jvanvik
4b922aba02 Merge upstream: sharded test runs, auto-release follows CI (3.1.0)
Some checks failed
CI / plan (push) Waiting to run
CI / part (push) Blocked by required conditions
CI / build (push) Waiting to run
CI / translations (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / timings (push) Blocked by required conditions
Container image / test (push) Has been cancelled
Container image / publish (push) Has been cancelled
The fork's Unreleased bullets stay above upstream's 3.1.0 section. The dark
mode test reads the theme script from the page's HTML, since the harness
now runs script bodies outside the DOM.
2026-11-07 10:29:33 +01:00
jvanvik
d1e127da67 Server-run play, part 1: game prerequisites and shared contracts
Groundwork for running multiplayer games on the session server; nothing
of it is switched on yet, and the plain build is unchanged.

- A new network in two halves (beginState/beginShow), the coach split into
  tutAdvance/coachDom, toastPop split out of toast, bootNotes() for the
  once-per-load toasts, the five text actions take their text as an
  argument, and srvOn() with its two checks in the loop.
- Live state is what a reload makes of it (migrate() is a no-op on it):
  new POPs, ports, PNIs, customers, attacks, dark fiber and the intern's
  notes are written in their saved shape; a 365-day test proves it.
- pniAll and bstdApply check the quote the sheet showed (bstdApply by its
  plan, within 1% for the daily hardware drift; utilityKit too).
- assemble({mp}) leaves src/game/98-server-play/ and its CSS out of every
  page but a multiplayer build's, which also gets a SIM_ID build id.
- Contracts for the server, protocol and browser parts: the action tables
  and envelope check (scripts/lib/mp-sim-acts.js), event fixtures, a shape
  checker, a fake engine, and load({mp:true}) in the test harness.
- route-fuzz judges both pages with one migrate(), so reload repairs of
  the base no longer count as divergences.
2026-11-07 10:26:06 +01:00
Frederic Jung
03523cb16b
Auto-release follows CI instead of testing the release again
A version bump on main ran the whole suite twice: once in CI for the
push, once more in auto-release. Auto-release now starts when CI
finishes on main and releases only if that run was green, tagging the
exact commit CI tested. Started by hand, it still tests first, since
there is no CI result to go by.
2026-11-07 10:00:15 +01:00
Frederic Jung
0342d90657
Faster tests, split everywhere: one sharded CI for pushes and releases
- The harness builds the DOM without the page's 2 MB of script text and
  runs the scripts straight in the window: a page load in tests takes
  about half the time (jsdom's parser was slow on the script text).
- That also took the game's source out of the DOM, which showed three
  tests that matched a phrase in the page source rather than the screen;
  they now check the panel, the routing window and the dictionary.
- CI plans its split once and runs the tests on 6 runners; every run on
  main records each file's time and caches it, so the parts stay even
  without anyone refreshing tests/durations.json.
- auto-release.yml and release.yml call the same sharded tests instead
  of running all 170 files on one runner each (11 and 15 min); a release
  is tested once, before it is tagged.
- Audit: five tests that duplicated a gameplay rule or checked nothing
  are gone; the two slowest checks sample a third of the cities, and a
  year of play to reach one due date became a moved due date.
2026-11-07 07:24:09 +01:00
Frederic Jung
7a6eb29013
Interns with specialities, optical upgrades, renewal haggles, seven French cities and smoother big networks (3.1.0) 2026-11-07 06:36:19 +01:00
80 changed files with 2487 additions and 233 deletions

View file

@ -5,8 +5,9 @@ description: Cut and ship a Series of Tubes release (patch or minor) from main v
# Releasing Series of Tubes # Releasing Series of Tubes
Bumping `version` in `package.json` on `main` is the release button. The Bumping `version` in `package.json` on `main` is the release button. CI tests the push
`auto-release.yml` workflow tests, tags `v<version>`, publishes a GitHub release with as usual; when it passes, `auto-release.yml` (which runs after every CI on `main`) sees
the new version, tags `v<version>` on the commit CI tested, publishes a GitHub release with
that version's CHANGELOG section as notes, and dispatches `release.yml`, which builds that version's CHANGELOG section as notes, and dispatches `release.yml`, which builds
`_site/` (`npm run build`: the page assembled from `src/` plus `site/`) and deploys it `_site/` (`npm run build`: the page assembled from `src/` plus `site/`) and deploys it
to GitHub Pages (https://seriesoftub.es). GitHub Pages is the only host, ever: see the to GitHub Pages (https://seriesoftub.es). GitHub Pages is the only host, ever: see the
@ -65,8 +66,8 @@ gh api repos/fjaeckel/seriesoftubes/releases/latest --jq '.tag_name+" "+.publish
## Steps ## Steps
1. Don't run the test suite, the game or benchmarks before a release: CI and the 1. Don't run the test suite, the game or benchmarks before a release: CI tests the
auto-release workflow test it, and the Performance workflow benchmarks it. Just version bump (a red CI releases nothing), and the Performance workflow benchmarks it. Just
check that the latest CI run on `main` is green (`gh run list --repo fjaeckel/seriesoftubes --limit 4`). check that the latest CI run on `main` is green (`gh run list --repo fjaeckel/seriesoftubes --limit 4`).
2. In `CHANGELOG.md`, move the bullets from `## [Unreleased]` into a new section 2. In `CHANGELOG.md`, move the bullets from `## [Unreleased]` into a new section
right below it: `## [x.y.z] — YYYY-MM-DD` (em dash, today's date). Keep an empty right below it: `## [x.y.z] — YYYY-MM-DD` (em dash, today's date). Keep an empty
@ -81,7 +82,7 @@ gh api repos/fjaeckel/seriesoftubes/releases/latest --jq '.tag_name+" "+.publish
--author="Frederic Jung <frederic@jc-ix.net>" -m "Short summary (x.y.z)" --author="Frederic Jung <frederic@jc-ix.net>" -m "Short summary (x.y.z)"
git push origin main git push origin main
``` ```
6. Watch the workflows until both finish: 6. Watch the workflows until all three finish (CI, then Auto-release, then Release to GitHub Pages):
```bash ```bash
gh run list --repo fjaeckel/seriesoftubes --limit 4 gh run list --repo fjaeckel/seriesoftubes --limit 4
gh run watch <id> --repo fjaeckel/seriesoftubes gh run watch <id> --repo fjaeckel/seriesoftubes

View file

@ -5,10 +5,15 @@ name: Auto-release
# as notes, and starts the deploy. Releases created with the workflow token do # as notes, and starts the deploy. Releases created with the workflow token do
# not fire the "released" event, so the deploy is started explicitly, from the # not fire the "released" event, so the deploy is started explicitly, from the
# tag, which keeps the github-pages environment's v* tag rule happy. # tag, which keeps the github-pages environment's v* tag rule happy.
#
# It runs when CI finishes on main, so a release never repeats the push's tests:
# CI green on the commit that bumped the version is the go. A red CI releases
# nothing. Started by hand, it has no CI result to go by, so it tests first.
on: on:
push: workflow_run:
workflows: [CI]
types: [completed]
branches: [main] branches: [main]
paths: [package.json]
workflow_dispatch: workflow_dispatch:
permissions: permissions:
@ -20,18 +25,26 @@ concurrency:
cancel-in-progress: false cancel-in-progress: false
jobs: jobs:
release: check:
# After CI: only a green run of a push to main (not a PR's run, not a release's own call).
if: >-
github.event_name == 'workflow_dispatch' ||
(github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push')
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
GH_TOKEN: ${{ github.token }} GH_TOKEN: ${{ github.token }}
outputs:
skip: ${{ steps.v.outputs.skip }}
ver: ${{ steps.v.outputs.ver }}
tag: ${{ steps.v.outputs.tag }}
pre: ${{ steps.v.outputs.pre }}
# The commit CI tested (main may have moved on since); by hand, main as it is now.
sha: ${{ github.event.workflow_run.head_sha || github.sha }}
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with: with:
ref: ${{ github.event.workflow_run.head_sha || github.sha }}
fetch-depth: 0 fetch-depth: 0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 24
cache: npm
- name: Work out the version and whether it is new - name: Work out the version and whether it is new
id: v id: v
@ -57,34 +70,47 @@ jobs:
case "$ver" in *-*) echo "pre=true" >> "$GITHUB_OUTPUT";; *) echo "pre=false" >> "$GITHUB_OUTPUT";; esac case "$ver" in *-*) echo "pre=true" >> "$GITHUB_OUTPUT";; *) echo "pre=false" >> "$GITHUB_OUTPUT";; esac
echo "skip=false" >> "$GITHUB_OUTPUT" echo "skip=false" >> "$GITHUB_OUTPUT"
- name: Test before releasing # Only when started by hand: after a push, CI has already tested this commit.
if: steps.v.outputs.skip == 'false' tests:
run: npm ci && npm test needs: check
if: needs.check.outputs.skip == 'false' && github.event_name == 'workflow_dispatch'
uses: ./.github/workflows/ci.yml
with:
ref: ${{ needs.check.outputs.sha }}
release:
needs: [check, tests]
if: >-
always() && needs.check.result == 'success' && needs.check.outputs.skip == 'false' &&
(needs.tests.result == 'success' || needs.tests.result == 'skipped')
runs-on: ubuntu-latest
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.check.outputs.tag }}
VER: ${{ needs.check.outputs.ver }}
PRE: ${{ needs.check.outputs.pre }}
SHA: ${{ needs.check.outputs.sha }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ needs.check.outputs.sha }}
- name: Publish the release - name: Publish the release
if: steps.v.outputs.skip == 'false'
env:
TAG: ${{ steps.v.outputs.tag }}
VER: ${{ steps.v.outputs.ver }}
PRE: ${{ steps.v.outputs.pre }}
run: | run: |
set -euo pipefail set -euo pipefail
awk -v v="$VER" 'index($0,"## ["v"]")==1{f=1;next} /^## \[/{f=0} f' CHANGELOG.md | sed -e '/./,$!d' > notes.md
pre=(); [ "$PRE" = "true" ] && pre=(--prerelease) pre=(); [ "$PRE" = "true" ] && pre=(--prerelease)
gh release create "$TAG" --repo "$GITHUB_REPOSITORY" \ gh release create "$TAG" --repo "$GITHUB_REPOSITORY" \
--target "$GITHUB_SHA" --title "$VER" --notes-file notes.md "${pre[@]}" --target "$SHA" --title "$VER" --notes-file notes.md "${pre[@]}"
- name: Deploy it - name: Deploy it
# Pre-releases are for testing and never go live. # Pre-releases are for testing and never go live. CI (or the tests above) already passed on this commit,
if: steps.v.outputs.skip == 'false' && steps.v.outputs.pre == 'false' # so the deploy does not test it again (tested=true).
env: if: env.PRE == 'false'
TAG: ${{ steps.v.outputs.tag }} run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG" -f tested=true
run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG"
- name: Publish the Docker image - name: Publish the Docker image
# Same pattern as the deploy above: the image is built and pushed from the # Same pattern as the deploy above: the image is built and pushed from the
# release tag by docker.yml. Pre-releases get one too: an image tag is # release tag by docker.yml. Pre-releases get one too: an image tag is
# pulled on purpose, so a test image costs nothing. # pulled on purpose, so a test image costs nothing.
if: steps.v.outputs.skip == 'false'
env:
TAG: ${{ steps.v.outputs.tag }}
run: gh workflow run docker.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG" run: gh workflow run docker.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG"

View file

@ -1,44 +1,89 @@
name: CI name: CI
# Every push and PR, and the releases too (auto-release.yml and release.yml call this workflow), so the tests run
# one way, split over several runners, everywhere.
on: on:
push: push:
branches: [main] branches: [main]
pull_request: pull_request:
workflow_call:
inputs:
ref:
description: The commit or tag to test (a release tag); the caller's commit when empty
type: string
default: ''
permissions: permissions:
contents: read contents: read
# A newer push to the same pull request makes the older run pointless: cancel it instead of queueing behind it. # A newer push to the same pull request makes the older run pointless: cancel it instead of queueing behind it.
# Runs on main always finish. # Runs on main always finish. A release's call gets a group of its own, so it never waits behind main's push run.
concurrency: concurrency:
group: ci-${{ github.ref }} group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}${{ inputs.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }} cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
# Runners for the tests. Standard GitHub-hosted runners (4 cores each) are the only free ones for a public repo,
# and a run may use up to 20 at once, so more parts is how the tests get faster. Each part costs ~30 s of setup.
PARTS: 6
jobs: jobs:
# The tests in four parts of about equal time, each on its own runner, each running as many files at once as # Splits the test files into parts of about equal time, once, so every part works from the same plan. The times
# it has cores (scripts/test.js; the split comes from tests/durations.json). # come from the last run on main (the cache, see "timings" below), else from the committed tests/durations.json.
plan:
runs-on: ubuntu-latest
outputs:
parts: ${{ steps.plan.outputs.parts }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ inputs.ref }}
- uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: tests/durations.json
key: test-durations-${{ github.run_id }}
restore-keys: test-durations-
- id: plan
run: echo "parts=$(node scripts/test.js --plan "$PARTS")" >> "$GITHUB_OUTPUT"
part: part:
name: test ${{ matrix.part }}/4 name: part ${{ strategy.job-index }}
needs: plan
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 20 timeout-minutes: 20
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
part: [1, 2, 3, 4] files: ${{ fromJSON(needs.plan.outputs.parts) }}
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ inputs.ref }}
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with: with:
node-version: 24 node-version: 24
cache: npm cache: npm
- run: npm ci - run: npm ci
- run: npm test -- --shard ${{ matrix.part }}/4 - name: Tests
env:
FILES: ${{ matrix.files }}
# Word splitting on purpose: FILES is a space-separated list of tests/*.test.js paths.
run: npm test -- --timings "$RUNNER_TEMP/timings.json" $FILES
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: always()
with:
name: timings-${{ strategy.job-index }}
path: ${{ runner.temp }}/timings.json
retention-days: 1
if-no-files-found: ignore
build: build:
name: build name: build
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ inputs.ref }}
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with: with:
node-version: 24 node-version: 24
@ -47,21 +92,12 @@ jobs:
- name: Build (not deployed — only releases deploy) - name: Build (not deployed — only releases deploy)
run: npm run build run: npm run build
# The one check to look at, named as before: green only when every part and the build are.
test:
needs: [part, build]
if: always()
runs-on: ubuntu-latest
steps:
- name: Every part and the build passed
run: |
echo "parts: ${{ needs.part.result }}, build: ${{ needs.build.result }}"
test "${{ needs.part.result }}" = success && test "${{ needs.build.result }}" = success
translations: translations:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ inputs.ref }}
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with: with:
node-version: 24 node-version: 24
@ -69,3 +105,38 @@ jobs:
- run: npm ci - run: npm ci
- name: Translation coverage - name: Translation coverage
run: node scripts/i18n-check.js --summary "$GITHUB_STEP_SUMMARY" run: node scripts/i18n-check.js --summary "$GITHUB_STEP_SUMMARY"
# The one check to look at: green only when the plan, every part, the build and the translations are.
test:
needs: [plan, part, build, translations]
if: always()
runs-on: ubuntu-latest
steps:
- name: Everything passed
run: |
echo "plan: ${{ needs.plan.result }}, parts: ${{ needs.part.result }}, build: ${{ needs.build.result }}, translations: ${{ needs.translations.result }}"
test "${{ needs.plan.result }}" = success && test "${{ needs.part.result }}" = success
test "${{ needs.build.result }}" = success && test "${{ needs.translations.result }}" = success
# After a run on main: each file's time from this run goes into the cache, so the next run (main or a PR) splits
# its parts by today's tests. Nobody has to remember to refresh tests/durations.json.
timings:
needs: part
if: always() && github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.part.result != 'skipped'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: tests/durations.json
key: test-durations-${{ github.run_id }}
restore-keys: test-durations-
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: timings-*
path: ${{ runner.temp }}/timings
- run: node scripts/test-timings.js --merge "$RUNNER_TEMP/timings"
- uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: tests/durations.json
key: test-durations-${{ github.run_id }}

View file

@ -23,6 +23,10 @@ on:
description: Only the weekly puzzles changed (weekly-puzzle.yml); the release itself was tested when it shipped description: Only the weekly puzzles changed (weekly-puzzle.yml); the release itself was tested when it shipped
type: boolean type: boolean
default: false default: false
tested:
description: The tag's tests already passed (auto-release.yml tests it before tagging)
type: boolean
default: false
# Least privilege: only the deploy job can write to Pages. # Least privilege: only the deploy job can write to Pages.
permissions: permissions:
@ -33,9 +37,18 @@ concurrency:
cancel-in-progress: false cancel-in-progress: false
jobs: jobs:
# The release's tests, split over several runners like every push (ci.yml). Skipped when auto-release.yml has just
# run them on this tag, and for a weekly redeploy (the build step below tests the weekly files against the tag).
tests:
if: ${{ (github.event_name == 'workflow_dispatch' || !github.event.release.prerelease) && !inputs.weekly && !inputs.tested }}
uses: ./.github/workflows/ci.yml
with:
ref: ${{ github.event.release.tag_name || inputs.tag }}
build: build:
needs: tests
# Pre-releases are for testing and never go live. # Pre-releases are for testing and never go live.
if: ${{ github.event_name == 'workflow_dispatch' || !github.event.release.prerelease }} if: ${{ always() && (github.event_name == 'workflow_dispatch' || !github.event.release.prerelease) && (needs.tests.result == 'success' || needs.tests.result == 'skipped') }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
TAG: ${{ github.event.release.tag_name || inputs.tag }} TAG: ${{ github.event.release.tag_name || inputs.tag }}
@ -93,10 +106,9 @@ jobs:
node scripts/weekly-puzzle.js --check node scripts/weekly-puzzle.js --check
if [ -f scripts/weekly-scenario.js ]; then node scripts/weekly-scenario.js --check; fi if [ -f scripts/weekly-scenario.js ]; then node scripts/weekly-scenario.js --check; fi
if [ -f scripts/weekly-architect.js ]; then node scripts/weekly-architect.js --check; fi if [ -f scripts/weekly-architect.js ]; then node scripts/weekly-architect.js --check; fi
- run: npm test # The weekly files come from main, not the tag: whatever tested the tag, they are tested against it here.
if: ${{ !inputs.weekly }}
- name: Test the weekly puzzles against this release - name: Test the weekly puzzles against this release
if: ${{ inputs.weekly && hashFiles('scripts/weekly-puzzle.js') != '' }} if: ${{ hashFiles('scripts/weekly-puzzle.js') != '' }}
run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js $(ls tests/weekly-scenario.test.js tests/weekly-architect.test.js 2>/dev/null) run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js $(ls tests/weekly-scenario.test.js tests/weekly-architect.test.js 2>/dev/null)
- name: Build site - name: Build site
run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build

View file

@ -10,16 +10,19 @@ All notable changes to this project are documented here. The project follows
- CGNAT gets a little cheaper every year: the world moves to IPv6 about two points a year, so less of your homes' traffic needs IPv4 and the CGNAT and NAT64 boxes carry less of it. - CGNAT gets a little cheaper every year: the world moves to IPv6 about two points a year, so less of your homes' traffic needs IPv4 and the CGNAT and NAT64 boxes carry less of it.
- The router model and the line system your intern standardizes on are now picked in one place, the build standard. Keep routers ahead and Upgrade optical transport take them from there and say so, with a button to the sheet. With a model or line system in the standard, both orders bring everything up to it and stop there (Upgrade optical transport on every fiber, even at POPs that Keep to the build standard skips); "Keep as is" leaves them to the next one up when busy. A model or line system you had picked in an order that was running moves into your standard, so new POPs get that model too. - The router model and the line system your intern standardizes on are now picked in one place, the build standard. Keep routers ahead and Upgrade optical transport take them from there and say so, with a button to the sheet. With a model or line system in the standard, both orders bring everything up to it and stop there (Upgrade optical transport on every fiber, even at POPs that Keep to the build standard skips); "Keep as is" leaves them to the next one up when busy. A model or line system you had picked in an order that was running moves into your standard, so new POPs get that model too.
- Your intern no longer takes a fiber dark for the build standard just because it looks quiet: like the optical upgrade order, it first checks that every gigabit, circuit and express gets around the fiber for the day. The two orders share one line system swap a night (two for Kevin), never work on the same fiber in one shift, and a wave the standard just upgraded is no longer handed back the same day. - Your intern no longer takes a fiber dark for the build standard just because it looks quiet: like the optical upgrade order, it first checks that every gigabit, circuit and express gets around the fiber for the day. The two orders share one line system swap a night (two for Kevin), never work on the same fiber in one shift, and a wave the standard just upgraded is no longer handed back the same day.
- Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse.
- The three interns now each have something they are best at: Anycast Annie peers every day and orders PNIs twice a week, Kevin from the night shift swaps two line systems a night and never fat-fingers anything, and Tracy Route buys capacity as if traffic were already 10% higher. They run the same orders at the same salary.
- Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night.
- Copies of the game you host yourself can now have multiplayer: friends join your session with a six-character code and build their networks next to yours in the same world, with a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player. - Copies of the game you host yourself can now have multiplayer: friends join your session with a six-character code and build their networks next to yours in the same world, with a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player.
- Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80). - Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80).
- Express lightpaths: light a wave straight through the cities between your own dark fibers, without touching the routers there. Wherever two or more of your ROADM fibers on land meet, a fiber's panel lists where an express can go and the link window gets an Express tab; it uses ports only at its two ends, saves a hop of latency and takes one channel slot on every fiber it rides, and the light has to reach all the way between regen sites. A cut or a line system swap on any of those fibers darkens it, and a fiber can only be given up once no express rides it. (#58) - Express lightpaths: light a wave straight through the cities between your own dark fibers, without touching the routers there. Wherever two or more of your ROADM fibers on land meet, a fiber's panel lists where an express can go and the link window gets an Express tab; it uses ports only at its two ends, saves a hop of latency and takes one channel slot on every fiber it rides, and the light has to reach all the way between regen sites. A cut or a line system swap on any of those fibers darkens it, and a fiber can only be given up once no express rides it. (#58)
- Teleports bring satellites to small islands and remote towns, long before you have a cable there or a rocket company (#83). Build one at a POP from level 2 and rent GEO circuits (about 600 ms round trip, and users notice) or, with tracking antennas from level 3, MEO circuits (about 130 ms) to any island or town its satellites see. Next to an island's only cable a circuit waits on standby (whether the cable or the circuit came first) and carries the island when the cable is cut, and a city with no cable at all gets a POP and a circuit in one order. - Teleports bring satellites to small islands and remote towns, long before you have a cable there or a rocket company (#83). Build one at a POP from level 2 and rent GEO circuits (about 600 ms round trip, and users notice) or, with tracking antennas from level 3, MEO circuits (about 130 ms) to any island or town its satellites see. Next to an island's only cable a circuit waits on standby (whether the cable or the circuit came first) and carries the island when the cable is cut, and a city with no cable at all gets a POP and a circuit in one order.
- Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through.
- Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. - Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section.
- IPv4 is scarce now: business customers need public address blocks, and the homes that do not fit share addresses behind CGNAT. A new network starts with a /21 from its registry, enough for its first months; buy, lease or sell blocks from /24 to /16 on the transfer market in the bank's new Address space section, or lease spare ones out for a monthly income. An offer you have no addresses for says so and waits, a customer that wants to grow at renewal stays at its size until you have the addresses, CGNAT costs a little and annoys some gamers, and you pick how many homes share an address. IPv6 stays free for everyone. This is part of On-call and BGP at 3 a.m.; the gentler rules, Sandbox, puzzles and scenarios keep IPv4 plentiful, and saved games get the addresses they already use plus room to grow (#150). - IPv4 is scarce now: business customers need public address blocks, and the homes that do not fit share addresses behind CGNAT. A new network starts with a /21 from its registry, enough for its first months; buy, lease or sell blocks from /24 to /16 on the transfer market in the bank's new Address space section, or lease spare ones out for a monthly income. An offer you have no addresses for says so and waits, a customer that wants to grow at renewal stays at its size until you have the addresses, CGNAT costs a little and annoys some gamers, and you pick how many homes share an address. IPv6 stays free for everyone. This is part of On-call and BGP at 3 a.m.; the gentler rules, Sandbox, puzzles and scenarios keep IPv4 plentiful, and saved games get the addresses they already use plus room to grow (#150).
## [3.1.0] — 2026-11-07
- Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse.
- The three interns now each have something they are best at: Anycast Annie peers every day and orders PNIs twice a week, Kevin from the night shift swaps two line systems a night and never fat-fingers anything, and Tracy Route buys capacity as if traffic were already 10% higher. They run the same orders at the same salary.
- Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night.
- Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through.
- France gets seven more cities: Lyon, Toulouse, Lille, Bordeaux, Strasbourg, Rennes and Nantes, all but Nantes with an exchange of their own (#288). SF-Error Telecom and Boy-Egg Telecom bring home broadband and mobile, Ov-Hatch Cloud and Scale-Away bring French clouds, Tangerine Telecom and Free as in Beer reach the new cities, Cogentle reaches Toulouse, Lille, Bordeaux and Strasbourg, and Andorable Telecom comes up to Toulouse. The Atlantic cables now come ashore where they really do: Ami-Tea at Bordeaux and Dunno-ant at Nantes, and Dunno-ant starts at Virginia Beach. - France gets seven more cities: Lyon, Toulouse, Lille, Bordeaux, Strasbourg, Rennes and Nantes, all but Nantes with an exchange of their own (#288). SF-Error Telecom and Boy-Egg Telecom bring home broadband and mobile, Ov-Hatch Cloud and Scale-Away bring French clouds, Tangerine Telecom and Free as in Beer reach the new cities, Cogentle reaches Toulouse, Lille, Bordeaux and Strasbourg, and Andorable Telecom comes up to Toulouse. The Atlantic cables now come ashore where they really do: Ami-Tea at Bordeaux and Dunno-ant at Nantes, and Dunno-ant starts at Virginia Beach.
- Big networks at ×8 no longer stop for a moment when a day reroutes, after a failure, an event, the intern's shift or the sales desk's signing. Every routing a day needs now runs in the background like the day's own, a long day lets the map draw between its steps, and the check for customers afraid of sharks no longer walks every land fiber for each of them. Quiet notifications now also apply while the game is running. - Big networks at ×8 no longer stop for a moment when a day reroutes, after a failure, an event, the intern's shift or the sales desk's signing. Every routing a day needs now runs in the background like the day's own, a long day lets the map draw between its steps, and the check for customers afraid of sharks no longer walks every land fiber for each of them. Quiet notifications now also apply while the game is running.

View file

@ -12,9 +12,12 @@ src/ the game page, in pieces
styles/NN-*.css → pasted into the page's <style>, in path order styles/NN-*.css → pasted into the page's <style>, in path order
game/NN-area/NN-*.js → pasted into the page's <script>, in path order game/NN-area/NN-*.js → pasted into the page's <script>, in path order
agent/NN-*.js → the agent facade the MCP server drives: development page only (@include-dev) agent/NN-*.js → the agent facade the MCP server drives: development page only (@include-dev)
game/98-server-play/, styles/43-server-play.css
→ server-run play: only in a multiplayer build's page (MP_API, assemble({mp}))
site/ static files copied to the build as they are (dictionaries, icons, sw.js…) site/ static files copied to the build as they are (dictionaries, icons, sw.js…)
scripts/lib/page.js the assembler: <!-- @include DIR --> → every file under src/DIR, sorted; scripts/lib/page.js the assembler: <!-- @include DIR --> → every file under src/DIR, sorted;
<!-- @include-dev DIR --> the same, in the development page only <!-- @include-dev DIR --> the same, in the development page only;
mp: true adds the multiplayer-only files (MP_ONLY), simId() is their build id
scripts/build.js _site/ = site/ + the assembled page, version-stamped, release notes baked in scripts/build.js _site/ = site/ + the assembled page, version-stamped, release notes baked in
``` ```
@ -80,9 +83,10 @@ Development runs on `npm run dev` (assembles the development page on every reque
| `scripts/agent/relay.js`, `scripts/lib/mcp-browser.js`, `scripts/lib/relay-client.js` | The agent relay `npm run dev` hosts at `/agent`, and the MCP server's side of it: how a tool reaches the game in the player's tab | | `scripts/agent/relay.js`, `scripts/lib/mcp-browser.js`, `scripts/lib/relay-client.js` | The agent relay `npm run dev` hosts at `/agent`, and the MCP server's side of it: how a tool reaches the game in the player's tab |
| `scripts/i18n-check.js`, `scripts/i18n-add.js`, `scripts/lib/dict.js` | Translation coverage and dictionary order; adding, renaming and removing entries | | `scripts/i18n-check.js`, `scripts/i18n-add.js`, `scripts/lib/dict.js` | Translation coverage and dictionary order; adding, renaming and removing entries |
| `scripts/legacy/` | The splitter that made `src/` from the old `site/index.html` (and gave its text labels), and `port-branch.js`, which carries older branches over | | `scripts/legacy/` | The splitter that made `src/` from the old `site/index.html` (and gave its text labels), and `port-branch.js`, which carries older branches over |
| `tests/harness.js` | Loads the assembled page in jsdom with a seeded `Math.random` and a fake canvas: the players' page, or the development page with `{agent: true}` | | `tests/harness.js` | Loads the assembled page in jsdom with a seeded `Math.random` and a fake canvas: the players' page, or the development page with `{agent: true}`. The page's scripts run straight in the window (jsdom's parser is slow on 2 MB of script) |
| `.github/workflows/ci.yml` | Tests and build on every push and PR | | `scripts/test.js`, `tests/durations.json` | Runs the tests, every file in its own process; splits them into parts of equal time for CI (`--plan`, `--shard`) by each file's seconds, which CI refreshes after every run on `main` |
| `.github/workflows/auto-release.yml` | On a `package.json` version bump on `main`: test, tag, GitHub release from the CHANGELOG, start the deploy | | `.github/workflows/ci.yml` | Tests (split over 6 runners), build and translations on every push and PR; the releases call it too, so the tests run one way everywhere |
| `.github/workflows/auto-release.yml` | After every green CI on `main`: if `package.json` has a new version, tag the commit CI tested, publish the GitHub release from the CHANGELOG, start the deploy (`tested=true`, so it does not test again) |
| `.github/workflows/release.yml` | Builds and deploys to GitHub Pages, the only workflow that can | | `.github/workflows/release.yml` | Builds and deploys to GitHub Pages, the only workflow that can |
| `.github/workflows/weekly-puzzle.yml` | Sunday 03:37 UTC: makes the week's puzzle, commits it to `main` (data only, no release) and starts `release.yml` for the live release tag with `weekly=true` | | `.github/workflows/weekly-puzzle.yml` | Sunday 03:37 UTC: makes the week's puzzle, commits it to `main` (data only, no release) and starts `release.yml` for the live release tag with `weekly=true` |
| `scripts/weekly-puzzle.js`, `site/puzzles/weekly/` | The weekly puzzle generator and its output, one `<key>.json` per week plus `index.json` (see below) | | `scripts/weekly-puzzle.js`, `site/puzzles/weekly/` | The weekly puzzle generator and its output, one `<key>.json` per week plus `index.json` (see below) |

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{ {
"name": "seriesoftubes", "name": "seriesoftubes",
"version": "3.0.0", "version": "3.1.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "seriesoftubes", "name": "seriesoftubes",
"version": "3.0.0", "version": "3.1.0",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@modelcontextprotocol/node": "2.1.2", "@modelcontextprotocol/node": "2.1.2",

View file

@ -1,6 +1,6 @@
{ {
"name": "seriesoftubes", "name": "seriesoftubes",
"version": "3.0.0", "version": "3.1.0",
"description": "A cartoon browser game about building the internet.", "description": "A cartoon browser game about building the internet.",
"private": true, "private": true,
"license": "MIT", "license": "MIT",

View file

@ -7,11 +7,12 @@
// npm run build VERSION, BUILD_DATE and OUT can be set in the environment // npm run build VERSION, BUILD_DATE and OUT can be set in the environment
// REQUIRE_NOTES=1 npm run build fail when CHANGELOG.md has no bullets for this version // REQUIRE_NOTES=1 npm run build fail when CHANGELOG.md has no bullets for this version
// MP_API=/api/mp npm run build a self-hosted copy with multiplayer (docs/MULTIPLAYER.md): the // MP_API=/api/mp npm run build a self-hosted copy with multiplayer (docs/MULTIPLAYER.md): the
// page talks to scripts/mp-server.js at that path, same origin // page talks to scripts/mp-server.js at that path, same origin, and
// has the server-run play (src/game/98-server-play/) and its SIM_ID
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { execFileSync } = require('node:child_process'); const { execFileSync } = require('node:child_process');
const { shipped, ROOT } = require('./lib/page'); const { shipped, simId, assemble, ROOT } = require('./lib/page');
const VERSION = process.env.VERSION || require(path.join(ROOT, 'package.json')).version; const VERSION = process.env.VERSION || require(path.join(ROOT, 'package.json')).version;
const BUILD_DATE = process.env.BUILD_DATE || new Date().toISOString().slice(0, 10); const BUILD_DATE = process.env.BUILD_DATE || new Date().toISOString().slice(0, 10);
@ -31,7 +32,9 @@ fs.cpSync(path.join(ROOT, 'site'), OUT, { recursive: true });
if (fs.existsSync(path.join(OUT, 'index.html'))) die('site/index.html must not exist: the page is assembled from src/'); if (fs.existsSync(path.join(OUT, 'index.html'))) die('site/index.html must not exist: the page is assembled from src/');
// The page and the translations ship with labels shrunk to short ids (docs/adr/0003-translations-by-label.md). // The page and the translations ship with labels shrunk to short ids (docs/adr/0003-translations-by-label.md).
const D = require('./lib/dict'); const D = require('./lib/dict');
const { html: page0, dicts } = shipped(Object.fromEntries(D.langs().map((l) => [l, D.read(l).dict]))); const { html: page0, dicts } = shipped(Object.fromEntries(D.langs().map((l) => [l, D.read(l).dict])), { mp: !!MP_API });
// Server-run play's build id: only a multiplayer build has one (scripts/lib/page.js simId()).
const SIM_ID = MP_API ? simId(assemble({ mp: true }).html) : '';
fs.writeFileSync(path.join(OUT, 'index.html'), page0); fs.writeFileSync(path.join(OUT, 'index.html'), page0);
for (const [lang, dict] of Object.entries(dicts)) fs.writeFileSync(path.join(OUT, 'i18n', `${lang}.js`), D.format(lang, '', dict)); for (const [lang, dict] of Object.entries(dicts)) fs.writeFileSync(path.join(OUT, 'i18n', `${lang}.js`), D.format(lang, '', dict));
@ -50,10 +53,13 @@ if (!html.includes(PH)) die('release-notes placeholder missing from the page');
// A release can also open with a story (prose before its first bullet), shown in full in "What's new". // A release can also open with a story (prose before its first bullet), shown in full in "What's new".
const story = execFileSync(process.execPath, [path.join(__dirname, 'release-notes.js'), VERSION, '--story'], { encoding: 'utf8' }), PS = '/*__RELEASE_STORY__*/[]'; const story = execFileSync(process.execPath, [path.join(__dirname, 'release-notes.js'), VERSION, '--story'], { encoding: 'utf8' }), PS = '/*__RELEASE_STORY__*/[]';
if (!html.includes(PS)) die('release-story placeholder missing from the page'); if (!html.includes(PS)) die('release-story placeholder missing from the page');
const PM = "/*__MP_API__*/''"; const PM = "/*__MP_API__*/''", PI = "/*__SIM_ID__*/''";
if (!html.includes(PM)) die('multiplayer placeholder missing from the page'); if (!html.includes(PM)) die('multiplayer placeholder missing from the page');
fs.writeFileSync(page, html.replace(PH, () => notes.replace(/</g, '\\u003c')).replace(PS, () => story.replace(/</g, '\\u003c')).replace(PM, () => `'${MP_API}'`)); if (!html.includes(PI)) die('server-play build id placeholder missing from the page');
fs.writeFileSync(path.join(OUT, 'version.json'), JSON.stringify({ version: VERSION, date: BUILD_DATE, notes: JSON.parse(notes), story: JSON.parse(story) }, null, 2) + '\n'); let out = html.replace(PH, () => notes.replace(/</g, '\\u003c')).replace(PS, () => story.replace(/</g, '\\u003c')).replace(PM, () => `'${MP_API}'`);
if (SIM_ID) out = out.replace(PI, () => `'${SIM_ID}'`);
fs.writeFileSync(page, out);
fs.writeFileSync(path.join(OUT, 'version.json'), JSON.stringify({ version: VERSION, date: BUILD_DATE, notes: JSON.parse(notes), story: JSON.parse(story), ...(SIM_ID ? { simId: SIM_ID } : {}) }, null, 2) + '\n');
// Nothing may ship half-stamped. // Nothing may ship half-stamped.
const left = []; const left = [];

View file

@ -16,8 +16,9 @@ const D = require('./lib/dict');
const { CALL } = require('./legacy/labels'); const { CALL } = require('./legacy/labels');
const SITE = path.join(__dirname, '..', 'site'); const SITE = path.join(__dirname, '..', 'site');
// The development page: it has every label, the agent's (src/agent/) too. // The development page of a multiplayer build: it has every label, the agent's (src/agent/) and the server-play
const page = () => require('./lib/page').assemble({ dev: true }).html; // client's (src/game/98-server-play/, only in MP builds) too. src: another source tree (tests).
const page = (src) => require('./lib/page').assemble({ src, dev: true, mp: true }).html;
const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/; const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/;
// The bodies of the page's bare <script> tags. Our own assembled page, so a plain search is enough. // The bodies of the page's bare <script> tags. Our own assembled page, so a plain search is enough.
@ -107,7 +108,7 @@ function checkEnglish(src, en) {
return out; return out;
} }
module.exports = { loadDict, brokenEntries, sourceLabels }; module.exports = { loadDict, brokenEntries, sourceLabels, page };
// A language file only works if the game offers it and the offline cache keeps it. // A language file only works if the game offers it and the offline cache keeps it.
function registration(lang, html) { function registration(lang, html) {

View file

@ -100,7 +100,8 @@
if (k === 'fail') { S.nextFail = S.day + 1; return ''; } if (k === 'fail') { S.nextFail = S.day + 1; return ''; }
if (k === 'event') { S.nextEvent = S.day + 1; return ''; } if (k === 'event') { S.nextEvent = S.day + 1; return ''; }
if (k === 'cash') { S.cash += a; after(); return ''; } if (k === 'cash') { S.cash += a; after(); return ''; }
if (k === 'lvl') { S.lvl = Math.min(LEVELS.length, (S.lvl || 0) + 1); after(); return ''; } // One level up from the level the game reads (lvl(): S.lvl, or 1 when a page never wrote it down).
if (k === 'lvl') { S.lvl = Math.min(LEVELS.length, (S.lvl || 1) + 1); after(); return ''; }
// Events that move routes, as the game's own events set them. // Events that move routes, as the game's own events set them.
if (k === 'ev') { if (k === 'ev') {
const n = NETS[a % NETS.length].id; const n = NETS[a % NETS.length].id;
@ -148,28 +149,49 @@
// ---------- digests ---------- // ---------- digests ----------
// Everything routing produced: R in full (with every link's R.ef), the flows (R.fl), and what the PNI lists read. // Everything routing produced: R in full (with every link's R.ef), the flows (R.fl), and what the PNI lists read.
// An attack's record names its attack by id (as rwPack does): the attack itself is game state, compared with S.
const rj = (v) => JSON.stringify(v, (k, x) => (k === 'attack' && x && typeof x === 'object' ? x.id : x));
const routing = () => { const routing = () => {
if (!R) return 'noR'; if (!R) return 'noR';
const r = JSON.stringify(R), fl = R.fl ? JSON.stringify(R.fl) : ''; const r = rj(R), fl = R.fl ? JSON.stringify(R.fl) : '';
let pf = ''; let pf = '';
if (typeof pniFlows === 'function' && S && !pzOn()) for (const c of Object.keys(S.pops).slice(0, 4)) try { pf += c + JSON.stringify(pniFlows(c)); } catch (e) { pf += c + 'E' + e.message; } if (typeof pniFlows === 'function' && S && !pzOn()) for (const c of Object.keys(S.pops).slice(0, 4)) try { pf += c + JSON.stringify(pniFlows(c)); } catch (e) { pf += c + 'E' + e.message; }
return r + '\n' + fl + '\n' + pf; return r + '\n' + fl + '\n' + pf;
}; };
const parts = () => { const o = {}; if (!R) return o; for (const k of Object.keys(R)) o[k] = JSON.stringify(R[k]); o.fl = R.fl ? JSON.stringify(R.fl) : ''; return o; }; const parts = () => { const o = {}; if (!R) return o; for (const k of Object.keys(R)) o[k] = rj(R[k]); o.fl = R.fl ? JSON.stringify(R.fl) : ''; return o; };
// A field only this checkout's game has (a new feature's state, on S or on its customers and offers) cannot match main // A field only this checkout's game has (a new feature's state, on S or on its customers and offers) cannot match main
// yet: the driver passes those (drop) and they are left out; every field both games have must still match. // yet: the driver passes those (drop) and they are left out; every field both games have must still match.
// The intern's state two levels deep (ops.on.sales, ops.wk.rev): a standing order one game has and the other retired. // The intern's state two levels deep (ops.on.sales, ops.wk.rev): a standing order one game has and the other retired.
const opsPaths = () => { const O = S.ops, out = []; if (!O || typeof O !== 'object') return out; // Compared as a reload makes it (migrate(), keys in order): the same game, whichever way each version writes the
// fields it fills in anyway (main may create a record without the defaults a reload gives it, in another order).
// One reload judges both: the driver passes the base page's live state (sLive) through this checkout's migrate()
// (sDigest(drop, json)), so a repair only one version's reload makes (main's re-aimed an attack whose customer left
// during the day) is no divergence. That reload runs with this page's own S in scope (sanitize reads S.rules through
// rule()): pages in lockstep have the same, and a difference in the rules shows up in the fields they decide. A POP without a router model plays the basic one (RG[p.rgen||0]): that is written
// down first, so the reload does not guess one from its ports (a free upgrade a page from before canonical state got).
// Puzzles are never saved: as they are. The rules stay as they are too: both pages may have set them alike (noIp4),
// and a base that does not know a rule would drop it on the way.
const sortK = (v) => (Array.isArray(v) ? v.map(sortK) : v && typeof v === 'object' ? Object.keys(v).sort().reduce((o, k) => ((o[k] = sortK(v[k])), o), {}) : v);
const sLive = () => JSON.stringify(S === undefined ? null : S);
const sOf = (json) => { const live = JSON.parse(json); if (!live || !S || pzOn() || live.mode === 'puzzle') return live; const u0 = uidN, r0 = S.rng;
try {
for (const c of Object.keys(live.pops || {})) if (live.pops[c] && live.pops[c].rgen === undefined) live.pops[c].rgen = 0;
const rules = live.rules === undefined ? undefined : JSON.parse(JSON.stringify(live.rules));
const s = migrate(live); s.rules = rules; return sortK(s);
} finally { uidN = u0; S.rng = r0; } };
const sNow = () => sOf(sLive());
const opsPaths = (s = sNow()) => { const O = s.ops, out = []; if (!O || typeof O !== 'object') return out;
for (const k of Object.keys(O)) { out.push(k); const v = O[k]; if (v && typeof v === 'object' && !Array.isArray(v)) for (const j of Object.keys(v)) out.push(k + '.' + j); } return out; }; for (const k of Object.keys(O)) { out.push(k); const v = O[k]; if (v && typeof v === 'object' && !Array.isArray(v)) for (const j of Object.keys(v)) out.push(k + '.' + j); } return out; };
const sKeys = () => ({ top: Object.keys(S), items: [...new Set([...(S.biz || []), ...(S.offers || [])].flatMap((x) => Object.keys(x)))], ops: opsPaths(), orders: typeof OPSK === 'object' ? Object.keys(OPSK) : [] }); const sKeys = () => { const s = sNow(); return { top: Object.keys(s), items: [...new Set([...(s.biz || []), ...(s.offers || [])].flatMap((x) => Object.keys(x)))], ops: opsPaths(s), orders: typeof OPSK === 'object' ? Object.keys(OPSK) : [] }; };
const opsDrop = (ops) => { const o = {}; for (const k of Object.keys(S.ops)) { if (ops.includes(k)) continue; const v = S.ops[k]; const opsDrop = (s, ops) => { const o = {}; for (const k of Object.keys(s.ops)) { if (ops.includes(k)) continue; const v = s.ops[k];
if (v && typeof v === 'object' && !Array.isArray(v)) { const w = {}; for (const j of Object.keys(v)) if (!ops.includes(k + '.' + j)) w[j] = v[j]; o[k] = w; } else o[k] = v; } return o; }; if (v && typeof v === 'object' && !Array.isArray(v)) { const w = {}; for (const j of Object.keys(v)) if (!ops.includes(k + '.' + j)) w[j] = v[j]; o[k] = w; } else o[k] = v; } return o; };
const sDrop = (drop) => { if (!drop || (!drop.top.length && !drop.items.length && !(drop.ops || []).length)) return S; const o = {}; // json: a live state to judge (the other page's, from sLive); without it, this page's own.
for (const k of Object.keys(S)) if (!drop.top.includes(k)) o[k] = k === 'ops' && S.ops && (drop.ops || []).length ? opsDrop(drop.ops) : S[k]; const sDrop = (drop, json) => { const s = json === undefined ? sNow() : sOf(json); if (!s || typeof s !== 'object' || !drop || (!drop.top.length && !drop.items.length && !(drop.ops || []).length)) return s; const o = {};
for (const k of Object.keys(s)) if (!drop.top.includes(k)) o[k] = k === 'ops' && s.ops && (drop.ops || []).length ? opsDrop(s, drop.ops) : s[k];
for (const k of ['biz', 'offers']) if (Array.isArray(o[k])) o[k] = o[k].map((x) => { const y = {}; for (const f of Object.keys(x)) if (!drop.items.includes(f)) y[f] = x[f]; return y; }); for (const k of ['biz', 'offers']) if (Array.isArray(o[k])) o[k] = o[k].map((x) => { const y = {}; for (const f of Object.keys(x)) if (!drop.items.includes(f)) y[f] = x[f]; return y; });
return o; }; return o; };
const sDigest = (drop) => JSON.stringify(sDrop(drop)); const sDigest = (drop, json) => JSON.stringify(sDrop(drop, json));
const sParts = (drop) => { const s = sDrop(drop), o = {}; for (const k of Object.keys(s)) o[k] = JSON.stringify(s[k]); return o; }; const sParts = (drop, json) => { const s = sDrop(drop, json), o = {}; if (s && typeof s === 'object') for (const k of Object.keys(s)) o[k] = JSON.stringify(s[k]); return o; };
/* After a move: what the move routed (a), routing again from the same state (b: on this checkout's page the kept /* After a move: what the move routed (a), routing again from the same state (b: on this checkout's page the kept
tables are used), and routing from that state with the cache off (c: RC.on=false where there is an RC). b and c tables are used), and routing from that state with the cache off (c: RC.on=false where there is an RC). b and c
route from the same previous R; c's R is kept, as a plain compute would. */ route from the same previous R; c's R is kept, as a plain compute would. */
@ -188,5 +210,5 @@
// Scarce IPv4 off (#150, rule ip4), the same rules object with its keys in the same order on both pages: the driver calls // Scarce IPv4 off (#150, rule ip4), the same rules object with its keys in the same order on both pages: the driver calls
// it only while the base has no such rule, so the pages play the same game until it lands. // it only while the base has no such rule, so the pages play the same game until it lands.
const noIp4 = () => { if (S && S.rules) { const { ip4, mods, ...r } = S.rules; S.rules = { ...r, ip4: false, mods }; } }; const noIp4 = () => { if (S && S.rules) { const { ip4, mods, ...r } = S.rules; S.rules = { ...r, ip4: false, mods }; } };
window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen, noIp4 }; window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sLive, sDigest, sParts, check, errs, modalOpen, noIp4 };
})(); })();

579
scripts/lib/mp-sim-acts.js Normal file
View file

@ -0,0 +1,579 @@
// What a page of a server-run network may ask the session server to do, as plain data, and the envelope check every
// request body passes before anything reaches a game (docs: the server-sim design, sections 5.8-5.9 and 10).
// Shared by the realm (scripts/lib/mp-sim-realm.js), the host (scripts/lib/mp-sim.js) and the page's own copies
// (src/game/98-server-play/40-acts.js), which tests hold equal to these tables. Plain data only: no game code here,
// and nothing here is ever evaluated.
//
// Every ACT is in exactly one of SEND, ASK, VOTE, LOCAL or PUZZLE (tests/mp-sim-contract.test.js names the act and this
// file when one is not). SEND is the agent's API_CMD minus the pz* acts and teCheck, traceRun, closeModal, plus
// connCancel, pieRename and tutSkip: a test derives it again, so nobody counts it by hand.
'use strict';
// Acts that change the game: the page sends them, the server runs them as a click (ACT[act](args)).
const SEND = [
'accept',
'ad',
'addCh',
'addGen',
'addPair',
'addRouter',
'addSite',
'applyCn',
'bstdApply',
'bstdSet',
'buildLink',
'buildPop',
'buildScrub',
'buyIx',
'buyNni',
'buySat',
'buySpare',
'buyTE',
'buyTransit',
'buyVxc',
'cache',
'cacheSite',
'callBank',
'cancelIx',
'cancelPni',
'cancelTransit',
'cancelVxc',
'charter',
'cleanPipe',
'confGo',
'confSponsor',
'connCancel',
'coreLab',
'coreSet',
'coreUp',
'crews',
'ddosAuto',
'ddosEngage',
'ddosTest',
'decline',
'declineLoan',
'decomGo',
'demoAsk',
'dkAccept',
'dkHaggle',
'dkOptOut',
'dkStay',
'dkWalk',
'downIx',
'downP',
'downT',
'dropBiz',
'fixInc',
'foundIx',
'hackback',
'hwLock',
'ip4Back',
'ip4Buy',
'ip4Lease',
'ip4Nat',
'ip4Nat64',
'ip4Out',
'ip4Return',
'ip4Sell',
'ip6Go',
'ip6Stop',
'lagIx',
'lagNni',
'lagP',
'lagT',
'launchBB',
'layShip',
'listFiber',
'metricMode',
'metricSet',
'mkBanana',
'myIxUp',
'opsCap',
'opsFire',
'opsFloor',
'opsHire',
'opsNewPop',
'opsParam',
'opsPop',
'opsToggle',
'opsTpl',
'orderCable',
'orderDf',
'peer',
'peerAll',
'peerPol',
'pieAnt',
'pieBid',
'pieDish',
'pieExim',
'pieFactory',
'pieFound',
'pieLaunch',
'pieLic',
'pieName',
'piePad',
'pieRd',
'pieRename',
'pieSafe',
'pieSpatPick',
'pni',
'pniAll',
'pniChase',
'popStdClear',
'popStdSet',
'regen',
'renameGo',
'renewLet',
'renewMatch',
'renewMeet',
'repayLoan',
'rmCache',
'rmCh',
'rmLink',
'rmNni',
'rmRouter',
'rmScrub',
'rmSite',
'rs',
'rtbh',
'sacrif',
'salesAuto',
'salesFire',
'salesHire',
'salesMin',
'salesRen',
'salesVp',
'satSize',
'scrubMode',
'scrubUp',
'seaRush',
'seatBuy',
'seatNo',
'sellSpare',
'setCarry',
'setChCount',
'setMetric',
'setPref',
'setRoute',
'setStandby',
'siteSet',
'spares',
'subUpgrade',
'takeLoan',
'teClear',
'teDeploy',
'teToggle',
'teleBuild',
'teleRm',
'teleTrk',
'togglePrem',
'tutSkip',
'unlistFiber',
'unpeer',
'unrtbh',
'upLink',
'upRouter',
'upSys',
'upVxc',
'utilityCaches',
'utilityKit',
'utilityPeers',
'utilityRouteServers',
'xpBuild',
'xpCh',
];
// What-ifs the server answers with the window they open, putting the game back as it was (5.9).
const ASK = ['linkCheck', 'teCheck', 'teSlop'];
// The clock's buttons: on a server network they are a vote for the session's speed (4.5).
const VOTE = ['phonePlay', 'phoneSpeed', 'speed'];
// The page runs these itself: views, drafts, settings, slots, session acts, teOpt.
const LOCAL = [
'addParallel',
'animSet',
'bank',
'bankClose',
'bstdOpen',
'chaosSet',
'chartToggle',
'closeModal',
'closePanel',
'cnPrem',
'connCity',
'connF',
'connFor',
'connNet',
'connOpen',
'connSort',
'cont',
'custCity',
'custF',
'custGo',
'custOpen',
'custSort',
'dash',
'dashClose',
'dashLink',
'dashSort',
'dashTab',
'decomOpen',
'decomToggle',
'dfMode',
'dfSrc',
'dfSys',
'exportSave',
'findGo',
'findOpen',
'focusCity',
'goConn',
'goEgress',
'help',
'helpClose',
'importGo',
'importPick',
'install',
'ip4Open',
'ip4Pick',
'keepPlaying',
'keys',
'langSet',
'leaseSwap',
'leftTab',
'listMore',
'logAll',
'logOpen',
'mapSet',
'meetGo',
'menu',
'modeSet',
'models',
'mpBack',
'mpChat',
'mpCopyLink',
'mpDoor',
'mpJoin',
'mpKeep',
'mpLeave',
'mpLeaveAsk',
'mpNewer',
'mpOpen',
'mpShare',
'mpStart',
'mute',
'netFilter',
'netFocus',
'newgame',
'nocWindow',
'offerStep',
'openVxc',
'opsCity',
'opsOpen',
'ownCab',
'phoneTab',
'pickHome',
'pickStart',
'pieCity',
'pieGlobeNight',
'pieGovOpen',
'pieHi',
'pieIns',
'pieLas',
'pieOpen',
'pieSpatOpen',
'pieTab',
'pitchSkip',
'pniAllOpen',
'pniAllSize',
'pniFilter',
'pniGrp',
'pniSort',
'popGo',
'popStep',
'popsReg',
'popsSort',
'prefSet',
'presetSet',
'puzzleDoor',
'puzzleMenu',
'randomName',
'rename',
'resetAsk',
'route',
'routingOpen',
'salesOpen',
'satOpen',
'scenarios',
'seaDesign',
'seaPackage',
'selLink',
'settings',
'settingsClose',
'share',
'shareDl',
'shareGo',
'slotBack',
'slotDel',
'slotDelGo',
'slotExport',
'slotMenu',
'slotRetry',
'slotSpace',
'slotSwitch',
'slotTake',
'soundSet',
'start',
'startScn',
'startWeekly',
'tab',
'tailTog',
'teBack',
'teClose',
'teEdit',
'teExample',
'teHelp',
'teOpt',
'teRecipe',
'themeSet',
'toTitle',
'toggleLeft',
'trace',
'traceCopy',
'traceMode',
'traceRun',
'updateLater',
'updateNow',
'utilities',
'utilityPick',
'via',
'vpSet',
'whatsNewShow',
'wsShare',
'xpOpen',
'zoomStep',
];
// Puzzles never run on the server: they stay on the device, like everything that starts with pz.
const PUZZLE = [
'pzAddPar',
'pzArAll',
'pzArGo',
'pzArNext',
'pzArSkip',
'pzArStart',
'pzCity',
'pzDiv',
'pzFinish',
'pzLeave',
'pzLink',
'pzLinkTo',
'pzLook',
'pzMkSkip',
'pzMonkey',
'pzPop',
'pzReset',
'pzRetry',
'pzRmLink',
'pzRmPop',
'pzRoute',
'pzRtAdd',
'pzRtModel',
'pzRtRm',
'pzShare',
'pzStart',
'pzTab',
'pzTier',
'pzUndo',
'pzVia',
'pzWeekly',
];
/* Two-click buttons: the first click arms the button on the page (a view change), only the second is sent, with
confirmed:true. 'arg': the act takes ok:1 and runs at once. Anything else: the key the first click writes to
UI.confirm, as a template over the act's args ({id} is String(args.id)); the server sets UI.confirm to it and runs the
act once. */
const CONFIRM = {
cancelIx: 'arg',
cancelPni: 'arg',
cancelTransit: 'arg',
cancelVxc: '{id}',
connCancel: 'cc:{k}:{id}',
dkOptOut: 'dk{city}{n}',
dropBiz: '{id}',
ip4Sell: '{id}',
opsFire: 'opsFire',
repayLoan: '{id}',
rmLink: '{id}',
rmScrub: 'scrub:{city}',
rmSite: 'site{city}',
salesFire: 'salesFire',
teleRm: 'tele:{city}',
};
// The UI.confirm key a preset act's first click writes (null for 'arg' acts and acts that do not confirm).
const SRV_ARM = Object.fromEntries(Object.entries(CONFIRM).filter(([, v]) => v !== 'arg'));
function armKey(act, args) {
const t = Object.prototype.hasOwnProperty.call(SRV_ARM, act) ? SRV_ARM[act] : null;
return t === null ? null : t.replace(/\{(\w+)\}/g, (m, k) => String(args && args[k] !== undefined ? args[k] : ''));
}
/* The UI drafts an act reads, and the only UI keys a request may set (its ui object). Types are checked here; the realm
checks the values against the game's catalogs (cities, CABLES, DF_SYS, SEA_DESIGNS, the route picker's values). */
const DRAFTS = {
buildLink: ['pending', 'route', 'via', 'cnPrem'],
decomGo: ['decom'],
orderCable: ['pending', 'seaDesign', 'seaterminal', 'seaengineering'],
orderDf: ['pending', 'dfSrc', 'dfSys'],
pieLaunch: ['pieIns', 'pieLas'],
teDeploy: ['slop'],
};
// pair: {a, b}, two different city-like ids; id: a short id string; ids: an array of at most 200 of them (a Set in the game).
const DRAFT_TYPES = {
cnPrem: 'boolean',
decom: 'ids',
dfSrc: ['lease', 'build', 'cable'],
dfSys: 'id',
pending: 'pair',
pieIns: 'boolean',
pieLas: 'boolean',
route: 'string',
seaDesign: 'id',
seaengineering: 'boolean',
seaterminal: 'boolean',
slop: 'boolean',
via: 'string',
};
// Args longer than the envelope's 64 characters: their own cap (the game cuts the texts shorter itself).
const TEXT = {
metricSet: { v: 16 },
pieRename: { name: 64 },
renameGo: { name: 64 },
teCheck: { script: 4000 },
teDeploy: { script: 4000 },
utilityCaches: { quote: 1024 },
};
/* Acts that charge a total the player saw in a window, planned again at the click: the arg that carries what the window
showed. The game refuses a different one ("The quote changed"); the server also refuses a request without it.
'quote' is the plan's key (a string), any other name the total (a number). pniAll: the exact total (fixed prices, so
the total names the plan). bstdApply: the plan's key, plus its total q, which may drift 1% (hardware prices move
daily under the market rule). utilityKit: the total, within 1%. utilityCaches: the list of boxes. */
const QUOTE = {
bstdApply: 'quote',
pniAll: 'q',
utilityCaches: 'quote',
utilityKit: 'cost',
};
const ID_RE = /^[a-z0-9]{8,16}$/, SIM_RE = /^[0-9a-f]{12}$/, KEY_RE = /^[A-Za-z][A-Za-z0-9]{0,15}$/, VIEW_RE = /^[a-z0-9]{1,16}$/, SHORT_RE = /^[A-Za-z0-9_.:|~-]{1,40}$/;
const SPEEDS = [0, 0.5, 1, 2, 4, 8];
// The viewport a request's ctx may set on the realm, in CSS pixels: checkEnvelope clamps ctx.w and ctx.h into it.
const VIEW_MIN = 200, VIEW_MAX = 4000;
const PREFS = ['pauseFurious', 'pauseIncident', 'warnUnhappy'];
const SETS = { SEND: new Set(SEND), ASK: new Set(ASK), CONFIRM: new Set(Object.keys(CONFIRM)) };
const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
const plain = (o) => !!o && typeof o === 'object' && !Array.isArray(o) && (Object.getPrototypeOf(o) === Object.prototype || Object.getPrototypeOf(o) === null);
const prim = (v, cap) => v === null || typeof v === 'boolean' || (typeof v === 'number' && Number.isFinite(v)) || (typeof v === 'string' && v.length <= cap);
// Keys a request object may never carry, whatever the regex says.
const BAD_KEY = new Set(['__proto__', 'constructor', 'prototype']);
function bad(error, code = 400, extra = {}) { return { ok: false, code, error, ...extra }; }
function checkArgs(act, args) {
if (!plain(args)) return 'args must be an object';
const keys = Object.keys(args);
if (keys.length > 12) return 'too many args';
const caps = own(TEXT, act) ? TEXT[act] : {};
for (const k of keys) {
if (!KEY_RE.test(k) || BAD_KEY.has(k)) return `bad arg name ${JSON.stringify(k).slice(0, 40)}`;
const v = args[k], cap = own(caps, k) ? caps[k] : 64;
if (Array.isArray(v)) { if (v.length > 64 || !v.every((x) => prim(x, 64))) return `bad arg ${k}`; continue; }
if (!prim(v, cap)) return `bad arg ${k}`;
}
if (own(QUOTE, act)) { const q = args[QUOTE[act]]; if (QUOTE[act] === 'quote' ? typeof q !== 'string' : !(typeof q === 'number' && Number.isFinite(q))) return `${act} needs the quoted ${QUOTE[act]}`; }
return null;
}
function checkDraft(k, v) {
const t = DRAFT_TYPES[k];
if (Array.isArray(t)) return t.includes(v);
if (t === 'boolean') return typeof v === 'boolean';
if (t === 'string') return typeof v === 'string' && v.length <= 64;
if (t === 'id') return typeof v === 'string' && SHORT_RE.test(v);
// Two different places: the game's own drag never opens a link from a city to itself.
if (t === 'pair') return plain(v) && Object.keys(v).length === 2 && typeof v.a === 'string' && typeof v.b === 'string' && SHORT_RE.test(v.a) && SHORT_RE.test(v.b) && v.a !== v.b;
if (t === 'ids') return Array.isArray(v) && v.length <= 200 && v.every((x) => typeof x === 'string' && SHORT_RE.test(x));
return false;
}
function checkCtx(c) {
if (!plain(c)) return 'ctx must be an object';
for (const k of Object.keys(c)) {
const v = c[k];
if (k === 'sel') { if (v !== null && !(plain(v) && Object.keys(v).length === 2 && (v.type === 'city' || v.type === 'link') && typeof v.id === 'string' && SHORT_RE.test(v.id))) return 'bad ctx.sel'; }
else if (k === 'tab' || k === 'left') { if (v !== null && !(typeof v === 'string' && VIEW_RE.test(v))) return `bad ctx.${k}`; }
else if (k === 'modal' || k === 'coarse') { if (typeof v !== 'boolean') return `bad ctx.${k}`; }
// The page sends its innerWidth/innerHeight as they are: a 5120-px monitor, or a desktop zoomed out, is wider than
// anything the layout tells apart (isPhone() and the like only ask whether it is under about 760). Clamped, not refused.
else if (k === 'w' || k === 'h') { if (!(typeof v === 'number' && Number.isFinite(v) && v > 0 && v <= 1e5)) return `bad ctx.${k}`; c[k] = Math.min(VIEW_MAX, Math.max(VIEW_MIN, v)); }
else return `unknown ctx.${String(k).slice(0, 20)}`;
}
return null;
}
const bool = (v) => v === undefined || typeof v === 'boolean';
/* The envelope of one request body, before anything reaches a game. kind: 'act' | 'ask' | 'vote' | 'here' | 'prefs'.
opts.sim: the server's build id; a request built by another one answers 409 {old:true}. Returns {ok:true} or
{ok:false, code (400 or 409), error, old?}. Only shapes are checked here; what the ids name is the realm's to check.
One repair, in place: ctx.w and ctx.h (any finite width up to 100000) are clamped into VIEW_MIN–VIEW_MAX, so the
realm only ever sees a viewport in that range. */
function checkEnvelope(kind, body, opts = {}) {
if (!plain(body)) return bad('the body must be a JSON object');
const keys = Object.keys(body);
const only = (allowed) => { for (const k of keys) if (!allowed.includes(k)) return `unknown field ${JSON.stringify(k).slice(0, 40)}`; return null; };
const simOk = () => {
if (typeof body.sim !== 'string' || !SIM_RE.test(body.sim)) return bad('sim must be the page\'s build id');
if (opts.sim && body.sim !== opts.sim) return bad('this page is from another build', 409, { old: true });
return null;
};
if (kind === 'act' || kind === 'ask') {
const e = only(kind === 'act' ? ['rid', 'dev', 'sim', 'act', 'args', 'ui', 'confirmed', 'ctx'] : ['rid', 'dev', 'sim', 'act', 'args', 'ctx']);
if (e) return bad(e);
if (typeof body.rid !== 'string' || !ID_RE.test(body.rid)) return bad('bad rid');
if (typeof body.dev !== 'string' || !ID_RE.test(body.dev)) return bad('bad dev');
const s = simOk(); if (s) return s;
if (typeof body.act !== 'string' || !(kind === 'act' ? SETS.SEND : SETS.ASK).has(body.act)) return bad(`${kind} ${JSON.stringify(String(body.act).slice(0, 40))} is not one the server runs`);
const a = checkArgs(body.act, body.args === undefined ? {} : body.args); if (a) return bad(a);
if (body.ui !== undefined) {
if (kind !== 'act' || !plain(body.ui)) return bad('bad ui');
const allowed = own(DRAFTS, body.act) ? DRAFTS[body.act] : [];
for (const k of Object.keys(body.ui)) if (!allowed.includes(k) || !checkDraft(k, body.ui[k])) return bad(`bad ui.${String(k).slice(0, 20)}`);
}
if (body.confirmed !== undefined && (body.confirmed !== true || !SETS.CONFIRM.has(body.act))) return bad('confirmed only goes with a two-click act');
if (body.ctx !== undefined) { const c = checkCtx(body.ctx); if (c) return bad(c); }
return { ok: true };
}
if (kind === 'vote') {
const e = only(['speed', 'sim']); if (e) return bad(e);
const s = simOk(); if (s) return s;
if (body.speed !== null && !SPEEDS.includes(body.speed)) return bad('bad speed');
return { ok: true };
}
if (kind === 'here') {
const e = only(['dev', 'hidden', 'hold', 'idle', 'away', 'view']); if (e) return bad(e);
if (typeof body.dev !== 'string' || !ID_RE.test(body.dev)) return bad('bad dev');
if (!['hidden', 'hold', 'idle', 'away'].every((k) => bool(body[k]))) return bad('bad flag');
if (body.view !== undefined) {
const v = body.view;
if (v !== null && !(plain(v) && Object.keys(v).every((k) => (k === 'link' || k === 'peer') && (v[k] === null || (typeof v[k] === 'string' && SHORT_RE.test(v[k])))))) return bad('bad view');
}
return { ok: true };
}
if (kind === 'prefs') {
const e = only(['prefs', 'lang']); if (e) return bad(e);
if (body.prefs !== undefined && !(plain(body.prefs) && Object.keys(body.prefs).every((k) => PREFS.includes(k) && typeof body.prefs[k] === 'boolean'))) return bad('bad prefs');
if (body.lang !== undefined && !(typeof body.lang === 'string' && /^[a-z]{2}(-[A-Za-z]{2,4})?$/.test(body.lang))) return bad('bad lang');
return { ok: true };
}
return bad(`unknown kind ${String(kind).slice(0, 20)}`);
}
// Body size caps per kind, in bytes (section 10), for the host's readJson.
const BODY_MAX = { act: 16384, ask: 8192, here: 2048, prefs: 1024, vote: 256 };
module.exports = { SEND, ASK, VOTE, LOCAL, PUZZLE, CONFIRM, SRV_ARM, armKey, DRAFTS, DRAFT_TYPES, TEXT, QUOTE, SPEEDS, PREFS, VIEW_MIN, VIEW_MAX, BODY_MAX, checkEnvelope };

View file

@ -8,9 +8,14 @@
// MCP server's own page and the tests that ask for it. Everywhere else the line is dropped whole, so // MCP server's own page and the tests that ask for it. Everywhere else the line is dropped whole, so
// the page players get is exactly what it would be without it (docs/adr/0004-dev-only-code.md). // the page players get is exactly what it would be without it (docs/adr/0004-dev-only-code.md).
// //
// The server-run play of a multiplayer build (src/game/98-server-play/ and src/styles/43-server-play.css) is only in a
// page assembled with mp: true, which MP_API=… npm run build asks for; every other page, the one players get on
// GitHub Pages included, has none of it.
//
// node scripts/lib/page.js [-o FILE] the page as it ships (stdout by default) // node scripts/lib/page.js [-o FILE] the page as it ships (stdout by default)
// node scripts/lib/page.js --source [-o FILE] assembled only, labels as in src/ (what tests use) // node scripts/lib/page.js --source [-o FILE] assembled only, labels as in src/ (what tests use)
// node scripts/lib/page.js --source --dev [-o FILE] the development page: with src/agent/ (what npm run dev serves) // node scripts/lib/page.js --source --dev [-o FILE] the development page: with src/agent/ (what npm run dev serves)
// node scripts/lib/page.js --mp [--source] [-o FILE] a multiplayer build's page: with the server-play client
// node scripts/lib/page.js --ref origin/main -o FILE the page as it ships at a git ref // node scripts/lib/page.js --ref origin/main -o FILE the page as it ships at a git ref
// //
// --ref uses that commit's own assembler, so it keeps working when this file changes; refs from before // --ref uses that commit's own assembler, so it keeps working when this file changes; refs from before
@ -22,6 +27,9 @@ const { execFileSync } = require('node:child_process');
const ROOT = path.join(__dirname, '..', '..'); const ROOT = path.join(__dirname, '..', '..');
const INCLUDE = /^<!-- @include(-dev)? ([\w./-]+) -->$/; const INCLUDE = /^<!-- @include(-dev)? ([\w./-]+) -->$/;
// Parts of src/ only a multiplayer build's page has (paths as the line map names them; a trailing / is a folder).
const MP_ONLY = ['game/98-server-play/', 'styles/43-server-play.css'];
const mpOnly = (f) => MP_ONLY.some((p) => (p.endsWith('/') ? f.startsWith(p) : f === p));
// Every file under dir, as paths relative to dir with '/' separators, in a stable order // Every file under dir, as paths relative to dir with '/' separators, in a stable order
// (plain code-unit comparison, so the order never depends on the machine's locale). // (plain code-unit comparison, so the order never depends on the machine's locale).
@ -36,11 +44,11 @@ function listFiles(dir, rel = '') {
return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
} }
// The partials that make up one include, in order: [{file, text}]. // The partials that make up one include, in order: [{file, text}]. Without mp, the multiplayer-only ones are left out.
function partials(src, dir) { function partials(src, dir, mp = true) {
const base = path.join(src, dir); const base = path.join(src, dir);
if (!fs.existsSync(base)) throw new Error(`@include ${dir}: no such directory under ${path.relative(ROOT, src) || '.'}`); if (!fs.existsSync(base)) throw new Error(`@include ${dir}: no such directory under ${path.relative(ROOT, src) || '.'}`);
return listFiles(base).map((r) => { return listFiles(base).filter((r) => mp || !mpOnly(dir + '/' + r)).map((r) => {
const file = path.join(base, r); const file = path.join(base, r);
const text = fs.readFileSync(file, 'utf8'); const text = fs.readFileSync(file, 'utf8');
if (text.includes('\r')) throw new Error(`${path.relative(ROOT, file)}: use LF line endings`); if (text.includes('\r')) throw new Error(`${path.relative(ROOT, file)}: use LF line endings`);
@ -52,7 +60,8 @@ function partials(src, dir) {
// The assembled page as a string, plus a map of which output line came from which source file. // The assembled page as a string, plus a map of which output line came from which source file.
// dev: also the @include-dev parts (the development page); without it, their lines are left out entirely. // dev: also the @include-dev parts (the development page); without it, their lines are left out entirely.
function assemble({ src = path.join(ROOT, 'src'), dev = false } = {}) { // mp: also the multiplayer-only parts (MP_ONLY); without it, those files are left out entirely.
function assemble({ src = path.join(ROOT, 'src'), dev = false, mp = false } = {}) {
const shell = fs.readFileSync(path.join(src, 'index.html'), 'utf8'); const shell = fs.readFileSync(path.join(src, 'index.html'), 'utf8');
const out = [], map = []; const out = [], map = [];
let line = 1; let line = 1;
@ -65,7 +74,7 @@ function assemble({ src = path.join(ROOT, 'src'), dev = false } = {}) {
return; return;
} }
if (m[1] && !dev) return; if (m[1] && !dev) return;
for (const p of partials(src, m[2])) { for (const p of partials(src, m[2], mp)) {
const n = p.text.split('\n').length - 1; const n = p.text.split('\n').length - 1;
map.push({ file: p.file, from: line, to: line + n - 1 }); map.push({ file: p.file, from: line, to: line + n - 1 });
out.push(p.text); out.push(p.text);
@ -95,10 +104,17 @@ function assembleRef(ref, cwd = ROOT) {
} }
// The page as it ships: assembled, with labels shrunk to short ids (compile-labels.js). Not version-stamped. // The page as it ships: assembled, with labels shrunk to short ids (compile-labels.js). Not version-stamped.
// `dicts` ({lang: label-keyed dictionary}) come back with the same ids. // `dicts` ({lang: label-keyed dictionary}) come back with the same ids. mp: a multiplayer build's page.
function shipped(dicts = {}) { function shipped(dicts = {}, { mp = false } = {}) {
const D = require('./dict'); const D = require('./dict');
return require('./compile-labels').compile(assemble().html, D.read('en').dict, dicts); return require('./compile-labels').compile(assemble({ mp }).html, D.read('en').dict, dicts);
}
/* The build id of server-run play (SIM_ID): the first 12 hex digits of sha256 of the multiplayer page as assembled from
src/, labels as written (game and server-play client together, so a change to either is a new id). The build stamps
it into MP pages and version.json; the session server works it out from its own src/ and refuses pages of another. */
function simId(html = assemble({ mp: true }).html) {
return require('node:crypto').createHash('sha256').update(html).digest('hex').slice(0, 12);
} }
// The shipped page written to a file, for tools that need a path (perf in a real browser, base vs head). // The shipped page written to a file, for tools that need a path (perf in a real browser, base vs head).
@ -107,12 +123,13 @@ function pageFile(file = path.join(os.tmpdir(), `tubes-page-${process.pid}.html`
return file; return file;
} }
module.exports = { assemble, assembleRef, shipped, pageFile, locate, listFiles, ROOT }; module.exports = { assemble, assembleRef, shipped, simId, pageFile, locate, listFiles, MP_ONLY, ROOT };
if (require.main === module) { if (require.main === module) {
const args = process.argv.slice(2); const args = process.argv.slice(2);
const opt = (k) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : null; }; const opt = (k) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : null; };
const html = opt('--ref') ? assembleRef(opt('--ref')) : args.includes('--source') ? assemble({ dev: args.includes('--dev') }).html : shipped().html; const mp = args.includes('--mp');
const html = opt('--ref') ? assembleRef(opt('--ref')) : args.includes('--source') ? assemble({ dev: args.includes('--dev'), mp }).html : shipped({}, { mp }).html;
const out = opt('-o'); const out = opt('-o');
if (out) { fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true }); fs.writeFileSync(out, html); } if (out) { fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true }); fs.writeFileSync(out, html); }
else process.stdout.write(html); else process.stdout.write(html);

View file

@ -82,8 +82,9 @@ function playGame(pages, seed, opts = {}) {
// standing order only one of them has (one this checkout retired, or added). // standing order only one of them has (one this checkout retired, or added).
const [k1, k2] = both('sKeys'), drop = { top: k2.top.filter((k) => !k1.top.includes(k)), items: k2.items.filter((k) => !k1.items.includes(k)), const [k1, k2] = both('sKeys'), drop = { top: k2.top.filter((k) => !k1.top.includes(k)), items: k2.items.filter((k) => !k1.items.includes(k)),
ops: [...k1.ops.filter((k) => !k2.ops.includes(k)), ...k2.ops.filter((k) => !k1.ops.includes(k))] }; ops: [...k1.ops.filter((k) => !k2.ops.includes(k)), ...k2.ops.filter((k) => !k1.ops.includes(k))] };
const [s1, s2] = both('sDigest', drop); // Both states as this checkout's reload makes them (see sLive in fuzz-page.js).
if (s1 !== s2) { fail(where + ': game state S', { diff: firstDiff(base.call('sParts', drop), head.call('sParts', drop)) }); return false; } const [j1, j2] = both('sLive'), s1 = head.call('sDigest', drop, j1), s2 = head.call('sDigest', drop, j2);
if (s1 !== s2) { fail(where + ': game state S', { diff: firstDiff(head.call('sParts', drop, j1), head.call('sParts', drop, j2)) }); return false; }
return true; return true;
}; };
@ -111,7 +112,11 @@ function playGame(pages, seed, opts = {}) {
const screen = (w) => { const [a0, b0] = both('screen', w); baseActs = baseActs || new Set(base.call('acts')); const screen = (w) => { const [a0, b0] = both('screen', w); baseActs = baseActs || new Set(base.call('acts'));
if (!retired) { const [o1, o2] = both('sKeys'); retired = new Set(o1.orders.filter((k) => !o2.orders.includes(k))); } if (!retired) { const [o1, o2] = both('sKeys'); retired = new Set(o1.orders.filter((k) => !o2.orders.includes(k))); }
const a = Array.isArray(a0) ? a0.filter((x) => !(/^ops/.test(x.act) && retired.has(x.args && x.args.k))) : a0; const a = Array.isArray(a0) ? a0.filter((x) => !(/^ops/.test(x.act) && retired.has(x.args && x.args.k))) : a0;
const b = Array.isArray(b0) ? b0.filter((x) => baseActs.has(x.act)) : b0; same('buttons of ' + JSON.stringify(w), a, b); return a || []; }; // Args only this checkout's buttons carry (the total or plan a window shows: pniAll's q, bstdApply's quote) are left
// out as well: the driver presses the base's button, which both pages take as before.
const b = Array.isArray(b0) ? b0.filter((x) => baseActs.has(x.act)).map((x, i) => { const y = Array.isArray(a) && a[i] && a[i].act === x.act ? a[i].args : null;
return y && x.args && typeof x.args === 'object' && typeof y === 'object' ? { act: x.act, args: Object.fromEntries(Object.entries(x.args).filter(([k]) => k in y)) } : x; }) : b0;
same('buttons of ' + JSON.stringify(w), a, b); return a || []; };
const press = (b, where) => { acts[b.act] = (acts[b.act] || 0) + 1; const [e1, e2] = both('press', b); same('press ' + where, e1, e2); note(where + ' ' + b.act + JSON.stringify(b.args) + (e1 ? ' !' + e1 : '')); }; const press = (b, where) => { acts[b.act] = (acts[b.act] || 0) + 1; const [e1, e2] = both('press', b); same('press ' + where, e1, e2); note(where + ' ' + b.act + JSON.stringify(b.args) + (e1 ? ' !' + e1 : '')); };
// Answer whatever window opened, a few levels deep, then close it. // Answer whatever window opened, a few levels deep, then close it.
const modal = (bias) => { const modal = (bias) => {

View file

@ -0,0 +1,18 @@
// A node:test reporter that writes how long each test file took, as JSON {"tests/x.test.js": seconds}, to its
// destination. scripts/test.js adds it next to the usual output with --timings FILE; CI merges the parts' files
// into tests/durations.json, which the next run splits its parts by.
const path = require('node:path');
module.exports = async function* timings(source) {
const sec = {};
for await (const { type, data } of source) {
// Top-level tests only: their durations include their subtests.
if ((type === 'test:pass' || type === 'test:fail') && data.nesting === 0 && data.file && data.details) {
const f = path.relative(process.cwd(), data.file).split(path.sep).join('/');
sec[f] = (sec[f] || 0) + (data.details.duration_ms || 0) / 1000;
}
}
const out = {};
for (const f of Object.keys(sec).sort()) out[f] = Math.round(sec[f] * 10) / 10;
yield JSON.stringify(out, null, 1) + '\n';
};

View file

@ -5,6 +5,7 @@
// machine has cores, so absolute numbers vary, but their sizes relative to each other are what count. // machine has cores, so absolute numbers vary, but their sizes relative to each other are what count.
// //
// npm run test:timings // npm run test:timings
// node scripts/test-timings.js --merge DIR (CI) fold the parts' --timings files into it
const fs = require('node:fs'); const fs = require('node:fs');
const os = require('node:os'); const os = require('node:os');
const path = require('node:path'); const path = require('node:path');
@ -12,6 +13,24 @@ const { spawn } = require('node:child_process');
const root = path.join(__dirname, '..'); const root = path.join(__dirname, '..');
const dir = path.join(root, 'tests'); const dir = path.join(root, 'tests');
// --merge DIR: fold the timings CI's parts wrote (scripts/test.js --timings) into tests/durations.json. Files that are
// gone drop out; files no part ran keep their old time.
const mi = process.argv.indexOf('--merge');
if (mi >= 0) {
const from = process.argv[mi + 1], dur = path.join(dir, 'durations.json');
let out = {};
try { out = JSON.parse(fs.readFileSync(dur, 'utf8')); } catch (e) { /* none yet */ }
let n = 0;
for (const f of fs.readdirSync(from, { recursive: true }).filter((f) => String(f).endsWith('.json'))) {
for (const [k, v] of Object.entries(JSON.parse(fs.readFileSync(path.join(from, String(f)), 'utf8')))) if (v > 0) { out[k] = v; n++; }
}
const have = new Set(fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).map((f) => 'tests/' + f));
const sorted = Object.fromEntries(Object.keys(out).filter((k) => have.has(k)).sort().map((k) => [k, out[k]]));
fs.writeFileSync(dur, JSON.stringify(sorted, null, 1) + '\n');
console.log(`merged ${n} timings; tests/durations.json has ${Object.keys(sorted).length} of ${have.size} files`);
process.exit(0);
}
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).sort().map((f) => 'tests/' + f); const files = fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).sort().map((f) => 'tests/' + f);
const jobs = Math.max(1, parseInt(process.env.TEST_JOBS, 10) || os.availableParallelism()); const jobs = Math.max(1, parseInt(process.env.TEST_JOBS, 10) || os.availableParallelism());
const out = {}; const out = {};

View file

@ -5,14 +5,18 @@
// //
// npm test everything // npm test everything
// npm test -- tests/peering.test.js just these files (other arguments go to node --test) // npm test -- tests/peering.test.js just these files (other arguments go to node --test)
// npm test -- --shard 2/4 one of four parts of about equal time (CI runs the four at once) // npm test -- --shard 2/4 one of four parts of about equal time
// npm test -- --shard 2/4 --list which files that part holds, without running them // npm test -- --shard 2/4 --list which files that part holds, without running them
// node scripts/test.js --plan 6 the split into 6 parts as JSON (CI's plan job: one list per runner)
// npm test -- --timings out.json also write each file's seconds to out.json (CI merges these into
// the durations the next run splits by)
// TEST_JOBS=1 npm test one file at a time, as it used to be // TEST_JOBS=1 npm test one file at a time, as it used to be
// npm test -- --stress 8 tests/x.test.js hunt a flaky test: 8 copies of these files at once, on a machine kept // npm test -- --stress 8 tests/x.test.js hunt a flaky test: 8 copies of these files at once, on a machine kept
// busier than CI ever is, and how many runs failed (and why) // busier than CI ever is, and how many runs failed (and why)
// //
// Parts are balanced by tests/durations.json, each file's typical seconds (refresh: npm run test:timings). // Parts are balanced by tests/durations.json, each file's typical seconds. CI keeps it fresh in its cache from every
// A file missing from it counts as a typical one, so a stale list only makes the parts a little uneven. // run on main (.github/workflows/ci.yml); npm run test:timings rewrites the committed copy. A file missing from it
// counts as a typical one, so a stale list only makes the parts a little uneven.
const fs = require('node:fs'); const fs = require('node:fs');
const os = require('node:os'); const os = require('node:os');
const path = require('node:path'); const path = require('node:path');
@ -31,6 +35,12 @@ if (ti >= 0) {
if (!(stress >= 1)) { console.error('--stress wants a count, like --stress 8'); process.exit(2); } if (!(stress >= 1)) { console.error('--stress wants a count, like --stress 8'); process.exit(2); }
args.splice(ti, 2); args.splice(ti, 2);
} }
let timings = null;
const tmi = args.indexOf('--timings');
if (tmi >= 0) { timings = args[tmi + 1]; args.splice(tmi, 2); if (!timings) { console.error('--timings wants a file'); process.exit(2); } }
let plan = 0;
const pi = args.indexOf('--plan');
if (pi >= 0) { plan = parseInt(args[pi + 1], 10); args.splice(pi, 2); if (!(plan >= 1)) { console.error('--plan wants a count, like --plan 6'); process.exit(2); } }
let shard = null; let shard = null;
const si = args.indexOf('--shard'); const si = args.indexOf('--shard');
if (si >= 0) { if (si >= 0) {
@ -58,6 +68,10 @@ function part(list, i, n) {
} }
return out[i - 1].sort(); return out[i - 1].sort();
} }
if (plan) {
console.log(JSON.stringify(Array.from({ length: plan }, (_, i) => part(files, i + 1, plan).join(' '))));
process.exit(0);
}
if (shard && files.length) { if (shard && files.length) {
files = part(files, shard[0], shard[1]); files = part(files, shard[0], shard[1]);
console.log(`# part ${shard[0]}/${shard[1]}: ${files.length} files`); console.log(`# part ${shard[0]}/${shard[1]}: ${files.length} files`);
@ -84,5 +98,7 @@ if (stress) {
}); });
return; return;
} }
const r = spawnSync(process.execPath, ['--test', `--test-concurrency=${jobs}`, ...args, ...files], { stdio: 'inherit', cwd: root }); const rep = timings ? ['--test-reporter=spec', '--test-reporter-destination=stdout',
`--test-reporter=${path.join(__dirname, 'lib', 'timings-reporter.js')}`, `--test-reporter-destination=${timings}`] : [];
const r = spawnSync(process.execPath, ['--test', `--test-concurrency=${jobs}`, ...rep, ...args, ...files], { stdio: 'inherit', cwd: root });
process.exit(r.status ?? 1); process.exit(r.status ?? 1);

View file

@ -56,6 +56,8 @@ const API_DOMAINS={
pzRouteMode:{kind:'enum',values:['normal','fast']}, pzRouteMode:{kind:'enum',values:['normal','fast']},
// The bulk PNI order takes one network or null for every network at every shared POP (ACT.pniAll). // The bulk PNI order takes one network or null for every network at every shared POP (ACT.pniAll).
pniAllNet:{kind:'fn',ok:v=>v===null||(typeof v==='string'&&!!NET[v])}, pniAllNet:{kind:'fn',ok:v=>v===null||(typeof v==='string'&&!!NET[v])},
// The total a sheet showed (pniAll, bstdApply carry it as q): the game refuses a different one (bstdApply: more than 1% away).
shownTotal:{kind:'fn',ok:v=>typeof v==='number'&&Number.isFinite(v)},
dashTab:{kind:'enum',values:()=>DTABS.slice()}, dashTab:{kind:'enum',values:()=>DTABS.slice()},
dashSortKey:{kind:'enum',values:['name','asn','type','traffic','cost','lost']}, dashSortKey:{kind:'enum',values:['name','asn','type','traffic','cost','lost']},
leftTab:{kind:'enum',values:['goals','deals','noc','nets']}, leftTab:{kind:'enum',values:['goals','deals','noc','nets']},

View file

@ -390,10 +390,10 @@ const API_CMD={
quote:a=>{const q=S&&S.ops?opsTplQuote(a.city):null;return q?{setup:q.cost}:{};}, quote:a=>{const q=S&&S.ops?opsTplQuote(a.city):null;return q?{setup:q.cost}:{};},
doc:'Open a city from the template in one go: the POP, then broadband, transit, an IX port and the redundancy kit as the template says — all or nothing on the price.'}, doc:'Open a city from the template in one go: the POP, then broadband, transit, an IX port and the redundancy kit as the template says — all or nothing on the price.'},
/* ---------- the bulk PNI order ---------- */ /* ---------- the bulk PNI order ---------- */
pniAll:{args:[['net','pniAllNet'],['tier','pniTier']], pniAll:{args:[['net','pniAllNet'],['tier','pniTier'],['q','shownTotal',false]],
quote:a=>{const b=pniBatch(a.net,a.tier);return b?{setup:b.cost,monthly:b.mo,blocked:(b.blocked||[]).map(q=>q.why).filter(Boolean)}:{};}, quote:a=>{const b=pniBatch(a.net,a.tier);return b?{setup:b.cost,monthly:b.mo,blocked:(b.blocked||[]).map(q=>q.why).filter(Boolean)}:{};},
watch:['pni'], watch:['pni'],
doc:'Order PNIs with one network (net) or every network (net:null) at all shared POPs: missing connections are added, smaller ones upgraded, each at its own minimum size. The quote is the batch total, lead times as for one PNI.'}, doc:'Order PNIs with one network (net) or every network (net:null) at all shared POPs: missing connections are added, smaller ones upgraded, each at its own minimum size. The quote is the batch total, lead times as for one PNI. q (optional): the total you were shown; a different one now is refused and the sheet shown again.'},
/* ---------- backbone technology ---------- */ /* ---------- backbone technology ---------- */
coreUp:{args:[],watch:['core'], coreUp:{args:[],watch:['core'],
quote:a=>{const n=S&&S.core?S.core.lv+1:1;return n<=4?{setup:CORE_COST[n],blocked:[(lvl()||1)<CORE_REQ[n]?tr('core.needs_customer_level_n',{n:CORE_REQ[n]}):''].filter(Boolean)}:{};}, quote:a=>{const n=S&&S.core?S.core.lv+1:1;return n<=4?{setup:CORE_COST[n],blocked:[(lvl()||1)<CORE_REQ[n]?tr('core.needs_customer_level_n',{n:CORE_REQ[n]}):''].filter(Boolean)}:{};},
@ -435,16 +435,16 @@ const API_CMD={
doc:'Clear the whole build standard; new POPs go back to one basic router.'}, doc:'Clear the whole build standard; new POPs go back to one basic router.'},
bstdSet:{args:[['k','bstdKey'],['v','string',false]],watch:['popStd'], bstdSet:{args:[['k','bstdKey'],['v','string',false]],watch:['popStd'],
doc:'Set one target of the build standard: g router model, rt routers, site2 second building, gen generator, lag LAG members on transit, IX and PNI ports, split LAGs across both buildings, ix an IX port wherever the city has an exchange, pni PNIs per network in at least that many cities, sys line system, opt fastest optics, wv waves at least that size. g and sys are also what the intern\'s routers and optup orders standardize on. Without v it steps to the next value; with v (a position in the list the sheet shows, 0 first, "keep" first) it picks that one.'}, doc:'Set one target of the build standard: g router model, rt routers, site2 second building, gen generator, lag LAG members on transit, IX and PNI ports, split LAGs across both buildings, ix an IX port wherever the city has an exchange, pni PNIs per network in at least that many cities, sys line system, opt fastest optics, wv waves at least that size. g and sys are also what the intern\'s routers and optup orders standardize on. Without v it steps to the next value; with v (a position in the list the sheet shows, 0 first, "keep" first) it picks that one.'},
bstdApply:{args:[],watch:['pops','transit','pni','ixp','ixn','ixSite','links','spares'], bstdApply:{args:[['quote','string',false],['q','shownTotal',false]],watch:['pops','transit','pni','ixp','ixn','ixSite','links','spares'],
quote:a=>{const q=bstdQuote(false);return {setup:q.cost,monthly:q.mo,blocked:q.held.map(w=>w.split('|').map(c=>CITY[c].name).join('–')+': its line system waits until the fiber is quiet or a parallel link can carry its load for the day it goes dark')};}, quote:a=>{const q=bstdQuote(false);return {setup:q.cost,monthly:q.mo,key:bstdPlanKey(bstdPlan(false)),blocked:q.held.map(w=>w.split('|').map(c=>CITY[c].name).join('–')+': its line system waits until the fiber is quiet or a parallel link can carry its load for the day it goes dark')};},
doc:'Bring everything up to the build standard now, the busiest first, while cash lasts: routers, buildings, generators, LAG members, IX ports, PNIs, line systems, optics and waves. A line-system swap waits unless the fiber is quiet or a parallel link carries its load: such a fiber gets the best optics its line system takes, and the quote lists it under blocked. The quote is the whole bill.'}, doc:'Bring everything up to the build standard now, the busiest first, while cash lasts: routers, buildings, generators, LAG members, IX ports, PNIs, line systems, optics and waves. A line-system swap waits unless the fiber is quiet or a parallel link carries its load: such a fiber gets the best optics its line system takes, and the quote lists it under blocked. The quote is the whole bill. quote and q (optional): the plan\'s key and the total you were shown; another plan, or a total more than 1% away, is refused and the sheet shown again.'},
/* ---------- utilities ---------- */ /* ---------- utilities ---------- */
utilityRouteServers:{args:[['city','cityId',false]],watch:['rs'], utilityRouteServers:{args:[['city','cityId',false]],watch:['rs'],
doc:'Join the route server at every IX you have a port at. One call does what the button does.'}, doc:'Join the route server at every IX you have a port at. One call does what the button does.'},
utilityKit:{args:[['city','cityId'],['cost','integer',false]],watch:['pops.#city','caches'], utilityKit:{args:[['city','cityId'],['cost','integer',false]],watch:['pops.#city','caches'],
quote:a=>{const q=S?utilityKit(a.city):null;return q?{setup:q.cost,monthly:q.mo}:{};}, quote:a=>{const q=S?utilityKit(a.city):null;return q?{setup:q.cost,monthly:q.mo}:{};},
pass:a=>({city:a.city,cost:a.cost??((utilityKit(a.city)||{}).cost)}), pass:a=>({city:a.city,cost:a.cost??((utilityKit(a.city)||{}).cost)}),
doc:'Install the POP redundancy kit in one go: generator, second building, a second router, and the cache boxes balanced between sites. Pass the quoted setup as cost; the game checks it still matches. Nothing to do reads as no_effect.'}, doc:'Install the POP redundancy kit in one go: generator, second building, a second router, and the cache boxes balanced between sites. Pass the quoted setup as cost; the game checks it still matches (within 1%: hardware prices drift by the day). Nothing to do reads as no_effect.'},
utilityCaches:{args:[['city','cityId'],['quote','string',false]],watch:['caches'], utilityCaches:{args:[['city','cityId'],['quote','string',false]],watch:['caches'],
quote:a=>{const q=S?utilityCaches(a.city):null;return q?{key:q.key}:{};}, quote:a=>{const q=S?utilityCaches(a.city):null;return q?{key:q.key}:{};},
pass:a=>({city:a.city,quote:a.quote??((utilityCaches(a.city)||{}).key)}), pass:a=>({city:a.city,quote:a.quote??((utilityCaches(a.city)||{}).key)}),

View file

@ -10,6 +10,8 @@ const IS_DEV=APP_VERSION.startsWith('__');
// Multiplayer (docs/MULTIPLAYER.md): the path of a self-hosted copy's session server, stamped by MP_API=/api/mp npm run build. // Multiplayer (docs/MULTIPLAYER.md): the path of a self-hosted copy's session server, stamped by MP_API=/api/mp npm run build.
// Empty, as in every plain build (and on seriesoftub.es), multiplayer stays off: no door, no requests. // Empty, as in every plain build (and on seriesoftub.es), multiplayer stays off: no door, no requests.
const MP_API=/*__MP_API__*/''; const MP_API=/*__MP_API__*/'';
// Server-run play's build id (scripts/lib/page.js simId()), stamped next to MP_API; the session server refuses a page of another build.
const SIM_ID=/*__SIM_ID__*/'';
// Only report from the real site; previews, localhost and the Claude viewer stay silent. // Only report from the real site; previews, localhost and the Claude viewer stay silent.
const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)&&!/[?&]noc=/.test(location.search)?'https://stats.seriesoftub.es':'',site:'seriesoftub.es'}; const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)&&!/[?&]noc=/.test(location.search)?'https://stats.seriesoftub.es':'',site:'seriesoftub.es'};
(function(){ (function(){

View file

@ -43,7 +43,14 @@ const WEEK_MODS=[{id:'pricey',n:tr('scenarios.transit_costs_30_more')},{id:'chao
function weekly(){const [y,w]=pzWeekKey(new Date()).split('-W').map(Number);let r=(y*100+w)*2654435761>>>0;const nx=()=>{r=(r*1103515245+12345)>>>0;return r/4294967296;};const city=WEEK_CITIES[Math.floor(nx()*WEEK_CITIES.length)];const mods=[];while(mods.length<2){const m=WEEK_MODS[Math.floor(nx()*WEEK_MODS.length)];if(!mods.includes(m))mods.push(m);}return {id:'weekly',key:`${y}-W${String(w).padStart(2,'0')}`,seed:y*100+w,city,mods,days:365};} function weekly(){const [y,w]=pzWeekKey(new Date()).split('-W').map(Number);let r=(y*100+w)*2654435761>>>0;const nx=()=>{r=(r*1103515245+12345)>>>0;return r/4294967296;};const city=WEEK_CITIES[Math.floor(nx()*WEEK_CITIES.length)];const mods=[];while(mods.length<2){const m=WEEK_MODS[Math.floor(nx()*WEEK_MODS.length)];if(!mods.includes(m))mods.push(m);}return {id:'weekly',key:`${y}-W${String(w).padStart(2,'0')}`,seed:y*100+w,city,mods,days:365};}
const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]); const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]);
function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}} function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}}
function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();newGame(nm,city);{const a=+(UI.asnTxt||UI.asnSug||0);if(asnOk(a))S.asn=a;UI.asnSug=null;}S.mode=o.mode||'normal'; function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();
beginState(nm,city,{...o,asn:+(UI.asnTxt||UI.asnSug||0)});UI.asnSug=null;beginShow(city,o);}
/* A new network in two halves. beginState() makes S (no screen, no storage, no slot), so a server can build a network
the way the page does; o.asn is the AS number the player typed, kept when asnOk(). beginShow() puts it on screen and
starts it: speed, camera, welcome, charter, tutorial. o.srv: the server built this network (beginState, compute,
beginHello) and set S.tut, so the page neither routes it (its R comes from the server), nor says welcome again, nor
starts the tutorial: it only shows the coach where S.tut is. */
function beginState(nm,city,o={}){newGame(nm,city);if(asnOk(o.asn))S.asn=o.asn;S.mode=o.mode||'normal';
// A multiplayer session (89-multiplayer.js): the server's AS number, and its seed, so every player starts in the same world. // A multiplayer session (89-multiplayer.js): the server's AS number, and its seed, so every player starts in the same world.
if(o.mp&&S.mode==='normal'){const m=o.mp;S.mp={code:m.code,pid:m.pid,asn:m.asn,seed:m.seed,preset:m.preset,color:m.color,title:m.title,seq:0};S.asn=m.asn;S.rng=m.seed|0;} if(o.mp&&S.mode==='normal'){const m=o.mp;S.mp={code:m.code,pid:m.pid,asn:m.asn,seed:m.seed,preset:m.preset,color:m.color,title:m.title,seq:0};S.asn=m.asn;S.rng=m.seed|0;}
// The rules are picked here and locked for the life of the network. Scenarios run on On-call plus their own rules. // The rules are picked here and locked for the life of the network. Scenarios run on On-call plus their own rules.
@ -51,11 +58,14 @@ function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,ci
if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}} if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}}
if(o.scn){const sc=o.scn;S.scn={id:sc.id,rules:sc.rules||{},days:sc.days,name:sc.n||tr('features.weekly_challenge_key',{key:sc.key}),key:sc.key||null,mods:(sc.mods||[]).map(m=>m.id)};S.rng=(o.seed||hstr(sc.id))|0;S.mode='scenario';S.asn=200000+Math.floor(Math.random()*15000); if(o.scn){const sc=o.scn;S.scn={id:sc.id,rules:sc.rules||{},days:sc.days,name:sc.n||tr('features.weekly_challenge_key',{key:sc.key}),key:sc.key||null,mods:(sc.mods||[]).map(m=>m.id)};S.rng=(o.seed||hstr(sc.id))|0;S.mode='scenario';S.asn=200000+Math.floor(Math.random()*15000);
if(sc.cash)S.cash=sc.cash;if(sc.setup)sc.setup(); if(sc.cash)S.cash=sc.cash;if(sc.setup)sc.setup();
for(const m of S.scn.mods){if(m==='pricey')S.priceMul=1.3;if(m==='poor')S.cash=100000;if(m==='chaos')S.scn.rules.chaos=true;if(m==='boom')S.scn.rules.boom=true;if(m==='dk')S.scn.rules.dkAll=true;if(m==='sharks')S.scn.rules.sharks=true;}} for(const m of S.scn.mods){if(m==='pricey')S.priceMul=1.3;if(m==='poor')S.cash=100000;if(m==='chaos')S.scn.rules.chaos=true;if(m==='boom')S.scn.rules.boom=true;if(m==='dk')S.scn.rules.dkAll=true;if(m==='sharks')S.scn.rules.sharks=true;}}}
// The welcome line: in the log, and on screen.
function beginHello(o={}){toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(S.name),asn:S.asn,city:CITY[S.home].name}),'goal');}
function beginShow(city,o={}){
// Every new network starts at ½ speed (#186), whatever the last one ran at: slow enough to look around, but things happen. // Every new network starts at ½ speed (#186), whatever the last one ran at: slow enough to look around, but things happen.
UI.lastSpeed=rule('clock')?0.5:0;setSpeed(UI.lastSpeed);UI.resumeSpeed=null; UI.lastSpeed=rule('clock')?0.5:0;setSpeed(UI.lastSpeed);UI.resumeSpeed=null;
track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city); track('game_new');UI.started=true;closeModal();if(!o.srv)compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city);
toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(nm),asn:S.asn,city:CITY[city].name}),'goal'); if(!o.srv)beginHello(o);
// A Normal game asks for its charter first; the tutorial starts once it is signed. // A Normal game asks for its charter first; the tutorial starts once it is signed.
renderAll();if(S.mp)mpStarted(o.mp);save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle'){charterAsk();if(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();} renderAll();if(S.mp)mpStarted(o.mp);save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle'){charterAsk();if(o.srv)renderCoach();else if(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();}
if(S.mp)mpStartTell();} if(S.mp)mpStartTell();}

View file

@ -68,11 +68,11 @@ function salesGolf(d){if(pieGolf(d))return;const mine=Object.keys(S.pops).filter
const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl()&&ip4Fits({type:x,bw:BIZ_T[x].opts[BIZ_T[x].opts.length-1]}));if(!t)return;const T=BIZ_T[t],city=mine.sort((a,b)=>CITY[b].P-CITY[a].P||(a<b?-1:1))[0]; const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl()&&ip4Fits({type:x,bw:BIZ_T[x].opts[BIZ_T[x].opts.length-1]}));if(!t)return;const T=BIZ_T[t],city=mine.sort((a,b)=>CITY[b].P-CITY[a].P||(a<b?-1:1))[0];
const list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n));const name=list.length?list[Math.floor(slR('golfn|'+d)*list.length)]:(T.names||BIZ_N)[0];useName(name); const list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n));const name=list.length?list[Math.floor(slR('golfn|'+d)*list.length)]:(T.names||BIZ_N)[0];useName(name);
const o={id:uid(),city,city2:null,name,type:t,bw:T.opts[T.opts.length-1],rate:Math.round((CITY[city].au?T.rate*AU_ARPU:T.rate)*mkt()*0.7),reqs:[],exp:d+40}; const o={id:uid(),city,city2:null,name,type:t,bw:T.opts[T.opts.length-1],rate:Math.round((CITY[city].au?T.rate*AU_ARPU:T.rate)*mkt()*0.7),reqs:[],exp:d+40};
const k=salesPromise(o);if(k)o.reqs.push(k);const b=offerCustomer(o);b.by='ceo';b.mk=mkt();S.biz.push(clSign(b)); const k=salesPromise(o);if(k)o.reqs.push(k);const b=offerCustomer(o);b.by='ceo';if(clOn(b))b.mk=mkt();S.biz.push(clSign(b));
toast(tr('sales.ceo_golf',{name:esc(name),city:esc(CITY[city].name),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)})+(k?' '+tr('sales.ceo_promised',{req:esc(typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l)}):''),'goal',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);sfx('coin');} toast(tr('sales.ceo_golf',{name:esc(name),city:esc(CITY[city].name),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)})+(k?' '+tr('sales.ceo_promised',{req:esc(typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l)}):''),'goal',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);sfx('coin');}
// Declining an offer the CEO likes: about one in three, he already shook hands on it. // Declining an offer the CEO likes: about one in three, he already shook hands on it.
function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||!ip4Fits(o)||slR('veto|'+slKey(o))>=0.33)return false; function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||!ip4Fits(o)||slR('veto|'+slKey(o))>=0.33)return false;
const b=offerCustomer(o);if(o.mk)b.mk=o.mk;b.by='ceo';S.offers=S.offers.filter(x=>x!==o);S.biz.push(clSign(b));toast(tr('sales.ceo_override',{name:esc(o.name)}),'');return true;} const b=offerCustomer(o);if(o.mk&&clOn(b))b.mk=o.mk;b.by='ceo';S.offers=S.offers.filter(x=>x!==o);S.biz.push(clSign(b));toast(tr('sales.ceo_override',{name:esc(o.name)}),'');return true;}
// Saves: who is at the desk, the VP on the way, the CEO's calendar; who brought each offer and signed each customer. // Saves: who is at the desk, the VP on the way, the CEO's calendar; who brought each offer and signed each customer.
function salesFix(s){const L=s.sales&&typeof s.sales==='object'&&!Array.isArray(s.sales)?s.sales:{},n=v=>Number.isInteger(v)&&v>=0&&v<1e7?v:null; function salesFix(s){const L=s.sales&&typeof s.sales==='object'&&!Array.isArray(s.sales)?s.sales:{},n=v=>Number.isInteger(v)&&v>=0&&v<1e7?v:null;
s.sales={p:own(SALES,L.p)?L.p:null,hired:n(L.hired)||0,vp:L.p==='ceo'?n(L.vp):null,golf:n(L.golf),say:n(L.say)}; s.sales={p:own(SALES,L.p)?L.p:null,hired:n(L.hired)||0,vp:L.p==='ceo'?n(L.vp):null,golf:n(L.golf),say:n(L.say)};

View file

@ -8,9 +8,13 @@ const TUT=[
{t:tr('tutorial.businesses_pop_up_as_bubbles_on'),sel:'[data-act="leftTab"][data-args*=\'"deals"\']',ok:()=>S.biz.length>0}, {t:tr('tutorial.businesses_pop_up_as_bubbles_on'),sel:'[data-act="leftTab"][data-args*=\'"deals"\']',ok:()=>S.biz.length>0},
]; ];
function tutorialStart(){let done=false;try{done=!!localStorage.getItem('sot-tut');}catch(e){}if(done||window.__TUBES_TEST__&&!window.__TUBES_TUT__)return;S.tut=0;renderCoach();} function tutorialStart(){let done=false;try{done=!!localStorage.getItem('sot-tut');}catch(e){}if(done||window.__TUBES_TEST__&&!window.__TUBES_TUT__)return;S.tut=0;renderCoach();}
function renderCoach(){const el=$('coach');if(!el)return;document.querySelectorAll('.coach-glow').forEach(x=>x.classList.remove('coach-glow')); // The coach: the steps done move S.tut on (tutAdvance, state only: a server runs it after every day and action), then
if(!S||S.tut===undefined||S.tut===null||S.lost){el.hidden=true;return;} // the box shows the step it is at (coachDom, the screen only).
function renderCoach(){if(!$('coach'))return;tutAdvance();coachDom();}
function tutAdvance(){if(!S||S.tut===undefined||S.tut===null||S.lost)return;
while(S.tut<TUT.length){const st=TUT[S.tut];let ok=false;try{ok=st.ok()||(st.skip&&st.skip());}catch(e){}if(!ok)break;S.tut++;} while(S.tut<TUT.length){const st=TUT[S.tut];let ok=false;try{ok=st.ok()||(st.skip&&st.skip());}catch(e){}if(!ok)break;S.tut++;}
if(S.tut>=TUT.length){S.tut=null;el.hidden=true;try{localStorage.setItem('sot-tut','1');}catch(e){}toast(tr('tutorial.you_know_the_basics_the_goals'),'goal');return;} if(S.tut>=TUT.length){S.tut=null;try{localStorage.setItem('sot-tut','1');}catch(e){}toast(tr('tutorial.you_know_the_basics_the_goals'),'goal');}}
function coachDom(){const el=$('coach');if(!el)return;document.querySelectorAll('.coach-glow').forEach(x=>x.classList.remove('coach-glow'));
if(!S||S.tut===undefined||S.tut===null||S.lost){el.hidden=true;return;}
const st=TUT[S.tut];el.innerHTML=`<div class="ct"><span class="cs">${tr('tutorial.step_n_of_total',{n:S.tut+1,total:TUT.length})}</span>${esc(st.t)}</div>${btn(tr('common.skip_tutorial'),'tutSkip',{},'ghost sm')}`;el.hidden=false; const st=TUT[S.tut];el.innerHTML=`<div class="ct"><span class="cs">${tr('tutorial.step_n_of_total',{n:S.tut+1,total:TUT.length})}</span>${esc(st.t)}</div>${btn(tr('common.skip_tutorial'),'tutSkip',{},'ghost sm')}`;el.hidden=false;
if(st.sel){const t=document.querySelector(st.sel);if(t)t.classList.add('coach-glow');}} if(st.sel){const t=document.querySelector(st.sel);if(t)t.classList.add('coach-glow');}}

View file

@ -1,6 +1,10 @@
// Every field a reload gives a game is here from the start (sanitize() would add the rest), so a new game is what a
// reload makes of it: a server checks every action against that (tests/canonical-state.test.js).
function newGame(name,home){ function newGame(name,home){
S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH, S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH,
ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ip4:ip4New(),ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{}, ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ip4:ip4New(),ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{},
done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null}; done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null,
lvl:1,hist:[],ach:{},ixn:{},ixPref:{},ixSite:{},confReg:{},cl:{odd:-1e9,mo:[]},sales:{p:null,hired:0,vp:null,golf:null,say:null},baronWon:0};
for(const o of OPS)S.ops.p[o.k]={};
} }

View file

@ -3,7 +3,7 @@
runs. Players share a session by a six-character code: each builds their own network in the same world (one seed, runs. Players share a session by a six-character code: each builds their own network in the same world (one seed,
one rules preset), each network's save is also kept on the server (so it can move to another device), and a small one rules preset), each network's save is also kept on the server (so it can move to another device), and a small
public card per player feeds the session's leaderboard and feed. The game itself stays local and keeps playing public card per player feeds the session's leaderboard and feed. The game itself stays local and keeps playing
when the server is away. S.mp = null | {code, pid, asn, seed, preset, color, title, seq}; the secret token is never in when the server is away. S.mp = null | {code, pid, asn, seed, preset, color, title, seq, sim?}; the secret token is never in
S (saves get exported and shared): it lives in this browser's storage, sot-mp:<code>:<pid>. */ S (saves get exported and shared): it lives in this browser's storage, sot-mp:<code>:<pid>. */
const MP_CODE=/^[0-9A-HJKMNP-TV-Z]{6}$/,MP_PID=/^[a-z0-9]{8}$/,MP_TOK=/^[0-9a-f]{64}$/,MP_COL=/^#[0-9a-f]{6}$/i; const MP_CODE=/^[0-9A-HJKMNP-TV-Z]{6}$/,MP_PID=/^[a-z0-9]{8}$/,MP_TOK=/^[0-9a-f]{64}$/,MP_COL=/^#[0-9a-f]{6}$/i;
// Pushes: a new game day, at most every 15 s; the roster every 5 s only while the session panel is open. A keepalive // Pushes: a new game day, at most every 15 s; the roster every 5 s only while the session panel is open. A keepalive
@ -23,10 +23,13 @@ function mpTok(m){if(!m||!MP_CODE.test(m.code)||!MP_PID.test(m.pid))return null;
function mpTokSet(c,p,t){try{if(t==null)localStorage.removeItem(mpTokK(c,p));else localStorage.setItem(mpTokK(c,p),t);}catch(e){}} function mpTokSet(c,p,t){try{if(t==null)localStorage.removeItem(mpTokK(c,p));else localStorage.setItem(mpTokK(c,p),t);}catch(e){}}
// The catalog's own AS numbers in the server's range: the server hands out one nobody on the map uses. // The catalog's own AS numbers in the server's range: the server hands out one nobody on the map uses.
const mpAvoid=()=>NETS.filter(n=>n.asn>=200000&&n.asn<=214999).map(n=>n.asn).slice(0,64); const mpAvoid=()=>NETS.filter(n=>n.asn>=200000&&n.asn<=214999).map(n=>n.asn).slice(0,64);
// sim:1, a network the session server runs (its days happen there, this page shows them). Only a page built with the
// server's client (src/game/98-server-play/, MP builds) says yes here; everywhere else this one stays.
function srvOn(){return false;}
function mpSanitize(s){const m=s.mp; function mpSanitize(s){const m=s.mp;
if(!m||typeof m!=='object'||Array.isArray(m)||!MP_CODE.test(m.code)||!MP_PID.test(m.pid)||s.mode!=='normal'){s.mp=null;return;} if(!m||typeof m!=='object'||Array.isArray(m)||!MP_CODE.test(m.code)||!MP_PID.test(m.pid)||s.mode!=='normal'){s.mp=null;return;}
s.mp={code:m.code,pid:m.pid,asn:int(m.asn,200000,214999,200000),seed:int(m.seed,-2147483648,2147483647,0),preset:NORMAL_PRESETS.includes(m.preset)?m.preset:'oncall', s.mp={code:m.code,pid:m.pid,asn:int(m.asn,200000,214999,200000),seed:int(m.seed,-2147483648,2147483647,0),preset:NORMAL_PRESETS.includes(m.preset)?m.preset:'oncall',
color:typeof m.color==='string'&&MP_COL.test(m.color)?m.color:'#ff4f9a',title:typeof m.title==='string'?m.title.slice(0,40):'',seq:int(m.seq,0,1e15,0)};} color:typeof m.color==='string'&&MP_COL.test(m.color)?m.color:'#ff4f9a',title:typeof m.title==='string'?m.title.slice(0,40):'',seq:int(m.seq,0,1e15,0),...(m.sim===1?{sim:1}:{})};}
// What the server said when a session started or someone joined: checked before it becomes S.mp. // What the server said when a session started or someone joined: checked before it becomes S.mp.
function mpJoinOk(j){if(!j||typeof j!=='object'||!MP_CODE.test(j.code)||!MP_PID.test(j.pid)||typeof j.token!=='string'||!MP_TOK.test(j.token)||!Number.isInteger(j.seed)||!Number.isInteger(j.asn)||j.asn<200000||j.asn>214999)return null; function mpJoinOk(j){if(!j||typeof j!=='object'||!MP_CODE.test(j.code)||!MP_PID.test(j.pid)||typeof j.token!=='string'||!MP_TOK.test(j.token)||!Number.isInteger(j.seed)||!Number.isInteger(j.asn)||j.asn<200000||j.asn>214999)return null;
return {code:j.code,pid:j.pid,token:j.token,asn:j.asn,seed:j.seed|0,preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',color:typeof j.color==='string'&&MP_COL.test(j.color)?j.color:'#ff4f9a',title:typeof j.title==='string'?j.title.slice(0,40):''};} return {code:j.code,pid:j.pid,token:j.token,asn:j.asn,seed:j.seed|0,preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',color:typeof j.color==='string'&&MP_COL.test(j.color)?j.color:'#ff4f9a',title:typeof j.title==='string'?j.title.slice(0,40):''};}

View file

@ -1,6 +1,7 @@
/* The sales engine of #185: would this offer work if signed now? The sales desk runs it once a day (39-sales-auto.js). /* The sales engine of #185: would this offer work if signed now? The sales desk runs it once a day (39-sales-auto.js).
It trials the new demand on a copy of the game, so a failed trial leaves the live game untouched. */ It trials the new demand on a copy of the game, so a failed trial leaves the live game untouched. */
function offerCustomer(o){return {id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined};} // Every field a reloaded save gives a customer (sanitize, unpackBiz), so live S is what a reload makes of it.
function offerCustomer(o){return {id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined,warned:false,warn60:false,pm:100};}
// OFFER_TRIED: the answer of a trial the intern's sales order already ran for this offer (the customer, or null). // OFFER_TRIED: the answer of a trial the intern's sales order already ran for this offer (the customer, or null).
let OFFER_TRIED=null; let OFFER_TRIED=null;
function autoOffer(o){if(OFFER_TRIED&&OFFER_TRIED.o===o)return OFFER_TRIED.b;const b=offerTrialOf(o);return b?offerTrial(b,offerHealthy(b)):null;} function autoOffer(o){if(OFFER_TRIED&&OFFER_TRIED.o===o)return OFFER_TRIED.b;const b=offerTrialOf(o);return b?offerTrial(b,offerHealthy(b)):null;}

View file

@ -9,9 +9,10 @@ function pniQuote(city,net,tier,reserved=0){tier=+tier;const g1=tier===-1;if(g1)
else if(!g1&&tier<pniMin(net))why=tr('sites_peering_caches.net_does_not_do_port_pnis',{net:esc(NET[net].name),port:PORT[tier].n}); else if(!g1&&tier<pniMin(net))why=tr('sites_peering_caches.net_does_not_do_port_pnis',{net:esc(NET[net].name),port:PORT[tier].n});
else if(slots>0&&portsUsed(city)+reserved+slots>portsMax(city)+1e-9)why=tr('ports.no_free_router_ports_in_city',{city:esc(CITY[city].name),u:fmtPorts(portsUsed(city)+reserved),m:portsMax(city)});} else if(slots>0&&portsUsed(city)+reserved+slots>portsMax(city)+1e-9)why=tr('ports.no_free_router_ports_in_city',{city:esc(CITY[city].name),u:fmtPorts(portsUsed(city)+reserved),m:portsMax(city)});}
return {city,net,tier,g1,ex,cost,slots,why};} return {city,net,tier,g1,ex,cost,slots,why};}
// A new PNI has every field sanitize() gives one, so live S is what a reload makes of it.
function pniPlace(q){const {city,net,tier,g1,ex}=q,lead=pniLead(net); function pniPlace(q){const {city,net,tier,g1,ex}=q,lead=pniLead(net);
if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1; if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1;
if(ex){ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};if(!lead)pniUpDone(ex);}else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead}); if(ex){ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};if(!lead)pniUpDone(ex);}else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead,lacp:null,site:'a',n:1,sacrif:false});
return lead;} return lead;}
// The ports a pending augment will add, and those of every pending augment at a city: what an order there must leave free. // The ports a pending augment will add, and those of every pending augment at a city: what an order there must leave free.
const pniUpSlots=p=>Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)); const pniUpSlots=p=>Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1));

View file

@ -26,6 +26,9 @@ function utilityCaches(city){const p=S&&S.pops[city];if(!p)return null;const sit
let cap=S.caches.filter(c=>c.city===city&&c.net===n.id).reduce((a,c)=>a+cacheG(c),0)+add.filter(x=>x.net===n.id).length*cacheG(nb); let cap=S.caches.filter(c=>c.city===city&&c.net===n.id).reduce((a,c)=>a+cacheG(c),0)+add.filter(x=>x.net===n.id).length*cacheG(nb);
while(cap+1e-9<dem){const i=box.indexOf(Math.min(...box));add.push({net:n.id,site:sites[i],...nb});box[i]++;cap+=cacheG(nb);}} while(cap+1e-9<dem){const i=box.indexOf(Math.min(...box));add.push({net:n.id,site:sites[i],...nb});box[i]++;cap+=cacheG(nb);}}
return {add,ports:cachePortsAdd(city,add),key:add.map(c=>c.net+'@'+c.site).join(','),mo:add.reduce((a,x)=>a+cacheMo(x),0),free:Math.max(0,portsMax(city)-portsUsed(city))};} return {add,ports:cachePortsAdd(city,add),key:add.map(c=>c.net+'@'+c.site).join(','),mo:add.reduce((a,x)=>a+cacheMo(x),0),free:Math.max(0,portsMax(city)-portsUsed(city))};}
// A total a window showed still holds within 1% either way: hardware prices drift a little every day under the market
// rule, and on a server-run network days go on while a window is open. A bigger change is a new plan, shown again.
const quoteNear=(shown,now)=>Math.abs(now-shown)<=Math.max(0.5,Math.abs(shown)*0.01);
function utilityKit(city){const p=S&&S.pops[city];if(!p)return null; function utilityKit(city){const p=S&&S.pops[city];if(!p)return null;
const gen=!p.gen,site=!p.site2,router=(p.routers||1)<2,g=p.rgen||0; const gen=!p.gen,site=!p.site2,router=(p.routers||1)<2,g=p.rgen||0;
return {gen,site,router,moves:utilityCacheMoves(city),cost:(gen?GEN_COST:0)+(site?SITE2_COST:0)+(router?routerCost(g,1):0), return {gen,site,router,moves:utilityCacheMoves(city),cost:(gen?GEN_COST:0)+(site?SITE2_COST:0)+(router?routerCost(g,1):0),

View file

@ -88,11 +88,12 @@ function sanitize(s){
{const A=s.ddosAuto&&typeof s.ddosAuto==='object'?s.ddosAuto:{};s.ddosAuto={rtbh:A.rtbh===true,scrub:A.scrub!==false};} {const A=s.ddosAuto&&typeof s.ddosAuto==='object'?s.ddosAuto:{};s.ddosAuto={rtbh:A.rtbh===true,scrub:A.scrub!==false};}
if(s.stats&&s.stats.ddT&&typeof s.stats.ddT==='object')s.stats.ddT={port:s.stats.ddT.port?1:0,fs:s.stats.ddT.fs?1:0,rtbh:s.stats.ddT.rtbh?1:0};else if(s.stats)delete s.stats.ddT; if(s.stats&&s.stats.ddT&&typeof s.stats.ddT==='object')s.stats.ddT={port:s.stats.ddT.port?1:0,fs:s.stats.ddT.fs?1:0,rtbh:s.stats.ddT.rtbh?1:0};else if(s.stats)delete s.stats.ddT;
// Keep the legacy primary attack so old saves and imports remain compatible; additional floods overlap it. // Keep the legacy primary attack so old saves and imports remain compatible; additional floods overlap it.
const repairAttack=a=>{if(!a||typeof a!=='object'||!isCity(a.city)||!s.pops[a.city]||!own(DDOS_VEC,a.vec))return null; // An attack whose POP or customer went during the day stays as it is: the next morning ends it (ddosExpire), as in play.
const repairAttack=a=>{if(!a||typeof a!=='object'||!isCity(a.city)||!own(DDOS_VEC,a.vec))return null;
a.id=sid(a.id);a.gbps=Math.max(0,num(a.gbps,2));a.until=num(a.until,s.day);a.bh=!!a.bh;a.start=Math.max(0,Math.min(s.day,num(a.start,s.day)));a.until=Math.min(a.until,a.start+Math.ceil(7*SPICY_LONG)); a.id=sid(a.id);a.gbps=Math.max(0,num(a.gbps,2));a.until=num(a.until,s.day);a.bh=!!a.bh;a.start=Math.max(0,Math.min(s.day,num(a.start,s.day)));a.until=Math.min(a.until,a.start+Math.ceil(7*SPICY_LONG));
// Attacks before 2.2 hit a city and came in on one port: they now hit someone in it, and spread (#242). // Attacks before 2.2 hit a city and came in on one port: they now hit someone in it, and spread (#242).
delete a.entries;delete a.entry;delete a.ixbh;delete a.fresh; delete a.entries;delete a.entry;delete a.ixbh;delete a.fresh;
if(typeof a.tgt!=='string'||(a.tgt.startsWith('bb:')?a.tgt!=='bb:'+a.city:!s.biz.some(b=>b.id===a.tgt&&b.city===a.city))){ if(typeof a.tgt!=='string'||a.tgt.length>40||own(Object.prototype,a.tgt)||(a.tgt.startsWith('bb:')&&a.tgt!=='bb:'+a.city)){
const bs=s.biz.filter(b=>b.city===a.city&&BIZ_T[b.type]&&!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber).sort((x,y)=>(DD_W[y.type]||1)-(DD_W[x.type]||1)||y.bw-x.bw);a.tgt=bs.length?bs[0].id:'bb:'+a.city;} const bs=s.biz.filter(b=>b.city===a.city&&BIZ_T[b.type]&&!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber).sort((x,y)=>(DD_W[y.type]||1)-(DD_W[x.type]||1)||y.bw-x.bw);a.tgt=bs.length?bs[0].id:'bb:'+a.city;}
a.carpet=!!a.carpet;a.sac=a.sac?1:0;a.colMax=clamp(num(a.colMax,0),0,1);if(a.worst!==undefined)a.worst=clamp(num(a.worst,1),0,1); a.carpet=!!a.carpet;a.sac=a.sac?1:0;a.colMax=clamp(num(a.colMax,0),0,1);if(a.worst!==undefined)a.worst=clamp(num(a.worst,1),0,1);
if(a.eng!==undefined){a.eng=num(a.eng,a.start);a.eng=Math.max(a.start,Math.min(s.day,a.eng));} if(a.eng!==undefined){a.eng=num(a.eng,a.start);a.eng=Math.max(a.start,Math.min(s.day,a.eng));}

View file

@ -27,7 +27,8 @@ function lagsN(){const o=[];for(const t of S.transit)if((t.n||1)>=2&&!(t.down>S.
// Several attacks can be live at once: the primary slot keeps older saves compatible, the rest overlap it. // Several attacks can be live at once: the primary slot keeps older saves compatible, the rest overlap it.
function ddosAll(s=S,live=true){return [s.ev.ddos,...(s.ev.ddosMore||[])].filter(a=>a&&(!live||a.until>s.day));} function ddosAll(s=S,live=true){return [s.ev.ddos,...(s.ev.ddosMore||[])].filter(a=>a&&(!live||a.until>s.day));}
const ddosFind=id=>ddosAll().find(a=>id===undefined||a.id===id); const ddosFind=id=>ddosAll().find(a=>id===undefined||a.id===id);
function ddosDrop(a){const left=ddosAll(S,false).filter(x=>x!==a);S.ev.ddos=left[0]||null;S.ev.ddosMore=left.slice(1);} // No primary attack is no ddos key at all, as sanitize() leaves it.
function ddosDrop(a){const left=ddosAll(S,false).filter(x=>x!==a);if(left[0])S.ev.ddos=left[0];else delete S.ev.ddos;S.ev.ddosMore=left.slice(1);}
const ddosBb=a=>!a.tgt||a.tgt.startsWith('bb:'); const ddosBb=a=>!a.tgt||a.tgt.startsWith('bb:');
const ddosBiz=a=>ddosBb(a)?null:S.biz.find(b=>b.id===a.tgt)||null; const ddosBiz=a=>ddosBb(a)?null:S.biz.find(b=>b.id===a.tgt)||null;
// An attack ends on its day, when its city is gone, or when its target is no longer your customer. // An attack ends on its day, when its city is gone, or when its target is no longer your customer.
@ -77,11 +78,13 @@ function ddosTick(){if(scnRule('ddos')){if(S.mode==='sandbox')return;let next=+S
if(!ddosSpicy()&&ddosAll().length)return; if(!ddosSpicy()&&ddosAll().length)return;
while(S.day>=next&&n++<2){ddosAttack(false);next+=floodGap();}S.scn.nextDdos=next<S.day?S.day+floodGap():next;return;} while(S.day>=next&&n++<2){ddosAttack(false);next+=floodGap();}S.scn.nextDdos=next<S.day?S.day+floodGap():next;return;}
if(ddosOff()||S.day<=40)return;if(ddosAll().length>=(ddosSpicy()?3:2))return;if(Math.random()<ddosRate())ddosAttack(false);} if(ddosOff()||S.day<=40)return;if(ddosAll().length>=(ddosSpicy()?3:2))return;if(Math.random()<ddosRate())ddosAttack(false);}
// A start older than a week no longer counts toward the cap: forgotten the morning it ages out, as sanitize() forgets it.
function ddosForget(d){const s=S.ddosStarts;if(Array.isArray(s)&&s.length&&s[0]<=d-7)S.ddosStarts=s.filter(x=>x>d-7);}
// A new attack. With recompute, its outcome is worked out and announced now; otherwise after the day's routing. // A new attack. With recompute, its outcome is worked out and announced now; otherwise after the day's routing.
function ddosAttack(recompute=true){const fl=scnRule('ddos');ddosExpire(); function ddosAttack(recompute=true){const fl=scnRule('ddos');ddosExpire();
S.ddosStarts=(S.ddosStarts||[]).filter(d=>d>S.day-7&&d<=S.day);if(S.ddosStarts.length>=14||!Object.keys(S.pops).length)return null;S.ddosStarts.push(S.day); S.ddosStarts=(S.ddosStarts||[]).filter(d=>d>S.day-7&&d<=S.day);if(S.ddosStarts.length>=14||!Object.keys(S.pops).length)return null;S.ddosStarts.push(S.day);
const [tgt,c]=ddosPickTgt(),vec=pick(ddosVectors(ddGame(tgt))),r=Math.random(),dur=r<0.7?1:r<0.95?2:3; const [tgt,c]=ddosPickTgt(),vec=pick(ddosVectors(ddGame(tgt))),r=Math.random(),dur=r<0.7?1:r<0.95?2:3;
const a={id:uid(),city:c,tgt,vec,gbps:0,until:S.day+dur,bh:false,start:S.day,carpet:Math.random()<0.2,fresh:1};a.gbps=ddosSize(a); const a={id:uid(),city:c,tgt,vec,gbps:0,until:S.day+dur,bh:false,start:S.day,carpet:Math.random()<0.2,fresh:1,sac:0,colMax:0,sla:[]};a.gbps=ddosSize(a);
if(fl)a.who=pick(FLOOD_WHO); if(fl)a.who=pick(FLOOD_WHO);
if(!S.ev.ddos)S.ev.ddos=a;else(S.ev.ddosMore||(S.ev.ddosMore=[])).push(a); if(!S.ev.ddos)S.ev.ddos=a;else(S.ev.ddosMore||(S.ev.ddosMore=[])).push(a);
addInc({type:'ddos',ref:c,atk:a.id,until:a.until,msg:tr('ddos.started',{g:fmtG(a.gbps),vec:DDOS_VEC[vec].n,who:ddosWho(a)}),cost:0}); addInc({type:'ddos',ref:c,atk:a.id,until:a.until,msg:tr('ddos.started',{g:fmtG(a.gbps),vec:DDOS_VEC[vec].n,who:ddosWho(a)}),cost:0});
@ -90,13 +93,15 @@ function ddosAttack(recompute=true){const fl=scnRule('ddos');ddosExpire();
/* After the day's routing: announce new attacks with what they are doing, pull the plug when Auto-RTBH says so, and /* After the day's routing: announce new attacks with what they are doing, pull the plug when Auto-RTBH says so, and
teach each lesson once. */ teach each lesson once. */
function ddosNews(){runNow(ddosNewsRun());} function ddosNews(){runNow(ddosNewsRun());}
// The lessons taught once a game, in the shape sanitize() gives them.
const ddosTaught=()=>S.stats.ddT||(S.stats.ddT={port:0,fs:0,rtbh:0});
// The same as a step of the day: its yield is the routing after Auto-RTBH pulled a plug. // The same as a step of the day: its yield is the routing after Auto-RTBH pulled a plug.
function* ddosNewsRun(){let again=false;const auto=S.ddosAuto&&S.ddosAuto.rtbh; function* ddosNewsRun(){let again=false;const auto=S.ddosAuto&&S.ddosAuto.rtbh;
for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue; for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue;
if(auto&&!a.bh&&m.full>0&&ddosCol(a)>=0.01){a.bh=true;a.sac=1;S.stats.rtbh=(S.stats.rtbh||0)+1;ddosRtbhMood(a);again=true; if(auto&&!a.bh&&m.full>0&&ddosCol(a)>=0.01){a.bh=true;a.sac=1;S.stats.rtbh=(S.stats.rtbh||0)+1;ddosRtbhMood(a);again=true;
toast(tr('ddos.auto_rtbh',{who:esc(ddosWho(a))}),'bad',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:a.city});}} toast(tr('ddos.auto_rtbh',{who:esc(ddosWho(a))}),'bad',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:a.city});}}
if(again)yield; if(again)yield;
const T=S.stats.ddT||(S.stats.ddT={}); const T=ddosTaught();
for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue; for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue;
if(a.fresh){delete a.fresh;const fl=scnRule('ddos'),col=ddosCol(a),sf=ddosSf(a),bad=col>=0.01||sf<0.97; if(a.fresh){delete a.fresh;const fl=scnRule('ddos'),col=ddosCol(a),sf=ddosSf(a),bad=col>=0.01||sf<0.97;
const how=a.bh?tr('ddos.news_rtbh'):col>=0.01?tr('ddos.news_ports',{n:m.full,k:m.slowed}):sf<0.97?tr('ddos.news_target',{p:pct(sf)}):tr('ddos.news_held'); const how=a.bh?tr('ddos.news_rtbh'):col>=0.01?tr('ddos.news_ports',{n:m.full,k:m.slowed}):sf<0.97?tr('ddos.news_target',{p:pct(sf)}):tr('ddos.news_held');

View file

@ -26,7 +26,9 @@ function* dayPreRun(){
if(!S||S.lost||!rule('clock'))return false; // no clock (puzzles): no days, no bills, nothing fires if(!S||S.lost||!rule('clock'))return false; // no clock (puzzles): no days, no bills, nothing fires
S.day++; S.day++;
const d=S.day; const d=S.day;
dkTick(d);ixPriceWar(d);peeringDeskDay(d);pniDay(d);mergerDay(d); // A charter never picked reads as the classic one once its days are over, as a reload reads it (specSanitize).
if(S.chartSet===false&&d>CHARTER_DAYS)S.chartSet=true;
ddosForget(d);dkTick(d);ixPriceWar(d);peeringDeskDay(d);pniDay(d);mergerDay(d);
yield DAY_REST; yield DAY_REST;
if(!S.phpDone&&d>45&&Math.random()<1/400)elephant(); if(!S.phpDone&&d>45&&Math.random()<1/400)elephant();
if(R&&R.teMoved)S.stats.teMax=Math.max(S.stats.teMax||0,R.teMoved); if(R&&R.teMoved)S.stats.teMax=Math.max(S.stats.teMax||0,R.teMoved);
@ -112,7 +114,7 @@ function* dayPost(d){
// the sales desk signs and declines deals, when the player lets it (39-sales-auto.js), then the intern's shift sees them // the sales desk signs and declines deals, when the player lets it (39-sales-auto.js), then the intern's shift sees them
yield* slAutoRun(d); yield* slAutoRun(d);
if(opsHired())yield DAY_REST; if(opsHired())yield DAY_REST;
yield* opsRun(d); yield* opsRun(d);opsTidy();
if(S.pie){pieDay(d);pieTier();} if(S.pie){pieDay(d);pieTier();}
// payday floaters // payday floaters
if(cal(d).d===1){for(const c in S.pops){let v=(R.cityEye[c]*sfOf(R,c)*EYE_RATE)+S.biz.filter(b=>b.city===c).reduce((a,b)=>a+b.bw*b.rate,0);v=v-R.cityEye[c]*sfOf(R,c)*EYE_RATE*(1-arpuOf(c));if(v>500)floater(CITY[c].x,CITY[c].y-30,'+'+fmt$(v),'#16A866');}sfx('coin');} if(cal(d).d===1){for(const c in S.pops){let v=(R.cityEye[c]*sfOf(R,c)*EYE_RATE)+S.biz.filter(b=>b.city===c).reduce((a,b)=>a+b.bw*b.rate,0);v=v-R.cityEye[c]*sfOf(R,c)*EYE_RATE*(1-arpuOf(c));if(v>500)floater(CITY[c].x,CITY[c].y-30,'+'+fmt$(v),'#16A866');}sfx('coin');}
@ -128,6 +130,10 @@ function* dayPost(d){
{const c=cal(d);if(c.m===0&&c.d===1&&[2,3,5].includes(c.y))track('game_year_'+c.y,true);} {const c=cal(d);if(c.m===0&&c.d===1&&[2,3,5].includes(c.y))track('game_year_'+c.y,true);}
if(d%10===0)save(); if(d%10===0)save();
} }
// The shift's notes as a reload keeps them (opsSanitize): at most three places a job in the day's log (the broken links
// were all listed), and no empty list in the week's tally. So live state is what a reload makes of it (server-sim 5.4).
function opsTidy(){const O=S.ops;if(!O)return;for(const e of O.log||[])for(const r of e.r||[])if(Array.isArray(r[2])&&r[2].length>3)r[2]=r[2].slice(0,3);
for(const w of [O.wk,O.rep])if(w&&w.wh)for(const k of Object.keys(w.wh))if(Array.isArray(w.wh[k])&&!w.wh[k].length)delete w.wh[k];}
function spawnOffer(){ function spawnOffer(){
const mine=spMine(Object.keys(S.pops).filter(bizCity)),lv=lvl(); const mine=spMine(Object.keys(S.pops).filter(bizCity)),lv=lvl();
const types=['dia','dia','game','host'];if(mine.length>=2)types.push('l2vpn','l2vpn');if(S.day>60)types.push('scrub'); const types=['dia','dia','game','host'];if(mine.length>=2)types.push('l2vpn','l2vpn');if(S.day>60)types.push('scrub');

View file

@ -1,8 +1,9 @@
Object.assign(ACT,{ Object.assign(ACT,{
buildPop:({city})=>{if(S.pops[city]||!CITY[city])return;if(!cityOn(city)){toast(popOffWhy(city),'bad');sfx('err');return;}const flipNote=CITY[city]&&CITY[city].au;if(cnCity(city)&&!cnOk()){toast(tr('pops_transit_ix.you_need_a_license_first_foreign'),'bad');sfx('err');return;}if(!spend(popCost(city)))return;S.pops[city]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};popStdApply(city);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');if(flipNote)toast(pick([tr('pops_transit_ix.router_installed_in_city_upside_down',{city:CITY[city].name}),tr('pops_transit_ix.router_installed_in_city_the_vendor',{city:CITY[city].name})]),'good',[],{a:'city',v:city});UI.tab='cust';after();}, buildPop:({city})=>{if(S.pops[city]||!CITY[city])return;if(!cityOn(city)){toast(popOffWhy(city),'bad');sfx('err');return;}const flipNote=CITY[city]&&CITY[city].au;if(cnCity(city)&&!cnOk()){toast(tr('pops_transit_ix.you_need_a_license_first_foreign'),'bad');sfx('err');return;}if(!spend(popCost(city)))return;S.pops[city]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(city);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');if(flipNote)toast(pick([tr('pops_transit_ix.router_installed_in_city_upside_down',{city:CITY[city].name}),tr('pops_transit_ix.router_installed_in_city_the_vendor',{city:CITY[city].name})]),'good',[],{a:'city',v:city});UI.tab='cust';after();},
launchBB:({city})=>{const p=S.pops[city];if(!p||p.bb)return;const C=CITY[city];if(!spend(bbCost(city)))return;p.bb={d:bbStart(city)};floater(C.x,C.y-30,tr('common.eyeballs_online'),'#16A866');after();}, launchBB:({city})=>{const p=S.pops[city];if(!p||p.bb)return;const C=CITY[city];if(!spend(bbCost(city)))return;p.bb={d:bbStart(city)};floater(C.x,C.y-30,tr('common.eyeballs_online'),'#16A866');after();},
ad:({city})=>{const p=S.pops[city];if(!p||!p.bb)return;if(!spend(8000))return;p.boost=S.day+30;floater(CITY[city].x,CITY[city].y-30,tr('common.ad_campaign'),'#FF8A3D');after();}, ad:({city})=>{const p=S.pops[city];if(!p||!p.bb)return;if(!spend(8000))return;p.boost=S.day+30;floater(CITY[city].x,CITY[city].y-30,tr('common.ad_campaign'),'#FF8A3D');after();},
buyTransit:({city,net,tier})=>{tier=+tier;if(scnRule('noTransit')){toast(tr('pops_transit_ix.no_transit_in_this_scenario_peering'),'bad');sfx('err');return;}if(!S.pops[city]||!NET[net]||!sellsAt(NET[net],city)||!PORT[tier])return;if(!portOk(city,tier)){toast(tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}),'bad');sfx('err');return;}const ex=S.transit.find(t=>t.city===city&&t.net===net);if(ex&&tier<=ex.tier)return;if(!portGate(city,ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier)))return;if(!spend(PORT[tier].setup*(ex&&ex.n||1)))return;if(ex)ex.tier=tier;else S.transit.push({id:uid(),city,net,tier,down:0,...(premOnlyAt(NET[net],city)?{premium:true}:{})});toast(tr('pops_transit_ix.net_transit_is_live_in_city',{net:esc(NET[net].name),city:CITY[city].name}),'good');after();}, // A new port has every field sanitize() gives one, so live S is what a reload makes of it.
buyTransit:({city,net,tier})=>{tier=+tier;if(scnRule('noTransit')){toast(tr('pops_transit_ix.no_transit_in_this_scenario_peering'),'bad');sfx('err');return;}if(!S.pops[city]||!NET[net]||!sellsAt(NET[net],city)||!PORT[tier])return;if(!portOk(city,tier)){toast(tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}),'bad');sfx('err');return;}const ex=S.transit.find(t=>t.city===city&&t.net===net);if(ex&&tier<=ex.tier)return;if(!portGate(city,ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier)))return;if(!spend(PORT[tier].setup*(ex&&ex.n||1)))return;if(ex)ex.tier=tier;else{const pr=premOnlyAt(NET[net],city);S.transit.push({id:uid(),city,net,tier,down:0,...(pr?{premium:true}:{}),lacp:null,site:'a',n:1,clean:false,...(pr?{}:{premium:false})});}toast(tr('pops_transit_ix.net_transit_is_live_in_city',{net:esc(NET[net].name),city:CITY[city].name}),'good');after();},
lagT:({id,d})=>{d=+d;if(d!==1&&d!==-1)return;const t=S.transit.find(x=>x.id===id);if(!t)return;const n=(t.n||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0){if(!portOk(t.city,t.tier)||!portGate(t.city,PORT_SLOT(t.tier)))return;if(!spend(PORT[t.tier].setup))return;}t.n=n;if(n<2&&t.site==='ab')t.site='a';toast(+d>0?tr('pops_transit_ix.lag_member_added_net_in_city',{net:esc(NET[t.net].name),city:CITY[t.city].name,lag:lagName(t.tier,n)}):tr('pops_transit_ix.lag_member_removed'),'good');after();}, lagT:({id,d})=>{d=+d;if(d!==1&&d!==-1)return;const t=S.transit.find(x=>x.id===id);if(!t)return;const n=(t.n||1)+(+d);if(n<1||n>LAG_MAX)return;if(+d>0){if(!portOk(t.city,t.tier)||!portGate(t.city,PORT_SLOT(t.tier)))return;if(!spend(PORT[t.tier].setup))return;}t.n=n;if(n<2&&t.site==='ab')t.site='a';toast(+d>0?tr('pops_transit_ix.lag_member_added_net_in_city',{net:esc(NET[t.net].name),city:CITY[t.city].name,lag:lagName(t.tier,n)}):tr('pops_transit_ix.lag_member_removed'),'good');after();},
lagP:({id,d})=>{d=+d;if(d!==1&&d!==-1)return;const p=S.pni.find(x=>x.id===id);if(!p)return;const n=(p.n||1)+(+d);if(n<1||n>LAG_MAX)return;if(d>0&&(!pniOn(p)||p.up||msfNope(p.net,p.city)))return;if(+d>0&&(!portGate(p.city,PORT_SLOT(p.tier))||!spend(1500+PORT[p.tier].setup/2)))return; lagP:({id,d})=>{d=+d;if(d!==1&&d!==-1)return;const p=S.pni.find(x=>x.id===id);if(!p)return;const n=(p.n||1)+(+d);if(n<1||n>LAG_MAX)return;if(d>0&&(!pniOn(p)||p.up||msfNope(p.net,p.city)))return;if(+d>0&&(!portGate(p.city,PORT_SLOT(p.tier))||!spend(1500+PORT[p.tier].setup/2)))return;
// A LAG member is an augment: the big networks take months for that too. // A LAG member is an augment: the big networks take months for that too.

View file

@ -8,8 +8,9 @@ Object.assign(ACT,{
teBack:()=>teModal(), teBack:()=>teModal(),
teRecipe:({id})=>{const r=TE_RECIPES.find(x=>x.id===id);if(!r)return;UI.teDraft=r.src().join('\n');teModal(`<p class="note">${tr('route_script_and_tools.loaded_name_check_it_then_deploy',{name:tr(r.n)})}</p>`);}, teRecipe:({id})=>{const r=TE_RECIPES.find(x=>x.id===id);if(!r)return;UI.teDraft=r.src().join('\n');teModal(`<p class="note">${tr('route_script_and_tools.loaded_name_check_it_then_deploy',{name:tr(r.n)})}</p>`);},
teClear:()=>{S.te.script='';UI.teDraft=undefined;TE_CACHE={src:null,p:null};after();teModal(`<p class="note">${tr('route_script_and_tools.script_removed_plain_auto_te_is')}</p>`);}, teClear:()=>{S.te.script='';UI.teDraft=undefined;TE_CACHE={src:null,p:null};after();teModal(`<p class="note">${tr('route_script_and_tools.script_removed_plain_auto_te_is')}</p>`);},
teCheck:()=>{const t=$('teSrc');const src=t?t.value:'';UI.teDraft=src;const p=teParse(src);if(p.errors.length){teModal(`<pre class="term err">${esc(p.errors.join('\n'))}</pre>`);return;}const r=teTrial(src);teModal(`<pre class="term">${esc(trn('route_script_and_tools.n_rule_ok',p.n)+'\n'+tr('route_script_and_tools.served_a_b',{a:fmtG(r.before.served),b:fmtG(r.after.served)})+'\n'+tr('route_script_and_tools.transit_a_mo_b_mo',{a:fmt$(r.before.tc),b:fmt$(r.after.tc)})+'\n'+tr('route_script_and_tools.spilled_g_onto_alternate_paths',{g:fmtG(r.after.moved)})+(r.after.bh?'\n'+tr('route_script_and_tools.blackholed_g',{g:fmtG(r.after.bh)}):''))}</pre>`);}, // The script as an argument (a server runs these without the editor), else the editor's text.
teDeploy:()=>{const t=$('teSrc');const src=(t?t.value:'').slice(0,4000);UI.teDraft=src;const p=teParse(src);if(p.errors.length){teModal(`<pre class="term err">${esc(tr('common.commit_failed')+'\n'+p.errors.join('\n'))}</pre>`);sfx('err');return;}const r=teTrial(src);S.te.script=src;S.te.on=true;TE_CACHE={src:null,p:null};UI.teDraft=undefined;after(); teCheck:({script}={})=>{const t=$('teSrc');const src=typeof script==='string'?script:t?t.value:'';UI.teDraft=src;const p=teParse(src);if(p.errors.length){teModal(`<pre class="term err">${esc(p.errors.join('\n'))}</pre>`);return;}const r=teTrial(src);teModal(`<pre class="term">${esc(trn('route_script_and_tools.n_rule_ok',p.n)+'\n'+tr('route_script_and_tools.served_a_b',{a:fmtG(r.before.served),b:fmtG(r.after.served)})+'\n'+tr('route_script_and_tools.transit_a_mo_b_mo',{a:fmt$(r.before.tc),b:fmt$(r.after.tc)})+'\n'+tr('route_script_and_tools.spilled_g_onto_alternate_paths',{g:fmtG(r.after.moved)})+(r.after.bh?'\n'+tr('route_script_and_tools.blackholed_g',{g:fmtG(r.after.bh)}):''))}</pre>`);},
teDeploy:({script}={})=>{const t=$('teSrc');const src=(typeof script==='string'?script:t?t.value:'').slice(0,4000);UI.teDraft=src;const p=teParse(src);if(p.errors.length){teModal(`<pre class="term err">${esc(tr('common.commit_failed')+'\n'+p.errors.join('\n'))}</pre>`);sfx('err');return;}const r=teTrial(src);S.te.script=src;S.te.on=true;TE_CACHE={src:null,p:null};UI.teDraft=undefined;after();
const drop=r.before.served>1?1-r.after.served/r.before.served:0,saved=r.before.tc>0?1-r.after.tc/r.before.tc:0; const drop=r.before.served>1?1-r.after.served/r.before.served:0,saved=r.before.tc>0?1-r.after.tc/r.before.tc:0;
if(drop>0.1&&UI.slop===src){if(drop>0.3)S.stats.fat=1;toast(tr('route_script_and_tools.commit_complete_traffic_down_p_the',{p:pct(drop)}),'bad');sfx('alert');} if(drop>0.1&&UI.slop===src){if(drop>0.3)S.stats.fat=1;toast(tr('route_script_and_tools.commit_complete_traffic_down_p_the',{p:pct(drop)}),'bad');sfx('alert');}
else if(drop>0.3){S.stats.fat=1;toast(tr('route_script_and_tools.commit_complete_traffic_down_p_you',{p:pct(drop)}),'bad');sfx('alert');} else if(drop>0.3){S.stats.fat=1;toast(tr('route_script_and_tools.commit_complete_traffic_down_p_you',{p:pct(drop)}),'bad');sfx('alert');}

View file

@ -20,7 +20,9 @@ Object.assign(ACT,{
toast(lead?tr('sites_peering_caches.pni_with_net_ordered_eta_a',{net:esc(NET[net].name),eta:pniWhen(lead),dc:esc(siteName(city,'a'))}):tr('sites_peering_caches.pni_with_net_is_up_already',{net:esc(NET[net].name),dc:esc(siteName(city,'a'))}),'good');after();}, toast(lead?tr('sites_peering_caches.pni_with_net_ordered_eta_a',{net:esc(NET[net].name),eta:pniWhen(lead),dc:esc(siteName(city,'a'))}):tr('sites_peering_caches.pni_with_net_is_up_already',{net:esc(NET[net].name),dc:esc(siteName(city,'a'))}),'good');after();},
pniAllOpen:({net})=>{pniAllModal(net);}, pniAllOpen:({net})=>{pniAllModal(net);},
pniAllSize:({v})=>{if(!UI.pniAll)return;pniAllModal(UI.pniAll.net,+v);$('modalCard').querySelector('[data-chg="pniAllSize"]')?.focus();}, pniAllSize:({v})=>{if(!UI.pniAll)return;pniAllModal(UI.pniAll.net,+v);$('modalCard').querySelector('[data-chg="pniAllSize"]')?.focus();},
pniAll:({net,tier})=>{const b=pniBatch(net,tier);if(!b||!b.orders.length)return;if(!spend(b.cost))return; // q: the total the sheet showed. The batch is planned again now; a different total (the prices are fixed, so another
// plan), or nothing left to order, is shown again, not bought.
pniAll:({net,tier,q})=>{const b=pniBatch(net,tier);if(!b)return;if(q!==undefined&&(+q!==b.cost||!b.orders.length)){pniAllModal(net,tier,tr('utilities.quote_changed'));sfx('err');return;}if(!b.orders.length)return;if(!spend(b.cost))return;
for(const q of b.orders)pniPlace(q);UI.pniAll=null;closeModal(); for(const q of b.orders)pniPlace(q);UI.pniAll=null;closeModal();
toast(trn('pni_all.n_orders_with_net',b.orders.length,{net:esc(net===null?tr('common.all_networks'):NET[net].name),kept:b.kept,blocked:b.blocked.length}),'good');after();}, toast(trn('pni_all.n_orders_with_net',b.orders.length,{net:esc(net===null?tr('common.all_networks'):NET[net].name),kept:b.kept,blocked:b.blocked.length}),'good');after();},
pniChase:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p||(pniOn(p)&&!p.up))return;const r=Math.random(); pniChase:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p||(pniOn(p)&&!p.up))return;const r=Math.random();

View file

@ -12,7 +12,7 @@ Object.assign(ACT,{
const more=o.type==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===o.link&&b.name===o.name); const more=o.type==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===o.link&&b.name===o.name);
if(more){const l=S.links.find(x=>x.id===o.link);S.offers=S.offers.filter(x=>x!==o);more.slots=(more.slots||0)+(o.slots||0);more.rate+=o.rate;if(l)more.what=wwWhat(l,more.slots); if(more){const l=S.links.find(x=>x.id===o.link);S.offers=S.offers.filter(x=>x!==o);more.slots=(more.slots||0)+(o.slots||0);more.rate+=o.rate;if(l)more.what=wwWhat(l,more.slots);
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();return;} floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();return;}
S.offers=S.offers.filter(x=>x!==o);if(o.mk)customer.mk=o.mk;if(o.by)customer.by=o.by;S.biz.push(clSign(customer)); S.offers=S.offers.filter(x=>x!==o);if(o.mk&&clOn(customer))customer.mk=o.mk;if(o.by)customer.by=o.by;S.biz.push(clSign(customer));
// The shark's commission: one month of what the deal pays, on signing. // The shark's commission: one month of what the deal pays, on signing.
if(o.by==='shark'){const c=Math.round(bizMo(customer));if(c>0){S.cash-=c;toast(tr('sales.commission',{name:esc(o.name),cost:fmt$(c)}),'');}} if(o.by==='shark'){const c=Math.round(bizMo(customer));if(c>0){S.cash-=c;toast(tr('sales.commission',{name:esc(o.name),cost:fmt$(c)}),'');}}
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();}, floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();},

View file

@ -13,13 +13,13 @@ Object.assign(ACT,{
if(i.slow&&i.until>S.day+1){i.rushed=true;i.cost=0;i.until=S.day+1;const p=S.pops[i.ref];if(p)p.down=Math.min(p.down,S.day+1);toast(tr('links.power_cycled_the_router_in_city',{city:esc(CITY[i.ref].name),chip:esc(RG[(p&&p.rgen)||0].chip)}),'good');after();return;}clearInc(i);toast(tr('links.fixed_what_resolved_early',{what:incTitle(i.type)}),'good');after();}, if(i.slow&&i.until>S.day+1){i.rushed=true;i.cost=0;i.until=S.day+1;const p=S.pops[i.ref];if(p)p.down=Math.min(p.down,S.day+1);toast(tr('links.power_cycled_the_router_in_city',{city:esc(CITY[i.ref].name),chip:esc(RG[(p&&p.rgen)||0].chip)}),'good');after();return;}clearInc(i);toast(tr('links.fixed_what_resolved_early',{what:incTitle(i.type)}),'good');after();},
myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();}, myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();},
foundIx:({city})=>{if(!isCity(city))return;const why=foundIxWhy(city);if(why){toast(why,'bad');sfx('err');return;}if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name; foundIx:({city})=>{if(!isCity(city))return;const why=foundIxWhy(city);if(why){toast(why,'bad');sfx('err');return;}if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name;
S.myIx[city]={name:nm,members:[],next:S.day+4};S.ixp[city]=2;toast(tr('links.you_founded_ix_networks_will_join',{ix:esc(nm)}),'goal');after();}, S.myIx[city]={name:nm,members:[],next:S.day+4,fab:0};S.ixp[city]=2;toast(tr('links.you_founded_ix_networks_will_join',{ix:esc(nm)}),'goal');after();},
buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1);
if(!linkFromOk(a)||!linkToOk(b)||((cnCity(a)||cnCity(b))&&!cnOk()))return; if(!linkFromOk(a)||!linkToOk(b)||((cnCity(a)||cnCity(b))&&!cnOk()))return;
if(!waveOk(a,b,tier)){toast(tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:esc(waveNeed(tier))}),'bad');sfx('err');return;} if(!waveOk(a,b,tier)){toast(tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:esc(waveNeed(tier))}),'bad');sfx('err');return;}
const wr=waveRoute(a,b,mult,border);if(!wr){toast(tr('links.no_cable_available_for_that_route'),'bad');sfx('err');return;} const wr=waveRoute(a,b,mult,border);if(!wr){toast(tr('links.no_cable_available_for_that_route'),'bad');sfx('err');return;}
{const so=soldOut(a,b,tier,wr.cab);if(so){toast(tr('links.no_wave_capacity_on_this_route',{wave:LT[tier].n,why:tr(so.why),n:Math.max(1,so.until-S.day)}),'bad');sfx('err');return;}}{const w=subWaveWhy(tier,wr.km,wr.sub);if(w){toast(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:esc(w)}),'bad');sfx('err');return;}}const base=Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm),cost=base+(S.pops[b]?0:popCost(b)); {const so=soldOut(a,b,tier,wr.cab);if(so){toast(tr('links.no_wave_capacity_on_this_route',{wave:LT[tier].n,why:tr(so.why),n:Math.max(1,so.until-S.day)}),'bad');sfx('err');return;}}{const w=subWaveWhy(tier,wr.km,wr.sub);if(w){toast(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:esc(w)}),'bad');sfx('err');return;}}const base=Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm),cost=base+(S.pops[b]?0:popCost(b));
if(!portGate(a,1)||!portGate(b,1))return;if(!spend(cost))return;if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};popStdApply(b);} if(!portGate(a,1)||!portGate(b,1))return;if(!spend(cost))return;if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);}
const id=uid();const l={id,a,b,kind:'wave',border,premium:border&&!!UI.cnPrem&&(a==='hkg'||b==='hkg'),tier,km:wr.km,sub:wr.sub,cable:wr.cab,mo:base,mult:wr.wm,trench:wr.cab?'cab:'+wr.cab:(jn?jn.k:id),cut:0,day:S.day};S.links.push(l);satBeside(a,b);closeModal(); const id=uid();const l={id,a,b,kind:'wave',border,premium:border&&!!UI.cnPrem&&(a==='hkg'||b==='hkg'),tier,km:wr.km,sub:wr.sub,cable:wr.cab,mo:base,mult:wr.wm,trench:wr.cab?'cab:'+wr.cab:(jn?jn.k:id),cut:0,day:S.day};S.links.push(l);satBeside(a,b);closeModal();
if(sib.length){UI.sel={type:'link',id};}else{UI.sel={type:'city',id:b};UI.tab='cust';} if(sib.length){UI.sel={type:'link',id};}else{UI.sel={type:'city',id:b};UI.tab='cust';}
floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');after();}, floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');after();},
@ -47,8 +47,9 @@ Object.assign(ACT,{
metricMode:({id,k})=>{if(k!=='f'&&k!=='w')return;const l=S.links.find(x=>x.id===id);if(!l)return;const key=edgeKey(l),c=pairCm(key);if(!c||c.k===k)return; metricMode:({id,k})=>{if(k!=='f'&&k!=='w')return;const l=S.links.find(x=>x.id===id);if(!l)return;const key=edgeKey(l),c=pairCm(key);if(!c||c.k===k)return;
// The cost stays what it was on this link, written the other way. // The cost stays what it was on this link, written the other way.
const w=pairW(key,l.km);S.pairMet[key]={k,v:clampM(k,k==='w'?w:w/(l.km+60))};metBlur();sfx('click');after();}, const w=pairW(key,l.km);S.pairMet[key]={k,v:clampM(k,k==='w'?w:w/(l.km+60))};metBlur();sfx('click');after();},
metricSet:({id})=>{const l=S.links.find(x=>x.id===id),t=$('metIn');if(!l||!t)return;const key=edgeKey(l),c=pairCm(key);if(!c)return;const v=parseFloat(String(t.value).replace(',','.'));if(!Number.isFinite(v)){sfx('err');return;} // v: the typed value as an argument (a server runs this without the field), else the field's.
t.blur();S.pairMet[key]={k:c.k,v:clampM(c.k,v)};sfx('click');after();}, metricSet:({id,v})=>{const l=S.links.find(x=>x.id===id),t=$('metIn'),txt=v!==undefined?v:t?t.value:undefined;if(!l||txt===undefined)return;const key=edgeKey(l),c=pairCm(key);if(!c)return;const x=parseFloat(String(txt).replace(',','.'));if(!Number.isFinite(x)){sfx('err');return;}
if(t)t.blur();S.pairMet[key]={k:c.k,v:clampM(c.k,x)};sfx('click');after();},
setCarry:({id,on})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;if(on)t.carry=true;else delete t.carry;sfx('click');after();}, setCarry:({id,on})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;if(on)t.carry=true;else delete t.carry;sfx('click');after();},
setStandby:({id,on})=>{const l=S.links.find(x=>x.id===id);if(!l)return;if(on)l.standby=true;else delete l.standby;sfx('click');after();}, setStandby:({id,on})=>{const l=S.links.find(x=>x.id===id);if(!l)return;if(on)l.standby=true;else delete l.standby;sfx('click');after();},
goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':k==='nni'?'links':'peer';renderPanel();}, goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':k==='nni'?'links':'peer';renderPanel();},

View file

@ -9,7 +9,7 @@ Object.assign(ACT,{
sacrif:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p)return;p.sacrif=!p.sacrif;toast(p.sacrif?tr('security_and_china.net_pni_is_now_a_sacrificial',{net:NET[p.net].name}):tr('security_and_china.net_pni_is_back_to_normal',{net:NET[p.net].name}),p.sacrif?'good':'');after();}, sacrif:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p)return;p.sacrif=!p.sacrif;toast(p.sacrif?tr('security_and_china.net_pni_is_now_a_sacrificial',{net:NET[p.net].name}):tr('security_and_china.net_pni_is_back_to_normal',{net:NET[p.net].name}),p.sacrif?'good':'');after();},
// RTBH blackholes the target upstream: your ports and everyone else are saved, the target is dark until you withdraw it. // RTBH blackholes the target upstream: your ports and everyone else are saved, the target is dark until you withdraw it.
rtbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('security_and_china.no_attack_to_blackhole_right_now'),'');return;}if(a.bh)return;a.bh=true;a.sac=1;S.stats.rtbh=(S.stats.rtbh||0)+1;ddosRtbhMood(a); rtbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('security_and_china.no_attack_to_blackhole_right_now'),'');return;}if(a.bh)return;a.bh=true;a.sac=1;S.stats.rtbh=(S.stats.rtbh||0)+1;ddosRtbhMood(a);
const T=S.stats.ddT||(S.stats.ddT={}),first=!T.rtbh;T.rtbh=1;toast(tr('ddos.rtbh_on',{who:esc(ddosWho(a))})+(first?'<br><i>'+tr('ddos.learn_rtbh')+'</i>':''),'bad');sfx('alert');after();}, const T=ddosTaught(),first=!T.rtbh;T.rtbh=1;toast(tr('ddos.rtbh_on',{who:esc(ddosWho(a))})+(first?'<br><i>'+tr('ddos.learn_rtbh')+'</i>':''),'bad');sfx('alert');after();},
unrtbh:({id}={})=>{const a=ddosFind(id);if(!a||!a.bh)return;a.bh=false;toast(tr('ddos.rtbh_off',{who:esc(ddosWho(a))}),'');after();}, unrtbh:({id}={})=>{const a=ddosFind(id);if(!a||!a.bh)return;a.bh=false;toast(tr('ddos.rtbh_off',{who:esc(ddosWho(a))}),'');after();},
// On-demand scrubbing, when it does not engage by itself: start the diversion now. // On-demand scrubbing, when it does not engage by itself: start the diversion now.
ddosEngage:({id}={})=>{const a=ddosFind(id);if(!a||!hasScrub()||a.eng!==undefined)return;a.eng=S.day;toast(tr('ddos.engaged'),'good');sfx('click');after();}, ddosEngage:({id}={})=>{const a=ddosFind(id);if(!a||!hasScrub()||a.eng!==undefined)return;a.eng=S.day;toast(tr('ddos.engaged'),'good');sfx('click');after();},

View file

@ -3,7 +3,7 @@ Object.assign(ACT,{
toast(tr('specialist.the_vendor_ships_a_demo_name',{name:esc(it.n),n:at-S.day,p:Math.round((DEMO_MUL-1)*100)}),'good');after();}, toast(tr('specialist.the_vendor_ships_a_demo_name',{name:esc(it.n),n:at-S.day,p:Math.round((DEMO_MUL-1)*100)}),'good');after();},
seatBuy:({n})=>{const o=S.seatOff;n=+n;if(!o||o.exp<=S.day||!SEAT_N.includes(n))return;const miss=[o.a,o.b].filter(c=>!S.pops[c]),cost=seatCost(o.km,n)+miss.reduce((x,c)=>x+popCost(c),0);if(!spend(cost))return; seatBuy:({n})=>{const o=S.seatOff;n=+n;if(!o||o.exp<=S.day||!SEAT_N.includes(n))return;const miss=[o.a,o.b].filter(c=>!S.pops[c]),cost=seatCost(o.km,n)+miss.reduce((x,c)=>x+popCost(c),0);if(!spend(cost))return;
for(const c of miss){S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(c);} for(const c of miss){S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(c);}
const id=uid(),days=seatDays(o.km);S.links.push({id,a:o.a,b:o.b,kind:'df',own:true,sub:true,seat:true,seaDesign:'standard',sys:'roadm',ch:[],km:o.km,cable:null,cname:o.name,mo:seatMo(o.km,n),trench:'seat:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:n,paid:seatCost(o.km,n)});satBeside(o.a,o.b); const id=uid(),days=seatDays(o.km);S.links.push({id,a:o.a,b:o.b,kind:'df',own:true,sub:true,seat:true,seaDesign:'standard',sys:'roadm',ch:[],km:o.km,cable:null,cname:o.name,mo:seatMo(o.km,n),trench:'seat:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:n,paid:seatCost(o.km,n),regen:0});satBeside(o.a,o.b);
S.seatOff=null;S.stats.seats=(S.stats.seats||0)+1;UI.sel={type:'link',id}; S.seatOff=null;S.stats.seats=(S.stats.seats||0)+1;UI.sel={type:'link',id};
toast(tr('specialist.you_own_n_fiber_pairs_on',{n,name:esc(o.name),a:CITY[o.a].name,b:CITY[o.b].name,d:days}),'goal');sfx('build');after();}, toast(tr('specialist.you_own_n_fiber_pairs_on',{n,name:esc(o.name),a:CITY[o.a].name,b:CITY[o.b].name,d:days}),'goal');sfx('build');after();},
seatNo:()=>{S.seatOff=null;after();}, seatNo:()=>{S.seatOff=null;after();},

View file

@ -10,7 +10,7 @@ Object.assign(ACT,{
orderCable:()=>{const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;if(ownCabWhy(a,b)||!linkFromOk(a)||!linkToOk(b))return;const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',up=seaUps(seaQuote(a,b,design).km),q=seaQuote(a,b,design,up),km=q.km,cost=q.cost+(S.pops[b]?0:popCost(b));if(seaLack(km,up).length||!spend(cost))return; orderCable:()=>{const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;if(ownCabWhy(a,b)||!linkFromOk(a)||!linkToOk(b))return;const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',up=seaUps(seaQuote(a,b,design).km),q=seaQuote(a,b,design,up),km=q.km,cost=q.cost+(S.pops[b]?0:popCost(b));if(seaLack(km,up).length||!spend(cost))return;
if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);} if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);}
const used=new Set(S.links.map(l=>l.cname).filter(Boolean)),cname=OWNCAB_NAMES.find(n=>!used.has(n))||`${pick(OWNCAB_NAMES)} ${used.size+1}`,id=uid(),ship=layName({id}),days=q.days; const used=new Set(S.links.map(l=>l.cname).filter(Boolean)),cname=OWNCAB_NAMES.find(n=>!used.has(n))||`${pick(OWNCAB_NAMES)} ${used.size+1}`,id=uid(),ship=layName({id}),days=q.days;
S.links.push({id,a,b,kind:'df',own:true,sub:true,seaDesign:design,seaPath:q.pts.map(p=>p.slice()),sys:'roadm',ch:[],km,cable:null,cname,mo:Math.round(km*OWNCAB_OM),trench:'own:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:1});satBeside(a,b); S.links.push({id,a,b,kind:'df',own:true,sub:true,seaDesign:design,seaPath:q.pts.map(p=>p.slice()),sys:'roadm',ch:[],km,cable:null,cname,mo:Math.round(km*OWNCAB_OM),trench:'own:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:1,regen:0});satBeside(a,b);
const laid=S.links[S.links.length-1];laid.paid=q.cost;for(const k of Object.keys(SUB_UPGRADES))if(up[k])laid['sub'+k]=laid.ready;UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false; const laid=S.links[S.links.length-1];laid.paid=q.cost;for(const k of Object.keys(SUB_UPGRADES))if(up[k])laid['sub'+k]=laid.ready;UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false;
S.stats.ownCab=(S.stats.ownCab||0)+1;UI.dfSrc='lease';closeModal();UI.sel={type:'link',id}; S.stats.ownCab=(S.stats.ownCab||0)+1;UI.dfSrc='lease';closeModal();UI.sel={type:'link',id};
toast(tr('fiber_and_hardware.the_ship_sets_sail_name_your',{ship,name:cname,km:km.toLocaleString(),a:CITY[a].name,b:CITY[b].name,n:days}),'goal');sfx('build');after();}, toast(tr('fiber_and_hardware.the_ship_sets_sail_name_your',{ship,name:cname,km:km.toLocaleString(),a:CITY[a].name,b:CITY[b].name,n:days}),'goal');sfx('build');after();},
@ -19,7 +19,7 @@ Object.assign(ACT,{
const up=(own?digCost(km):0)+sysCost(sys)+ampCount(km)*AMP_COST+(S.pops[b]?0:popCost(b));if(!spend(up))return; const up=(own?digCost(km):0)+sysCost(sys)+ampCount(km)*AMP_COST+(S.pops[b]?0:popCost(b));if(!spend(up))return;
if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);} if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);}
const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),id=uid(); const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),id=uid();
const l={id,a,b,kind:'df',own,sys,ch:[],km,sub:!!sc,cable:sc?sc.cid:null,mo:own?Math.round(km*0.15):dfLeaseMo(km),trench:sc?'cab:'+sc.cid:id,cut:0,day:S.day,ready:S.day+(own?dfBuildDays(km):leadDays(IRU_DAYS)),spares:false}; const l={id,a,b,kind:'df',own,sys,ch:[],km,sub:!!sc,cable:sc?sc.cid:null,mo:own?Math.round(km*0.15):dfLeaseMo(km),trench:sc?'cab:'+sc.cid:id,cut:0,day:S.day,ready:S.day+(own?dfBuildDays(km):leadDays(IRU_DAYS)),spares:false,regen:0};
S.links.push(l);satBeside(a,b);closeModal();UI.sel={type:'link',id}; S.links.push(l);satBeside(a,b);closeModal();UI.sel={type:'link',id};
toast(own?tr('fiber_and_hardware.groundbreaking_your_own_fiber_from_a',{a:CITY[a].name,b:CITY[b].name,n:dfBuildDays(km)}):tr('fiber_and_hardware.dark_fiber_iru_signed_a_b',{a:CITY[a].name,b:CITY[b].name}),'goal');after();}, toast(own?tr('fiber_and_hardware.groundbreaking_your_own_fiber_from_a',{a:CITY[a].name,b:CITY[b].name,n:dfBuildDays(km)}):tr('fiber_and_hardware.dark_fiber_iru_signed_a_b',{a:CITY[a].name,b:CITY[b].name}),'goal');after();},
regen:({id,d})=>{d=+d;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||(l.sub&&!l.seat)||(d!==1&&d!==-1))return;const n=(l.regen|0)+d;if(n<0||n>REGEN_MAX)return; regen:({id,d})=>{d=+d;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||(l.sub&&!l.seat)||(d!==1&&d!==-1))return;const n=(l.regen|0)+d;if(n<0||n>REGEN_MAX)return;

View file

@ -16,7 +16,7 @@ Object.assign(ACT,{
// Next to a link you already have between the two, it goes on standby: the backup that carries only when the cable is down. // Next to a link you already have between the two, it goes on standby: the backup that carries only when the cable is down.
buySat:({a,b,bird,g})=>{g=+g;const why=satWhy(a,b,bird,g);if(why){toast(why,'bad');sfx('err');return;} buySat:({a,b,bird,g})=>{g=+g;const why=satWhy(a,b,bird,g);if(why){toast(why,'bad');sfx('err');return;}
if(!portGate(a,1)||!portGate(b,1))return;const mo=satMo(bird,g),pop=!S.pops[b];if(!spend(mo+(pop?popCost(b):0)))return; if(!portGate(a,1)||!portGate(b,1))return;const mo=satMo(bird,g),pop=!S.pops[b];if(!spend(mo+(pop?popCost(b):0)))return;
if(pop){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};popStdApply(b);} if(pop){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);}
const sb=pairLinks(a,b).some(l=>l.kind!=='sat'),n=leadDays(SAT_ORB[SATS[bird].orb].days),id=uid(); const sb=pairLinks(a,b).some(l=>l.kind!=='sat'),n=leadDays(SAT_ORB[SATS[bird].orb].days),id=uid();
S.links.push({id,a,b,kind:'sat',bird,g,km:satKm(bird,a,b),sub:true,mo,cut:0,day:S.day,ready:S.day+n,...(sb?{standby:true}:{})}); S.links.push({id,a,b,kind:'sat',bird,g,km:satKm(bird,a,b),sub:true,mo,cut:0,day:S.day,ready:S.day+n,...(sb?{standby:true}:{})});
closeModal();UI.sel={type:'link',id}; closeModal();UI.sel={type:'link',id};

View file

@ -1,4 +1,8 @@
// The build standard sheet (93-ui/59-build-standard.js): pick a target, or bring everything up to the standard in one go. // The build standard sheet (93-ui/59-build-standard.js): pick a target, or bring everything up to the standard in one go.
// The plan a sheet showed, as a short key: its jobs, in any order (the plan sorts POPs by today's load).
function bstdPlanKey(J){const s=J.map(j=>j.grp+' '+j.k+' '+j.ch+' '+j.w).sort().join('\n');let h=0x811c9dc5;
for(let i=0;i<s.length;i++){h^=s.charCodeAt(i);h=Math.imul(h,0x01000193);}return J.length+'.'+(h>>>0).toString(36);}
const bstdSum=J=>Math.round(J.reduce((a,j)=>a+j.cost,0));
Object.assign(ACT,{ Object.assign(ACT,{
bstdOpen:()=>{if(S&&!pzOn())bstdModal();}, bstdOpen:()=>{if(S&&!pzOn())bstdModal();},
// v: a position in the list the sheet shows; without v, the next value (the MCP tools step through a list). // v: a position in the list the sheet shows; without v, the next value (the MCP tools step through a list).
@ -6,9 +10,13 @@ Object.assign(ACT,{
D[k]=x;S.popStd=bstdPut(D);sfx('click');after();opsRedraw('bstdSet',{k},bstdModal);}, D[k]=x;S.popStd=bstdPut(D);sfx('click');after();opsRedraw('bstdSet',{k},bstdModal);},
// The same jobs, in the same order and through the same gates as the intern's order, while the cash lasts. One // The same jobs, in the same order and through the same gates as the intern's order, while the cash lasts. One
// recompute at the end, and one toast: what got done, and what still waits. // recompute at the end, and one toast: what got done, and what still waits.
bstdApply:()=>{if(!S||pzOn()||!S.popStd)return;const J=bstdPlan(false);if(!J.length)return;const c0=S.cash;let n=0; // quote: the plan the sheet showed (bstdPlanKey), q: its total. Another plan, a total that moved more than a day's drift
// (quoteNear), or nothing left to do is shown again, not built.
bstdApply:({quote,q}={})=>{if(!S||pzOn()||!S.popStd)return;const J=bstdPlan(false);
if((quote!==undefined||q!==undefined)&&(!J.length||(quote!==undefined&&String(quote)!==bstdPlanKey(J))||(q!==undefined&&!quoteNear(+q,bstdSum(J))))){bstdModal(tr('utilities.quote_changed'));sfx('err');return;}
if(!J.length)return;const c0=S.cash;let n=0;
opsQuiet(()=>{n=bstdDo(J,j=>{const c=bstdPrice(j);return c<=0||S.cash>=c;},j=>!!j.go()).length;}); opsQuiet(()=>{n=bstdDo(J,j=>{const c=bstdPrice(j);return c<=0||S.cash>=c;},j=>!!j.go()).length;});
after();const q=bstdQuote(false),left=q.pops+q.ports+q.links; after();const z=bstdQuote(false),left=z.pops+z.ports+z.links;
toast((n?trn('bstd.applied',n,{cost:fmt$(c0-S.cash)}):tr('bstd.applied_none'))+(left?' '+trn('bstd.left',left):''),n?'good':'bad');sfx(n?'build':'err'); toast((n?trn('bstd.applied',n,{cost:fmt$(c0-S.cash)}):tr('bstd.applied_none'))+(left?' '+trn('bstd.left',left):''),n?'good':'bad');sfx(n?'build':'err');
if(bstdShown())bstdModal();}, if(bstdShown())bstdModal();},
}); });

View file

@ -4,8 +4,8 @@ Object.assign(ACT,{
utilityRouteServers:({city}={})=>{if(!S)return;const ids=utilityRouteServers();for(const ix of ids)S.rs[ix]=true; utilityRouteServers:({city}={})=>{if(!S)return;const ids=utilityRouteServers();for(const ix of ids)S.rs[ix]=true;
if(ids.length){sfx('build');after();}utilitiesModal(city,tr('utilities.route_servers_joined',{n:ids.length}));}, if(ids.length){sfx('build');after();}utilitiesModal(city,tr('utilities.route_servers_joined',{n:ids.length}));},
utilityKit:({city,cost,modal})=>{const q=utilityKit(city);if(!q||(!q.cost&&!q.moves.length))return; utilityKit:({city,cost,modal})=>{const q=utilityKit(city);if(!q||(!q.cost&&!q.moves.length))return;
// Prices can change while a modal is open. Refresh the quote before spending more. // Prices can change while a modal is open. Refresh the quote before spending more (a day's drift is fine: quoteNear).
if(q.cost!==+cost){if(modal)utilitiesModal(city,tr('utilities.quote_changed'));else{renderPanel();toast(tr('utilities.quote_changed'));}return;} if(!quoteNear(+cost,q.cost)){if(modal)utilitiesModal(city,tr('utilities.quote_changed'));else{renderPanel();toast(tr('utilities.quote_changed'));}return;}
if(q.cost&&!spend(q.cost))return;const p=S.pops[city]; if(q.cost&&!spend(q.cost))return;const p=S.pops[city];
if(q.gen)p.gen=true;if(q.site){p.site2=true;p.site2Day=S.day;}if(q.router)p.routers=2; if(q.gen)p.gen=true;if(q.site){p.site2=true;p.site2Day=S.day;}if(q.router)p.routers=2;
const moves=new Map(q.moves.map(m=>[m.id,m.site]));for(const c of S.caches)if(moves.has(c.id))c.site=moves.get(c.id); const moves=new Map(q.moves.map(m=>[m.id,m.site]));for(const c of S.caches)if(moves.has(c.id))c.site=moves.get(c.id);

View file

@ -24,7 +24,8 @@ Object.assign(ACT,{
slotTake:({id})=>{if(!slotOkId(id))return;const w=SLOT.wait={id,go:()=>{if(SLOT.wait!==w)return;SLOT.wait=null;clearTimeout(w.t);slotOpen(id,true);}}; slotTake:({id})=>{if(!slotOkId(id))return;const w=SLOT.wait={id,go:()=>{if(SLOT.wait!==w)return;SLOT.wait=null;clearTimeout(w.t);slotOpen(id,true);}};
w.t=setTimeout(w.go,BC?1500:0);try{if(BC)BC.postMessage({t:'take',id});}catch(e){w.go();}}, w.t=setTimeout(w.go,BC?1500:0);try{if(BC)BC.postMessage({t:'take',id});}catch(e){w.go();}},
rename:()=>{if(!S||!UI.started||pzOn())return;openModal(`<h2 style="font-size:26px">${tr('slots.rename_your_network')}</h2><label class="f" for="rnIn">${tr('title.name_your_network')}</label><div class="network-name"><input class="t" id="rnIn" maxlength="24" value="${esc(S.name)}" autocomplete="off"></div><div class="btns" style="margin-top:12px">${btn(tr('slots.rename'),'renameGo',{},'pink big')}${btn(tr('common.cancel'),'menu',{},'ghost big')}</div>`);}, rename:()=>{if(!S||!UI.started||pzOn())return;openModal(`<h2 style="font-size:26px">${tr('slots.rename_your_network')}</h2><label class="f" for="rnIn">${tr('title.name_your_network')}</label><div class="network-name"><input class="t" id="rnIn" maxlength="24" value="${esc(S.name)}" autocomplete="off"></div><div class="btns" style="margin-top:12px">${btn(tr('slots.rename'),'renameGo',{},'pink big')}${btn(tr('common.cancel'),'menu',{},'ghost big')}</div>`);},
renameGo:()=>{const el=$('rnIn');if(!S||!el||pzOn())return;const v=el.value.replace(/\s+/g,' ').trim().slice(0,24);if(!v)return;S.name=v;closeModal();after();toast(tr('slots.renamed_to_name',{name:esc(v)}),'good');}, // name: the new name as an argument (a server runs this without the sheet), else the sheet's field.
renameGo:({name}={})=>{const el=$('rnIn'),raw=typeof name==='string'?name:el?el.value:null;if(!S||raw===null||pzOn())return;const v=raw.replace(/\s+/g,' ').trim().slice(0,24);if(!v)return;S.name=v;closeModal();after();toast(tr('slots.renamed_to_name',{name:esc(v)}),'good');},
}); });
// No game on screen: the map stays empty behind the title. // No game on screen: the map stays empty behind the title.
function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();} function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();}

View file

@ -27,7 +27,8 @@ Object.assign(ACT,{
if(!pieSpend(pieLicPrice(cc)))return pieRe();P.lic[cc]={state:'ok',until:Math.max(S.day,l&&l.state==='ok'?l.until:0)+PIE_LIC_DAYS};toast(tr('pie.t_lic',{n:pieLicCountry(cc)}),'good');pieRe();}, if(!pieSpend(pieLicPrice(cc)))return pieRe();P.lic[cc]={state:'ok',until:Math.max(S.day,l&&l.state==='ok'?l.until:0)+PIE_LIC_DAYS};toast(tr('pie.t_lic',{n:pieLicCountry(cc)}),'good');pieRe();},
pieSafe:()=>{const P=pieGet();if(!P||!P.co)return;P.safe=!P.safe;sfx('click');pieRe();}, pieSafe:()=>{const P=pieGet();if(!P||!P.co)return;P.safe=!P.safe;sfx('click');pieRe();},
pieName:()=>{const P=pieGet();if(!P||!P.co)return;const i=PIE_NAMES.indexOf(P.co.name);P.co.name=PIE_NAMES[(i+1)%PIE_NAMES.length];pieFounder(N_('pie.fp_rename'));pieRe();}, pieName:()=>{const P=pieGet();if(!P||!P.co)return;const i=PIE_NAMES.indexOf(P.co.name);P.co.name=PIE_NAMES[(i+1)%PIE_NAMES.length];pieFounder(N_('pie.fp_rename'));pieRe();},
pieRename:()=>{const P=pieGet(),el=$('pieNm');if(!P||!P.co||!el)return;const v=el.value.replace(/\s+/g,' ').trim().slice(0,40);if(!v)return;P.co.name=v;pieFounder(N_('pie.fp_rename'));pieRe();}, // name: the new name as an argument (a server runs this without the field), else the field's.
pieRename:({name}={})=>{const P=pieGet(),el=$('pieNm'),raw=typeof name==='string'?name:el?el.value:null;if(!P||!P.co||raw===null)return;const v=raw.replace(/\s+/g,' ').trim().slice(0,40);if(!v)return;P.co.name=v;pieFounder(N_('pie.fp_rename'));pieRe();},
// Government money (60-features/99-pie-subsidies.js): its section in the bank, a bid, the Ex-Im loan. It was Pie Control's Gov tab; the name stays for old toasts. // Government money (60-features/99-pie-subsidies.js): its section in the bank, a bid, the Ex-Im loan. It was Pie Control's Gov tab; the name stays for old toasts.
pieGovOpen:()=>{if(!S||pzOn()||!pieOn())return;if(!$('modal').hidden)closeModal();ACT.bank();const g=$('bankGov');if(g&&g.scrollIntoView)g.scrollIntoView({block:'start'});}, pieGovOpen:()=>{if(!S||pzOn()||!pieOn())return;if(!$('modal').hidden)closeModal();ACT.bank();const g=$('bankGov');if(g&&g.scrollIntoView)g.scrollIntoView({block:'start'});},
pieBid:({id,f})=>{const P=pieGet();f=+f;const a=P&&P.gov.auc.find(x=>x.id===id);if(!a||!PIE_RDF_BIDS.includes(f))return;if(!pieCanBuild())return pieNo(tr('pie.why_not_t1')); pieBid:({id,f})=>{const P=pieGet();f=+f;const a=P&&P.gov.auc.find(x=>x.id===id);if(!a||!PIE_RDF_BIDS.includes(f))return;if(!pieCanBuild())return pieNo(tr('pie.why_not_t1'));

View file

@ -80,3 +80,7 @@ function importFile(file){if(!file)return;if(file.size>64e6){toast(tr('save.that
function loadSave(){UI.loadBad=false;const raw=slotRaw(UI.slot);if(raw==null)return null; function loadSave(){UI.loadBad=false;const raw=slotRaw(UI.slot);if(raw==null)return null;
try{const t=raw.startsWith(GZ)?raw===UI.gzRaw?UI.gzText:null:raw;if(t){const s=JSON.parse(t);if(s&&s.v===1){if(!s.lost)return s;return null;}}}catch(e){} try{const t=raw.startsWith(GZ)?raw===UI.gzRaw?UI.gzText:null:raw;if(t){const s=JSON.parse(t);if(s&&s.v===1){if(!s.lost)return s;return null;}}}catch(e){}
UI.loadBad=true;return null;} UI.loadBad=true;return null;}
// What a network says once when it is opened again: new networks on the map (the courtesy route), Australia's prices.
// Boot calls it; a server-run network hears it from the server instead (it changes S).
function bootNotes(){if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);}
if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});}}

View file

@ -17,9 +17,10 @@ function bstdVal(k,v){if(v===BSTDK[k].d&&k!=='rt')return tr('bstd.keep');
case 'wv':return tr('bstd.or_better',{x:LT[v].n});} case 'wv':return tr('bstd.or_better',{x:LT[v].n});}
return String(v);} return String(v);}
const bstdShown=()=>!!$('modal')&&!$('modal').hidden&&!!$('modalCard').querySelector('[data-sheet="bstd"]'); const bstdShown=()=>!!$('modal')&&!$('modal').hidden&&!!$('modalCard').querySelector('[data-sheet="bstd"]');
function bstdModal(){if(!S||pzOn())return;const D=bstd(),q=bstdQuote(false),hired=opsHired(),on=hired&&S.ops.on.std; // msg: why the sheet is shown again (the quote changed).
function bstdModal(msg){if(!S||pzOn())return;const D=bstd(),q=bstdQuote(false),hired=opsHired(),on=hired&&S.ops.on.std;
let h=`<div data-sheet="bstd" style="display:flex;align-items:center"><div><div class="eyebrow">${tr('ops.ops')}</div><h2 style="font-size:26px">${tr('bstd.title')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div> let h=`<div data-sheet="bstd" style="display:flex;align-items:center"><div><div class="eyebrow">${tr('ops.ops')}</div><h2 style="font-size:26px">${tr('bstd.title')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('bstd.tagline')}</p>`; <p class="tagline">${tr('bstd.tagline')}</p>${typeof msg==='string'&&msg?`<p class="why">${esc(msg)}</p>`:''}`;
for(const [g,lab] of BSTD_GRP)h+=`<section><h3>${tr(lab)}</h3><div class="ops-p">${BSTD.filter(x=>x.grp===g).map(x=>opsSel(tr(x.l),'bstdSet',{k:x.k},bstdOpts(x.k),D[x.k],v=>bstdVal(x.k,v))).join('')}</div> for(const [g,lab] of BSTD_GRP)h+=`<section><h3>${tr(lab)}</h3><div class="ops-p">${BSTD.filter(x=>x.grp===g).map(x=>opsSel(tr(x.l),'bstdSet',{k:x.k},bstdOpts(x.k),D[x.k],v=>bstdVal(x.k,v))).join('')}</div>
<p class="note">${g==='pop'?tr('bstd.new_pops_note'):g==='port'?tr('bstd.port_note'):tr('bstd.fiber_note_two')}</p></section>`; <p class="note">${g==='pop'?tr('bstd.new_pops_note'):g==='port'?tr('bstd.port_note'):tr('bstd.fiber_note_two')}</p></section>`;
// What is below it today, and what bringing it all up costs: a quote, nothing changes until the button. A fiber whose // What is below it today, and what bringing it all up costs: a quote, nothing changes until the button. A fiber whose
@ -34,5 +35,6 @@ function bstdModal(){if(!S||pzOn())return;const D=bstd(),q=bstdQuote(false),hire
<button class="b sm ${on?'green':'ghost'}" data-act="opsToggle" data-args='{"k":"std"}' aria-pressed="${on}" aria-label="${esc(tr('ops.o_std'))}">${on?tr('common.on'):tr('ops.paused')}</button></div> <button class="b sm ${on?'green':'ghost'}" data-act="opsToggle" data-args='{"k":"std"}' aria-pressed="${on}" aria-label="${esc(tr('ops.o_std'))}">${on?tr('common.on'):tr('ops.paused')}</button></div>
${on?`<div class="ops-p">${opsSel(tr('ops.budget'),'opsCap',{k:'std'},opsCaps('std'),opsCap('std'),v=>opsCapName('std',v))}</div>`:''}</div>` ${on?`<div class="ops-p">${opsSel(tr('ops.budget'),'opsCap',{k:'std'},opsCaps('std'),opsCap('std'),v=>opsCapName('std',v))}</div>`:''}</div>`
:`<p class="meta">${tr('bstd.hire_note')}</p><div class="btns">${btn(tr('ops.hire_an_intern'),'opsOpen',{},'ghost sm',!opsCanHire()||!rule('clock'))}</div>`}</section>`; :`<p class="meta">${tr('bstd.hire_note')}</p><div class="btns">${btn(tr('ops.hire_an_intern'),'opsOpen',{},'ghost sm',!opsCanHire()||!rule('clock'))}</div>`}</section>`;
h+=`<div class="btns cta">${btn(q.n?tr('bstd.apply_now',{cost:fmt$(q.cost)}):w?tr('bstd.apply_wait'):tr('bstd.apply_nothing'),'bstdApply',{},'pink',!q.n)}</div>`; // The button carries the plan it shows and its total (bstdApply checks both again).
h+=`<div class="btns cta">${btn(q.n?tr('bstd.apply_now',{cost:fmt$(q.cost)}):w?tr('bstd.apply_wait'):tr('bstd.apply_nothing'),'bstdApply',{quote:bstdPlanKey(bstdPlan(false)),q:q.cost},'pink',!q.n)}</div>`;
openModal(h,'ops');} openModal(h,'ops');}

View file

@ -1,8 +1,11 @@
/* ---------- toasts & modals ---------- */ /* ---------- toasts & modals ---------- */
function toast(html,kind='',actions=[],open=null){ function toast(html,kind='',actions=[],open=null){
if(S)logNote(html,kind,actions,open); if(S)logNote(html,kind,actions,open);
toastPop(html,kind,actions,UI.tick);}
// The toast on screen only (the log line is toast()'s). tick: the day announced it (UI.tick when it was said).
function toastPop(html,kind='',actions=[],tick=false){
// Quiet notifications: what the day announces pops up only for trouble and milestones; the rest stays in the NOC log. // Quiet notifications: what the day announces pops up only for trouble and milestones; the rest stays in the NOC log.
if(UI.tick&&kind!=='bad'&&kind!=='goal'&&quietOn())return; if(tick&&kind!=='bad'&&kind!=='goal'&&quietOn())return;
const el=document.createElement('div');el.className='toast '+kind;el.dataset.born=performance.now(); const el=document.createElement('div');el.className='toast '+kind;el.dataset.born=performance.now();
el.innerHTML=`<div class="tx">${html}</div>${actions.map(a=>btn(a.l,a.act,a.args,'sm')).join('')}`; el.innerHTML=`<div class="tx">${html}</div>${actions.map(a=>btn(a.l,a.act,a.args,'sm')).join('')}`;
const box=$('toasts');box.prepend(el);const max=innerWidth<760?2:3;while(box.children.length>max)box.lastChild.remove(); const box=$('toasts');box.prepend(el);const max=innerWidth<760?2:3;while(box.children.length>max)box.lastChild.remove();

View file

@ -1,10 +1,11 @@
function pniAllModal(net,tier=1){const b=pniBatch(net,tier);if(!b)return;UI.pniAll={net,tier}; // msg: why the sheet is shown again (the quote changed).
function pniAllModal(net,tier=1,msg=''){const b=pniBatch(net,tier);if(!b)return;UI.pniAll={net,tier};
const all=net===null,n=NET[net],port=tier===-1?'1G':PORT[tier].n,up=b.orders.filter(q=>q.ex).length,byNet={}; const all=net===null,n=NET[net],port=tier===-1?'1G':PORT[tier].n,up=b.orders.filter(q=>q.ex).length,byNet={};
if(all)for(const q of b.orders)(byNet[q.net]||(byNet[q.net]=[])).push(q.city); if(all)for(const q of b.orders)(byNet[q.net]||(byNet[q.net]=[])).push(q.city);
const controls=`<div class="btns">${btn(all?tr('pni_all.all_at_port',{port}):tr('pni_all.peer_at_port',{port}),'pniAll',{net,tier},'pink',!b.orders.length||S.cash<b.cost)}${btn(tr('common.cancel'),'closeModal',{},'ghost')}</div>`; const controls=`<div class="btns">${btn(all?tr('pni_all.all_at_port',{port}):tr('pni_all.peer_at_port',{port}),'pniAll',{net,tier,q:b.cost},'pink',!b.orders.length||S.cash<b.cost)}${btn(tr('common.cancel'),'closeModal',{},'ghost')}</div>`;
const blocked=b.blocked.map(q=>`<p class="why"><b>${all?esc(NET[q.net].name)+' · ':''}${esc(CITY[q.city].name)}:</b> ${q.why}</p>`).join(''); const blocked=b.blocked.map(q=>`<p class="why"><b>${all?esc(NET[q.net].name)+' · ':''}${esc(CITY[q.city].name)}:</b> ${q.why}</p>`).join('');
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${all?tr('common.all_networks'):`AS${n.asn} · ${esc(n.name)}`}</div><h2>${all?tr('pni_all.peer_all_networks'):tr('pni_all.peer_on_all_pops')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div> openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${all?tr('common.all_networks'):`AS${n.asn} · ${esc(n.name)}`}</div><h2>${all?tr('pni_all.peer_all_networks'):tr('pni_all.peer_on_all_pops')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<p class="lead">${tr('pni_all.order_missing_and_upgrade_smaller')}</p> <p class="lead">${tr('pni_all.order_missing_and_upgrade_smaller')}</p>${msg?`<p class="why">${esc(msg)}</p>`:''}
<div class="trsel"><label>${tr('pni_all.pni_size')}<select data-chg="pniAllSize">${pniG1(net)?`<option value="-1"${tier===-1?' selected':''}>1G</option>`:''}${PORT.map((p,i)=>portShown(i)&&(all||i>=pniMin(net))?`<option value="${i}"${tier===i?' selected':''}>${p.n}</option>`:'').join('')}</select></label></div> <div class="trsel"><label>${tr('pni_all.pni_size')}<select data-chg="pniAllSize">${pniG1(net)?`<option value="-1"${tier===-1?' selected':''}>1G</option>`:''}${PORT.map((p,i)=>portShown(i)&&(all||i>=pniMin(net))?`<option value="${i}"${tier===i?' selected':''}>${p.n}</option>`:'').join('')}</select></label></div>
<div class="kv"><span>${tr('pni_all.new_and_upgrades',{fresh:b.orders.length-up,up})}</span><b>${all?tr('pni_all.n_of_total_connections',{n:b.orders.length,total:b.shared.length}):tr('pni_all.n_of_total_pops',{n:b.orders.length,total:b.shared.length})}</b></div> <div class="kv"><span>${tr('pni_all.new_and_upgrades',{fresh:b.orders.length-up,up})}</span><b>${all?tr('pni_all.n_of_total_connections',{n:b.orders.length,total:b.shared.length}):tr('pni_all.n_of_total_pops',{n:b.orders.length,total:b.shared.length})}</b></div>
<div class="kv"><span>${tr('pni_all.setup_total')}</span><b>${fmt$(b.cost)}</b></div> <div class="kv"><span>${tr('pni_all.setup_total')}</span><b>${fmt$(b.cost)}</b></div>

View file

@ -0,0 +1,6 @@
/* ================= SERVER-RUN PLAY (multiplayer builds only) =================
This folder is only in a page built with MP_API (scripts/lib/page.js leaves it out of every other page, the one on
GitHub Pages included). A network of a server session (S.mp.sim===1) runs its days on the session server; this page
shows it and sends the player's clicks. The folder hooks in by rebinding top-level functions of earlier files, like
srvOn() (60-features/89-multiplayer.js), bootNotes() (91-save.js) and renderCoach(), and by adding to ACT. It sorts
before 99-loop.js, whose two srvOn() checks keep the clock and the boot routing off for such a network. */

View file

@ -14,7 +14,8 @@ function frame(now){
// The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them. // The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them.
if(UI.panelsDue){NOC.dirty=true;UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();} if(UI.panelsDue){NOC.dirty=true;UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}
if(NOC.peer)nocPump(now); if(NOC.peer)nocPump(now);
if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn())runClock(dt); // A network the server runs (srvOn) has its days there: this page only shows them.
if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn()&&!srvOn())runClock(dt);
if((UI.speed||pzOn())&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */ if((UI.speed||pzOn())&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */
const t=animOn()?animT:0; const t=animOn()?animT:0;
if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){const d0=DIAG.on?performance.now():0;try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;if(DIAG.on)DIAG.dms=performance.now()-d0;} if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){const d0=DIAG.on?performance.now():0;try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;if(DIAG.on)DIAG.dms=performance.now()-d0;}
@ -51,11 +52,10 @@ function boot(data){
applyAnim(); applyAnim();
if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();} if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();}
else{const sv=UI.slot?loadSave():null,stamp=sv&&sv.sv;if(sv)delete sv.sv; else{const sv=UI.slot?loadSave():null,stamp=sv&&sv.sv;if(sv)delete sv.sv;
let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} let okSave=false;if(sv){try{S=migrate(sv);if(!srvOn())compute();okSave=true;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
if(okSave){slotIn(UI.slot,stamp);if(MP_API)mpResume();UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1); if(okSave){slotIn(UI.slot,stamp);if(MP_API)mpResume();UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}} if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}}
renderAll();if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);} renderAll();bootNotes();
if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});}
if(!whatsNew(true))toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');} if(!whatsNew(true))toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');}
// A save that cannot be loaded stays where it is, marked damaged: it can still be exported, or deleted. // A save that cannot be loaded stays where it is, marked damaged: it can still be exported, or deleted.
else if(UI.slot&&(sv||UI.loadBad))slotBroke(UI.slot); else if(UI.slot&&(sv||UI.loadBad))slotBroke(UI.slot);

View file

@ -0,0 +1,3 @@
/* ================= SERVER-RUN PLAY (multiplayer builds only) =================
The look of src/game/98-server-play/: only in a page built with MP_API (scripts/lib/page.js leaves it out of every
other page). */

View file

@ -38,9 +38,10 @@ test('a new network runs plain IGP: no Auto-TE until the backbone is upgraded, o
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.core)')), { lv: 0, run: 0 }); assert.deepEqual(JSON.parse(ev('JSON.stringify(S.core)')), { lv: 0, run: 0 });
ev('ACT.buyTE()'); ev('ACT.buyTE()');
assert.equal(ev('!!S.te'), false, 'no Auto-TE on plain IGP'); assert.equal(ev('!!S.te'), false, 'no Auto-TE on plain IGP');
ev("ACT.leftTab({t:'noc'})"); // The backbone lives in the NOC's routing window; the refusal is a toast.
assert.match(dom.window.document.body.textContent, /Backbone/); ev('ACT.routingOpen()');
assert.match(dom.window.document.body.textContent, /Auto-TE needs an RSVP-TE/); assert.match(dom.window.document.getElementById('modal').textContent, /Backbone/);
assert.match(dom.window.document.getElementById('toasts').textContent, /Auto-TE needs an RSVP-TE/);
const cash = ev('S.cash'); const cash = ev('S.cash');
ev('ACT.coreUp()'); ev('ACT.coreUp()');
assert.equal(ev('S.core.lv'), 1); assert.equal(ev('S.core.lv'), 1);

View file

@ -23,14 +23,6 @@ test('#257 the calendar has real months and leap years',()=>{
assert.deepEqual(errors,[]); assert.deepEqual(errors,[]);
}finally{dom.window.close();} }finally{dom.window.close();}
}); });
test('#257 a calendar month costs its monthly price, whatever its length',()=>{
const {ev,dom}=load();try{
ev("ACT.start({});S.day=31");// 1 February Y1
const before=ev('S.cash'),net=ev('R.revMo-R.costMo');
ev("for(let i=0;i<28;i++)S.cash+=(R.revMo-R.costMo)/monLen(S.day+i)");
assert.ok(Math.abs(ev('S.cash')-before-net)<1e-6,'28 days of February add up to one month');
}finally{dom.window.close();}
});
test('#257 loan statements and the intern budget follow calendar months',()=>{ test('#257 loan statements and the intern budget follow calendar months',()=>{
const {ev,dom}=load();try{ const {ev,dom}=load();try{
ev("ACT.start({})"); ev("ACT.start({})");

View file

@ -0,0 +1,131 @@
// Canonical live state (the server-sim design, 5.4): the game as it runs is exactly what a reload makes of its save.
// A server-run network's page loads the server's state with migrate() (it never trusts state it did not check), and
// the server checks every action against the save path; both need migrate(live S) to change nothing. A year of a big
// network with everything on (DDoS, failures, events, the intern on every order, the sales desk on auto, IPv6-only, and
// once before the year everything else a network can own: an own exchange, scrubbing centers, teleports, satellites,
// dark fiber, an own cable, a subsea seat, exchange points, the backbone core, the redundancy kit, the bulk orders),
// checked every day. T1_BASE=<git ref> also plays the same year on the page at that ref: the same money, customers,
// incidents, dice and ids every day, so making the state canonical changed no play.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { load } = require('./harness');
const { assembleRef } = require('../scripts/lib/page');
const { lit } = require('../scripts/lib/js-literal');
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
const DAYS = 365;
function open(file) {
const h = load(file ? { file, seed: 4242 } : { seed: 4242 });
h.ev(`Date.now=()=>1.7e12;S=migrate(JSON.parse(${lit(BIG)}));S.rng=7;S.rules=makeRules('bgp');UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();
S.lvl=Math.max(S.lvl,6);S.cash+=5e8;ACT.opsHire({id:'kevin'});for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;closeModal();
ACT.salesHire({id:'shark'});ACT.salesAuto();closeModal();
for(const c of Object.keys(S.pops).filter(c=>S.pops[c].bb).slice(0,3))ACT.ip6Go({city:c});closeModal();`);
// Everything else, each through its own action as a player clicks it (__did: the ones that changed the network).
h.ev(`window.__did=[];const tryA=(n,a)=>{const s0=JSON.stringify(S);try{ACT[n](a);}catch(e){__did.push(n+' threw '+e.message);return;}closeModal();if(JSON.stringify(S)!==s0)__did.push(n);};
const pops=Object.keys(S.pops);
for(const c of pops.slice(0,40)){if(Object.keys(S.myIx).length)break;tryA('foundIx',{city:c});}
for(const c of pops.slice(0,6))tryA('buildScrub',{city:c});
for(const c of pops.slice(0,4))tryA('teleBuild',{city:c});
{let n=0;for(const a of pops.slice(0,12))for(const b of pops.slice(12,30)){if(n>=2)break;for(const bird of Object.keys(SATS))for(const g of [1,2,5,10]){if(n>=2)break;if(!satWhy(a,b,bird,g)){tryA('buySat',{a,b,bird,g});n++;}}}}
{let n=0;for(const a of pops.slice(0,10))for(const b of pops.slice(10,40)){if(n>=2)break;if(kmBetween(a,b)<900&&!noTalk(a,b)){UI.pending={a,b};UI.dfSrc='build';const k=S.links.length;tryA('orderDf');if(S.links.length>k)n++;}}}
{let n=0;for(const a of pops.slice(0,30))for(const b of Object.keys(CITY)){if(n>=1)break;if(S.pops[b]||a===b)continue;UI.pending={a,b};const k=S.links.length;if(!ownCabWhy(a,b)){tryA('orderCable');if(S.links.length>k)n++;}}}
seatConf(null);if(S.seatOff)tryA('seatBuy',{n:SEAT_N[0]});
tryA('ddosAuto');S.ddosAuto={rtbh:true,scrub:true};tryA('coreUp');tryA('coreUp');
for(const c of pops.slice(0,3))tryA('xpBuild',{city:c});
for(const c of pops.slice(0,3))tryA('utilityKit',{city:c,cost:(utilityKit(c)||{}).cost});
tryA('utilityRouteServers');tryA('utilityPeers');tryA('pniAll',{net:null,tier:1,q:(pniBatch(null,1)||{}).cost});
tryA('bstdSet',{k:'gen'});tryA('bstdSet',{k:'site2'});tryA('bstdApply',typeof bstdPlanKey==='function'?{quote:bstdPlanKey(bstdPlan(false)),q:bstdQuote(false).cost}:{});
UI.pending=null;closeModal();compute();`);
return h;
}
const BUILT = ['foundIx', 'buildScrub', 'teleBuild', 'buySat', 'orderDf', 'orderCable', 'seatBuy', 'coreUp', 'xpBuild', 'utilityKit', 'pniAll', 'bstdApply'];
// In the page: every top-level key whose JSON differs between live S and what a reload makes of it, both ways a reload
// happens (the full state a page takes, and the save text). uidN and the dice are put back: a reload may draw ids.
const CHECK = `window.__sortK=v=>Array.isArray(v)?v.map(__sortK):v&&typeof v==='object'?Object.keys(v).sort().reduce((o,k)=>(v[k]!==undefined&&(o[k]=__sortK(v[k])),o),{}):v;
window.__canon=()=>{const u0=uidN,r0=S.rng,out=[];
const live=JSON.parse(JSON.stringify(S)),snap=JSON.parse(JSON.stringify(migrate(JSON.parse(JSON.stringify(S)))));uidN=u0;S.rng=r0;
const pl=JSON.parse(JSON.stringify(packSave(S))),pm=JSON.parse(JSON.stringify(packSave(migrate(JSON.parse(JSON.stringify(packSave(S)))))));uidN=u0;S.rng=r0;
for(const k of new Set([...Object.keys(live),...Object.keys(snap)])){
// Exactly, key order included (a page's mirror stays byte for byte the server's), except the order of S.ops's keys,
// which the standing orders' own sanitizing (95-standing-orders.js) writes its way. Its content is checked as it is.
const a=k==='ops'?__sortK(live[k]):live[k],b=k==='ops'?__sortK(snap[k]):snap[k];
if(JSON.stringify(a)!==JSON.stringify(b))out.push('snapshot '+k);}
for(const k of new Set([...Object.keys(pl),...Object.keys(pm)]))if(JSON.stringify(__sortK(pl[k]))!==JSON.stringify(__sortK(pm[k])))out.push('save '+k);
return out;};
window.__diff=k=>{const u0=uidN,r0=S.rng;const a=JSON.parse(JSON.stringify(S))[k],b=JSON.parse(JSON.stringify(migrate(JSON.parse(JSON.stringify(S)))))[k];uidN=u0;S.rng=r0;
const out=[];const walk=(x,y,p)=>{if(out.length>4||JSON.stringify(x)===JSON.stringify(y))return;
if(x&&y&&typeof x==='object'&&typeof y==='object'){for(const kk of new Set([...Object.keys(x),...Object.keys(y)]))walk(x[kk],y[kk],p+'.'+kk);if(!out.length)out.push(p+': key order');return;}
out.push(p+': '+JSON.stringify(x)+' → '+JSON.stringify(y));};walk(a,b,k);return out.join('; ');};`;
const PLAY = `JSON.stringify({day:S.day,cash:S.cash,rng:S.rng,uidN,biz:S.biz.map(b=>b.id+':'+b.mood+':'+b.rate).join(),offers:S.offers.map(o=>o.id).join(),
inc:S.inc.map(i=>i.id+i.type).join(),links:S.links.map(l=>l.id+':'+(l.ch||[]).length).join(),transit:S.transit.map(t=>t.id+':'+t.tier+':'+(t.n||1)).join(),
pni:S.pni.map(p=>p.id+':'+p.tier+':'+(p.n||1)).join(),pops:Object.keys(S.pops).join(),ddos:ddosAll(S,false).map(a=>a.id+':'+a.tgt+':'+a.until).join(),
stats:Object.fromEntries(Object.entries(S.stats).filter(([k])=>k!=='ddT')),served:R.served,lost:S.lost,
ops:JSON.stringify(S.ops.log.map(e=>({...e,r:e.r.map(r=>[r[0],r[1],r[2].slice(0,3)])})))})`;
// (The day's log names at most three places a job now, as a reload always kept it: the base page listed every broken link.)
test(`a year of a big network with everything on: live state is what a reload makes of it, every day${process.env.T1_BASE ? ', and play is as before' : ''}`, (t) => {
const head = open();
t.after(() => head.dom.window.close());
head.ev(CHECK);
let base = null;
if (process.env.T1_BASE) {
const f = path.join(os.tmpdir(), `tubes-canon-base-${process.pid}.html`);
fs.writeFileSync(f, assembleRef(process.env.T1_BASE));
base = open(f);
t.after(() => { base.dom.window.close(); fs.rmSync(f, { force: true }); });
}
assert.equal(head.ev('S.ops.intern'), 'kevin');
const did = JSON.parse(head.ev('JSON.stringify(__did)'));
assert.deepEqual(did.filter((x) => / threw /.test(x)), [], 'nothing threw while building');
for (const a of BUILT) assert.ok(did.includes(a), `${a} built something before the year (${did.join(', ')})`);
assert.equal(head.ev('S.slAuto.on'), true);
assert.ok(head.ev("Object.values(S.pops).filter(p=>p.bb&&(p.bb.v6||p.bb.v6e)).length") >= 3, 'IPv6-only homes on the way');
const seen = { ddos: 0, inc: 0, starts: 0 };
for (let d = 1; d <= DAYS; d++) {
head.ev('dayTick()');
const bad = JSON.parse(head.ev('JSON.stringify(__canon())'));
if (bad.length) assert.fail(`day ${d}: ${bad.join(', ')} differ: ${bad.map((k) => head.ev(`__diff(${lit(k.split(' ')[1])})`)).join(' | ')}`);
if (base) { base.ev('dayTick()'); assert.equal(base.ev(PLAY), head.ev(PLAY), `day ${d}: play differs from the base page`); }
seen.ddos = Math.max(seen.ddos, head.ev('ddosAll().length'));
seen.inc = Math.max(seen.inc, head.ev('S.inc.length'));
seen.starts = Math.max(seen.starts, head.ev('S.ddosStarts.length'));
}
// It was a year of trouble, not a quiet one.
assert.ok(seen.ddos >= 1 && seen.starts >= 2, `attacks came (${JSON.stringify(seen)})`);
assert.ok(head.ev('S.stats.incidents') > 50, 'failures and events came');
assert.ok(head.ev('S.ops.log.length') > 0, 'the intern worked');
const kept = JSON.parse(head.ev(`JSON.stringify({myIx:Object.keys(S.myIx).length,scrubs:S.scrubs.length,sat:S.links.filter(l=>l.kind==='sat').length,df:S.links.filter(l=>l.kind==='df').length})`));
assert.ok(kept.myIx && kept.scrubs && kept.sat && kept.df, `what was built lived through the year (${JSON.stringify(kept)})`);
assert.equal(head.ev('S.lost'), false);
assert.deepEqual(head.errors, []);
});
test('fresh Normal games played at random, move by move: everything a player builds is what a reload makes of it', (t) => {
// The moves of the route fuzz (scripts/lib/route-fuzz.js): buttons on panels, windows and the dashboard, links, days.
const { openPage, playGame } = require('../scripts/lib/route-fuzz');
const { assemble } = require('../scripts/lib/page');
const file = path.join(os.tmpdir(), `tubes-canon-fresh-${process.pid}.html`);
fs.writeFileSync(file, assemble().html);
t.after(() => fs.rmSync(file, { force: true }));
for (const seed of [3, 5]) {
const P = { base: openPage(file, 'base'), head: openPage(file, 'head') };
t.after(() => { P.base.dom.window.close(); P.head.dom.window.close(); });
P.head.ev(CHECK);
let checked = 0;
const g = playGame(P, seed, { moves: 120, onMove: () => {
// Only a Normal game runs on a server. The fuzz may open a link from a city to itself, which the game's own drag
// never does (and the server's envelope refuses): such a state is skipped.
if (!P.head.ev("!!S&&!pzOn()&&S.mode==='normal'&&!S.links.some(l=>l.a===l.b)")) return;
const bad = JSON.parse(P.head.ev('JSON.stringify(__canon())'));
if (bad.length) assert.fail(`seed ${seed} after ${checked} moves: ${bad.join(', ')} differ: ${bad.map((k) => P.head.ev(`__diff(${lit(k.split(' ')[1])})`)).join(' | ')}`);
checked++;
} });
assert.equal(g.div, null, `seed ${seed}: the two copies stayed in step`);
assert.ok(checked > 60, `seed ${seed}: ${checked} moves checked in a Normal game`);
assert.deepEqual(g.errors, []);
}
});

View file

@ -49,10 +49,11 @@ test('the choice applies at boot, from the <head>, before the page is painted',
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
dom.window.close(); dom.window.close();
} }
// The script that sets it sits in the <head>, before the styles: nothing is painted in the wrong colours first. // The script that sets it sits in the <head>, before the styles: nothing is painted in the wrong colours first. Read
const doc = load().dom.window.document, head = [...doc.head.children]; // from the page's HTML (the harness runs script bodies outside the DOM, so a <script>'s text is empty there).
const s = head.findIndex((e) => e.tagName === 'SCRIPT' && /sot-theme/.test(e.textContent)), st = head.findIndex((e) => e.tagName === 'STYLE'); const html = assemble().html, headEnd = html.indexOf('</head>'), st = html.indexOf('<style>');
assert.ok(s >= 0 && s < st, 'the theme script runs before the stylesheet'); const scripts = [...html.slice(0, headEnd).matchAll(/<script>([\s\S]*?)<\/script>/g)], s = scripts.find((m) => /sot-theme/.test(m[1]));
assert.ok(s && st >= 0 && st < headEnd && s.index < st, 'the theme script runs before the stylesheet');
// Auto with a dark device: dark from the first paint as well. // Auto with a dark device: dark from the first paint as well.
const d = device(true), h = load({ browser: d }); const d = device(true), h = load({ browser: d });
assert.equal(h.dom.window.document.documentElement.getAttribute('data-theme'), 'dark'); assert.equal(h.dom.window.document.documentElement.getAttribute('data-theme'), 'dark');

View file

@ -161,11 +161,14 @@ test('saves before 2.2 load: an attack on a city finds its target, and an IX bla
assert.equal(ev('S.ev.ddos.tgt'), 'g', 'the most attractive customer in the city'); assert.equal(ev('S.ev.ddos.tgt'), 'g', 'the most attractive customer in the city');
assert.equal(ev('S.ev.ddos.ixbh'), undefined); assert.equal(ev('S.ev.ddos.ixbh'), undefined);
assert.equal(ev('S.ev.ddos.entry'), undefined); assert.equal(ev('S.ev.ddos.entry'), undefined);
assert.equal(ev('S.ev.ddosMore[0].tgt'), 'g'); // A customer target that is no customer here stays as it is: in play that is a customer who left during the day, and
// the next morning ends the attack (ddosExpire), so a reload must not aim it at someone else.
assert.equal(ev('S.ev.ddosMore[0].tgt'), 'nobody');
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosAuto)')), { rtbh: false, scrub: true }); assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosAuto)')), { rtbh: false, scrub: true });
ev("const s=JSON.parse(JSON.stringify(packSave(S)));s.ddosAuto='yes';s.stats.ddT='x';S=migrate(s)"); ev("const s=JSON.parse(JSON.stringify(packSave(S)));s.ddosAuto='yes';s.stats.ddT='x';S=migrate(s)");
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosAuto)')), { rtbh: false, scrub: true }); assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosAuto)')), { rtbh: false, scrub: true });
ev('for(let i=0;i<3;i++)dayTick()'); ev('for(let i=0;i<3;i++)dayTick()');
assert.equal(ev("ddosAll(S,false).some(a=>a.id==='o2')"), false, 'and the morning ended it');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });

View file

@ -5,6 +5,7 @@
"tests/backbone-core.test.js": 27.5, "tests/backbone-core.test.js": 27.5,
"tests/badges-variants.test.js": 20.2, "tests/badges-variants.test.js": 20.2,
"tests/build.test.js": 1.3, "tests/build.test.js": 1.3,
"tests/canonical-state.test.js": 64.0,
"tests/capacity-deals.test.js": 12.6, "tests/capacity-deals.test.js": 12.6,
"tests/chaos-monkey.test.js": 30.3, "tests/chaos-monkey.test.js": 30.3,
"tests/city-size.test.js": 8.5, "tests/city-size.test.js": 8.5,
@ -31,6 +32,7 @@
"tests/modes.test.js": 41.1, "tests/modes.test.js": 41.1,
"tests/more-cables.test.js": 14.3, "tests/more-cables.test.js": 14.3,
"tests/moscow-premium.test.js": 12.0, "tests/moscow-premium.test.js": 12.0,
"tests/mp-sim-contract.test.js": 7.0,
"tests/networks-list.test.js": 6.4, "tests/networks-list.test.js": 6.4,
"tests/new-game-speed.test.js": 10.1, "tests/new-game-speed.test.js": 10.1,
"tests/optic-counts.test.js": 9.7, "tests/optic-counts.test.js": 9.7,
@ -59,6 +61,7 @@
"tests/save-slots.test.js": 48.5, "tests/save-slots.test.js": 48.5,
"tests/scenarios-playtest.test.js": 113.2, "tests/scenarios-playtest.test.js": 113.2,
"tests/sea-routing.test.js": 42.6, "tests/sea-routing.test.js": 42.6,
"tests/server-sim-prereqs.test.js": 16.0,
"tests/services.test.js": 15.7, "tests/services.test.js": 15.7,
"tests/specialist.test.js": 14.3, "tests/specialist.test.js": 14.3,
"tests/speed.test.js": 144.6, "tests/speed.test.js": 144.6,

1
tests/fixtures/mp-sim/clock.json vendored Normal file
View file

@ -0,0 +1 @@
{"t":"clock","speed":1,"eff":1,"run":true,"why":null,"votes":{"efgh5678":4},"tally":{"4":1},"need":2,"active":["abcd1234","efgh5678"],"hold":[],"idle":[],"day":518,"last":1,"max":8,"off":{"abcd1234":-473,"efgh5678":0}}

1
tests/fixtures/mp-sim/roster.json vendored Normal file
View file

@ -0,0 +1 @@
{"t":"roster","code":"K7Q2XD","title":"Friday","preset":"oncall","seed":424242,"created":1730913600000,"players":[{"pid":"abcd1234","name":"Packet Pals","asn":201234,"color":"#3a86ff","card":{"day":45,"name":"Packet Pals","asn":201234,"tier":"t3","t1":false,"lvl":2,"pops":["fra","ams"],"links":[["ams","fra",10]],"ix":[],"transit":["cog"],"ppol":"open","reach":1,"peak":47.3,"served":47.3,"cust":0,"rev":7099,"cashB":5,"score":47},"seen":1731000000000,"joined":1730913600000},{"pid":"efgh5678","name":"Tubular Bells","asn":207777,"color":"#ff4f9a","card":null,"seen":1730999940000,"joined":1730996400000}],"feed":[{"k":"join","pid":"abcd1234","name":"Packet Pals","at":1730913600000},{"k":"join","pid":"efgh5678","name":"Tubular Bells","at":1730996400000},{"k":"chat","pid":"efgh5678","name":"Tubular Bells","at":1730999940000,"text":"peer with me?"}],"on":["abcd1234","efgh5678"]}

1
tests/fixtures/mp-sim/snap.json vendored Normal file

File diff suppressed because one or more lines are too long

1
tests/fixtures/mp-sim/sub.json vendored Normal file

File diff suppressed because one or more lines are too long

1
tests/fixtures/mp-sim/upd-act.json vendored Normal file

File diff suppressed because one or more lines are too long

1
tests/fixtures/mp-sim/upd-day.json vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -15,12 +15,6 @@ test('every city sits on its landmass', () => {
assert.equal(off, ''); assert.equal(off, '');
}); });
test('every cable lands at two known cities and has a length', () => {
const { ev } = load();
const bad = ev("CABLE_PAIRS.filter(c=>!CITY[c.a]||!CITY[c.b]||!(c.km>0)).map(c=>c.cid).join()");
assert.equal(bad, '');
});
test('a year of scripted play stays healthy', () => { test('a year of scripted play stays healthy', () => {
const { ev, errors } = load(); const { ev, errors } = load();
seed(ev, 7); seed(ev, 7);

View file

@ -258,7 +258,7 @@ test('M3: every subsystem that can annoy the player reads a rule', () => {
const reads = [['dayPost', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], const reads = [['dayPost', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'],
['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'], ['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'],
['dfBuildDays', 'leadDays'], ['dayPreRun', "rule('clock')"], ['snub', "rule('market')"], ['failureRun', 'shipsOn()'], ['dfBuildDays', 'leadDays'], ['dayPreRun', "rule('clock')"], ['snub', "rule('market')"], ['failureRun', 'shipsOn()'],
['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toast', 'quietOn()'], ['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toastPop', 'quietOn()'],
['ip4On', "rule('ip4')"], ['ip4Fits', 'ip4On()'], ['ip4Money', 'ip4On()'], ['ip4Day', 'ip4On()'], ['ip4On', "rule('ip4')"], ['ip4Fits', 'ip4On()'], ['ip4Money', 'ip4On()'], ['ip4Day', 'ip4On()'],
['ip6Day', 'ip4On()'], ['ip6Grow', 'ip4On()'], ['ip6Why', 'ip4On()'], ['ip6Html', 'ip4On()'], ['ip4Can', 'ip4On()']]; ['ip6Day', 'ip4On()'], ['ip6Grow', 'ip4On()'], ['ip6Why', 'ip4On()'], ['ip6Html', 'ip4On()'], ['ip4Can', 'ip4On()']];
fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${lit(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)'); fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${lit(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)');

View file

@ -6,30 +6,57 @@
// it fails here rather than in production. // it fails here rather than in production.
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const vm = require('node:vm');
const { JSDOM, VirtualConsole } = require('jsdom'); const { JSDOM, VirtualConsole } = require('jsdom');
const { assemble } = require('../scripts/lib/page'); const { assemble, simId } = require('../scripts/lib/page');
const PAGE = {}; const PAGE = {};
const page = (dev) => PAGE[dev] || (PAGE[dev] = assemble({ dev }).html); const page = (dev, mp) => PAGE[dev + '|' + mp] || (PAGE[dev + '|' + mp] = assemble({ dev, mp }).html);
// The build id an MP page carries (scripts/lib/page.js simId()), worked out once per test process.
let SIM;
const simOf = () => SIM || (SIM = simId(assemble({ mp: true }).html));
// The page's inline scripts, taken out of the HTML once per process and compiled once. jsdom's HTML parser is slow
// on 2 MB of script text (it was more than half of every load()), so the DOM is built from the rest of the page and
// the scripts then run in its window, in order, the same way jsdom runs them (vm.Script.runInContext). Only plain
// <script> tags run, as in the browser here; data blocks (ld+json) stay in the page untouched.
const SPLIT = new Map();
function split(html) {
let s = SPLIT.get(html);
if (s) return s;
const code = [];
const shell = html.replace(/<script>([\s\S]*?)<\/script>/g, (m, src) => {
code.push(new vm.Script(src, { filename: `page-script-${code.length}.js` }));
return '<script></script>';
});
// With scripting on, the parser keeps a <noscript>'s content as text; with scripts run from outside it builds those
// elements (an extra <h1>, <p>, <div>). Escaped, the content stays one text node, as players' browsers have it.
const page = shell.replace(/(<noscript>)([\s\S]*?)(<\/noscript>)/g, (m, a, body, b) => a + body.replace(/&/g, '&amp;').replace(/</g, '&lt;') + b);
SPLIT.set(html, s = { shell: page, code });
return s;
}
// opts.file: a built or older page to load instead (the perf bench, the release build test). // opts.file: a built or older page to load instead (the perf bench, the release build test).
// opts.agent: the development page, with src/agent/. // opts.agent: the development page, with src/agent/.
// opts.mp: the page with multiplayer on, as MP_API=… npm run build stamps it; opts.fetch: the page's fetch, from the start. // opts.mp: the page with multiplayer on, as MP_API=… npm run build makes it: the server-play client in it, MP_API
// stamped (opts.mp's path, or '/api/mp' for true) and SIM_ID too; opts.fetch: the page's fetch, from the start
// (fakeFetch() below fakes the session server, streams included).
function load(opts = {}) { function load(opts = {}) {
let html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent); let html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent, !!opts.mp);
if (opts.mp) html = html.replace("/*__MP_API__*/''", () => JSON.stringify(opts.mp)); if (opts.mp) html = html.replace("/*__MP_API__*/''", () => JSON.stringify(opts.mp === true ? '/api/mp' : opts.mp)).replace("/*__SIM_ID__*/''", () => JSON.stringify(simOf()));
const errors = []; const errors = [];
const vc = new VirtualConsole(); const vc = new VirtualConsole();
vc.on('jsdomError', (e) => { vc.on('jsdomError', (e) => {
// jsdom has no canvas; drawing calls are expected to be unimplemented. // jsdom has no canvas; drawing calls are expected to be unimplemented.
if (!/getContext|Not implemented/.test(e.message)) errors.push(e.message); if (!/getContext|Not implemented/.test(e.message)) errors.push(e.message);
}); });
const dom = new JSDOM(html, { const { shell, code } = split(html);
const dom = new JSDOM(shell, {
// opts.url: the origin the page is "served" from. Tests that dial the agent relay pass the relay's own host, so // opts.url: the origin the page is "served" from. Tests that dial the agent relay pass the relay's own host, so
// the page's WebSocket Origin matches (the relay refuses a cross-site one); everything else stays on a made-up // the page's WebSocket Origin matches (the relay refuses a cross-site one); everything else stays on a made-up
// https origin nothing can reach. // https origin nothing can reach.
url: opts.url || 'https://tests.invalid/', url: opts.url || 'https://tests.invalid/',
runScripts: 'dangerously', runScripts: 'outside-only',
pretendToBeVisual: true, pretendToBeVisual: true,
virtualConsole: vc, virtualConsole: vc,
beforeParse(window) { beforeParse(window) {
@ -47,6 +74,8 @@ function load(opts = {}) {
if (opts.lang) { window.localStorage.setItem('sot-lang', opts.lang); window.eval(fs.readFileSync(path.join(opts.dir || path.join(__dirname, '..', 'site', 'i18n'), opts.lang + '.js'), 'utf8')); } if (opts.lang) { window.localStorage.setItem('sot-lang', opts.lang); window.eval(fs.readFileSync(path.join(opts.dir || path.join(__dirname, '..', 'site', 'i18n'), opts.lang + '.js'), 'utf8')); }
// jsdom has no CompressionStream; {gzip:true} lends the page Node's, the same API browsers have (#176). // jsdom has no CompressionStream; {gzip:true} lends the page Node's, the same API browsers have (#176).
if (opts.gzip) for (const k of ['CompressionStream', 'DecompressionStream', 'TextEncoder', 'TextDecoder']) window[k] = globalThis[k]; if (opts.gzip) for (const k of ['CompressionStream', 'DecompressionStream', 'TextEncoder', 'TextDecoder']) window[k] = globalThis[k];
// An MP page reads its server's stream through fetch: the decoder and streams it needs, Node's (as browsers have them).
if (opts.mp) for (const k of ['TextEncoder', 'TextDecoder', 'ReadableStream']) if (!window[k]) window[k] = globalThis[k];
window.Path2D = class { moveTo() {} lineTo() {} quadraticCurveTo() {} bezierCurveTo() {} arc() {} rect() {} closePath() {} }; window.Path2D = class { moveTo() {} lineTo() {} quadraticCurveTo() {} bezierCurveTo() {} arc() {} rect() {} closePath() {} };
// A recording 2D context, so draw code really runs under test (jsdom has no canvas). // A recording 2D context, so draw code really runs under test (jsdom has no canvas).
const fake = () => { const calls = { n: 0 }; const fake = () => { const calls = { n: 0 };
@ -64,6 +93,14 @@ function load(opts = {}) {
window.HTMLCanvasElement.prototype.toBlob = (cb) => cb(null); window.HTMLCanvasElement.prototype.toBlob = (cb) => cb(null);
}, },
}); });
// The language picker document.write()s a dictionary <script src> for a non-English player. jsdom fetched nothing
// for it anyway (opts.lang registers the dictionary), and after parsing a real write would wipe the page.
const doc = dom.window.document, ctx = dom.getInternalVMContext();
doc.write = () => {};
for (const sc of code) {
try { sc.runInContext(ctx); } catch (e) { vc.emit('jsdomError', Object.assign(new Error(`Uncaught [${e}]`), { detail: e })); }
}
delete doc.write;
const ev = (src) => dom.window.eval(src); const ev = (src) => dom.window.eval(src);
// Deterministic by default so a test never passes or fails by luck; pass {seed:false} to opt out. // Deterministic by default so a test never passes or fails by luck; pass {seed:false} to opt out.
// (Seeded in beforeParse, so the game's own seeded-games wrapper around Math.random stays in place.) // (Seeded in beforeParse, so the game's own seeded-games wrapper around Math.random stays in place.)
@ -115,4 +152,58 @@ function browser({ locks = true, channel = true } = {}) {
} }
const flush = (n = 3) => new Promise((r) => { const go = (i) => (i ? setTimeout(() => go(i - 1), 2) : r()); go(n); }); const flush = (n = 3) => new Promise((r) => { const go = (i) => (i ? setTimeout(() => go(i - 1), 2) : r()); go(n); });
module.exports = { load, seed, browser, flush }; /* One server-sent event as it goes over the wire (section 5.1 of the server-sim design): event, optional id, one line
of JSON data. */
const sse = (event, data, id) => `event: ${event}\n${id === undefined ? '' : `id: ${id}\n`}data: ${JSON.stringify(data)}\n\n`;
/* A fake session server for an MP page (load({mp: true, fetch: f})). routes: [regexp on "METHOD url", reply |
(call) => reply], where a reply is {status, json, headers?}, an Error (the network failed) or a promise of either (an
answer still on its way; the page aborting meanwhile rejects it, as fetch does). A GET of …/stream that no route
answers opens an event stream the test writes to:
f.streams every stream opened, in order; await f.stream(i) the i-th one (0 first), once the page opens it
s.send(event, data, id) one event (sse() above); s.comment('hb'); s.close(); s.fail(err)
s.aborted the page aborted it (its AbortSignal); s.closed it ended either way; s.call its request
Every request is in f.calls: {url, method, path (without MP_API's base), query, headers, raw, body (parsed JSON),
keepalive, signal}. Responses are Node's own Headers and ReadableStream, which is what browsers hand a page. */
function fakeFetch(routes = [], { base = '/api/mp' } = {}) {
const calls = [], streams = [], waiting = [], enc = new TextEncoder();
const aborted = () => { const e = new Error('aborted'); e.name = 'AbortError'; return e; };
const res = (r) => (r instanceof Error ? Promise.reject(r) : Promise.resolve({ ok: r.status < 400, status: r.status, headers: new Headers(r.headers || { 'content-type': 'application/json' }),
body: null, json: () => (r.json === undefined ? Promise.reject(new SyntaxError('no body')) : Promise.resolve(r.json)), text: () => Promise.resolve(r.json === undefined ? '' : JSON.stringify(r.json)) }));
function open(c) {
let ctl;
const s = { call: c, closed: false, aborted: false, sent: [],
write(t) { if (!s.closed) ctl.enqueue(enc.encode(t)); return s; },
send(event, data, id) { const t = sse(event, data, id); s.sent.push({ event, data, id }); return s.write(t); },
comment(text = 'hb') { return s.write(`: ${text}\n\n`); },
close() { if (!s.closed) { s.closed = true; ctl.close(); } return s; },
fail(e = new Error('network')) { if (!s.closed) { s.closed = true; ctl.error(e); } return s; } };
const body = new ReadableStream({ start(k) { ctl = k; }, cancel() { s.closed = true; } });
if (c.signal) c.signal.addEventListener('abort', () => { s.aborted = true; s.fail(aborted()); });
streams.push(s);
for (const w of waiting.filter((x) => x.i < streams.length)) { waiting.splice(waiting.indexOf(w), 1); w.ok(streams[w.i]); }
return Promise.resolve({ ok: true, status: 200, headers: new Headers({ 'content-type': 'text/event-stream; charset=utf-8' }), body,
json: () => Promise.reject(new SyntaxError('an event stream')), text: () => Promise.reject(new TypeError('an event stream')) });
}
const f = (url, o = {}) => {
const u = new URL(String(url), 'https://tests.invalid/'), method = (o.method || 'GET').toUpperCase();
const headers = {}; for (const [k, v] of Object.entries(o.headers || {})) headers[k.toLowerCase()] = v;
let body; try { body = typeof o.body === 'string' ? JSON.parse(o.body) : undefined; } catch (e) { body = undefined; }
const c = { url: String(url), method, path: u.pathname.startsWith(base) ? u.pathname.slice(base.length) : u.pathname, query: Object.fromEntries(u.searchParams),
headers, raw: o.body, body, keepalive: !!o.keepalive, signal: o.signal };
calls.push(c);
if (o.signal && o.signal.aborted) return Promise.reject(aborted());
for (const [re, h] of f.routes) if (re.test(`${method} ${c.url}`)) {
const r = typeof h === 'function' ? h(c) : h;
if (!r || typeof r.then !== 'function') return res(r);
return new Promise((ok, no) => { if (o.signal) o.signal.addEventListener('abort', () => no(aborted())); r.then((x) => res(x).then(ok, no), no); });
}
if (method === 'GET' && /\/stream$/.test(c.path)) return open(c);
return res({ status: 404, json: { error: 'not here' } });
};
f.routes = routes; f.calls = calls; f.streams = streams;
f.stream = (i = 0) => (streams[i] ? Promise.resolve(streams[i]) : new Promise((ok) => waiting.push({ i, ok })));
return f;
}
module.exports = { load, seed, browser, flush, sse, fakeFetch };

View file

@ -0,0 +1,187 @@
// A stand-in for the server-run engine (scripts/lib/mp-sim-engine.js, track T2), for testing the session host without
// worker threads or a game: the same API, every method a promise of the worker reply that section 4.2 of the
// server-sim design names, made from the canned stream in tests/fixtures/mp-sim/. Each reply passes
// tests/lib/mp-sim-shape.js checkWorker(); an upd or snap inside one passes checkEvent().
//
// const engine = createFakeEngine();
// engine.load(code, nets:[{nid, env?, begin?, lang, prefs}]) → [{t:'loaded', nid, epoch, day, lost, saved?}], one per
// net; a network that did not load is {t:'loaded', nid, err} (broken, 4.7)
// engine.day(code, {d, speed, last, alone:[nid], nets:[nid], mute}) → {t:'dayDone', code, d, nets:{[nid]:{day, lost,
// pause?, err?, retried?, ms}}}
// engine.act(code, nid, msg) → {t:'actDone', nid, epoch, rid, outcome, why?, v, upd} (msg: the request body, 5.8)
// engine.ask(code, nid, msg) → {t:'askDone', nid, rid, modal:{h, c}, ui?}
// engine.pull(code, nid, {snap, views}) → {t:'pulled', nid, epoch, v, upd?, snap?, subs?} (views: [{link} | {peer}])
// engine.sub(code, nid, {views}) → {t:'subbed', nid, epoch, v, subs}
// engine.prefs(code, nid, {prefs}) → undefined; engine.greet(code, nid) → a pulled
// engine.save(code, nid) → {t:'saved', nid, txt, uidN, rt, day, lost}; engine.card(code, nid) → {t:'card', nid, card}
// engine.unload(code, nid?) → {t:'unloaded', code, nid?}; engine.stats() → {workers, realms, sessions} (not a promise)
//
// For the tests of the host: engine.calls (every call, [method, ...args]); engine.outcome = (msg) => outcome to answer
// acts with ('applied' unless set); engine.lose(code, nid) / engine.pause(code, nid) (the next day ends bankrupt / asks
// for a pause); engine.hold(method) keeps that method's answers back until engine.release(method); engine.exit() is a worker
// that died: every pending call rejects and every realm is gone.
// Failures, in the shapes the real engine answers them (4.2, 4.3, 4.7): engine.failNext(method, what, nid?) with what
// 'timeout' or 'throw' (or 'exit': the call rejects, as when the worker died):
// load → that network (every network of the call without nid) answers {t:'loaded', nid, err} and has no realm;
// day → the day failed twice: nets[nid] = {day (unchanged), lost, err, retried:true, ms} and the network is broken
// (left out of later days; acts answer 'stopped'); without nid, the first network of the day;
// other → {t:'err', code, nid, what, msg}.
// A timeout leaves a fresh realm behind (4.2): a new epoch, v from 0. engine.breakNext(code, nid): the next load of that
// network fails (a save that does not migrate). engine.flaky(code, nid): its next day fails once and passes on the retry
// (retried:true, no err).
'use strict';
const { fixture } = require('./mp-sim-shape');
function createFakeEngine(opts = {}) {
const F = { snap: fixture('snap'), day: fixture('upd-day'), act: fixture('upd-act'), sub: fixture('sub'), roster: fixture('roster') };
const realms = new Map(), held = new Map(), fails = new Map(), pending = new Set(), breaks = new Set(), flaky = new Set();
const key = (code, nid) => code + '/' + nid;
let epochN = 0;
const newEpoch = () => 'e' + (++epochN).toString(36);
const realm = (code, nid) => { const r = realms.get(key(code, nid)); if (!r) throw new Error(`no realm ${key(code, nid)}`); return r; };
// A realm the worker had to build again after a timeout: a new epoch, versions from 0.
const rebuilt = (r) => { if (r) { r.epoch = newEpoch(); r.v = 0; r.dirty = false; } };
// Every answer goes through here: held back, failed, or rejected when the worker exits meanwhile. failed(f): the reply
// for an injected failure, when the method has its own shape for one (load, day); else {t:'err'}.
function answer(method, make, code = 'K7Q2XD', nid = 'abcd1234', failed = null) {
return new Promise((ok, no) => {
const job = { ok, no };
const run = () => {
pending.delete(job);
const f = fails.get(method);
if (f) {
fails.delete(method);
if (f.what === 'exit') return no(Object.assign(new Error('worker exited'), { code: 'EXIT' }));
if (failed) { try { return ok(failed(f)); } catch (e) { return no(e); } }
if (f.what === 'timeout') rebuilt(realms.get(key(code, f.nid || nid)));
return ok({ t: 'err', code, nid: f.nid || nid, what: f.what, msg: `injected ${f.what}` });
}
try { ok(make()); } catch (e) { no(e); }
};
job.run = run;
pending.add(job);
const h = held.get(method);
if (h) h.push(job); else if (opts.sync) run(); else setImmediate(run);
});
}
const upd = (r, base, extra = {}) => {
const from = r.v, v = ++r.v;
const s = { ...base.s, day: r.day };
return JSON.stringify({ ...base, from, v, now: Date.now(), day: r.day, s, ...extra });
};
const snapOf = (code, nid, r) => {
const S = { ...F.snap.S, day: r.day, lost: r.lost, mp: { ...F.snap.S.mp, code, pid: nid } };
return JSON.stringify({ ...F.snap, epoch: r.epoch, v: r.v, now: Date.now(), S, keep: r.keep.splice(0) });
};
const subsOf = (views = []) => {
const o = {};
for (const w of views) {
if (w && typeof w.link === 'string') o['link:' + w.link] = { ef: F.sub.ef, egd: F.sub.egd };
if (w && typeof w.peer === 'string') o['peer:' + w.peer] = { pf: { [w.peer]: Object.values(F.sub.pf)[0] || {} } };
}
return o;
};
const savedOf = (code, nid, r) => ({ t: 'saved', nid, txt: JSON.stringify({ ...F.snap.S, day: r.day, lost: r.lost, mp: { ...F.snap.S.mp, code, pid: nid } }), uidN: 100 + r.day, rt: { load: {}, l2route: {}, efg: {} }, day: r.day, lost: r.lost });
const engine = {
calls: [],
outcome: () => 'applied',
load(code, nets) {
engine.calls.push(['load', code, nets]);
const one = (n, err) => {
if (err) { realms.delete(key(code, n.nid)); return { t: 'loaded', nid: n.nid, err }; }
const day = n.begin ? 0 : (n.env && Number.isInteger(n.env.day) ? n.env.day : F.snap.S.day);
const r = { epoch: newEpoch(), v: 0, day, lost: false, broken: false, dirty: false, pause: false, loseNext: false, keep: [], lang: n.lang || 'en' };
realms.set(key(code, n.nid), r);
return { t: 'loaded', nid: n.nid, epoch: r.epoch, day, lost: false, ...(n.begin ? { saved: savedOf(code, n.nid, r) } : {}) };
};
const bad = (n) => { const k = key(code, n.nid); if (!breaks.has(k)) return null; breaks.delete(k); return 'migrate threw: injected'; };
return answer('load', () => nets.map((n) => one(n, bad(n))), code, nets[0] && nets[0].nid,
(f) => nets.map((n) => one(n, f.nid === undefined || f.nid === n.nid ? `injected ${f.what}` : bad(n))));
},
day(code, { d, nets = [] } = {}) {
engine.calls.push(['day', code, { d, nets }]);
const ids = [...nets].sort();
const run = (f) => {
const out = {};
for (const nid of ids) {
const r = realm(code, nid);
if (r.lost || r.broken) continue;
// Failed twice (f names it): back to the mark, broken at its pre-day state.
if (f && (f.nid || ids.find((x) => !realm(code, x).lost && !realm(code, x).broken)) === nid) {
r.broken = true; if (f.what === 'timeout') rebuilt(r);
out[nid] = { day: r.day, lost: r.lost, err: `injected ${f.what}`, retried: true, ms: 2000 };
continue;
}
const again = flaky.delete(key(code, nid));
r.day++; r.dirty = true;
if (r.loseNext) { r.lost = true; r.loseNext = false; r.keep.push(['modal', 'lose']); }
out[nid] = { day: r.day, lost: r.lost, ms: 1, ...(r.pause ? { pause: true } : {}), ...(again ? { retried: true } : {}) };
r.pause = false;
}
return { t: 'dayDone', code, d, nets: out };
};
return answer('day', () => run(null), code, ids[0], run);
},
act(code, nid, msg) {
engine.calls.push(['act', code, nid, msg]);
return answer('act', () => {
const r = realm(code, nid);
if (r.lost || r.broken) return { t: 'actDone', nid, epoch: r.epoch, rid: msg.rid, outcome: 'stopped', v: r.v, upd: null };
const outcome = engine.outcome(msg);
r.dirty = false;
const u = upd(r, F.act, { acts: [{ rid: msg.rid, dev: msg.dev, ui: {} }] });
return { t: 'actDone', nid, epoch: r.epoch, rid: msg.rid, outcome, ...(outcome === 'error' ? { why: 'the game threw' } : {}), v: r.v, upd: u };
}, code, nid);
},
ask(code, nid, msg) {
engine.calls.push(['ask', code, nid, msg]);
return answer('ask', () => { realm(code, nid); return { t: 'askDone', nid, rid: msg.rid, modal: { h: `<h2>${msg.act}</h2><p>What if…</p>`, c: '' } }; }, code, nid);
},
pull(code, nid, { snap = false, views } = {}) {
engine.calls.push(['pull', code, nid, { snap, views }]);
return answer('pull', () => {
const r = realm(code, nid), o = { t: 'pulled', nid, epoch: r.epoch };
if (r.dirty) { o.upd = upd(r, F.day); r.dirty = false; }
o.v = r.v;
if (snap) o.snap = snapOf(code, nid, r);
if (views) o.subs = subsOf(views);
return o;
}, code, nid);
},
sub(code, nid, { views = [] } = {}) {
engine.calls.push(['sub', code, nid, { views }]);
return answer('sub', () => { const r = realm(code, nid); return { t: 'subbed', nid, epoch: r.epoch, v: r.v, subs: subsOf(views) }; }, code, nid);
},
prefs(code, nid, { prefs } = {}) { engine.calls.push(['prefs', code, nid, { prefs }]); return answer('prefs', () => { realm(code, nid); return undefined; }, code, nid); },
greet(code, nid) {
engine.calls.push(['greet', code, nid]);
return answer('greet', () => { const r = realm(code, nid); r.dirty = true; const o = { t: 'pulled', nid, epoch: r.epoch, upd: upd(r, F.day, { fx: [['told', 'grace']] }) }; r.dirty = false; o.v = r.v; return o; }, code, nid);
},
save(code, nid) { engine.calls.push(['save', code, nid]); return answer('save', () => savedOf(code, nid, realm(code, nid)), code, nid); },
card(code, nid) { engine.calls.push(['card', code, nid]); return answer('card', () => { realm(code, nid); return { t: 'card', nid, card: F.roster.players[0].card }; }, code, nid); },
unload(code, nid) {
engine.calls.push(['unload', code, nid]);
return answer('unload', () => { for (const k of [...realms.keys()]) if (k.startsWith(code + '/') && (nid === undefined || k === key(code, nid))) realms.delete(k); return { t: 'unloaded', code, ...(nid ? { nid } : {}) }; }, code, nid);
},
stats() { return { workers: 1, realms: realms.size, sessions: new Set([...realms.keys()].map((k) => k.split('/')[0])).size }; },
// Test controls.
lose(code, nid) { realm(code, nid).loseNext = true; },
pause(code, nid) { realm(code, nid).pause = true; },
keep(code, nid, fx) { realm(code, nid).keep.push(fx); },
hold(method) { if (!held.has(method)) held.set(method, []); },
release(method) { const h = held.get(method) || []; held.delete(method); for (const j of h) j.run(); },
failNext(method, what = 'throw', nid) { fails.set(method, { what, nid }); },
breakNext(code, nid) { breaks.add(key(code, nid)); },
flaky(code, nid) { flaky.add(key(code, nid)); },
exit() {
const e = Object.assign(new Error('worker exited'), { code: 'EXIT' });
for (const j of [...pending]) { pending.delete(j); j.no(e); }
held.clear(); realms.clear();
},
realms,
};
return engine;
}
module.exports = { createFakeEngine };

View file

@ -0,0 +1,91 @@
// The canned stream of a server-run network (tests/fixtures/mp-sim/*.json): what the session server sends a page, made
// here from a real seeded game the way the server's realm will make it (section 5 of the server-sim design): live S,
// a top-level key diff per update, slim R, the effects a day and two actions leave. The client tests (and the fake
// engine) use these until the integration step records real streams in their place; every one passes
// tests/lib/mp-sim-shape.js. Run `node tests/lib/mp-sim-fixtures.js` to write them again.
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('../harness');
const DIR = path.join(__dirname, '..', 'fixtures', 'mp-sim');
const CODE = 'K7Q2XD', PID = 'abcd1234', PID2 = 'efgh5678', EPOCH = 'k3f9', DEV = '9f8e7d6c', NOW = 1731000000000;
const MP = { code: CODE, pid: PID, asn: 201234, seed: 424242, preset: 'oncall', color: '#3a86ff', title: 'Friday' };
// In the page: the effects the realm would capture (its epilogue rebinds these the same way), and slim R (5.5).
const RIG = `window.__fx=[];
toast=(h,k='',a=[],o=null)=>{if(S)logNote(h,k,a,o);__fx.push(['toast',{h,k,a,o,tick:!!UI.tick}]);};
sfx=n=>{__fx.push(['sfx',n]);};haptic=n=>{__fx.push(['haptic',n]);};
floater=(x,y,t,c)=>{if(__fx.filter(f=>f[0]==='floater').length<40)__fx.push(['floater',[x,y,t,c]]);};
window.__slimR=()=>{const {o}=rwPack(R);for(const k of ['ef','fl','efp','flc','efg','egDesc','l2route','bbF','peered','cityBlocked'])delete o[k];
const tn={};for(const id in o.tNet)tn[id]=Object.fromEntries(Object.entries(o.tNet[id]).sort((a,b)=>b[1]-a[1]).slice(0,4));o.tNet=tn;
o.tTop8=transitTop(S.transit.map(t=>t.id),8);
const r6=v=>typeof v==='number'?(Number.isInteger(v)||!isFinite(v)?v:+v.toPrecision(6)):Array.isArray(v)?v.map(r6):v&&typeof v==='object'?Object.fromEntries(Object.entries(v).map(([k,x])=>[k,r6(x)])):v;
return r6(JSON.parse(JSON.stringify(o)));};
window.__keys=()=>Object.fromEntries(Object.keys(S).map(k=>[k,JSON.stringify(S[k])]));`;
function make() {
const { ev, errors, dom } = load({ seed: 4242 });
ev(`Date.now=()=>${NOW};`);
// A network of a server session, built the way the server builds one (beginState, then the server's own marks), with
// the intern on every order and a fiber cut it rushes: the snapshot carries a shift's log and the week's tally.
ev(`UI.pitched=true;beginState('Packet Pals','fra',{mode:'normal',preset:'oncall',mp:${JSON.stringify(MP)}});S.mp.sim=1;S.tut=null;compute();beginHello();
S.nextFail=S.nextEvent=1e9;UI.speed=0;UI.started=true;ACT.charter({k:'global'});
ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});ACT.launchBB({city:'ams'});
UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0});closeModal();
S.lvl=Math.max(S.lvl,2);ACT.opsHire({id:'kevin'});for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;closeModal();
for(let i=0;i<45;i++){if(i===20)dayGo(failureRun('cut'));dayTick();}`);
ev(RIG);
const snapS = JSON.parse(ev('JSON.stringify(S)'));
const r0 = JSON.parse(ev('JSON.stringify(__slimR())'));
const diff = (before) => { const now = JSON.parse(ev('JSON.stringify(__keys())')), s = {}, del = [];
for (const k of Object.keys(now)) if (now[k] !== before[k]) s[k] = JSON.parse(now[k]);
for (const k of Object.keys(before)) if (!(k in now)) del.push(k);
return { s, del, keys: now }; };
const fx = () => JSON.parse(ev('JSON.stringify(__fx.splice(0))'));
const clock = { t: 'clock', speed: 1, eff: 1, run: true, why: null, votes: { [PID2]: 4 }, tally: { 4: 1 }, need: 2, active: [PID, PID2], hold: [], idle: [],
day: 518, last: 1, max: 8, off: { [PID]: S0day(snapS) - 518, [PID2]: 0 } };
const card = JSON.parse(ev('JSON.stringify(mpCard())'));
const roster = { t: 'roster', code: CODE, title: 'Friday', preset: 'oncall', seed: MP.seed, created: NOW - 864e5,
players: [{ pid: PID, name: 'Packet Pals', asn: MP.asn, color: MP.color, card, seen: NOW, joined: NOW - 864e5 },
{ pid: PID2, name: 'Tubular Bells', asn: 207777, color: '#ff4f9a', card: null, seen: NOW - 6e4, joined: NOW - 36e5 }],
feed: [{ k: 'join', pid: PID, name: 'Packet Pals', at: NOW - 864e5 }, { k: 'join', pid: PID2, name: 'Tubular Bells', at: NOW - 36e5 }, { k: 'chat', pid: PID2, name: 'Tubular Bells', at: NOW - 6e4, text: 'peer with me?' }],
on: [PID, PID2] };
const snap = { t: 'snap', epoch: EPOCH, v: 412, now: NOW, S: snapS, r: r0, clock, roster, since: { days: 37, again: 0 }, keep: [['badge', { id: 'firstpop', v: 'oncall' }]] };
// A day: the keys it changed, a new R, what it said.
let base = JSON.parse(ev('JSON.stringify(__keys())'));
ev('UI.tick=false;dayTick();');
const d1 = diff(base), dayFx = fx();
if (!dayFx.length) dayFx.push(['sfx', 'coin']);
const updDay = { t: 'upd', from: 412, v: 413, now: NOW + 2500, day: JSON.parse(ev('S.day')), s: d1.s, del: d1.del, r: JSON.parse(ev('JSON.stringify(__slimR())')), fx: dayFx };
// Two quick taps in one update: a new POP (the panel moves to it) and a transit port there.
base = d1.keys;
ev("ACT.buildPop({city:'par'});");
const ui1 = { sel: { type: 'city', id: 'par' }, tab: 'cust' };
ev("ACT.buyTransit({city:'par',net:'cog',tier:1});");
const d2 = diff(base), actFx = fx();
const updAct = { t: 'upd', from: 413, v: 414, now: NOW + 3100, day: updDay.day, s: d2.s, del: d2.del, r: JSON.parse(ev('JSON.stringify(__slimR())')), fx: actFx,
acts: [{ rid: 'a1b2c3d4e5', dev: DEV, ui: ui1 }, { rid: 'a1b2c3d4e6', dev: DEV, ui: {} }] };
// A stream's flow records: the link it shows and its traffic's ways in, and a city's Peering tab.
const sub = JSON.parse(ev(`(()=>{const l=S.links[0],k=edgeKey(l),rec=R.ef[k],egd={};if(rec)for(const e in rec.eg||{})if(R.egDesc[e])egd[e]=R.egDesc[e];
return JSON.stringify({t:'sub',v:414,ef:rec?{[k]:rec}:{},egd,pf:{fra:pniFlows('fra')}});})()`));
if (errors.length) throw new Error('the game failed while making fixtures: ' + errors.join('; '));
dom.window.close();
return { snap, 'upd-day': updDay, 'upd-act': updAct, sub, clock, roster };
}
// The calendar offset of the network in the fixtures: its own date against the session day (open question 1).
function S0day(S) { return S.day; }
function write() {
fs.mkdirSync(DIR, { recursive: true });
const out = make();
for (const [k, v] of Object.entries(out)) fs.writeFileSync(path.join(DIR, k + '.json'), JSON.stringify(v) + '\n');
return Object.keys(out);
}
module.exports = { make, write, DIR, CODE, PID, PID2, EPOCH, DEV, NOW };
if (require.main === module) console.log('wrote', write().map((k) => `tests/fixtures/mp-sim/${k}.json`).join(', '));

183
tests/lib/mp-sim-shape.js Normal file
View file

@ -0,0 +1,183 @@
// The shapes of server-run play on the wire and between host and worker (the server-sim design, sections 4.2 and 5.3),
// checked: the session server's real output (its tests run every event they write through checkEvent) and the canned
// streams in tests/fixtures/mp-sim/ (the client's tests) must agree on them.
//
// checkEvent(e) problems with one stream event ([] when fine): snap, upd, sub, clock, roster, bye
// checkFx(f) problems with one effect entry, [kind, payload]
// checkWorker(m) problems with one worker → host reply: loaded, dayDone, actDone, askDone, pulled, subbed, saved,
// card, unloaded, err
//
// The epoch (5.10): the worker mints a new one at every realm load (a load, a begin, and the fresh realm it builds
// after a timeout, 4.2) and puts the realm's current one on every reply that carries versions: loaded, pulled, actDone,
// subbed. The host keeps the last one per network and writes it into every event's id (`id: <epoch>.<v>`); a reply with
// another epoch than the host holds means the realm was built again, so v started over and every page takes a snapshot.
// A network that did not load (loaded.err: its save failed, 4.7) has no realm, so no epoch, day or lost.
// A toast effect's k and a may be left out (toastPop's defaults: '' and []): a game call toast(html) has neither.
// parseSse(text) the events of an event-stream text: [{event, id, data (parsed)}], comments and heartbeats skipped
// fixture(name) tests/fixtures/mp-sim/<name>.json, parsed
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const SPEEDS = [0, 0.5, 1, 2, 4, 8];
const PID = /^[a-z0-9]{8}$/, RID = /^[a-z0-9]{8,16}$/, EPOCH = /^[a-z0-9]{1,16}$/, CODE = /^[0-9A-HJKMNP-TV-Z]{6}$/;
// What slim R never carries (5.5): compute inputs, internals, and what goes on demand in sub events.
const R_NEVER = ['ef', 'fl', 'efp', 'flc', 'efg', 'egDesc', 'l2route', 'bbF', 'peered', 'cityBlocked'];
const FX_KINDS = ['toast', 'sfx', 'haptic', 'floater', 'track', 'pause', 'modal', 'badge', 'mk', 'told'];
const WHY = [null, 'empty', 'hold', 'slow', 'loading', 'vote'];
const BYE = ['gone', 'old', 'moved', 'slow', 'shutdown'];
const OUTCOMES = ['applied', 'no_effect', 'rejected', 'error', 'stopped'];
const UI_KEYS = ['sel', 'tab', 'left', 'confirm', 'closed', 'modal'];
const obj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
const int = (v) => Number.isInteger(v);
const nat = (v) => Number.isInteger(v) && v >= 0;
const num = (v) => typeof v === 'number' && Number.isFinite(v);
const str = (v) => typeof v === 'string';
const bool = (v) => typeof v === 'boolean';
// fields: {name: test | [test, 'opt']}; extra keys are problems too (a typo on one side is caught by the other).
function fields(o, spec, where, out, open = false) {
if (!obj(o)) { out.push(`${where}: not an object`); return; }
for (const [k, t] of Object.entries(spec)) {
const [f, opt] = Array.isArray(t) ? t : [t];
if (!(k in o) || o[k] === undefined) { if (!opt) out.push(`${where}.${k}: missing`); continue; }
const r = f(o[k], `${where}.${k}`, out);
if (r === false) out.push(`${where}.${k}: bad value ${JSON.stringify(o[k]).slice(0, 80)}`);
}
if (!open) for (const k of Object.keys(o)) if (!(k in spec)) out.push(`${where}.${k}: unknown field`);
}
const listOf = (t) => (v, w, out) => { if (!Array.isArray(v)) return false; v.forEach((x, i) => { if (t(x, `${w}[${i}]`, out) === false) out.push(`${w}[${i}]: bad value ${JSON.stringify(x).slice(0, 60)}`); }); return true; };
const mapOf = (kt, vt) => (v, w, out) => { if (!obj(v)) return false; for (const [k, x] of Object.entries(v)) { if (!kt(k)) out.push(`${w}: bad key ${k}`); if (vt(x, `${w}.${k}`, out) === false) out.push(`${w}.${k}: bad value ${JSON.stringify(x).slice(0, 60)}`); } return true; };
// Live S, as the server's realm holds it: what every page reads first (the full check is the game's own migrate()).
function liveS(S, w, out) {
if (!obj(S)) return false;
if (S.v !== 1 || !nat(S.day) || !num(S.cash) || !obj(S.pops) || !Array.isArray(S.links) || !Array.isArray(S.biz) || !obj(S.stats)) out.push(`${w}: not a game state (v, day, cash, pops, links, biz, stats)`);
if (!obj(S.mp) || !CODE.test(S.mp.code) || !PID.test(S.mp.pid) || S.mp.sim !== 1) out.push(`${w}.mp: not a server network (code, pid, sim:1)`);
if (S.mode !== 'normal') out.push(`${w}.mode: server networks are Normal games`);
return true;
}
function slimR(r, w, out) {
if (!obj(r)) return false;
for (const k of R_NEVER) if (k in r) out.push(`${w}.${k}: slim R never carries it`);
for (const k of ['served', 'demand', 'reach', 'revMo', 'costMo']) if (!num(r[k])) out.push(`${w}.${k}: missing or not a number`);
for (const k of ['load', 'useT', 'tNet', 'cityDem', 'citySrv']) if (!obj(r[k])) out.push(`${w}.${k}: missing`);
if (!Array.isArray(r.ddos)) out.push(`${w}.ddos: missing`);
else r.ddos.forEach((m, i) => { if (m.attack !== null && !str(m.attack)) out.push(`${w}.ddos[${i}].attack: an attack's id (or null)`); });
if (!Array.isArray(r.tTop8) || r.tTop8.length > 8 || !r.tTop8.every((x) => Array.isArray(x) && x.length === 2 && str(x[0]) && num(x[1]))) out.push(`${w}.tTop8: [[net, gbps]] × ≤ 8`);
if (obj(r.tNet)) for (const [id, m] of Object.entries(r.tNet)) if (!obj(m) || Object.keys(m).length > 4) out.push(`${w}.tNet.${id}: at most the top 4 networks`);
return true;
}
const sel = (v) => v === null || (obj(v) && (v.type === 'city' || v.type === 'link') && str(v.id) && Object.keys(v).length === 2);
function actUi(u, w, out) {
fields(u, { sel: [sel, 'opt'], tab: [(v) => v === null || str(v), 'opt'], left: [(v) => v === null || str(v), 'opt'], confirm: [(v) => v === null || str(v), 'opt'],
closed: [(v) => v === 1 || v === true, 'opt'], modal: [(v) => obj(v) && str(v.h) && str(v.c) && Object.keys(v).length === 2, 'opt'] }, w, out);
return true;
}
const actEntry = (a, w, out) => { fields(a, { rid: (v) => RID.test(v), dev: (v) => RID.test(v), ui: actUi }, w, out); return true; };
function checkFx(f, w = 'fx', out = []) {
if (!Array.isArray(f) || f.length !== 2 || !str(f[0])) { out.push(`${w}: an effect is [kind, payload]`); return out; }
const [k, p] = f;
const bad = () => out.push(`${w}: bad ${k} payload ${JSON.stringify(p).slice(0, 80)}`);
switch (k) {
case 'toast': fields(p, { h: str, k: [str, 'opt'], a: [listOf((x) => obj(x) && str(x.l) && str(x.act)), 'opt'], o: [(v) => v === null || obj(v), 'opt'], tick: [bool, 'opt'] }, `${w}.toast`, out); break;
case 'sfx': case 'haptic': if (!str(p)) bad(); break;
case 'floater': if (!Array.isArray(p) || p.length !== 4 || !num(p[0]) || !num(p[1]) || !str(p[2]) || !str(p[3])) bad(); break;
case 'track': if (!Array.isArray(p) || p.length !== 2 || !str(p[0]) || !(p[1] === undefined || p[1] === null || bool(p[1]))) bad(); break;
case 'pause': if (p !== 1) bad(); break;
case 'modal': if (!['win', 'lose', 'baron'].includes(p)) bad(); break;
case 'badge': if (!obj(p) || !str(p.id) || !(p.v === undefined || str(p.v))) bad(); break;
case 'mk': if (!obj(p) || !str(p.e)) bad(); break;
case 'told': break;
default: out.push(`${w}: unknown effect ${k}`);
}
return out;
}
const fxList = (v, w, out) => { if (!Array.isArray(v)) return false; v.forEach((f, i) => checkFx(f, `${w}[${i}]`, out)); return true; };
const CLOCK = { t: (v) => v === 'clock', speed: (v) => SPEEDS.includes(v), eff: (v) => num(v) && v >= 0, run: bool, why: (v) => WHY.includes(v),
votes: mapOf((k) => PID.test(k), (v) => v === null || SPEEDS.includes(v)), tally: mapOf((k) => SPEEDS.includes(+k), nat), need: (v) => int(v) && v >= 1,
active: listOf((v) => PID.test(v)), hold: listOf((v) => PID.test(v)), idle: listOf((v) => PID.test(v)), day: nat, last: (v) => SPEEDS.includes(v) && v > 0,
max: (v) => SPEEDS.includes(v) && v > 0,
// The calendar offset of every network of the session: its own S.day minus the session day (open question 1: "own
// date"). One field, so a shared date later only means all zeros.
off: mapOf((k) => PID.test(k), int) };
const PLAYER = { pid: (v) => PID.test(v), name: str, asn: nat, color: (v) => /^#[0-9a-f]{6}$/i.test(v), card: (v) => v === null || obj(v), seen: nat, joined: nat,
lost: [bool, 'opt'], broken: [bool, 'opt'] };
const ROSTER = { t: (v) => v === 'roster', code: (v) => CODE.test(v), title: str, preset: str, seed: int, created: nat,
players: listOf((p, w, out) => { fields(p, PLAYER, w, out); return true; }),
feed: listOf((f, w, out) => { fields(f, { k: str, pid: str, name: str, at: nat, text: [str, 'opt'] }, w, out); return true; }),
on: listOf((v) => PID.test(v)) };
function checkEvent(e) {
const out = [];
if (!obj(e) || !str(e.t)) return ['an event is an object with t'];
const w = e.t;
if (e.t === 'snap') fields(e, { t: str, epoch: (v) => EPOCH.test(v), v: nat, now: nat, S: liveS, r: slimR,
clock: (v, ww, o) => { fields(v, CLOCK, ww, o); return true; }, roster: (v, ww, o) => { fields(v, ROSTER, ww, o); return true; },
since: (v, ww, o) => { fields(v, { days: nat, again: nat }, ww, o); return true; },
keep: (v, ww, o) => { if (!Array.isArray(v) || v.length > 32) return false; v.forEach((f, i) => { checkFx(f, `${ww}[${i}]`, o); if (f[0] !== 'badge' && f[0] !== 'modal') o.push(`${ww}[${i}]: keep holds only badge and modal`); }); return true; } }, w, out);
else if (e.t === 'upd') {
fields(e, { t: str, from: nat, v: nat, now: nat, day: nat, s: obj, del: [listOf(str), 'opt'], r: [slimR, 'opt'], fx: [fxList, 'opt'], acts: [listOf(actEntry), 'opt'] }, w, out);
if (nat(e.v) && nat(e.from) && e.v !== e.from + 1) out.push('upd: v is from + 1 (only a pull makes a version)');
if (obj(e.s) && Array.isArray(e.del)) for (const k of e.del) if (k in e.s) out.push(`upd: ${k} both changed and deleted`);
if (obj(e.s) && 'day' in e.s && e.s.day !== e.day) out.push('upd: day differs from s.day');
if (Array.isArray(e.fx) && e.fx.length > 60) out.push('upd: more than 60 effects');
} else if (e.t === 'sub') fields(e, { t: str, v: nat, ef: [obj, 'opt'], egd: [obj, 'opt'], pf: [obj, 'opt'] }, w, out);
else if (e.t === 'clock') fields(e, CLOCK, w, out);
else if (e.t === 'roster') fields(e, ROSTER, w, out);
else if (e.t === 'bye') fields(e, { t: str, why: (v) => BYE.includes(v) }, w, out);
else out.push(`unknown event ${e.t}`);
return out;
}
// Worker → host replies (4.2). Big payloads (an update, a snapshot) are JSON text, ready to write to every stream.
const json = (t) => (v, w, out) => { if (!str(v)) return false; let e; try { e = JSON.parse(v); } catch (x) { return false; } for (const p of checkEvent(e)) out.push(`${w}: ${p}`); if (e.t !== t) out.push(`${w}: not a ${t}`); return true; };
const subs = mapOf((k) => /^(link|peer):.{1,40}$/.test(k), (v) => obj(v));
const epoch = (v) => EPOCH.test(v);
const WORKER = {
// epoch, day and lost: required unless err says the network did not load (checkWorker).
loaded: { t: str, nid: (v) => PID.test(v), epoch: [epoch, 'opt'], day: [nat, 'opt'], lost: [bool, 'opt'], err: [str, 'opt'], saved: [(v, w, out) => { for (const p of checkWorker(v)) out.push(`${w}: ${p}`); return true; }, 'opt'] },
// A day that failed twice: err, retried, and day as it was before (the network is broken at its pre-day state, 4.3).
dayDone: { t: str, code: (v) => CODE.test(v), d: nat, nets: mapOf((k) => PID.test(k), (v, w, out) => { fields(v, { day: nat, lost: bool, pause: [bool, 'opt'], err: [str, 'opt'], retried: [bool, 'opt'], ms: (x) => num(x) && x >= 0 }, w, out); return true; }) },
actDone: { t: str, nid: (v) => PID.test(v), epoch, rid: (v) => RID.test(v), outcome: (v) => OUTCOMES.includes(v), why: [str, 'opt'], v: nat, upd: [(v, w, out) => v === null || json('upd')(v, w, out), 'opt'] },
askDone: { t: str, nid: (v) => PID.test(v), rid: (v) => RID.test(v), modal: [(v) => obj(v) && str(v.h) && str(v.c), 'opt'], ui: [obj, 'opt'], err: [str, 'opt'] },
pulled: { t: str, nid: (v) => PID.test(v), epoch, v: nat, upd: [json('upd'), 'opt'], snap: [json('snap'), 'opt'], subs: [subs, 'opt'] },
subbed: { t: str, nid: (v) => PID.test(v), epoch, v: nat, subs },
saved: { t: str, nid: (v) => PID.test(v), txt: str, uidN: nat, rt: obj, day: nat, lost: bool },
card: { t: str, nid: (v) => PID.test(v), card: (v) => v === null || obj(v) },
unloaded: { t: str, code: (v) => CODE.test(v), nid: [(v) => PID.test(v), 'opt'] },
err: { t: str, code: (v) => CODE.test(v), nid: (v) => PID.test(v), rid: [(v) => RID.test(v), 'opt'], what: (v) => ['timeout', 'throw', 'oom', 'exit', 'load'].includes(v), msg: str },
};
function checkWorker(m) {
const out = [];
if (!obj(m) || !str(m.t) || !WORKER[m.t]) return [`unknown worker reply ${obj(m) ? m.t : typeof m}`];
fields(m, WORKER[m.t], m.t, out);
if (m.t === 'loaded' && m.err === undefined) for (const k of ['epoch', 'day', 'lost']) if (m[k] === undefined) out.push(`loaded.${k}: missing`);
if (m.t === 'loaded' && m.err !== undefined && m.saved !== undefined) out.push('loaded: a network that did not load has nothing saved');
if (m.t === 'pulled' && m.snap !== undefined && str(m.snap)) { try { const e = JSON.parse(m.snap); if (e.epoch !== m.epoch) out.push('pulled: the snapshot\'s epoch is not the realm\'s'); } catch (x) { /* reported above */ } }
return out;
}
function parseSse(text) {
const out = [];
for (const block of String(text).split('\n\n')) {
if (!block.trim()) continue;
let event = 'message', id, data = '';
for (const line of block.split('\n')) {
if (!line || line.startsWith(':')) continue;
const i = line.indexOf(':'), k = i < 0 ? line : line.slice(0, i), v = i < 0 ? '' : line.slice(i + 1).replace(/^ /, '');
if (k === 'event') event = v; else if (k === 'id') id = v; else if (k === 'data') data += (data ? '\n' : '') + v;
}
if (data) out.push({ event, id, data: JSON.parse(data) });
}
return out;
}
const DIR = path.join(__dirname, '..', 'fixtures', 'mp-sim');
const fixture = (name) => JSON.parse(fs.readFileSync(path.join(DIR, name + '.json'), 'utf8'));
const FIXTURES = ['snap', 'upd-day', 'upd-act', 'sub', 'clock', 'roster'];
module.exports = { checkEvent, checkFx, checkWorker, parseSse, fixture, FIXTURES, FX_KINDS, R_NEVER, SPEEDS };

View file

@ -19,11 +19,13 @@ test('diversity map: the indexed graph answers like disjointRoutes() over every
const cp = ev('CABLE_PAIRS[0].cid+":"+CABLE_PAIRS[0].a+"-"+CABLE_PAIRS[0].b'); const cp = ev('CABLE_PAIRS[0].cid+":"+CABLE_PAIRS[0].a+"-"+CABLE_PAIRS[0].b');
for (const st of [{ won: false }, { won: true }, { won: false, scn: { rules: { banCities: ['jam', 'lon'], banPairs: [cp] } } }]) { for (const st of [{ won: false }, { won: true }, { won: false, scn: { rules: { banCities: ['jam', 'lon'], banPairs: [cp] } } }]) {
const r = JSON.parse(ev(`(()=>{const st=${lit(st)},L=plainLinks(st);diversityMap=null;diversityPossible('fra','nyc',st); const r = JSON.parse(ev(`(()=>{const st=${lit(st)},L=plainLinks(st);diversityMap=null;diversityPossible('fra','nyc',st);
const ids=CITIES.map(c=>c.id),bad=[];let n=0;for(let i=0;i<ids.length;i+=3)for(let j=i+1;j<ids.length;j+=3){n++;const a=ids[i],b=ids[j]; const ids=CITIES.map(c=>c.id),bad=[];let n=0;for(let i=0;i<ids.length;i+=9)for(let j=i+1;j<ids.length;j+=9){n++;const a=ids[i],b=ids[j];
const want=(st.scn&&st.scn.rules.banCities.some(x=>x===a||x===b))?diversityPossible(a,b,st):disjointRoutes(a,b,L);if(diversityPossible(a,b,st)!==want)bad.push(a+'-'+b);} const want=(st.scn&&st.scn.rules.banCities.some(x=>x===a||x===b))?diversityPossible(a,b,st):disjointRoutes(a,b,L);if(diversityPossible(a,b,st)!==want)bad.push(a+'-'+b);}
return JSON.stringify({links:L.length,mine:diversityMap.links,n,bad})})()`)); return JSON.stringify({links:L.length,mine:diversityMap.links,n,bad})})()`));
assert.equal(r.mine, r.links, 'the same possible links'); assert.equal(r.mine, r.links, 'the same possible links');
assert.ok(r.n > 2000); // Every 9th city against every 9th after it: over a thousand pairs, near and far, in all regions (each pair walks
// every possible link the plain way, so all pairs took 90 s).
assert.ok(r.n > 1000);
assert.deepEqual(r.bad, [], JSON.stringify(st)); assert.deepEqual(r.bad, [], JSON.stringify(st));
} }
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
@ -41,7 +43,7 @@ test('link curves: skipping far-away cities gives the same bend around the ones
const cand=[1,1.5,2.1,2.9,3.8].map(k=>lim(sg*mag*k)).concat([1,1.5,2.1,2.9,3.8].map(k=>lim(-sg*Math.max(mag,base)*k)));let best=null,bs=-Infinity; const cand=[1,1.5,2.1,2.9,3.8].map(k=>lim(sg*mag*k)).concat([1,1.5,2.1,2.9,3.8].map(k=>lim(-sg*Math.max(mag,base)*k)));let best=null,bs=-Infinity;
for(const off of cand){const cx=mx+nx*off,cy=my+ny*off,c=clear(cx,cy);if(c>=need){best=[cx,cy];break;}const sc=Math.min(c,need)-Math.abs(off)*0.35;if(sc>bs){bs=sc;best=[cx,cy];}} for(const off of cand){const cx=mx+nx*off,cy=my+ny*off,c=clear(cx,cy);if(c>=need){best=[cx,cy];break;}const sc=Math.min(c,need)-Math.abs(off)*0.35;if(sc>bs){bs=sc;best=[cx,cy];}}
return {ax:A.x,ay:A.y,bx,by,cx:best[0],cy:best[1],len};}`); return {ax:A.x,ay:A.y,bx,by,cx:best[0],cy:best[1],len};}`);
const bad = JSON.parse(ev(`(()=>{const ids=CITIES.map(c=>c.id),bad=[];for(let i=0;i<ids.length;i+=6)for(let j=i+1;j<ids.length;j+=5)for(const k of [0,1,4]){ const bad = JSON.parse(ev(`(()=>{const ids=CITIES.map(c=>c.id),bad=[];for(let i=0;i<ids.length;i+=12)for(let j=i+1;j<ids.length;j+=10)for(const k of [0,1,4]){
const l={id:'x'+i+'_'+j,a:ids[i],b:ids[j]};if(JSON.stringify(bezGeom(l,k))!==JSON.stringify(plainGeom(l,k)))bad.push(l.a+'-'+l.b+'#'+k);}return JSON.stringify(bad)})()`)); const l={id:'x'+i+'_'+j,a:ids[i],b:ids[j]};if(JSON.stringify(bezGeom(l,k))!==JSON.stringify(plainGeom(l,k)))bad.push(l.a+'-'+l.b+'#'+k);}return JSON.stringify(bad)})()`));
assert.deepEqual(bad, []); assert.deepEqual(bad, []);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);

View file

@ -0,0 +1,308 @@
// The contracts server-run play is built against (the server-sim design, sections 4.2, 5 and 10): the act tables and
// the envelope check (scripts/lib/mp-sim-acts.js), the canned stream (tests/fixtures/mp-sim/) and its shape checker
// (tests/lib/mp-sim-shape.js), the fake engine (tests/lib/mp-sim-fake-engine.js), and the harness's MP page with its
// fake streaming fetch. The engine, the host and the client each test their side against these.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load, fakeFetch, sse, flush } = require('./harness');
const { simId } = require('../scripts/lib/page');
const { lit } = require('../scripts/lib/js-literal');
const A = require('../scripts/lib/mp-sim-acts');
const { checkEvent, checkFx, checkWorker, parseSse, fixture, FIXTURES } = require('./lib/mp-sim-shape');
const { createFakeEngine } = require('./lib/mp-sim-fake-engine');
const fs = require('node:fs');
const path = require('node:path');
const SIM = simId();
const env = (act, args = {}, more = {}) => ({ rid: 'a1b2c3d4e5', dev: '9f8e7d6c', sim: SIM, act, args, ...more });
test('every ACT is classified once: SEND, ASK, VOTE, LOCAL or PUZZLE; SEND is the agent\'s game commands, adjusted', (t) => {
// The development page of a multiplayer build: every ACT there is, the server-play client's (98-server-play) too.
const { ev, errors, dom } = load({ agent: true, mp: true });
t.after(() => dom.window.close());
const acts = JSON.parse(ev('JSON.stringify(Object.keys(ACT))'));
const lists = { SEND: A.SEND, ASK: A.ASK, VOTE: A.VOTE, LOCAL: A.LOCAL, PUZZLE: A.PUZZLE };
const where = {};
for (const [name, list] of Object.entries(lists)) {
assert.deepEqual([...list].sort(), list, `${name} stays sorted, one per line`);
for (const a of list) { assert.equal(where[a], undefined, `ACT.${a} is in both ${where[a]} and ${name}`); where[a] = name; }
}
for (const a of acts) assert.ok(where[a], `ACT.${a} is not classified: add it to SEND, ASK, VOTE or LOCAL in scripts/lib/mp-sim-acts.js`);
for (const a of Object.keys(where)) assert.ok(acts.includes(a), `${a} is in scripts/lib/mp-sim-acts.js (${where[a]}) but ACT has no such act`);
for (const a of A.PUZZLE) assert.match(a, /^pz[A-Z]/);
// SEND, derived again: never counted by hand.
const cmd = JSON.parse(ev('JSON.stringify(Object.keys(API_CMD))'));
const want = cmd.filter((k) => !/^pz[A-Z]/.test(k) && !['teCheck', 'traceRun', 'closeModal'].includes(k)).concat(['connCancel', 'pieRename', 'tutSkip']).sort();
assert.deepEqual(A.SEND, want, 'SEND = API_CMD − pz* − {teCheck, traceRun, closeModal} + {connCancel, pieRename, tutSkip}');
// The other tables only name sent acts (asks for ASK), and their own args.
for (const a of [...Object.keys(A.CONFIRM), ...Object.keys(A.DRAFTS), ...Object.keys(A.QUOTE)]) assert.ok(A.SEND.includes(a), `${a} is sent`);
for (const a of Object.keys(A.TEXT)) assert.ok(A.SEND.includes(a) || A.ASK.includes(a), `${a} is sent or asked`);
for (const ks of Object.values(A.DRAFTS)) for (const k of ks) assert.ok(A.DRAFT_TYPES[k], `draft ${k} has a type`);
assert.equal(A.armKey('connCancel', { k: 't', id: 'i9' }), 'cc:t:i9');
assert.equal(A.armKey('rmSite', { city: 'fra' }), 'sitefra');
assert.equal(A.armKey('cancelTransit', { id: 'x' }), null, "an 'arg' act arms with ok:1, not a key");
assert.deepEqual(errors, []);
});
// Every button and drop-down a rich game shows, as the page would send it: [act, args].
function crawl(ev) {
ev(`window.__btns=[];window.__grab=()=>{for(const el of document.querySelectorAll('[data-act],[data-chg]')){const act=el.dataset.act||el.dataset.chg;let a={};try{a=el.dataset.args?JSON.parse(el.dataset.args):{};}catch(e){a={bad:el.dataset.args};}
if(el.dataset.chg){a={...a,v:el.value}}__btns.push([act,a]);}};`);
const views = [
"for(const c of ['fra','ams','nyc','sin','syd']){for(const tab of ['cust','up','peer','infra','links']){UI.sel={type:'city',id:c};UI.tab=tab;renderPanel();__grab();}}",
"for(const l of S.links.slice(0,40)){UI.sel={type:'link',id:l.id};renderPanel();__grab();}",
"UI.leftOpen=true;for(const k of ['goals','deals','noc','nets']){UI.left=k;renderLeft();__grab();}",
"$('dash').hidden=false;for(const k of DTABS){UI.dtab=k;renderDash();__grab();}$('dash').hidden=true;",
'ACT.bank();__grab();ACT.bankClose();',
"for(const [a,x] of [['opsOpen',{}],['utilities',{city:'fra'}],['bstdOpen',{}],['pniAllOpen',{net:null}],['pniAllOpen',{net:'cog'}],['salesOpen',{}],['routingOpen',{}],['ip4Open',{}],['models',{}],['decomOpen',{}],['teEdit',{}]]){try{ACT[a](x);}catch(e){}__grab();closeModal();}",
"openLinkModal('fra','nyc');__grab();closeModal();openLinkModal('fra','ams');__grab();closeModal();",
"UI.confirm=null;for(const t of S.transit.slice(0,3)){UI.sel={type:'city',id:t.city};UI.tab='up';UI.confirm=t.id;renderPanel();__grab();}UI.confirm=null;",
];
for (const v of views) ev(v);
return JSON.parse(ev('JSON.stringify(__btns)'));
}
test('the envelope check passes every button a rich game shows for a sent act, as the page sends it', (t) => {
const fsx = require('node:fs');
const BIG = fsx.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
const { ev, errors, dom } = load({ seed: 77 });
t.after(() => dom.window.close());
ev(`Date.now=()=>1.7e12;S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.lvl=Math.max(S.lvl,6);
ACT.opsHire({id:'kevin'});closeModal();ACT.salesHire({id:'eng'});closeModal();S.popStd=bstdPut({...bstd(),rt:2});compute();renderAll();`);
const btns = crawl(ev);
const sent = btns.filter(([a]) => A.SEND.includes(a));
assert.ok(sent.length > 200, `a real sweep: ${sent.length} sent buttons of ${btns.length}`);
const acts = new Set(sent.map(([a]) => a));
assert.ok(acts.size > 40, `${acts.size} different acts`);
for (const q of ['pniAll', 'bstdApply', 'utilityKit']) assert.ok(acts.has(q), `the sweep found ${q}`);
for (const [act, args] of sent) {
// The page adds the drafts the act reads, as they are, and confirms a two-click act's second click.
const ui = A.DRAFTS[act] ? JSON.parse(ev(`JSON.stringify({pending:UI.pending||{a:'fra',b:'ams'},route:UI.route||'',via:UI.via||'',cnPrem:!!UI.cnPrem,dfSrc:'lease',dfSys:'lite',seaDesign:'standard',
seaterminal:false,seaengineering:false,decom:['fra'],slop:false,pieIns:false,pieLas:false})`)) : null;
const body = env(act, args, { ...(ui ? { ui: Object.fromEntries(A.DRAFTS[act].map((k) => [k, ui[k]])) } : {}), ...(A.CONFIRM[act] ? { confirmed: true } : {}),
ctx: { sel: { type: 'city', id: 'fra' }, tab: 'cust', left: 'noc', modal: false, w: 390, h: 844, coarse: true } });
const r = A.checkEnvelope('act', JSON.parse(JSON.stringify(body)), { sim: SIM });
assert.ok(r.ok, `${act} ${JSON.stringify(args)}: ${r.error}`);
}
assert.deepEqual(errors, []);
});
test('the envelope check refuses what section 10 refuses', () => {
const ok = (kind, b) => A.checkEnvelope(kind, b, { sim: SIM });
assert.equal(ok('act', env('buyTransit', { city: 'fra', net: 'cog', tier: 1 })).ok, true);
const no = (kind, b, why) => { const r = ok(kind, b); assert.equal(r.ok, false, `${why}: refused`); assert.equal(r.code, 400, why); };
const proto = JSON.parse('{"__proto__":{"polluted":1}}');
for (const [b, why] of [
[null, 'null'], [[], 'an array'], ['x', 'a string'], [{ ...env('buildPop', { city: 'fra' }), rid: 'AB' }, 'a bad rid'], [{ ...env('buildPop', { city: 'fra' }), dev: 'x'.repeat(17) }, 'a bad dev'],
[{ ...env('buildPop', { city: 'fra' }), sim: 'nothex' }, 'a bad sim'], [{ ...env('buildPop', { city: 'fra' }), extra: 1 }, 'an unknown field'],
[env('start', {}), 'a session act'], [env('pzStart', {}), 'a puzzle act'], [env('speed', { v: 8 }), 'a vote'], [env('teOpt', {}), 'a local act'],
[env('constructor', {}), 'constructor'], [env('__proto__', {}), '__proto__'], [env('toString', {}), 'toString'],
[env('buildPop', { city: { id: 'fra' } }), 'a nested object'], [env('buildPop', proto), '__proto__ in args'], [env('buildPop', { constructor: 1 }), 'constructor in args'],
[env('buildPop', Object.fromEntries(Array.from({ length: 13 }, (x, i) => ['k' + i, i]))), '13 args'], [env('buildPop', { city: 'x'.repeat(65) }), 'a 65-character string'],
[env('buildPop', { city: Array(65).fill('fra') }), 'an array of 65'], [env('buildPop', { city: [{}] }), 'an object in an array'], [env('buildPop', { city: NaN }), 'NaN'],
[env('buildPop', { 'bad-key': 1 }), 'a bad arg name'], [env('buildPop', [1, 2]), 'args as an array'],
[env('buildLink', { tier: 1 }, { ui: { pending: 'fra-ams' } }), 'a draft of the wrong type'], [env('buildLink', { tier: 1 }, { ui: { decom: ['fra'] } }), 'a draft the act does not read'],
[env('buildLink', { tier: 1 }, { ui: { pending: { a: 'fra', b: 'ams', c: 'x' } } }), 'a pair with more'], [env('buildLink', { tier: 1 }, { ui: { pending: { a: 'fra', b: 'fra' } } }), 'a link from a city to itself'], [env('buildPop', { city: 'fra' }, { ui: { pending: { a: 'fra', b: 'ams' } } }), 'drafts on an act without'],
[env('decomGo', {}, { ui: { decom: Array(201).fill('fra') } }), '201 cities'],
[env('buildPop', { city: 'fra' }, { confirmed: true }), 'confirmed on a one-click act'], [env('rmLink', { id: 'l1' }, { confirmed: false }), 'confirmed false'],
[env('buildPop', { city: 'fra' }, { ctx: { sel: { type: 'ix', id: 'fra' } } }), 'a selection of another type'], [env('buildPop', { city: 'fra' }, { ctx: { tab: 'Cust' } }), 'a tab with capitals'],
[env('buildPop', { city: 'fra' }, { ctx: { w: 0 } }), 'a viewport of nothing'], [env('buildPop', { city: 'fra' }, { ctx: { h: Infinity } }), 'an endless viewport'], [env('buildPop', { city: 'fra' }, { ctx: { w: '390' } }), 'a viewport as text'],
[env('buildPop', { city: 'fra' }, { ctx: { evil: 1 } }), 'an unknown ctx field'], [env('buildPop', { city: 'fra' }, { ctx: [] }), 'ctx as an array'],
[env('pniAll', { net: null, tier: 1 }), 'a quote act without its quote'], [env('utilityCaches', { city: 'fra', quote: 5 }), 'a key quote as a number'],
[env('bstdApply', { q: 5 }), 'the build standard without its plan'], [env('bstdApply', { quote: 5 }), 'a plan key as a number'],
[env('teDeploy', { script: 'x'.repeat(4001) }), 'a script over 4000'], [env('metricSet', { id: 'l1', v: '1'.repeat(17) }), 'a metric over 16'],
]) no('act', b, why);
assert.equal(ok('act', env('teDeploy', { script: 'x'.repeat(4000) })).ok, true, 'a long script within its cap');
// A viewport outside what the layout tells apart is clamped, not refused: a 5120-px monitor, a desktop zoomed out.
for (const [w, h, cw, ch] of [[5120, 1440, A.VIEW_MAX, 1440], [100, 50, A.VIEW_MIN, A.VIEW_MIN], [390, 844, 390, 844]]) {
const b = env('buildPop', { city: 'fra' }, { ctx: { w, h } });
assert.equal(ok('act', b).ok, true, `${w}×${h}`);
assert.deepEqual([b.ctx.w, b.ctx.h], [cw, ch], `${w}×${h} clamped into ${A.VIEW_MIN}–${A.VIEW_MAX}`);
}
assert.equal(ok('act', env('rmLink', { id: 'l1' }, { confirmed: true })).ok, true);
const old = ok('act', { ...env('buildPop', { city: 'fra' }), sim: 'ffffffffffff' });
assert.deepEqual([old.ok, old.code, old.old], [false, 409, true], 'a page of another build is told it is old');
// Asks: only the three what-ifs, without drafts or confirmations.
assert.equal(ok('ask', env('teCheck', { script: 'prefer cog at fra' })).ok, true);
assert.equal(ok('ask', env('linkCheck', { id: 'l1' })).ok, true);
no('ask', env('buildPop', { city: 'fra' }), 'a sent act as an ask');
no('ask', env('linkCheck', { id: 'l1' }, { confirmed: true }), 'an ask confirmed');
// Votes, presence, settings.
for (const s of [0, 0.5, 1, 2, 4, 8, null]) assert.equal(ok('vote', { speed: s, sim: SIM }).ok, true, `vote ${s}`);
no('vote', { speed: 3, sim: SIM }, 'a speed that is none'); no('vote', { speed: 1, sim: SIM, x: 1 }, 'a vote with more');
assert.equal(ok('vote', { speed: 1, sim: 'ffffffffffff' }).code, 409);
assert.equal(ok('here', { dev: '9f8e7d6c', hidden: false, hold: true, view: { link: 'l1' } }).ok, true);
no('here', { dev: '9f8e7d6c', view: { link: { x: 1 } } }, 'a view with an object'); no('here', { dev: '9f8e7d6c', hidden: 'yes' }, 'a flag that is no boolean');
assert.equal(ok('prefs', { prefs: { pauseFurious: true }, lang: 'de' }).ok, true);
no('prefs', { prefs: { muted: true } }, 'a preference that is not the network\'s'); no('prefs', { lang: '../x' }, 'a language that is no code');
no('nope', {}, 'an unknown kind');
});
test('the canned stream: every fixture passes the shape checker, and the shape checker catches broken ones', () => {
for (const n of FIXTURES) assert.deepEqual(checkEvent(fixture(n)), [], n);
const upd = fixture('upd-act');
assert.equal(upd.acts.length, 2, 'two actions in one update');
assert.equal(upd.v, upd.from + 1);
assert.equal(fixture('upd-day').from, fixture('snap').v, 'the day follows the snapshot');
assert.equal(upd.from, fixture('upd-day').v, 'the actions follow the day');
assert.ok('off' in fixture('clock'), 'the clock carries each network\'s calendar offset');
const broken = [
[{ ...upd, v: upd.from + 2 }, /from \+ 1/], [{ ...upd, r: { ...upd.r, ef: {} } }, /never carries/], [{ ...upd, fx: [['boom', 1]] }, /unknown effect/],
[{ ...upd, acts: [{ rid: 'x', dev: '9f8e7d6c', ui: {} }] }, /rid/], [{ ...fixture('clock'), speed: 3 }, /speed/], [{ ...fixture('roster'), on: ['NOPE'] }, /on/],
[{ ...fixture('snap'), S: { ...fixture('snap').S, mp: { ...fixture('snap').S.mp, sim: undefined } } }, /server network/], [{ t: 'bye', why: 'tired' }, /why/], [{ t: 'nope' }, /unknown event/],
[{ ...upd, s: { ...upd.s, day: 1 }, day: 2 }, /day/],
];
for (const [e, re] of broken) assert.match(checkEvent(e).join('\n'), re);
assert.deepEqual(checkFx(['floater', [1, 2, 'x', '#fff']]), []);
assert.match(checkFx(['toast', { h: 1 }]).join(), /toast/);
// Over the wire: sse() writes what parseSse() reads.
const text = FIXTURES.map((n, i) => sse(fixture(n).t, fixture(n), i % 2 ? `k3f9.${i}` : undefined)).join(': hb\n\n');
const back = parseSse(text);
assert.deepEqual(back.map((e) => e.data), FIXTURES.map(fixture));
assert.equal(back[1].id, 'k3f9.1');
});
test('the canned state is the game\'s own: migrate() keeps the snapshot and every update applied to it as they are', (t) => {
const { ev, errors, dom } = load();
t.after(() => dom.window.close());
const same = (s) => ev(`(()=>{const a=${lit(JSON.stringify(s))},b=JSON.stringify(migrate(JSON.parse(a)));return a===b?'':b.slice(0,0)+'differs';})()`);
let S = fixture('snap').S;
assert.equal(same(S), '', 'the snapshot');
for (const n of ['upd-day', 'upd-act']) {
const u = fixture(n);
S = { ...S, ...u.s };
for (const k of u.del || []) delete S[k];
assert.equal(same(S), '', `after ${n}`);
}
assert.deepEqual(errors, []);
});
test('the fake engine answers every call in the shapes of section 4.2', async () => {
const e = createFakeEngine(), code = 'K7Q2XD', a = 'abcd1234', b = 'efgh5678';
const all = [];
const L = await e.load(code, [{ nid: a, begin: { name: 'Packet Pals', home: 'fra', preset: 'oncall', asn: 201234, mp: {}, tut: false }, lang: 'en', prefs: {} }, { nid: b, env: { day: 40 }, lang: 'de', prefs: {} }]);
assert.equal(L.length, 2); assert.ok(L[0].saved, 'a new network is checkpointed at once');
assert.ok(L[0].epoch && L[1].epoch && L[0].epoch !== L[1].epoch, 'each realm load has its own epoch');
all.push(...L);
const D = await e.day(code, { d: 1, speed: 1, last: 1, alone: [], nets: [b, a] });
assert.deepEqual(Object.keys(D.nets), [a, b]); assert.equal(D.nets[b].day, 41);
all.push(D);
const P1 = await e.pull(code, a, {}), P2 = await e.pull(code, a, {});
assert.ok(P1.upd && !P2.upd, 'a pull sends what changed, once'); assert.equal(P2.v, P1.v, 'only a pull with something to send is a version');
const act = await e.act(code, a, env('buildPop', { city: 'par' }));
assert.equal(act.v, P1.v + 1); assert.equal(JSON.parse(act.upd).acts[0].rid, 'a1b2c3d4e5');
assert.deepEqual([P1.epoch, P2.epoch, act.epoch], [L[0].epoch, L[0].epoch, L[0].epoch], 'every versioned reply names the realm\'s epoch');
all.push(P1, P2, act, await e.ask(code, a, env('linkCheck', { id: 'l1' })), await e.pull(code, b, { snap: true, views: [{ link: 'l1' }, { peer: 'fra' }] }),
await e.sub(code, a, { views: [{ link: 'l1' }] }), await e.greet(code, a), await e.save(code, b), await e.card(code, a));
assert.equal(await e.prefs(code, a, { prefs: { pauseFurious: true } }), undefined);
e.lose(code, b);
const D2 = await e.day(code, { d: 2, nets: [a, b] });
assert.equal(D2.nets[b].lost, true);
const D3 = await e.day(code, { d: 3, nets: [a, b] });
assert.equal(D3.nets[b], undefined, 'a lost network has no more days');
assert.equal((await e.act(code, b, env('buildPop', { city: 'par' }))).outcome, 'stopped');
e.failNext('act', 'timeout');
const tmo = await e.act(code, a, env('buildPop', { city: 'par' }));
assert.deepEqual([tmo.t, tmo.what], ['err', 'timeout']);
// The worker built that realm again: a new epoch, versions from 0, so every page of it takes a snapshot.
const P3 = await e.pull(code, a, { snap: true });
assert.notEqual(P3.epoch, L[0].epoch); assert.equal(P3.v, 0); assert.equal(JSON.parse(P3.snap).epoch, P3.epoch);
all.push(D2, D3, tmo, P3);
for (const m of all) assert.deepEqual(checkWorker(m), [], JSON.stringify(m).slice(0, 80));
// Held answers wait; a worker that dies rejects everything pending.
e.hold('day');
let done = false; const p = e.day(code, { d: 4, nets: [a] }).then(() => { done = true; });
await new Promise((r) => setImmediate(r));
assert.equal(done, false, 'held');
e.release('day'); await p; assert.equal(done, true);
e.hold('save');
const s1 = e.save(code, a), s2 = e.save(code, b);
e.exit();
await assert.rejects(s1, /worker exited/); await assert.rejects(s2, /worker exited/);
assert.equal(e.stats().realms, 0);
e.failNext('load', 'exit');
await assert.rejects(e.load(code, [{ nid: a, env: {}, lang: 'en', prefs: {} }]), /worker exited/);
assert.deepEqual(checkWorker({ t: 'unloaded', code }), []);
assert.ok(e.calls.length > 15);
});
test('the fake engine fails the way the engine does: a network that does not load, a day that fails twice or once', async () => {
const a = 'abcd1234', b = 'efgh5678', c = 'ijkl9012', net = (nid) => ({ nid, env: { day: 5 }, lang: 'en', prefs: {} });
// A save that does not load (4.7): that network is broken, the others load.
const e = createFakeEngine(), code = 'K7Q2XD';
e.breakNext(code, b);
const L = await e.load(code, [net(a), net(b)]);
assert.equal(Array.isArray(L), true);
assert.deepEqual([!!L[0].err, !!L[1].err], [false, true]);
assert.deepEqual(Object.keys(L[1]).sort(), ['err', 'nid', 't'], 'a broken load has no realm: no epoch, day or lost');
e.failNext('load', 'timeout', c);
const L2 = await e.load('Q9W8E7', [net(a), net(c)]);
assert.deepEqual([!!L2[0].err, !!L2[1].err], [false, true], 'a failed load call names the network it failed');
e.failNext('load', 'throw');
const L3 = await e.load('Z2X3C4', [net(a), net(b)]);
assert.deepEqual(L3.map((l) => !!l.err), [true, true], 'without a network, every network of the call');
// Days: one that fails once and passes on the retry, one that fails twice (broken at its pre-day state).
e.flaky(code, a);
const D1 = await e.day(code, { d: 1, nets: [a] });
assert.deepEqual([D1.nets[a].day, D1.nets[a].retried, D1.nets[a].err], [6, true, undefined]);
const E = createFakeEngine();
await E.load(code, [net(a), net(b)]);
E.failNext('day', 'throw', b);
const D2 = await E.day(code, { d: 1, nets: [a, b] });
assert.equal(D2.nets[a].day, 6);
assert.deepEqual([D2.nets[b].day, D2.nets[b].retried, typeof D2.nets[b].err], [5, true, 'string']);
const D3 = await E.day(code, { d: 2, nets: [a, b] });
assert.equal(D3.nets[b], undefined, 'a broken network has no more days');
assert.equal((await E.act(code, b, env('buildPop', { city: 'par' }))).outcome, 'stopped');
// A day that timed out twice leaves a fresh realm (a new epoch) as well.
const ep = (await E.pull(code, a, {})).epoch;
E.failNext('day', 'timeout');
const D4 = await E.day(code, { d: 3, nets: [a] });
assert.equal(typeof D4.nets[a].err, 'string');
assert.notEqual((await E.pull(code, a, {})).epoch, ep);
for (const m of [...L, ...L2, ...L3, D1, D2, D3, D4]) assert.deepEqual(checkWorker(m), [], JSON.stringify(m).slice(0, 80));
// The checker holds the host to it.
assert.match(checkWorker({ t: 'loaded', nid: a, day: 1, lost: false }).join(), /epoch: missing/);
assert.match(checkWorker({ t: 'pulled', nid: a, v: 1 }).join(), /epoch: missing/);
assert.match(checkWorker({ t: 'loaded', nid: a, err: 'x', saved: { t: 'saved' } }).join(), /nothing saved/);
assert.deepEqual(checkFx(['toast', { h: 'one argument', tick: false }]), [], 'toast(html): k and a may be left out');
});
test('the harness: load({mp:true}) is a stamped MP page, and fakeFetch streams events the page reads through fetch', async (t) => {
const f = fakeFetch([[/^POST \/api\/mp\/sessions\/K7Q2XD\/act$/, (c) => ({ status: 200, json: { rid: c.body.rid, outcome: 'applied', v: 414 } })]]);
const { ev, errors, dom } = load({ mp: true, fetch: f });
t.after(() => dom.window.close());
assert.equal(ev('MP_API'), '/api/mp');
assert.equal(ev('SIM_ID'), SIM);
// A stream, read the way a page reads one.
ev(`window.__got=[];window.__end='';window.__ac=new AbortController();
fetch(MP_API+'/sessions/K7Q2XD/stream?dev=9f8e7d6c&sim='+SIM_ID,{headers:{Authorization:'Bearer abcd1234.x'},signal:__ac.signal}).then(r=>{
if(!r.ok||!/event-stream/.test(r.headers.get('content-type')))return;const rd=r.body.getReader(),dc=new TextDecoder();let buf='';
const go=()=>rd.read().then(({done,value})=>{if(done){__end='done';return;}buf+=dc.decode(value,{stream:true});let i;
while((i=buf.indexOf('\\n\\n'))>=0){const blk=buf.slice(0,i);buf=buf.slice(i+2);const d=blk.split('\\n').filter(l=>l.startsWith('data: ')).map(l=>l.slice(6)).join('\\n');if(d)__got.push(JSON.parse(d).t);}go();},e=>{__end=e.name;});go();});`);
const s = await f.stream(0);
assert.equal(s.call.path, '/sessions/K7Q2XD/stream');
assert.deepEqual(s.call.query, { dev: '9f8e7d6c', sim: SIM });
assert.equal(s.call.headers.authorization, 'Bearer abcd1234.x');
s.send('snap', fixture('snap'), 'k3f9.412').comment().send('upd', fixture('upd-day'), 'k3f9.413');
await flush(5);
assert.deepEqual(JSON.parse(ev('JSON.stringify(__got)')), ['snap', 'upd']);
ev('__ac.abort()');
await flush(5);
assert.equal(s.aborted, true, 'the page aborted it');
assert.equal(ev('__end'), 'AbortError');
// A second stream that the server ends.
ev(`fetch(MP_API+'/sessions/K7Q2XD/stream?dev=9f8e7d6c&sim='+SIM_ID).then(r=>r.body.getReader().read()).then(x=>{window.__d2=x.done;})`);
(await f.stream(1)).close();
await flush(5);
assert.equal(ev('__d2'), true);
// A POST answered by a route; the call is recorded with its parsed body.
ev(`fetch(MP_API+'/sessions/K7Q2XD/act',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({rid:'a1b2c3d4e5'})}).then(r=>r.json()).then(j=>{window.__j=j;})`);
await flush(5);
assert.equal(ev('__j.outcome'), 'applied');
assert.equal(f.calls.at(-1).body.rid, 'a1b2c3d4e5');
ev(`fetch(MP_API+'/sessions/K7Q2XD/vote',{method:'POST',body:'{}'}).then(r=>{window.__st=r.status;})`);
await flush(5);
assert.equal(ev('__st'), 404, 'anything else is not here');
assert.deepEqual(errors, []);
});

View file

@ -72,6 +72,29 @@ test('pages: the build carries no agent code, and is the page assembled without
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('pages: the build carries nothing of server-run play; only a multiplayer build has it, with its build id', () => {
// src/game/98-server-play/ and its CSS are for self-hosted multiplayer copies (MP_API): left out of this page whole,
// and the SIM_ID placeholder stays as it is. Lines of those files (long enough to be theirs, and without labels,
// which the build turns into ids) are looked for in both builds.
const page = require('../scripts/lib/page');
const mp = page.assemble({ mp: true }), lines = mp.html.split('\n'), mine = [];
for (const m of mp.map) if (page.MP_ONLY.some((p) => (p.endsWith('/') ? m.file.startsWith(p) : m.file === p)))
for (let i = m.from; i <= m.to; i++) { const l = lines[i - 1].trim(); if (l.length >= 40 && !/\b(tr|trn|N_)\(/.test(l)) mine.push(l); }
assert.ok(mine.length >= 2, 'the server-play files have lines to look for');
const html = read('index.html');
for (const l of mine) assert.equal(html.includes(l), false, `the page has no "${l.slice(0, 60)}…"`);
assert.match(html, /const SIM_ID=\/\*__SIM_ID__\*\/'';/, 'and no build id');
assert.equal('simId' in JSON.parse(read('version.json')), false);
const MPOUT = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-pages-mp-'));
try {
execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT: MPOUT, VERSION: '1.2.3', BUILD_DATE: '2026-10-27', MP_API: '/api/mp' } });
const mph = fs.readFileSync(path.join(MPOUT, 'index.html'), 'utf8'), id = page.simId(mp.html);
for (const l of mine) assert.ok(mph.includes(l), `the multiplayer page has "${l.slice(0, 60)}…"`);
assert.match(mph, new RegExp(`const SIM_ID='${id}';`), 'stamped with its build id');
assert.equal(JSON.parse(fs.readFileSync(path.join(MPOUT, 'version.json'), 'utf8')).simId, id, 'which version.json names too');
} finally { fs.rmSync(MPOUT, { recursive: true, force: true }); }
});
test('pages: only the release workflow deploys, and only with the GitHub Pages actions', () => { test('pages: only the release workflow deploys, and only with the GitHub Pages actions', () => {
const dir = path.join(root, '.github', 'workflows'); const dir = path.join(root, '.github', 'workflows');
for (const f of fs.readdirSync(dir)) { for (const f of fs.readdirSync(dir)) {

View file

@ -105,14 +105,3 @@ test('old saves with inbox, max-prefix and Large Peering Model state load and pl
assert.equal(ev('__o.pdeskRep'), null); assert.equal(ev('__o.pdeskRep'), null);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('max-prefix incidents can no longer fire', () => {
const { ev, errors } = load();
setup(ev);
assert.equal(ev("failureRun.toString().includes('maxpfx')"), false);
ev("S.day=100;const src=failureRun.toString().replace(/^function\* failureRun/,'function*').replace('let tot=opts.reduce',\"opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce\");window.__ff=eval('('+src+')')");
ev("__reseed(7);for(let i=0;i<200;i++){runNow(__ff());S.inc=S.inc.filter(x=>x.type!=='maxpfx'||(window.__mp=1,0));}");
assert.equal(ev('!!window.__mp'), false);
assert.equal(ev("typeof inboxDay+typeof ibx+typeof ACT.inboxRaiseAll+typeof ACT.inboxBot"), 'undefinedundefinedundefinedundefined');
assert.deepEqual(errors, []);
});

View file

@ -127,23 +127,6 @@ test('launches fill crusts, the party is billed, heavy test flights explode', ()
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('O5: launches only fail with chaos on, and never in the first 90 days', () => {
const run = (after) => {
const { ev } = load();
won(ev); company(ev);
ev(`S.day=S.pie.born+${after};Math.random=()=>0`); // the unluckiest dice there are
ev("ACT.pieLaunch({rk:'falcon',cr:'short'});S.pie.q[0].day=S.day;pieDay(S.day)");
return ev("pieLive('short')");
};
assert.equal(run(10), 20, 'quiet days');
assert.equal(run(120), 0, 'chaos can lose a launch');
const { ev } = load();
sandbox(ev);
company(ev);
ev("S.day=500;S.pie.pads[0].next=0;Math.random=()=>0;ACT.pieLaunch({rk:'falcon',cr:'short'});S.pie.q[0].day=S.day;pieDay(S.day)");
assert.equal(ev("pieLive('short')"), 20, 'chaos none: nothing fails');
});
test('cohorts wear out over the end of their life, and a crust carries a share from 40%, all of it from 60%', () => { test('cohorts wear out over the end of their life, and a crust carries a share from 40%, all of it from 60%', () => {
const { ev, errors } = load(); const { ev, errors } = load();
won(ev); won(ev);
@ -186,7 +169,9 @@ test('promises slip a year and get broken', () => {
won(ev); won(ev);
company(ev); company(ev);
assert.equal(ev('S.pie.founder.promises'), 1); assert.equal(ev('S.pie.founder.promises'), 1);
ev('for(let i=0;i<361;i++)dayTick()'); assert.ok(ev('S.pie.founder.due[0]-S.day') >= 359, 'due a year from the promise');
// Then a year passes: rather than play 360 days, the due date moves to tomorrow.
ev('S.pie.founder.due[0]=S.day+1;for(let i=0;i<2;i++)dayTick()');
assert.equal(ev('S.pie.founder.broken'), 1); assert.equal(ev('S.pie.founder.broken'), 1);
assert.ok(ev("S.pie.founder.posts.some(p=>p.k==='pie.fp_slip')")); assert.ok(ev("S.pie.founder.posts.some(p=>p.k==='pie.fp_slip')"));
assert.match(ev('pieFpText(S.pie.founder.posts[0])'), /\w/); assert.match(ev('pieFpText(S.pie.founder.posts[0])'), /\w/);

View file

@ -166,11 +166,6 @@ test('F4: the chaos monkey snips a laser link while it visits, healed within a w
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('the booster that falls over on the drone ship is the foundation\'s', () => {
const { ev } = load();
assert.ok(ev("pieFly.toString().includes('fp_booster')"));
});
test('sanitize drops orbit incidents that make no sense, and old saves are untouched', () => { test('sanitize drops orbit incidents that make no sense, and old saves are untouched', () => {
const { ev, errors } = load(); const { ev, errors } = load();
sky(ev); sky(ev);

View file

@ -121,7 +121,7 @@ test('the global batch, now in the Ops sheet, preserves scope, keyboard focus an
select.dispatchEvent(new dom.window.Event('change', { bubbles: true })); select.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
assert.equal(doc.activeElement, doc.querySelector('#modalCard select')); assert.equal(doc.activeElement, doc.querySelector('#modalCard select'));
const submit = doc.querySelector('#modalCard [data-act="pniAll"]'); const submit = doc.querySelector('#modalCard [data-act="pniAll"]');
assert.deepEqual(JSON.parse(submit.dataset.args), { net: null, tier: 0 }, lang); assert.deepEqual(JSON.parse(submit.dataset.args), { net: null, tier: 0, q: ev('pniBatch(null,0).cost') }, lang);
assert.equal(submit.disabled, false, lang); assert.equal(submit.disabled, false, lang);
assert.ok(doc.querySelectorAll('#modalCard details').length > 0, 'long lists are collapsed'); assert.ok(doc.querySelectorAll('#modalCard details').length > 0, 'long lists are collapsed');
assert.equal(ev('S.cash'), cash, 'preview does not buy anything'); assert.equal(ev('S.cash'), cash, 'preview does not buy anything');

View file

@ -1021,7 +1021,8 @@ test('Down Under: routers upside down, BrisVegas, Next-Door-DC and everything tr
assert.match(ev("siteName('bne','b')"), /^Next-Door-DC B[12]$/); assert.match(ev("siteName('bne','b')"), /^Next-Door-DC B[12]$/);
assert.equal(ev("siteName('cbr','b')"), 'Next-Door-DC C1'); assert.equal(ev("siteName('cbr','b')"), 'Next-Door-DC C1');
// everything is trying to kill you: the new outages can come up on Australian links and POPs // everything is trying to kill you: the new outages can come up on Australian links and POPs
const src = ev("document.documentElement.innerHTML"); // (The game's English text, where the outages are written; the page once carried it in its <script>.)
const src = ev("JSON.stringify(I18N.en)");
for (const s of ['drop bear', 'eastern brown snake', 'Magpie swooping', 'Box jellyfish', 'Vegemite as thermal paste', 'brought Marmite', 'four o’clock storm']) assert.ok(src.includes(s), s); for (const s of ['drop bear', 'eastern brown snake', 'Magpie swooping', 'Box jellyfish', 'Vegemite as thermal paste', 'brought Marmite', 'four o’clock storm']) assert.ok(src.includes(s), s);
assert.match(ev("ixName('syd~2')"), /At-The-Edge/); assert.match(ev("XIX.find(x=>x.id==='syd~2').blurb"), /Vegemite/); assert.match(ev("ixName('syd~2')"), /At-The-Edge/); assert.match(ev("XIX.find(x=>x.id==='syd~2').blurb"), /Vegemite/);
ev('cam.z=2;draw(0);cam.z=0.4;draw(0)'); ev('cam.z=2;draw(0);cam.z=0.4;draw(0)');

View file

@ -22,8 +22,10 @@ test('#157 a POP can grow past six routers, with a cage extension', () => {
assert.equal(withCage - without, ev('ROUTER_MO+RG[S.pops.fra.rgen||0].mo+CAGE_MO'), 'the cage extension is billed monthly'); assert.equal(withCage - without, ev('ROUTER_MO+RG[S.pops.fra.rgen||0].mo+CAGE_MO'), 'the cage extension is billed monthly');
ev("S.pops.fra.routers=7;compute()"); ev("S.pops.fra.routers=7;compute()");
assert.ok(ev('nodeCap("fra")') === ev('RG[S.pops.fra.rgen||0].cap*7'), 'every router adds forwarding'); assert.ok(ev('nodeCap("fra")') === ev('RG[S.pops.fra.rgen||0].cap*7'), 'every router adds forwarding');
ev("UI.sel={k:'city',id:'fra'};renderAll()"); // The routers live on the city's Infra tab. (Not the whole body: that once held the game's source, dictionary
assert.match(dom.window.document.body.innerHTML, /Cage extension/); // and all, so a phrase was always found there.)
ev("UI.sel={type:'city',id:'fra'};UI.tab='links';renderAll()");
assert.match(dom.window.document.getElementById('panel').innerHTML, /Cage extension/);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });

View file

@ -0,0 +1,389 @@
// What server-run play needs from the game before it is built (the server-sim design, track T1): new games in two
// halves (beginState/beginHello/beginShow), the tutorial's state apart from its box (tutAdvance/coachDom), a toast on
// screen without its log line (toastPop), the boot's one-shot notes in bootNotes(), the five acts that read a typed
// field taking the text as an argument, srvOn() and its two checks in the loop, mpSanitize keeping sim, the quote checks,
// and the multiplayer-only client folder left out of every other page. None of it changes play in any build.
// T1_BASE=<git ref> also compares the refactors with the page at that ref (before them): same state, same screen.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { load } = require('./harness');
const { assemble, assembleRef, simId, MP_ONLY, ROOT } = require('../scripts/lib/page');
const { lit } = require('../scripts/lib/js-literal');
const BASE = process.env.T1_BASE;
let baseHtml = null;
const baseFile = () => { if (!baseHtml) { baseHtml = path.join(os.tmpdir(), `tubes-t1-base-${process.pid}.html`); fs.writeFileSync(baseHtml, assembleRef(BASE)); } return baseHtml; };
// The pages to compare: this one, and the base page when T1_BASE is set.
const pages = (opts = {}) => [load(opts), ...(BASE ? [load({ ...opts, file: baseFile() })] : [])];
const pin = 'Date.now=()=>1.7e12;';
// What the player sees: the toasts (without their birth time), the panel, the HUD, a window, the coach. (Without the
// label ids the shipped base page writes into data-i18n attributes: the words are compared.)
const screen = (ev) => ev(`JSON.stringify({toasts:$('toasts').innerHTML,panel:$('panel').innerHTML,hud:$('hud').innerHTML,
modal:$('modal').hidden?'':$('modalCard').innerHTML,coach:$('coach').hidden?'':$('coach').innerHTML,glow:document.querySelectorAll('.coach-glow').length})`)
.replace(/ data-born=\\"[^"\\]*\\"/g, '').replace(/ data-i18n[-a-z]*=\\"[^"\\]*\\"/g, '');
// The game as a reload makes it, keys in order: what "the same game as before" means across this change, which writes
// the fields a reload fills in when it creates things (tests/canonical-state.test.js).
// stamp: false leaves out when log lines were written and their ids (a boot runs before a test can pin the clock).
const canon = (ev, stamp = true) => ev(`(()=>{const u=uidN,r=S.rng,k=v=>Array.isArray(v)?v.map(k):v&&typeof v==='object'?Object.keys(v).sort().reduce((o,x)=>(o[x]=k(v[x]),o),{}):v;
try{const s=migrate(JSON.parse(JSON.stringify(S)));if(!${stamp})for(const e of s.log)delete e.at,delete e.id;return JSON.stringify(k(s));}finally{uidN=u;S.rng=r;}})()`);
const M = { code: 'K7Q2XD', pid: 'abcd1234', asn: 201234, seed: 424242, preset: 'bgp', color: '#3a86ff', title: 'Friday' };
test('a new network in halves: the server path (beginState, compute, beginHello, then beginShow with srv) gives the page the same game and screen as beginGame', (t) => {
const A = load(), B = load();
t.after(() => { A.dom.window.close(); B.dom.window.close(); });
for (const h of [A, B]) h.ev(pin + 'UI.pitched=true;UI.asnTxt="";');
A.ev(`beginGame('Packet Pals','fra',{mode:'normal',preset:'bgp',mp:${lit(M)}})`);
// The server: the state, its marks, its routing and its welcome; no screen, no storage.
const keys0 = B.ev('Object.keys(localStorage).sort().join()'), toasts0 = B.ev("$('toasts').children.length"), started0 = B.ev('UI.started');
B.ev(`beginState('Packet Pals','fra',{mode:'normal',preset:'bgp',mp:${lit(M)},asn:201234})`);
assert.equal(B.ev('Object.keys(localStorage).sort().join()'), keys0, 'beginState stores nothing');
assert.equal(B.ev("$('toasts').children.length"), toasts0, 'and shows nothing');
assert.equal(B.ev('UI.started'), started0, 'nor starts the clock');
B.ev('S.mp.sim=1;S.tut=null;compute();beginHello();');
// The page: makes its slot for the network, then shows it, without routing it again, a second welcome or a tutorial.
B.ev(`slotLeave();slotNew();window.__c=0;const c0=compute;compute=()=>{__c++;c0();};beginShow('fra',{mode:'normal',preset:'bgp',mp:${lit(M)},srv:true});compute=c0;`);
assert.equal(B.ev('__c'), 0, 'the page does not route a server network');
const plain = (ev) => ev('JSON.stringify({...S,tut:undefined,mp:{...S.mp,sim:undefined}})');
assert.equal(plain(B.ev), plain(A.ev), 'the same game');
assert.equal(B.ev("S.log.filter(e=>/Welcome/.test(e.t)).length"), 1, 'one welcome in the log');
assert.equal(screen(B.ev), screen(A.ev), 'the same screen');
assert.equal(B.ev('S.mp.sim'), 1);
assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []);
});
test('a new game from the title still starts as it did: Normal, sandbox, a scenario', (t) => {
for (const how of ["UI.preset='bgp';ACT.start({})", "ACT.modeSet({m:'sandbox'});ACT.start({})", 'ACT.startScn({id:SCN[0].id})']) {
const P = pages();
t.after(() => P.forEach((h) => h.dom.window.close()));
for (const h of P) h.ev(pin + `UI.pitched=true;${how};`);
assert.ok(P[0].ev('!!S&&UI.started'), how);
for (const h of P.slice(1)) {
assert.equal(canon(h.ev), canon(P[0].ev), `${how}: the same game as before`);
assert.equal(screen(h.ev), screen(P[0].ev), `${how}: the same screen as before`);
}
for (const h of P) assert.deepEqual(h.errors, []);
}
});
test('the coach: tutAdvance moves S.tut on and draws nothing, coachDom draws and changes nothing; renderCoach is the two', (t) => {
const P = pages();
t.after(() => P.forEach((h) => h.dom.window.close()));
const steps = ["ACT.launchBB({city:'fra'})", "ACT.buyTransit({city:'fra',net:'cog',tier:1})", "ACT.buyIx({city:'fra',tier:0,signed:true});ACT.rs({city:'fra'})",
'for(let i=0;i<6;i++)dayTick();renderAll()', "ACT.buildPop({city:'ams'});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0})", "for(let i=0;i<40&&!S.biz.length;i++){dayTick();if(S.offers[0])ACT.accept({id:S.offers[0].id});}renderAll()"];
for (const h of P) h.ev(pin + "window.__TUBES_TUT__=true;UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;UI.speed=0;S.cash=1e7;");
assert.equal(P[0].ev('S.tut'), 0, 'the tutorial started');
const coach = (ev) => ev("$('coach').hidden+'|'+$('coach').innerHTML+'|'+document.querySelectorAll('.coach-glow').length");
for (const s of steps) {
for (const h of P) h.ev(s);
const ev = P[0].ev;
// The two halves on their own, on this page.
const box = coach(ev), st = ev('JSON.stringify(S)');
ev('coachDom()');
assert.equal(ev('JSON.stringify(S)'), st, `${s}: coachDom changes no state`);
const tut = ev('S.tut');
ev("window.__box=$('coach').innerHTML;tutAdvance()");
assert.equal(ev("$('coach').innerHTML===__box"), true, `${s}: tutAdvance draws nothing`);
assert.equal(ev('S.tut'), tut, `${s}: renderAll already advanced it`);
assert.equal(coach(ev), box);
for (const h of P.slice(1)) {
assert.equal(h.ev('S.tut'), tut, `${s}: the same step as before`);
assert.equal(coach(h.ev), box, `${s}: the same coach as before`);
}
}
assert.equal(P[0].ev('S.tut'), null, 'the tutorial ran to its end');
assert.match(P[0].ev('S.log[0].t+S.log[1].t+S.log[2].t'), /basics/, 'and said so');
for (const h of P) assert.deepEqual(h.errors, []);
});
test('toastPop shows a toast without its log line; toast() is the log line and toastPop, quiet days included', (t) => {
const { ev, errors, dom } = load();
t.after(() => dom.window.close());
ev(pin + "UI.pitched=true;ACT.start({});closeModal();$('toasts').innerHTML='';");
const n0 = ev('S.log.length');
ev("toastPop('<b>Hi</b> there','good',[{l:'Open',act:'leftTab',args:{t:'noc'}}])");
assert.equal(ev('S.log.length'), n0, 'no log line');
assert.match(ev("$('toasts').innerHTML"), /<b>Hi<\/b> there.*data-act="leftTab"/);
ev("toast('Logged too','good')");
assert.equal(ev('S.log.length'), n0 + 1);
// Quiet notifications: what a day says (tick) pops up only for trouble and milestones.
ev("$('toasts').innerHTML='';window.__q=PREFS.quiet;PREFS.quiet=true;toastPop('a day note','',[],true);toastPop('not a day','',[],false);toastPop('trouble','bad',[],true);PREFS.quiet=__q");
assert.equal(ev("$('toasts').children.length"), 2, 'the quiet day note stays in the log only');
assert.deepEqual(errors, []);
});
// A save that has both boot notes to say: new networks on the map since it was saved, and Australia's prices.
function notesSave() {
const { ev, dom } = load();
try {
ev(pin + "UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;closeModal();ACT.buildPop({city:'syd'});for(let i=0;i<5;i++)dayTick();S.seen=S.seen.slice(3);delete S.auV;");
return ev('JSON.stringify(packSave(S))');
} finally { dom.window.close(); }
}
test('bootNotes: a reopened network says once that new networks are on the map and that Australia changed, as the boot always did', (t) => {
const txt = notesSave();
const P = pages({ storage: { 'sot-save-v1': txt } });
t.after(() => P.forEach((h) => h.dom.window.close()));
const ev = P[0].ev;
assert.equal(ev('typeof bootNotes'), 'function');
assert.equal(ev('S.grace.told'), 1, 'the courtesy route was announced');
assert.equal(ev("'auNews' in S"), false, 'Australia was announced');
const said = ev("S.log.slice(0,3).map(e=>e.t).join(' | ')");
assert.match(said, /new networks/i);
assert.match(said, /Australia/i);
ev('bootNotes()');
assert.equal(ev("S.log.slice(0,3).map(e=>e.t).join(' | ')"), said, 'once only');
for (const h of P.slice(1)) {
assert.equal(canon(h.ev, false), canon(ev, false), 'the same as before');
assert.equal(screen(h.ev), screen(ev));
}
// Declared before the multiplayer client's folder, so that folder can rebind it.
const { map } = assemble({ mp: true });
const where = map.find((m) => fs.readFileSync(path.join(ROOT, 'src', m.file), 'utf8').includes('function bootNotes('));
assert.ok(where && where.file < 'game/98-server-play/', `bootNotes() is in ${where && where.file}`);
for (const h of P) assert.deepEqual(h.errors, []);
});
test('the five acts that read a typed field take the text as an argument first: the same game either way', (t) => {
const setup = pin + "UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;closeModal();S.cash=1e8;S.lvl=4;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});" +
"ACT.buildPop({city:'ams'});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0});closeModal();S.te={on:true,day:0};compute();";
const script = 'prefer cog at fra';
const cases = [
['renameGo', "ACT.rename();$('rnIn').value=' Tubular Bells ';ACT.renameGo({})", "closeModal();ACT.renameGo({name:' Tubular Bells '})", 'S.name'],
['metricSet', "ACT.setMetric({id:S.links[0].id,v:'custom'});UI.sel={type:'link',id:S.links[0].id};renderPanel();$('metIn').value='2.5';ACT.metricSet({id:S.links[0].id})",
"ACT.setMetric({id:S.links[0].id,v:'custom'});ACT.metricSet({id:S.links[0].id,v:'2.5'})", 'JSON.stringify(S.pairMet)'],
['teDeploy', `ACT.teEdit();$('teSrc').value=${lit(script)};ACT.teDeploy({})`, `closeModal();ACT.teDeploy({script:${lit(script)}})`, 'JSON.stringify(S.te)'],
];
for (const [act, field, arg, pick] of cases) {
const A = load(), B = load();
t.after(() => { A.dom.window.close(); B.dom.window.close(); });
A.ev(setup); B.ev(setup);
A.ev(field); B.ev(arg);
assert.equal(B.ev(pick), A.ev(pick), `${act}: what it changed`);
assert.equal(B.ev('JSON.stringify(S)'), A.ev('JSON.stringify(S)'), `${act}: the whole game`);
assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []);
}
{
const D = load();
t.after(() => D.dom.window.close());
assert.equal(D.ev(setup + "ACT.rename();$('rnIn').value='Tubular Bells';ACT.renameGo({});S.name"), 'Tubular Bells');
}
// teCheck: the same report from the argument as from the editor.
{
const A = load(), B = load();
t.after(() => { A.dom.window.close(); B.dom.window.close(); });
A.ev(setup + `ACT.teEdit();$('teSrc').value=${lit(script)};ACT.teCheck({})`);
B.ev(setup + `closeModal();ACT.teCheck({script:${lit(script)}})`);
assert.match(A.ev("$('modalCard').textContent"), /rule/);
assert.equal(B.ev("$('modalCard').querySelector('pre').textContent"), A.ev("$('modalCard').querySelector('pre').textContent"));
assert.equal(B.ev('JSON.stringify(S)'), A.ev('JSON.stringify(S)'));
}
// pieRename: the rocket company's name, in a sandbox (where anyone may found one).
{
const pie = pin + "UI.pitched=true;ACT.modeSet({m:'sandbox'});ACT.start({});closeModal();ACT.pieFound();closeModal();";
const A = load(), B = load();
t.after(() => { A.dom.window.close(); B.dom.window.close(); });
A.ev(pie); B.ev(pie);
assert.ok(A.ev('!!(S.pie&&S.pie.co)'), 'a rocket company');
A.ev("UI.pieTab='co';ACT.pieOpen()");
assert.ok(A.ev("!!$('pieNm')"), 'the name field is on screen');
A.ev("$('pieNm').value=' Orbit Pie ';ACT.pieRename({})");
B.ev("closeModal();ACT.pieRename({name:' Orbit Pie '})");
assert.equal(A.ev('S.pie.co.name'), 'Orbit Pie');
assert.equal(B.ev('JSON.stringify(S)'), A.ev('JSON.stringify(S)'));
assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []);
}
// Without the argument and without the field, nothing happens, as before.
const C = load();
t.after(() => C.dom.window.close());
C.ev(setup + "closeModal();window.__s=JSON.stringify(S);ACT.renameGo({});ACT.metricSet({id:S.links[0].id});ACT.pieRename({});");
assert.equal(C.ev('JSON.stringify(S)===__s'), true);
});
test('the field paths of the five acts play as before', { skip: !BASE && 'set T1_BASE to compare with the page before' }, (t) => {
const setup = pin + "UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;closeModal();S.cash=1e8;S.lvl=4;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});" +
"ACT.buildPop({city:'ams'});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0});closeModal();S.te={on:true,day:0};compute();" +
"ACT.rename();$('rnIn').value='Tubular Bells';ACT.renameGo({});ACT.setMetric({id:S.links[0].id,v:'custom'});UI.sel={type:'link',id:S.links[0].id};renderPanel();$('metIn').value='2.5';ACT.metricSet({id:S.links[0].id});" +
"ACT.teEdit();$('teSrc').value='prefer cog at fra';ACT.teCheck({});ACT.teDeploy({});";
const P = pages();
t.after(() => P.forEach((h) => h.dom.window.close()));
for (const h of P) h.ev(setup);
assert.equal(canon(P[1].ev), canon(P[0].ev));
});
test('srvOn(): false in every page this track ships; a server-play folder that says yes keeps the loop and the boot from running the network', (t) => {
// The plain page and the MP page with only the folder's placeholder: the stub, and a network with sim plays locally.
for (const opts of [{}, { mp: true }]) {
const { ev, errors, dom } = load(opts);
t.after(() => dom.window.close());
assert.equal(ev('srvOn()'), false);
assert.deepEqual(errors, []);
}
// A page whose folder rebinds srvOn (as the real client will) and opens a server network's mirror.
const src = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-srv-src-'));
t.after(() => fs.rmSync(src, { recursive: true, force: true }));
fs.cpSync(path.join(ROOT, 'src'), src, { recursive: true });
fs.writeFileSync(path.join(src, 'game', '98-server-play', '50-t1-test.js'), 'srvOn=()=>!!(S&&S.mp&&S.mp.sim===1);bootNotes=()=>{window.__notes=(window.__notes||0)+1;};\n');
const file = path.join(src, 'page.html');
fs.writeFileSync(file, assemble({ src, mp: true }).html.replace("/*__MP_API__*/''", "'/api/mp'"));
const mk = load();
t.after(() => mk.dom.window.close());
mk.ev(pin + `UI.pitched=true;beginState('Packet Pals','fra',{mode:'normal',preset:'oncall',mp:${lit(M)}});S.mp.sim=1;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});compute();`);
const txt = mk.ev('JSON.stringify(packSave(S))');
const run = (ev) => { ev("closeModal();UI.speed=8;let t=performance.now();for(let i=0;i<40;i++){t+=200;frame(t);}"); return ev('S.day'); };
{
const { ev, errors, dom } = load({ file, storage: { 'sot-save-v1': txt } });
t.after(() => dom.window.close());
assert.equal(ev('S.mp.sim'), 1, 'mpSanitize kept sim');
assert.equal(ev('srvOn()'), true);
assert.equal(ev('R.served'), 0, 'the boot did not route it (the server does)');
assert.equal(ev('window.__notes'), 1, 'the boot called the rebound bootNotes');
const d0 = ev('S.day');
assert.equal(run(ev), d0, 'no day ran on this page');
assert.deepEqual(errors, []);
}
{
// The same save in the page this track ships: a sim network nobody runs for it plays here, as phase 1 does.
const { ev, errors, dom } = load({ storage: { 'sot-save-v1': txt } });
t.after(() => dom.window.close());
assert.ok(ev('R.served') > 0, 'routed at boot');
const d0 = ev('S.day');
assert.ok(run(ev) > d0, 'and days run');
assert.deepEqual(errors, []);
}
});
test('mpSanitize keeps sim:1 and nothing else in its place', (t) => {
const { ev, errors, dom } = load();
t.after(() => dom.window.close());
ev(pin + `UI.pitched=true;ACT.start({});closeModal();S.mp=${lit({ ...M, seq: 3 })};`);
const back = (sim) => JSON.parse(ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.mp.sim=${lit(sim)};return JSON.stringify(migrate(s).mp);})()`));
assert.equal(back(1).sim, 1);
for (const v of [2, '1', true, null, { x: 1 }]) assert.equal('sim' in back(v), false, JSON.stringify(v));
assert.equal('sim' in JSON.parse(ev('JSON.stringify(migrate(JSON.parse(JSON.stringify(S))).mp)')), false, 'a phase-1 network has none');
assert.deepEqual(errors, []);
});
test('quote checks: a bulk order whose total changed under its window is shown again, not bought', (t) => {
const { ev, errors, dom } = load();
t.after(() => dom.window.close());
ev(pin + "UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;closeModal();S.cash=1e9;S.lvl=6;for(const c of ['fra','ams','lon','par'])ACT.buildPop({city:c});compute();");
// pniAll: the sheet's button carries the total it shows.
ev("ACT.pniAllOpen({net:null})");
const args = JSON.parse(ev(`$('modalCard').querySelector('[data-act="pniAll"]').dataset.args`));
assert.equal(args.q, ev(`pniBatch(null,${args.tier}).cost`), 'the button carries the quoted total');
const n0 = ev('S.pni.length'), c0 = ev('S.cash');
ev(`ACT.pniAll(${lit({ ...args, q: args.q + 1 })})`);
assert.equal(ev('S.pni.length'), n0, 'a changed total buys nothing');
assert.equal(ev('S.cash'), c0);
assert.match(ev("$('modalCard').textContent"), /quote changed/i, 'the sheet says why, with the new total');
ev(`ACT.pniAll(${lit(args)})`);
assert.ok(ev('S.pni.length') > n0, 'the shown total buys');
// Without q (the agent, older callers): as before.
ev("closeModal();ACT.buildPop({city:'nyc'});window.__n=S.pni.length;ACT.pniAll({net:null,tier:1})");
assert.ok(ev('S.pni.length') > ev('__n'));
// A sheet whose batch was ordered meanwhile (another tap, the intern): shown again, not a silent nothing.
ev("ACT.pniAllOpen({net:null})");
const gone = JSON.parse(ev(`$('modalCard').querySelector('[data-act="pniAll"]').dataset.args`));
ev(`closeModal();ACT.pniAll(${lit({ net: gone.net, tier: gone.tier })});window.__n=S.pni.length;ACT.pniAll(${lit(gone)})`);
assert.equal(ev('S.pni.length'), ev('__n'));
assert.match(ev("$('modal').hidden?'':$('modalCard').textContent"), /quote changed/i, 'an emptied plan says so');
// bstdApply: the build standard's "Bring everything up now" carries the plan it shows (its key) and its total.
ev("closeModal();S.popStd=bstdPut({...bstd(),rt:2});ACT.bstdOpen()");
const b = JSON.parse(ev(`$('modalCard').querySelector('[data-act="bstdApply"]').dataset.args`));
assert.deepEqual(b, JSON.parse(ev('JSON.stringify({quote:bstdPlanKey(bstdPlan(false)),q:bstdQuote(false).cost})')));
const rts = "JSON.stringify(Object.values(S.pops).map(p=>p.routers))", r0 = ev(rts);
ev(`ACT.bstdApply(${lit({ ...b, quote: b.quote + 'x' })})`);
assert.equal(ev(rts), r0, 'another plan builds nothing');
assert.match(ev("$('modalCard').textContent"), /quote changed/i);
ev(`closeModal();ACT.bstdApply(${lit({ ...b, q: Math.round(b.q * 0.9) })})`);
assert.equal(ev(rts), r0, 'a total 10% away builds nothing');
assert.match(ev("$('modalCard').textContent"), /quote changed/i);
// Hardware prices drift a little every day under the market rule: the same plan a day later still builds.
ev(`closeModal();ACT.bstdApply(${lit({ ...b, q: b.q + 1 })})`);
assert.notEqual(ev(rts), r0, 'the shown plan builds, at today\'s prices');
ev(`ACT.bstdApply(${lit(b)})`);
assert.match(ev("$('modal').hidden?'':$('modalCard').textContent"), /quote changed/i, 'and once it is all done, the old sheet is shown again');
// The two that always checked: utilityKit (cost) and utilityCaches (quote).
ev("closeModal();window.__s=JSON.stringify(S);ACT.utilityKit({city:'fra',cost:-1,modal:true});ACT.utilityCaches({city:'fra',quote:'nope',modal:true})");
assert.equal(ev('JSON.stringify(S)===__s'), true);
// utilityKit takes a day's drift too (the kit's router is priced by the market), not a whole part of the kit.
ev("closeModal();ACT.buildPop({city:'mad'});window.__k=utilityKit('mad').cost;ACT.utilityKit({city:'mad',cost:__k+GEN_COST})");
assert.equal(ev('S.pops.mad.gen'), false);
ev('ACT.utilityKit({city:\'mad\',cost:__k+1})');
assert.equal(ev('S.pops.mad.gen&&S.pops.mad.site2&&S.pops.mad.routers===2'), true);
assert.deepEqual(errors, []);
});
test('quote checks hold on a server-run day: the build standard\'s plan a few days old still builds, while hardware prices drift', (t) => {
// The review's case: routers on the big network, the market rule on; every day moves the total a little.
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
const { ev, errors, dom } = load({ seed: 77 });
t.after(() => dom.window.close());
ev(`${pin}S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.lvl=Math.max(S.lvl,6);S.rules=makeRules('oncall');
S.nextFail=S.nextEvent=1e9;S.day=400;S.cash=1e10;compute();S.popStd=bstdPut({...bstd(),rt:8});ACT.bstdOpen();`);
assert.equal(ev("rule('market')"), true);
const b = JSON.parse(ev(`$('modalCard').querySelector('[data-act="bstdApply"]').dataset.args`));
ev('closeModal();for(let i=0;i<3;i++){S.cash=1e10;dayTick();}');
assert.notEqual(ev('bstdQuote(false).cost'), b.q, 'the total moved');
assert.equal(ev('bstdPlanKey(bstdPlan(false))'), b.quote, 'the plan did not');
const r0 = ev("Object.values(S.pops).reduce((a,p)=>a+(p.routers||1),0)");
ev(`ACT.bstdApply(${lit(b)})`);
assert.ok(ev("Object.values(S.pops).reduce((a,p)=>a+(p.routers||1),0)") > r0, 'and it builds');
assert.deepEqual(errors, []);
});
test('the multiplayer client folder and its CSS are in an MP page only, and SIM_ID is its build id', (t) => {
const plain = assemble(), mp = assemble({ mp: true });
const only = (f) => MP_ONLY.some((p) => (p.endsWith('/') ? f.startsWith(p) : f === p));
assert.deepEqual(plain.map.filter((m) => only(m.file)), [], 'the plain page has none of it');
const mine = mp.map.filter((m) => only(m.file));
assert.ok(mine.some((m) => m.file.startsWith('game/98-server-play/')) && mine.some((m) => m.file === 'styles/43-server-play.css'), 'the MP page has both');
// The MP page is the plain page plus exactly those files.
const lines = mp.html.split('\n'), drop = new Set();
for (const m of mine) for (let i = m.from; i <= m.to; i++) drop.add(i);
assert.equal(lines.filter((l, i) => !drop.has(i + 1)).join('\n'), plain.html);
assert.equal(assemble({ dev: true }).map.filter((m) => only(m.file)).length, 0, 'nor the development page without mp');
// The build id: 12 hex digits of the MP page, a new one for any change.
assert.match(simId(), /^[0-9a-f]{12}$/);
assert.equal(simId(), simId(mp.html));
assert.notEqual(simId(mp.html + ' '), simId(mp.html));
assert.match(plain.html, /const SIM_ID=\/\*__SIM_ID__\*\/'';/, 'unstamped in the source');
const h = load({ mp: true });
t.after(() => h.dom.window.close());
assert.equal(h.ev('SIM_ID'), simId(), 'load({mp:true}) is a stamped MP page');
assert.equal(h.ev('MP_API'), '/api/mp');
assert.deepEqual(h.errors, []);
});
test('the translation check reads the server-play client too: a label used only there counts as used', (t) => {
const { page, sourceLabels } = require('../scripts/i18n-check');
const src = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-srv-i18n-'));
t.after(() => fs.rmSync(src, { recursive: true, force: true }));
fs.cpSync(path.join(ROOT, 'src'), src, { recursive: true });
fs.writeFileSync(path.join(src, 'game', '98-server-play', '50-t1-label.js'), "function srvProbe(){return tr('zzsrv.probe_label');}\n");
assert.equal(sourceLabels(page(src)).labels.has('zzsrv.probe_label'), true, 'the checked page has the MP-only folder');
assert.equal(assemble({ src }).html.includes('zzsrv.probe_label'), false, 'and the plain page still has none of it');
});
test('a new POP has its router in its state from the start: a reload keeps the one play had, even under a port it cannot take', (t) => {
// Before canonical state a POP had no rgen until a reload inferred one from its ports: founding an exchange (a tier-2
// port, which foundIx does not check against the router) and reloading gave a free router upgrade. Play always read
// the basic router (RG[p.rgen||0]); now the state says so, and a reload keeps it.
const { ev, errors, dom } = load({ seed: 9 });
t.after(() => dom.window.close());
const out = JSON.parse(ev(`${pin}UI.pitched=true;ACT.start({});closeModal();S.cash=1e8;S.lvl=6;let c=null;
for(const x of Object.keys(CITY)){if(S.pops[x]||!cityOn(x)||cnCity(x))continue;ACT.buildPop({city:x});closeModal();if(S.pops[x]&&!foundIxWhy(x)){c=x;break;}}
ACT.foundIx({city:c});closeModal();const u=uidN,r=S.rng,back=migrate(JSON.parse(JSON.stringify(packSave(S))));uidN=u;S.rng=r;
JSON.stringify({c,live:S.pops[c].rgen,ix:S.ixp[c],reload:back.pops[c].rgen,maxP:RG[0].maxP})`));
assert.ok(out.c, 'a city to found an exchange in');
assert.equal(out.live, 0, 'the basic router, written down');
assert.ok(out.ix > out.maxP, 'an exchange port above what that router takes (foundIx does not check it: its own owner\'s to decide)');
assert.equal(out.reload, 0, 'a reload keeps the router play had');
// An old save's POP without the field still gets the router its ports need.
assert.equal(ev(`(()=>{const s=JSON.parse(JSON.stringify(S));delete s.pops[${lit(out.c)}].rgen;const u=uidN,r=S.rng;try{return migrate(s).pops[${lit(out.c)}].rgen;}finally{uidN=u;S.rng=r;}})()`) > 0, true);
assert.deepEqual(errors, []);
});

View file

@ -37,7 +37,8 @@ test('kit is all-or-nothing, rejects stale quotes and handles missing PoPs', t =
ev("ACT.utilityKit({city:'fra',cost:quote})"); ev("ACT.utilityKit({city:'fra',cost:quote})");
assert.equal(ev('JSON.stringify(S.pops.fra)'), before); assert.equal(ev('JSON.stringify(S.pops.fra)'), before);
assert.equal(ev('S.cash'), ev('quote-1')); assert.equal(ev('S.cash'), ev('quote-1'));
ev("S.cash=1e8;ACT.utilityKit({city:'fra',cost:quote+1,modal:true})"); // A quote a whole part of the kit away is stale (a day's price drift, within 1%, is not: server-sim-prereqs).
ev("S.cash=1e8;ACT.utilityKit({city:'fra',cost:quote+GEN_COST,modal:true})");
assert.equal(ev('JSON.stringify(S.pops.fra)'), before); assert.equal(ev('JSON.stringify(S.pops.fra)'), before);
assert.match(ev("document.getElementById('modalCard').textContent"), /quote changed/); assert.match(ev("document.getElementById('modalCard').textContent"), /quote changed/);
ev("ACT.utilityKit({city:'not-a-city',cost:0});ACT.utilityKit({city:'ams',cost:0})"); ev("ACT.utilityKit({city:'not-a-city',cost:0});ACT.utilityKit({city:'ams',cost:0})");