arcadible 1.0.29 → 1.0.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,6 +10,7 @@ import { MEDIA, PACKAGED } from "../../config/file.js";
10
10
  import { deployDirMissing, packageIndexMissing, packagePathReserved, packageTooLarge, runnerNotBuilt, unableToFind, } from "../../phrase/index.js";
11
11
  import { ZIP_SIZE } from "../../config/limit.js";
12
12
  import { check, measure } from "./limits.js";
13
+ import { favicon } from "../../util/favicon.js";
13
14
  import { handle, tool } from "../../config/product.js";
14
15
  import { toMb } from "../../util/size.js";
15
16
  import { unsound } from "./unsound.js";
@@ -21,6 +22,8 @@ const resolve = path.resolve;
21
22
  const TOOL = tool;
22
23
  // [declare]
23
24
  const MAIN = "index.html";
25
+ // what browsers ask a build for, which packing adds when it has none
26
+ const FAVICON = "favicon.ico";
24
27
  const MANIFEST = PACKAGED;
25
28
  const OUTPUT = `.${TOOL}/package`;
26
29
  // the folder every build's origin keeps for Arcadible's own files, such as
@@ -87,7 +90,7 @@ function verifyTotal(zip) {
87
90
  // [function]
88
91
  // `deployDir` when the input is deploy_dir, rather than a folder --input
89
92
  // named: a missing deploy_dir means the build hasn't written it.
90
- function pack(name, game, { deployDir, inputPath, mediaPath, onWarning, outputPath, runner, client, }) {
93
+ function pack(name, game, { deployDir, icon, inputPath, mediaPath, onWarning, outputPath, runner, client, }) {
91
94
  const zip = new Zip(name);
92
95
  return pathExists(inputPath)
93
96
  .then((existsInput) => {
@@ -102,7 +105,14 @@ function pack(name, game, { deployDir, inputPath, mediaPath, onWarning, outputPa
102
105
  return zip;
103
106
  })
104
107
  .then(verifyPartial)
105
- .then(() => pathExists(mediaPath))
108
+ .then(async () => {
109
+ // never over the developer's own: only a build without one gets it,
110
+ // so a direct and a git release have the same
111
+ if (!zip.has(FAVICON)) {
112
+ zip.addBuffer(FAVICON, await favicon(icon));
113
+ }
114
+ return pathExists(mediaPath);
115
+ })
106
116
  .then((existsMedia) => {
107
117
  if (existsMedia) {
108
118
  zip.addDir(mediaPath, MEDIA);
@@ -158,6 +168,7 @@ export function packTool({ input, onWarning, output, ...conf }) {
158
168
  const inputPath = resolve(root, input ?? workflow.deploy_dir);
159
169
  return pack(parse(file).name, game, {
160
170
  deployDir: inputPath === deployDir,
171
+ icon: game.icon ? resolve(root, game.icon) : null,
161
172
  inputPath,
162
173
  mediaPath: resolve(root, MEDIA),
163
174
  onWarning,
@@ -12,7 +12,8 @@ import { ARGUMENT_INVALID, DEPLOY_DIR_MISSING, PORT_IN_USE, } from "../../config
12
12
  import { clientNames } from "../../schema/client.js";
13
13
  import { buildCommand } from "../../util/command.js";
14
14
  import { ArcError } from "../../util/error.js";
15
- import { dirFiles } from "../../serve/files.js";
15
+ import { dirFiles, withDefault } from "../../serve/files.js";
16
+ import { favicon } from "../../util/favicon.js";
16
17
  import { given } from "../../parser/given.js";
17
18
  import * as phrase from "../../phrase/index.js";
18
19
  import { media } from "../../parser/media.js";
@@ -254,7 +255,14 @@ export async function serveTool(conf) {
254
255
  if (!(await pathExists(deployDir))) {
255
256
  throw new ArcError(DEPLOY_DIR_MISSING, phrase.deployDirMissing(relative(root, deployDir) || "."));
256
257
  }
257
- const served = await listen({ ...options, files: dirFiles(deployDir) });
258
+ // a build without a favicon.ico is answered with the one arc pack would
259
+ // add, made from the store icon as it is when asked
260
+ const files = withDefault(dirFiles(deployDir), "favicon.ico", async () => {
261
+ const { game: art } = await media(root);
262
+ const icon = art?.["icon"];
263
+ return favicon(typeof icon === "string" ? join(root, icon) : null);
264
+ });
265
+ const served = await listen({ ...options, files });
258
266
  const stop = watchDir(deployDir, () => {
259
267
  served.reload();
260
268
  handler.onReload();
@@ -148,6 +148,11 @@ export default defineCommand({
148
148
  [phrase.playLabel(), `${served.page}/`],
149
149
  [phrase.serveAlone(), served.game],
150
150
  ...(served.runner ? [[phrase.runnerLabel(), served.runner.url]] : []),
151
+ // a game with a function or servers of its own can be played by
152
+ // more than one player: a window each, named by its address
153
+ ...(served.runner || served.forServer
154
+ ? [[phrase.servePlayer(), `${served.page}/?player=Kim`]]
155
+ : []),
151
156
  ...(served.forServer
152
157
  ? [[phrase.serveServer(), `ARCADIBLE_SERVE=${served.page}`]]
153
158
  : []),
@@ -0,0 +1,10 @@
1
+ // the package's own files, in `assets` beside `dist`, since the build copies
2
+ // only what it compiles. Nothing else is imported here, so arc serve's
3
+ // server, which needs nothing else from the CLI, can read it.
4
+ // [import]
5
+ import { join } from "node:path";
6
+ // [declare]
7
+ // the play page's own favicon.ico (app/src/web/arcadible-play/content): the
8
+ // local play page's for a game without a store icon, and a build's when it
9
+ // has neither its own nor a store icon (../util/favicon.ts).
10
+ export const FAVICON = join(import.meta.dirname, "..", "..", "assets", "favicon.ico");
@@ -3,6 +3,13 @@
3
3
  // [import]
4
4
  import { blocks } from "./internal.js";
5
5
  // [function]
6
+ // a function that imports a package that isn't the Function SDK: the
7
+ // Server SDK, for a server of one's own, or the SDK, for a game. A fact, as
8
+ // a warning is: the build goes on.
9
+ export function functionImportWrong({ for: meant, name, }) {
10
+ return blocks(`Your function imports ${name}, which is for ${meant === "game" ? "a game" : "a server of your own"}.`, "A function uses @arcadible/function-sdk.");
11
+ }
12
+ // [function]
6
13
  export function secretRemoveQuestion({ channel, name, }) {
7
14
  return `Remove ${name} from ${channel}? Your function reads nothing for it within a minute.`;
8
15
  }
@@ -43,6 +43,12 @@ export function serveServer() {
43
43
  return "For your server:";
44
44
  }
45
45
  // [function]
46
+ // the label before the play page's address for a second local player: each
47
+ // window opened with `?player=<name>` plays as a player of its own.
48
+ export function servePlayer() {
49
+ return "As another player:";
50
+ }
51
+ // [function]
46
52
  export function playerInvalid() {
47
53
  return "`--player` must be a name, up to 200 characters.";
48
54
  }
@@ -19,27 +19,68 @@ import { ArcError } from "../util/error.js";
19
19
  // origin keeps for Arcadible's own files, which is never served.
20
20
  export const BUILT = join(".arc", "runner", "function.js");
21
21
  export const PACKED = "arcadible/function.js";
22
+ // the package a function uses with Arcadible, and the two it mustn't, each
23
+ // with what it's for: the Server SDK asks for a key a function never has,
24
+ // and the SDK starts a game's client.
25
+ export const FUNCTION_SDK = "@arcadible/function-sdk";
26
+ export const WRONG = {
27
+ "@arcadible/sdk": "game",
28
+ "@arcadible/server-sdk": "server",
29
+ };
22
30
  // [function]
23
31
  // bundles the runner whose code is at `main`, a full path, into `outfile`;
24
32
  // code that isn't there, or doesn't build, fails as a build does.
25
- export async function bundle({ main, outfile, }) {
33
+ //
34
+ // `onPackages`, when given, hears the `@arcadible/` packages the bundle took
35
+ // in, by name, each once, so a build can say when a function imports one
36
+ // that isn't the Function SDK (`misimported`). Nothing passes it yet: what it
37
+ // finds is a warning, a warning has a code, and a code has an entry on the
38
+ // public Errors page, which says nothing of functions until they ship
39
+ // (TODO.md, Agreed next).
40
+ export async function bundle({ main, onPackages, outfile, }) {
26
41
  if (!(await pathExists(main))) {
27
42
  throw new ArcError(BUILD_FAILED, phrase.runnerMissing(main));
28
43
  }
44
+ let inputs;
29
45
  try {
30
- await build({
46
+ const result = await build({
31
47
  bundle: true,
32
48
  conditions: ["workerd", "worker", "browser"],
33
49
  format: "esm",
34
50
  logLevel: "silent",
51
+ metafile: Boolean(onPackages),
35
52
  outfile,
36
53
  platform: "neutral",
37
54
  entryPoints: [main],
38
55
  target: "es2022",
39
56
  });
57
+ inputs = Object.keys(result.metafile?.inputs ?? {});
40
58
  }
41
59
  catch (ex) {
42
60
  throw new ArcError(BUILD_FAILED, phrase.runnerBuildFailed(ex instanceof Error ? ex.message : String(ex)), { cause: ex });
43
61
  }
62
+ onPackages?.(packagesOf(inputs));
44
63
  return outfile;
45
64
  }
65
+ // [function]
66
+ // the `@arcadible/` packages a bundle's inputs come from, by name, each
67
+ // once, in the order first met: an input under `node_modules/@arcadible/<name>/`.
68
+ export function packagesOf(inputs) {
69
+ const names = new Set();
70
+ for (const input of inputs) {
71
+ const found = /(?:^|\/)node_modules\/(@arcadible\/[^/]+)\//u.exec(input.split("\\").join("/"));
72
+ if (found?.[1])
73
+ names.add(found[1]);
74
+ }
75
+ return [...names];
76
+ }
77
+ // [function]
78
+ // of the packages a function took in, those it mustn't use, each with what
79
+ // it's for: a game's (`@arcadible/sdk`) or a server of one's own
80
+ // (`@arcadible/server-sdk`).
81
+ export function misimported(names) {
82
+ return names.flatMap((name) => {
83
+ const meant = WRONG[name];
84
+ return meant ? [{ for: meant, name }] : [];
85
+ });
86
+ }
@@ -12,26 +12,54 @@
12
12
  export const ENTRY_MODULE = "entry.js";
13
13
  export const FUNCTION_MODULE = "function.js";
14
14
  // [declare]
15
- // A runner's calls to Arcadible carry the dispatcher's claim, which the
16
- // dispatcher puts on each request (x-arcadible-claim), and the Server SDK
17
- // reads from the process's environment, where arc serve's address is too.
18
- // Its secrets arrive the same way (x-arcadible-secrets, opened by the
19
- // dispatcher), and are added to what the code is given, `env`. Neither
20
- // header reaches the developer's code.
15
+ // A function's calls to Arcadible go through the transport the entry sets
16
+ // (plan/SERVER-SDK-SPLIT.md, 5), which the Function SDK reads: `fetch(path,
17
+ // init)` sends a request to the server API (`path` after /v1/server, `init`
18
+ // fetch's own), with the newest of the dispatcher's claims as its bearer
19
+ // (x-arcadible-claim, on each request), or under arc serve to its own API
20
+ // with none; it resolves with the answer, and never throws (Arcadible
21
+ // unreached is a 503). `version` is raised whenever the transport gains
22
+ // something, and never goes down: every Function SDK published reads it.
23
+ // Until online Reversi is released on the Function SDK, the entry also
24
+ // keeps the Server SDK's old way: its mark, and the claim and arc serve's
25
+ // address in a `process.env` of the entry's making. A function's secrets
26
+ // arrive as a header too (x-arcadible-secrets, opened by the dispatcher),
27
+ // and are added to what the code is given, `env`. Neither header reaches
28
+ // the developer's code.
21
29
  export const ENTRY = `import handler from "./${FUNCTION_MODULE}";
22
30
  const CLAIM = "x-arcadible-claim";
23
31
  const SECRETS = "x-arcadible-secrets";
24
- // says the code is running as a function, where Arcadible has checked each
25
- // request: the Server SDK's players.primary(request) works only with it
32
+ const API = "https://api.arcadible.com/v1/server";
33
+ // the newest claim, and arc serve's address under it
34
+ let claimed = null;
35
+ let serve = null;
36
+ globalThis[Symbol.for("arcadible.function.api")] = {
37
+ version: 1,
38
+ async fetch(path, init = {}) {
39
+ try {
40
+ const headers = new Headers(init.headers);
41
+ if (!serve && claimed) headers.set("authorization", "Bearer " + claimed);
42
+ const base = serve ? serve + "/_arcadible/v1/server" : API;
43
+ return await fetch(base + path, { ...init, headers });
44
+ } catch {
45
+ return new Response(null, { status: 503 });
46
+ }
47
+ },
48
+ };
49
+ // the old mark, which says the code is running as a function
26
50
  globalThis[Symbol.for("arcadible.function")] = true;
27
51
  export default {
28
52
  async fetch(request, env, ctx) {
29
53
  const process = (globalThis.process ??= {});
30
54
  const set = (process.env ??= {});
31
- if (env.ARCADIBLE_SERVE) set.ARCADIBLE_SERVE = env.ARCADIBLE_SERVE;
55
+ if (env.ARCADIBLE_SERVE) {
56
+ serve = env.ARCADIBLE_SERVE;
57
+ set.ARCADIBLE_SERVE = env.ARCADIBLE_SERVE;
58
+ }
32
59
  const claim = request.headers.get(CLAIM);
33
60
  const secrets = request.headers.get(SECRETS);
34
61
  if (claim) {
62
+ claimed = claim;
35
63
  set.ARCADIBLE_CLAIM = claim;
36
64
  } else {
37
65
  delete set.ARCADIBLE_CLAIM;
@@ -125,11 +125,16 @@ export function client() {
125
125
  });
126
126
  }
127
127
  if (clientNames(table).join(" ").length > MAX_NAMES_LENGTH) {
128
+ // the servers are named only where the manifest lists them, since
129
+ // the docs leave `server_origins` out until it ships (message.ts).
130
+ const servers = table.server_origins?.length
131
+ ? ", with client.server_origins,"
132
+ : "";
128
133
  ctx.addIssue({
129
134
  code: "custom",
130
135
  path: ["outbound_hosts"],
131
136
  ...message("outbound_hosts", [
132
- `Must be, with client.server_origins, at most ${MAX_NAMES_LENGTH.toLocaleString("en-US")} characters together.`,
137
+ `Must be${servers} at most ${MAX_NAMES_LENGTH.toLocaleString("en-US")} characters together.`,
133
138
  ], ISSUE.TOO_LONG),
134
139
  });
135
140
  }
@@ -6,6 +6,7 @@
6
6
  import { createReadStream } from "node:fs";
7
7
  import { readdir, stat } from "node:fs/promises";
8
8
  import { join } from "node:path";
9
+ import { Readable } from "node:stream";
9
10
  // [function]
10
11
  // whether every segment of `segments` is named exactly so in `root`.
11
12
  async function exactCase(root, segments) {
@@ -37,3 +38,26 @@ export function dirFiles(root) {
37
38
  },
38
39
  };
39
40
  }
41
+ // [function]
42
+ // `files`, with `name` at the root answered by `make()` when `files` has
43
+ // none, as a build without a favicon.ico has Arcadible's packing add one.
44
+ // It's made each time it's asked for, so a change to what it's made from
45
+ // shows on the next request.
46
+ export function withDefault(files, name, make) {
47
+ return {
48
+ async find(segments) {
49
+ const found = await files.find(segments);
50
+ if (found || segments.length !== 1 || segments[0] !== name) {
51
+ return found;
52
+ }
53
+ const body = await make();
54
+ return {
55
+ mtime: new Date(),
56
+ open: (range) => Readable.from([
57
+ range ? body.subarray(range.start, range.end + 1) : body,
58
+ ]),
59
+ size: body.length,
60
+ };
61
+ },
62
+ };
63
+ }
@@ -8,9 +8,9 @@
8
8
  // game's store icon, as the play page's does, or Arcadible's.
9
9
  // [import]
10
10
  import { readFile } from "node:fs/promises";
11
- import { join } from "node:path";
12
11
  // [import]
13
12
  import { endWith, pathOf } from "./game.js";
13
+ import { FAVICON } from "../config/asset.js";
14
14
  import { isTable } from "../util/objs.js";
15
15
  import { originOf } from "./ticket.js";
16
16
  import { SCOPES, } from "./values.js";
@@ -36,6 +36,13 @@ export const JWKS = "/.well-known/jwks.json";
36
36
  export const LOGIN = "/_arcadible/api/login";
37
37
  // who a guest logs in as, without `--player` to name one.
38
38
  const LOGIN_NAME = "Player";
39
+ // where a window's own player asks for its tickets and values: a window
40
+ // opened as `/?player=<name>` plays as that local player (or, with no name,
41
+ // a guest), and its page asks under `/_arcadible/as/<id>` (or `.../guest`),
42
+ // since every window shares the page's cookies. One arc serve plays as any
43
+ // number of local players, each with its own id, saves, and values.
44
+ export const AS = "/_arcadible/as";
45
+ const GUEST = "guest";
39
46
  // the server API, as a game's own server reaches Arcadible's with its key
40
47
  // (/v1/server/...): here it needs none, since only this machine can ask.
41
48
  const SERVER = "/_arcadible/v1/server";
@@ -95,11 +102,6 @@ const BODY_MAX = 4096;
95
102
  // the loading screen's art and icon, PNGs, or 404 without.
96
103
  const ART = "/_arcadible/art.png";
97
104
  const ICON_PNG = "/_arcadible/icon.png";
98
- // the play page's own favicon.ico (app/src/web/arcadible-play/content), for a
99
- // game without a store icon, and for /favicon.ico, which browsers ask for.
100
- // It's in the package's `assets`, beside `dist`, since the build copies only
101
- // what it compiles.
102
- export const FAVICON = join(import.meta.dirname, "..", "..", "assets", "favicon.ico");
103
105
  // [declare]
104
106
  // the headers of the page's responses, as the play page's: it's
105
107
  // cross-origin isolated, and nothing frames it.
@@ -167,7 +169,10 @@ export function policy(src) {
167
169
  // with the play page's styles and loading screen; without a host that can,
168
170
  // the page frames the game by itself, and the game stands alone, as off
169
171
  // Arcadible.
170
- export function html(game, pictures = { art: false, icon: false }) {
172
+ export function html(game, pictures = { art: false, icon: false }, opened) {
173
+ // a window named by its address asks under its own path, and offers no
174
+ // log-in: it plays as the player its address names.
175
+ const own = opened ? `${AS}/${opened.player ? opened.player.id : GUEST}` : "";
171
176
  const config = {
172
177
  allow: ALLOW,
173
178
  // the loading screen's art, or the icon, blurred, with none, as the play
@@ -178,21 +183,21 @@ export function html(game, pictures = { art: false, icon: false }) {
178
183
  game: game.id,
179
184
  icon: pictures.icon ? ICON_PNG : null,
180
185
  // where a guest logs in, when the game asks for a log-in
181
- logIn: LOGIN,
186
+ ...(opened ? {} : { logIn: LOGIN }),
182
187
  // who the game runs for: a local player (`arc serve --player`), or null,
183
188
  // a guest.
184
- player: game.player ?? null,
189
+ player: opened ? opened.player : (game.player ?? null),
185
190
  // where the game's runner is, when the project has one
186
191
  runner: game.runner?.url ?? null,
187
192
  sandbox: SANDBOX,
188
193
  src: game.src,
189
194
  // tickets for the game's own servers, from arc serve itself, as the
190
195
  // play page asks its own server
191
- tickets: TICKETS,
196
+ tickets: `${own}${TICKETS}`,
192
197
  title: game.title,
193
198
  // the game's values, from arc serve itself, as the play page asks its
194
199
  // own server
195
- values: VALUES,
200
+ values: `${own}${VALUES}`,
196
201
  version: game.version,
197
202
  };
198
203
  return `<!doctype html>
@@ -266,9 +271,9 @@ function readJson(req, max = BODY_MAX) {
266
271
  // a ticket for one of the game's servers, for the page (the game's host), or
267
272
  // for a shell on this machine. Only JSON is taken: a page elsewhere can't
268
273
  // send that across origins without asking first, and isn't answered. The
269
- // player is the page's own (`game.player`), or, from a shell, the one the
270
- // request names.
271
- async function sendTicket(req, res, { game, playerOf, tickets, }) {
274
+ // player is the window's (`playing`), or, from a shell, the one the request
275
+ // names.
276
+ async function sendTicket(req, res, { playerOf, playing, tickets, }) {
272
277
  const type = ((req.headers["content-type"] ?? "").split(";")[0] ?? "").trim();
273
278
  const data = type.toLowerCase() === "application/json" ? await readJson(req) : null;
274
279
  if (data === null || typeof data !== "object") {
@@ -278,7 +283,7 @@ async function sendTicket(req, res, { game, playerOf, tickets, }) {
278
283
  // a list names no server, and no player.
279
284
  const asked = isTable(data) ? data : {};
280
285
  const named = Object.hasOwn(asked, "player") && !req.headers.origin;
281
- const player = named ? playerOf(asked["player"]) : (game.player ?? null);
286
+ const player = named ? playerOf(asked["player"]) : playing;
282
287
  if (player === false) {
283
288
  res.writeHead(400, HEADERS).end();
284
289
  return;
@@ -323,12 +328,12 @@ async function sendLogIn(req, res, { game, playerOf, tickets, }) {
323
328
  // a game's values, for the page (the game's host), as the play site's route
324
329
  // answers (arcadible-play's /api/games/<game>/values/<verb>, and the API
325
330
  // behind it): the game's call, read, written, removed, or listed, for who
326
- // the page runs the game for. A game reads the developer's and the game's,
331
+ // the page's window runs the game for. A game reads the developer's and the game's,
327
332
  // and reads and writes its own player's: the server's scope, a write to any
328
333
  // but a player's, a guest's call for a player's, or a player who isn't the
329
334
  // one playing is 403. Only JSON is taken, as for a ticket, so a page
330
335
  // elsewhere can't ask. A refusal is its status, with no body.
331
- async function sendGameValues(req, res, verb, { game, values }) {
336
+ async function sendGameValues(req, res, verb, { player, values }) {
332
337
  const refuse = function (status) {
333
338
  res.writeHead(status, HEADERS).end();
334
339
  };
@@ -346,7 +351,6 @@ async function sendGameValues(req, res, verb, { game, values }) {
346
351
  return;
347
352
  }
348
353
  const write = verb === "write" || verb === "remove";
349
- const player = game.player ?? null;
350
354
  if (scope === "server" ||
351
355
  (write && scope !== "player") ||
352
356
  (scope === "player" && (!player || body["player"] !== player.id))) {
@@ -397,6 +401,44 @@ function sendData(req, res, status, data, count) {
397
401
  endWith(req, res, JSON.stringify({ data, meta }));
398
402
  }
399
403
  // [function]
404
+ // the player a window's address names: `?player=<name>`, a local player
405
+ // made from the name and the game, as `--player` makes one; `?player=` with
406
+ // no name, a guest (null); without it, undefined, the page's own. False for
407
+ // a name that can't be one.
408
+ function playerAsked(req, playerOf) {
409
+ let query;
410
+ try {
411
+ query = new URL(req.url ?? "", "http://page").searchParams;
412
+ }
413
+ catch {
414
+ return undefined;
415
+ }
416
+ const name = query.get("player");
417
+ if (name === null)
418
+ return undefined;
419
+ if (name.trim() === "")
420
+ return null;
421
+ return playerOf(name) || false;
422
+ }
423
+ // [function]
424
+ // a window's own player and the rest of the path, from a path under
425
+ // `/_arcadible/as/<id>/`: undefined for any other path, and false for an id
426
+ // no window was opened as.
427
+ function windowOf(pathname, named) {
428
+ if (!pathname.startsWith(`${AS}/`))
429
+ return undefined;
430
+ const rest = pathname.slice(AS.length + 1);
431
+ const cut = rest.indexOf("/");
432
+ if (cut < 0)
433
+ return false;
434
+ const key = rest.slice(0, cut);
435
+ const path = rest.slice(cut);
436
+ if (key === GUEST)
437
+ return { path, player: null };
438
+ const player = named.get(key);
439
+ return player ? { path, player } : false;
440
+ }
441
+ // [function]
400
442
  // a refusal in the API's own envelope: what it says of the status.
401
443
  function sendRefusal(req, res, status) {
402
444
  const [title, message] = REFUSALS[status] ?? ["", ""];
@@ -537,9 +579,19 @@ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = F
537
579
  return null;
538
580
  });
539
581
  };
582
+ // the players windows were opened as, by id, so a window's path names one
583
+ const named = new Map();
540
584
  return function (req, res) {
541
585
  // a target that can't be read as a URL (`//`) is no path of the page's.
542
- const pathname = pathOf(req) ?? "";
586
+ const whole = pathOf(req) ?? "";
587
+ // a window's own player, from its path (undefined: the page's default)
588
+ const opened = windowOf(whole, named);
589
+ if (opened === false) {
590
+ res.writeHead(404, HEADERS).end();
591
+ return Promise.resolve();
592
+ }
593
+ const pathname = opened ? opened.path : whole;
594
+ const playing = opened ? opened.player : (game.player ?? null);
543
595
  if (tickets && pathname.startsWith(`${SERVER}/`)) {
544
596
  return sendServer(req, res, pathname.slice(SERVER.length), {
545
597
  game,
@@ -557,9 +609,9 @@ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = F
557
609
  res.writeHead(405, { ...HEADERS, allow: "POST" }).end();
558
610
  return Promise.resolve();
559
611
  }
560
- return sendGameValues(req, res, verb, { game, values });
612
+ return sendGameValues(req, res, verb, { player: playing, values });
561
613
  }
562
- if (pathname === LOGIN) {
614
+ if (pathname === LOGIN && !opened) {
563
615
  if (req.method !== "POST") {
564
616
  res.writeHead(405, { ...HEADERS, allow: "POST" }).end();
565
617
  return Promise.resolve();
@@ -571,13 +623,33 @@ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = F
571
623
  res.writeHead(405, { ...HEADERS, allow: "POST" }).end();
572
624
  return Promise.resolve();
573
625
  }
574
- return sendTicket(req, res, { game, playerOf, tickets });
626
+ return sendTicket(req, res, { playerOf, playing, tickets });
627
+ }
628
+ if (opened) {
629
+ // only the page's own API is under a window's path
630
+ res.writeHead(404, HEADERS).end();
631
+ return Promise.resolve();
575
632
  }
576
633
  if (req.method !== "GET" && req.method !== "HEAD") {
577
634
  res.writeHead(405, { ...HEADERS, allow: "GET, HEAD" }).end();
578
635
  return Promise.resolve();
579
636
  }
580
637
  if (pathname === "/") {
638
+ // the window's player, when its address names one: `?player=<name>`,
639
+ // or `?player=` for a guest
640
+ const asked = playerAsked(req, playerOf);
641
+ if (asked === false) {
642
+ res.writeHead(400, {
643
+ ...HEADERS,
644
+ "content-type": "text/plain; charset=utf-8",
645
+ });
646
+ res.end("?player= must be a name, up to 200 characters, or empty for a guest.\n");
647
+ return Promise.resolve();
648
+ }
649
+ if (asked) {
650
+ named.set(asked.id, asked);
651
+ tickets?.remember(asked);
652
+ }
581
653
  // read for each request, so art added while serving shows on the next
582
654
  // load.
583
655
  return Promise.all([
@@ -589,7 +661,7 @@ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = F
589
661
  "content-security-policy": policy(game.src),
590
662
  "content-type": "text/html; charset=utf-8",
591
663
  });
592
- endWith(req, res, html(game, { art: Boolean(splash), icon: Boolean(mark) }));
664
+ endWith(req, res, html(game, { art: Boolean(splash), icon: Boolean(mark) }, asked === undefined ? undefined : { player: asked }));
593
665
  });
594
666
  }
595
667
  if (pathname === ICON) {
@@ -0,0 +1,63 @@
1
+ // a build's favicon.ico, for a build without its own: the project's store
2
+ // icon scaled to 16, 32, and 48 pixels, each a PNG inside the ICO, or the
3
+ // play page's own without one. `arc pack` puts it in the package, and `arc
4
+ // serve` answers /favicon.ico with it, so every build has one.
5
+ // [import]
6
+ import { readFile } from "node:fs/promises";
7
+ // [import]
8
+ import { FAVICON } from "../config/asset.js";
9
+ import { decode, encode, scale } from "./png.js";
10
+ // [declare]
11
+ // what browsers pick from for a tab, a bookmark, and a shortcut. An ICO's
12
+ // images are at most 256 a side, and the icon is at least 512.
13
+ export const SIZES = [16, 32, 48];
14
+ // [declare]
15
+ const DIR_SIZE = 6;
16
+ const ENTRY_SIZE = 16;
17
+ // [function]
18
+ // an ICO holding `images`, each a PNG of `size` pixels a side, in order.
19
+ export function ico(images) {
20
+ const dir = Buffer.alloc(DIR_SIZE);
21
+ dir.writeUInt16LE(0, 0);
22
+ dir.writeUInt16LE(1, 2);
23
+ dir.writeUInt16LE(images.length, 4);
24
+ let offset = DIR_SIZE + ENTRY_SIZE * images.length;
25
+ const entries = images.map(({ png, size }) => {
26
+ const entry = Buffer.alloc(ENTRY_SIZE);
27
+ // 0 says 256
28
+ entry.writeUInt8(size % 256, 0);
29
+ entry.writeUInt8(size % 256, 1);
30
+ entry.writeUInt8(0, 2);
31
+ entry.writeUInt8(0, 3);
32
+ entry.writeUInt16LE(1, 4);
33
+ entry.writeUInt16LE(32, 6);
34
+ entry.writeUInt32LE(png.length, 8);
35
+ entry.writeUInt32LE(offset, 12);
36
+ offset += png.length;
37
+ return entry;
38
+ });
39
+ return Buffer.concat([dir, ...entries, ...images.map(({ png }) => png)]);
40
+ }
41
+ // [function]
42
+ // the favicon.ico made from `icon`, a PNG's bytes, scaled to each of SIZES.
43
+ // Throws for one that can't be read as a PNG.
44
+ export function iconIco(icon) {
45
+ const pixels = decode(icon);
46
+ return ico(SIZES.map((size) => ({ png: encode(scale(pixels, size, size)), size })));
47
+ }
48
+ // [function]
49
+ // the favicon.ico for a build without its own: made from `icon`, the store
50
+ // icon's path, when there is one and it can be read as a PNG, else the play
51
+ // page's own. `arc validate` reads only the icon's header, so one whose
52
+ // pixels can't be read gets Arcadible's rather than failing the pack.
53
+ export async function favicon(icon) {
54
+ if (icon) {
55
+ try {
56
+ return iconIco(await readFile(icon));
57
+ }
58
+ catch {
59
+ // the play page's own, below
60
+ }
61
+ }
62
+ return readFile(FAVICON);
63
+ }