tickflare 0.0.0-stage → 0.2.0

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.
Files changed (125) hide show
  1. package/CHANGELOG.md +240 -0
  2. package/LICENSE +21 -0
  3. package/README.md +112 -2
  4. package/dist/binary.d.ts +91 -0
  5. package/dist/binary.js +466 -0
  6. package/dist/binary.js.map +1 -0
  7. package/dist/client/accounts.d.ts +193 -0
  8. package/dist/client/accounts.js +306 -0
  9. package/dist/client/accounts.js.map +1 -0
  10. package/dist/client/buffered.d.ts +88 -0
  11. package/dist/client/buffered.js +229 -0
  12. package/dist/client/buffered.js.map +1 -0
  13. package/dist/client/clock.d.ts +36 -0
  14. package/dist/client/clock.js +83 -0
  15. package/dist/client/clock.js.map +1 -0
  16. package/dist/client/draft.d.ts +17 -0
  17. package/dist/client/draft.js +133 -0
  18. package/dist/client/draft.js.map +1 -0
  19. package/dist/client/index.d.ts +182 -0
  20. package/dist/client/index.js +496 -0
  21. package/dist/client/index.js.map +1 -0
  22. package/dist/client/interpolate.d.ts +31 -0
  23. package/dist/client/interpolate.js +59 -0
  24. package/dist/client/interpolate.js.map +1 -0
  25. package/dist/client/lockstep.d.ts +86 -0
  26. package/dist/client/lockstep.js +339 -0
  27. package/dist/client/lockstep.js.map +1 -0
  28. package/dist/client/matchmaking.d.ts +21 -0
  29. package/dist/client/matchmaking.js +55 -0
  30. package/dist/client/matchmaking.js.map +1 -0
  31. package/dist/client/pacer.d.ts +22 -0
  32. package/dist/client/pacer.js +65 -0
  33. package/dist/client/pacer.js.map +1 -0
  34. package/dist/client/predict.d.ts +75 -0
  35. package/dist/client/predict.js +203 -0
  36. package/dist/client/predict.js.map +1 -0
  37. package/dist/client/token.d.ts +10 -0
  38. package/dist/client/token.js +15 -0
  39. package/dist/client/token.js.map +1 -0
  40. package/dist/lockstep.d.ts +154 -0
  41. package/dist/lockstep.js +140 -0
  42. package/dist/lockstep.js.map +1 -0
  43. package/dist/patch.d.ts +54 -0
  44. package/dist/patch.js +186 -0
  45. package/dist/patch.js.map +1 -0
  46. package/dist/protocol.d.ts +268 -0
  47. package/dist/protocol.js +54 -0
  48. package/dist/protocol.js.map +1 -0
  49. package/dist/server/accounts.d.ts +320 -0
  50. package/dist/server/accounts.js +1223 -0
  51. package/dist/server/accounts.js.map +1 -0
  52. package/dist/server/delta.d.ts +50 -0
  53. package/dist/server/delta.js +426 -0
  54. package/dist/server/delta.js.map +1 -0
  55. package/dist/server/frames.d.ts +15 -0
  56. package/dist/server/frames.js +23 -0
  57. package/dist/server/frames.js.map +1 -0
  58. package/dist/server/gateway.d.ts +80 -0
  59. package/dist/server/gateway.js +144 -0
  60. package/dist/server/gateway.js.map +1 -0
  61. package/dist/server/index.d.ts +21 -0
  62. package/dist/server/index.js +22 -0
  63. package/dist/server/index.js.map +1 -0
  64. package/dist/server/limiter.d.ts +12 -0
  65. package/dist/server/limiter.js +43 -0
  66. package/dist/server/limiter.js.map +1 -0
  67. package/dist/server/lockstep.d.ts +127 -0
  68. package/dist/server/lockstep.js +549 -0
  69. package/dist/server/lockstep.js.map +1 -0
  70. package/dist/server/matches.d.ts +31 -0
  71. package/dist/server/matches.js +69 -0
  72. package/dist/server/matches.js.map +1 -0
  73. package/dist/server/matchmaker.d.ts +121 -0
  74. package/dist/server/matchmaker.js +479 -0
  75. package/dist/server/matchmaker.js.map +1 -0
  76. package/dist/server/room.d.ts +402 -0
  77. package/dist/server/room.js +1896 -0
  78. package/dist/server/room.js.map +1 -0
  79. package/dist/server/signals.d.ts +18 -0
  80. package/dist/server/signals.js +37 -0
  81. package/dist/server/signals.js.map +1 -0
  82. package/dist/server/storage.d.ts +117 -0
  83. package/dist/server/storage.js +330 -0
  84. package/dist/server/storage.js.map +1 -0
  85. package/dist/server/tokens.d.ts +74 -0
  86. package/dist/server/tokens.js +117 -0
  87. package/dist/server/tokens.js.map +1 -0
  88. package/dist/server/tracked.d.ts +47 -0
  89. package/dist/server/tracked.js +270 -0
  90. package/dist/server/tracked.js.map +1 -0
  91. package/dist/world.d.ts +20 -0
  92. package/dist/world.js +21 -0
  93. package/dist/world.js.map +1 -0
  94. package/package.json +74 -4
  95. package/src/binary.ts +496 -0
  96. package/src/client/accounts.ts +423 -0
  97. package/src/client/buffered.ts +264 -0
  98. package/src/client/clock.ts +86 -0
  99. package/src/client/draft.ts +138 -0
  100. package/src/client/index.ts +631 -0
  101. package/src/client/interpolate.ts +60 -0
  102. package/src/client/lockstep.ts +398 -0
  103. package/src/client/matchmaking.ts +61 -0
  104. package/src/client/pacer.ts +67 -0
  105. package/src/client/predict.ts +239 -0
  106. package/src/client/token.ts +22 -0
  107. package/src/lockstep.ts +285 -0
  108. package/src/patch.ts +188 -0
  109. package/src/protocol.ts +300 -0
  110. package/src/server/accounts.ts +1474 -0
  111. package/src/server/delta.ts +467 -0
  112. package/src/server/frames.ts +23 -0
  113. package/src/server/gateway.ts +213 -0
  114. package/src/server/index.ts +86 -0
  115. package/src/server/limiter.ts +41 -0
  116. package/src/server/lockstep.ts +617 -0
  117. package/src/server/matches.ts +99 -0
  118. package/src/server/matchmaker.ts +537 -0
  119. package/src/server/room.ts +1999 -0
  120. package/src/server/signals.ts +46 -0
  121. package/src/server/storage.ts +392 -0
  122. package/src/server/tokens.ts +184 -0
  123. package/src/server/tracked.ts +260 -0
  124. package/src/world.ts +29 -0
  125. package/tools/rooms-report.mjs +168 -0
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Signed join tokens: how a room knows who is connecting without trusting
3
+ * the client.
4
+ *
5
+ * Your own backend creates a token once it knows who the player is (after a
6
+ * login, or when it hands out a guest account). The client presents it when
7
+ * connecting, and `tokenAuth` checks it at the gateway. A token is an
8
+ * HMAC-SHA256 signature over the player id and an expiry, so it cannot be
9
+ * forged or altered without the secret.
10
+ */
11
+ import type { Authenticated } from "./gateway.js";
12
+ /** What a join token says. See `createJoinToken`. */
13
+ export interface JoinTokenClaims {
14
+ /** The player this token speaks for. */
15
+ player: string;
16
+ /**
17
+ * The player's account name. Rooms see it as `player.name`. Leave it out
18
+ * for guests: `Accounts` takes a token with a name for a signed-in player.
19
+ */
20
+ name?: string;
21
+ /** If set, the token only opens the room or matchmaking queue with this id. */
22
+ scope?: string;
23
+ /**
24
+ * The party the player queues with: friends who are to be matched
25
+ * together. Every member's token carries the same `id`, and `size` says
26
+ * how many they are. Only your server should make these, once it knows
27
+ * the player is in that party: a player who could name any party could
28
+ * join a stranger's.
29
+ */
30
+ party?: Party;
31
+ /** Lifetime in seconds. Defaults to one hour. */
32
+ expiresIn?: number;
33
+ }
34
+ /** Friends who queue together. See `JoinTokenClaims.party`. */
35
+ export interface Party {
36
+ /** The same for every member: any string of up to 64 visible characters. */
37
+ id: string;
38
+ /** How many members the party has, the player included. */
39
+ size: number;
40
+ }
41
+ /** What a valid join token said. See `verifyJoinToken`. */
42
+ export interface VerifiedJoinToken {
43
+ /** The player it speaks for. */
44
+ player: string;
45
+ /** The account name, if it carried one. */
46
+ name?: string;
47
+ /** The room or queue it is limited to, if any. */
48
+ scope?: string;
49
+ /** The party the player queues with, if it carried one. */
50
+ party?: Party;
51
+ /** When it stops working, in epoch seconds. */
52
+ expiresAt: number;
53
+ }
54
+ /** Sign a token for a player. Keep the secret on the server: `wrangler secret put JOIN_SECRET`. */
55
+ export declare function createJoinToken(secret: string, claims: JoinTokenClaims): Promise<string>;
56
+ /**
57
+ * Check a token. Returns what it says, or `null` if it is malformed, signed
58
+ * with another secret, expired, or scoped to a different room or queue than
59
+ * `scope`.
60
+ */
61
+ export declare function verifyJoinToken(secret: string, token: string, scope?: string): Promise<VerifiedJoinToken | null>;
62
+ /** How `tokenAuth` checks tokens. */
63
+ export interface TokenAuthOptions {
64
+ /** The signing secret, e.g. `env.JOIN_SECRET`. At least 16 characters. */
65
+ secret: string;
66
+ /** Query parameter the client sends the token in. Defaults to `token`. */
67
+ param?: string;
68
+ }
69
+ /**
70
+ * An `authenticate` function for `routeToRoom` and `routeToMatchmaker` that
71
+ * accepts signed join tokens. The client connects with `?token=...`; plain
72
+ * HTTP requests may send `Authorization: Bearer ...` instead.
73
+ */
74
+ export declare function tokenAuth(options: TokenAuthOptions): (request: Request, scope: string) => Promise<Authenticated | Response>;
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Signed join tokens: how a room knows who is connecting without trusting
3
+ * the client.
4
+ *
5
+ * Your own backend creates a token once it knows who the player is (after a
6
+ * login, or when it hands out a guest account). The client presents it when
7
+ * connecting, and `tokenAuth` checks it at the gateway. A token is an
8
+ * HMAC-SHA256 signature over the player id and an expiry, so it cannot be
9
+ * forged or altered without the secret.
10
+ */
11
+ const VERSION = "v1";
12
+ const MIN_SECRET_LENGTH = 16;
13
+ const encoder = new TextEncoder();
14
+ const decoder = new TextDecoder();
15
+ const keys = new Map();
16
+ /** Sign a token for a player. Keep the secret on the server: `wrangler secret put JOIN_SECRET`. */
17
+ export async function createJoinToken(secret, claims) {
18
+ const payload = {
19
+ p: claims.player,
20
+ e: Math.floor(Date.now() / 1000) + (claims.expiresIn ?? 3600),
21
+ };
22
+ if (claims.name !== undefined)
23
+ payload.n = claims.name;
24
+ if (claims.scope !== undefined)
25
+ payload.s = claims.scope;
26
+ if (claims.party !== undefined) {
27
+ payload.pa = claims.party.id;
28
+ payload.ps = claims.party.size;
29
+ }
30
+ const body = `${VERSION}.${toBase64Url(encoder.encode(JSON.stringify(payload)))}`;
31
+ const signature = await crypto.subtle.sign("HMAC", await keyFor(secret), encoder.encode(body));
32
+ return `${body}.${toBase64Url(new Uint8Array(signature))}`;
33
+ }
34
+ /**
35
+ * Check a token. Returns what it says, or `null` if it is malformed, signed
36
+ * with another secret, expired, or scoped to a different room or queue than
37
+ * `scope`.
38
+ */
39
+ export async function verifyJoinToken(secret, token, scope) {
40
+ const key = await keyFor(secret);
41
+ const parts = token.split(".");
42
+ if (parts.length !== 3 || parts[0] !== VERSION)
43
+ return null;
44
+ try {
45
+ const valid = await crypto.subtle.verify("HMAC", key, fromBase64Url(parts[2]), encoder.encode(`${parts[0]}.${parts[1]}`));
46
+ if (!valid)
47
+ return null;
48
+ const payload = JSON.parse(decoder.decode(fromBase64Url(parts[1])));
49
+ if (typeof payload.p !== "string" || typeof payload.e !== "number")
50
+ return null;
51
+ if (payload.e <= Date.now() / 1000)
52
+ return null;
53
+ if (payload.s !== undefined && payload.s !== scope)
54
+ return null;
55
+ const verified = { player: payload.p, expiresAt: payload.e };
56
+ if (typeof payload.n === "string")
57
+ verified.name = payload.n;
58
+ if (payload.s !== undefined)
59
+ verified.scope = payload.s;
60
+ if (typeof payload.pa === "string" && typeof payload.ps === "number")
61
+ verified.party = { id: payload.pa, size: payload.ps };
62
+ return verified;
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ }
68
+ /**
69
+ * An `authenticate` function for `routeToRoom` and `routeToMatchmaker` that
70
+ * accepts signed join tokens. The client connects with `?token=...`; plain
71
+ * HTTP requests may send `Authorization: Bearer ...` instead.
72
+ */
73
+ export function tokenAuth(options) {
74
+ const param = options.param ?? "token";
75
+ return async (request, scope) => {
76
+ const bearer = /^Bearer (.+)$/.exec(request.headers.get("Authorization") ?? "")?.[1];
77
+ const token = new URL(request.url).searchParams.get(param) ?? bearer;
78
+ if (!token)
79
+ return new Response("Missing join token", { status: 401 });
80
+ const verified = await verifyJoinToken(options.secret, token, scope);
81
+ if (!verified)
82
+ return new Response("Invalid or expired join token", { status: 401 });
83
+ if (verified.name === undefined && verified.party === undefined)
84
+ return verified.player;
85
+ return {
86
+ id: verified.player,
87
+ ...(verified.name !== undefined ? { name: verified.name } : {}),
88
+ ...(verified.party !== undefined ? { party: verified.party } : {}),
89
+ };
90
+ };
91
+ }
92
+ function keyFor(secret) {
93
+ if (typeof secret !== "string" || secret.length < MIN_SECRET_LENGTH) {
94
+ // Also catches a missing binding, which would otherwise sign with "undefined".
95
+ throw new TypeError(`The join token secret must be a string of at least ${MIN_SECRET_LENGTH} characters`);
96
+ }
97
+ let key = keys.get(secret);
98
+ if (!key) {
99
+ key = crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
100
+ "sign",
101
+ "verify",
102
+ ]);
103
+ keys.set(secret, key);
104
+ }
105
+ return key;
106
+ }
107
+ function toBase64Url(bytes) {
108
+ let binary = "";
109
+ for (const byte of bytes)
110
+ binary += String.fromCharCode(byte);
111
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
112
+ }
113
+ function fromBase64Url(text) {
114
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
115
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
116
+ }
117
+ //# sourceMappingURL=tokens.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tokens.js","sourceRoot":"","sources":["../../src/server/tokens.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AA2DH,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,IAAI,GAAG,IAAI,GAAG,EAA8B,CAAC;AAEnD,mGAAmG;AACnG,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,MAAc,EAAE,MAAuB;IAC3E,MAAM,OAAO,GAAY;QACvB,CAAC,EAAE,MAAM,CAAC,MAAM;QAChB,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,SAAS,IAAI,IAAI,CAAC;KAC9D,CAAC;IACF,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS;QAAE,OAAO,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC;IACvD,IAAI,MAAM,CAAC,KAAK,KAAK,SAAS;QAAE,OAAO,CAAC,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC;IACzD,IAAI,MA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AAS,CAAC,sDAAsD,iBAAiB,aAAa,CAAC,CAAC;IAC5G,CAAC;IACD,IAAI,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC3B,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE;YACrG,MAAM;YACN,QAAQ;SACT,CAAC,CAAC;QACH,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,WAAW,CAAC,KAAiB;IACpC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAC9D,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACjF,CAAC;AAED,SAAS,aAAa,CAAC,IAAY;IACjC,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;IAChE,OAAO,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;AAC/D,CAAC"}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Tracks what a hook writes to the room's state, so that the kernel knows
3
+ * whether anything changed and can put it back, without making a copy of the
4
+ * whole state before every hook.
5
+ *
6
+ * Inside a hook `this.state` is not the state itself but a proxy of it, and
7
+ * so is every object and array reached through it. Reading passes straight
8
+ * through. Writing is noted first: which slot, and what was in it. Undoing
9
+ * a hook is replaying those notes backwards.
10
+ *
11
+ * The state underneath stays made of plain objects only: a proxy that is
12
+ * written into the state is replaced by the object it stands for. So the
13
+ * simulation, the views and the saves, which run outside these hooks, work
14
+ * on plain objects at full speed.
15
+ */
16
+ /**
17
+ * The object itself behind something read from `this.state` inside a hook,
18
+ * for the few things a proxy cannot stand in for: `structuredClone`, or
19
+ * comparing with `===` against an object that did not come from the state.
20
+ * Read from it; a change made through it is not tracked, so it is neither
21
+ * sent nor undone with the hook.
22
+ */
23
+ export declare function plain<T>(value: T): T;
24
+ export declare class Tracker {
25
+ #private;
26
+ constructor();
27
+ /** Whether a hook is being tracked. */
28
+ get active(): boolean;
29
+ /** Whether the hook being tracked has changed anything so far. */
30
+ get changed(): boolean;
31
+ /** Start tracking a hook. */
32
+ begin(): void;
33
+ /** The hook is over and its changes stand. */
34
+ end(): void;
35
+ /** The hook is over and everything it wrote is put back. */
36
+ undo(): void;
37
+ /** Note a change the tracker cannot see by itself, with how to undo it. */
38
+ note(undo: () => void): void;
39
+ /** What `this.state` gives a hook: the proxy of `value` if it is an object or an array of the state. */
40
+ wrap<T>(value: T): T;
41
+ /**
42
+ * A value on its way into the state, with every proxy in it replaced by the
43
+ * object it stands for. New objects are looked through, and changed in
44
+ * place: they are the state's from here on.
45
+ */
46
+ clean<T>(value: T): T;
47
+ }
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Tracks what a hook writes to the room's state, so that the kernel knows
3
+ * whether anything changed and can put it back, without making a copy of the
4
+ * whole state before every hook.
5
+ *
6
+ * Inside a hook `this.state` is not the state itself but a proxy of it, and
7
+ * so is every object and array reached through it. Reading passes straight
8
+ * through. Writing is noted first: which slot, and what was in it. Undoing
9
+ * a hook is replaying those notes backwards.
10
+ *
11
+ * The state underneath stays made of plain objects only: a proxy that is
12
+ * written into the state is replaced by the object it stands for. So the
13
+ * simulation, the views and the saves, which run outside these hooks, work
14
+ * on plain objects at full speed.
15
+ */
16
+ /** The object behind each proxy, for every tracker: `plain()` needs no tracker to look it up. */
17
+ const TARGETS = new WeakMap();
18
+ /** An object literal, or anything else with no class of its own: what JSON turns back into an object. */
19
+ function isPlainObject(value) {
20
+ const prototype = Object.getPrototypeOf(value);
21
+ return prototype === Object.prototype || prototype === null;
22
+ }
23
+ const NOT_JSON = "Room state must be JSON-serializable";
24
+ const OUTSIDE = "The room's state was changed outside a hook. Change it in a hook, or from `act()` after an await.";
25
+ /**
26
+ * The object itself behind something read from `this.state` inside a hook,
27
+ * for the few things a proxy cannot stand in for: `structuredClone`, or
28
+ * comparing with `===` against an object that did not come from the state.
29
+ * Read from it; a change made through it is not tracked, so it is neither
30
+ * sent nor undone with the hook.
31
+ */
32
+ export function plain(value) {
33
+ if (typeof value !== "object" || value === null)
34
+ return value;
35
+ return TARGETS.get(value) ?? value;
36
+ }
37
+ export class Tracker {
38
+ /** The proxy of each object of the state that has been read through one. */
39
+ #proxies = new WeakMap();
40
+ /** What the running hook has written, oldest first. Null while no hook is running. */
41
+ #notes = null;
42
+ /**
43
+ * The keys of each object the running hook has deleted a key from, as they
44
+ * were before. Putting a deleted key back puts it last, and the order of
45
+ * the keys is part of what the state looks like as JSON.
46
+ */
47
+ #orders = new Map();
48
+ #handler;
49
+ /** `includes`, `indexOf` and `lastIndexOf` for proxied arrays: see `#search`. */
50
+ #searches;
51
+ constructor() {
52
+ this.#handler = {
53
+ get: (target, key, receiver) => this.#get(target, key, receiver),
54
+ set: (target, key, value) => this.#set(target, key, value),
55
+ deleteProperty: (target, key) => this.#delete(target, key),
56
+ defineProperty: (target, key, descriptor) => this.#define(target, key, descriptor),
57
+ };
58
+ this.#searches = {
59
+ includes: this.#search("includes"),
60
+ indexOf: this.#search("indexOf"),
61
+ lastIndexOf: this.#search("lastIndexOf"),
62
+ };
63
+ }
64
+ /** Whether a hook is being tracked. */
65
+ get active() {
66
+ return this.#notes !== null;
67
+ }
68
+ /** Whether the hook being tracked has changed anything so far. */
69
+ get changed() {
70
+ return this.#notes !== null && this.#notes.length > 0;
71
+ }
72
+ /** Start tracking a hook. */
73
+ begin() {
74
+ this.#notes = [];
75
+ }
76
+ /** The hook is over and its changes stand. */
77
+ end() {
78
+ this.#notes = null;
79
+ this.#orders.clear();
80
+ }
81
+ /** The hook is over and everything it wrote is put back. */
82
+ undo() {
83
+ const notes = this.#notes;
84
+ this.#notes = null;
85
+ if (!notes)
86
+ return;
87
+ for (let i = notes.length - 1; i >= 0; i--) {
88
+ const note = notes[i];
89
+ if ("undo" in note) {
90
+ note.undo();
91
+ }
92
+ else if ("descriptor" in note) {
93
+ if (note.descriptor)
94
+ Object.defineProperty(note.target, note.key, note.descriptor);
95
+ else
96
+ delete note.target[note.key];
97
+ }
98
+ else {
99
+ if (note.had)
100
+ note.target[note.key] = note.value;
101
+ else
102
+ delete note.target[note.key];
103
+ // Writing past the end of an array made it longer, and deleting does not make it shorter.
104
+ if (note.length !== undefined)
105
+ note.target.length = note.length;
106
+ }
107
+ }
108
+ for (const [target, keys] of this.#orders) {
109
+ // Every key is back, with its value. Taking each out and putting it in again, in the
110
+ // order they were in, leaves them in that order.
111
+ for (const key of keys) {
112
+ // A key the hook added before it first deleted one is in the list, and gone again by now.
113
+ if (!Object.hasOwn(target, key))
114
+ continue;
115
+ const value = target[key];
116
+ delete target[key];
117
+ target[key] = value;
118
+ }
119
+ }
120
+ this.#orders.clear();
121
+ }
122
+ /** Note a change the tracker cannot see by itself, with how to undo it. */
123
+ note(undo) {
124
+ if (this.#notes === null)
125
+ throw new TypeError(OUTSIDE);
126
+ this.#notes.push({ undo });
127
+ }
128
+ /** What `this.state` gives a hook: the proxy of `value` if it is an object or an array of the state. */
129
+ wrap(value) {
130
+ if (typeof value !== "object" || value === null)
131
+ return value;
132
+ const known = this.#proxies.get(value);
133
+ if (known)
134
+ return known;
135
+ if (!Array.isArray(value) && !isPlainObject(value))
136
+ return value;
137
+ const proxy = new Proxy(value, this.#handler);
138
+ this.#proxies.set(value, proxy);
139
+ TARGETS.set(proxy, value);
140
+ return proxy;
141
+ }
142
+ /**
143
+ * A value on its way into the state, with every proxy in it replaced by the
144
+ * object it stands for. New objects are looked through, and changed in
145
+ * place: they are the state's from here on.
146
+ */
147
+ clean(value) {
148
+ return this.#clean(value, undefined);
149
+ }
150
+ #clean(value, above) {
151
+ if (typeof value === "bigint")
152
+ throw new TypeError(NOT_JSON);
153
+ if (typeof value !== "object" || value === null)
154
+ return value;
155
+ const target = TARGETS.get(value);
156
+ if (target)
157
+ return target;
158
+ // Already part of the state, which holds no proxies; or not something JSON looks into.
159
+ if (this.#proxies.has(value))
160
+ return value;
161
+ const list = Array.isArray(value);
162
+ if (!list && !isPlainObject(value))
163
+ return value;
164
+ if (above?.has(value))
165
+ throw new TypeError(NOT_JSON);
166
+ (above ??= new Set()).add(value);
167
+ const inside = value;
168
+ for (const key of list ? value.keys() : Object.keys(value)) {
169
+ const item = inside[key];
170
+ if (typeof item === "bigint")
171
+ throw new TypeError(NOT_JSON);
172
+ if (typeof item !== "object" || item === null)
173
+ continue;
174
+ const cleaned = this.#clean(item, above);
175
+ if (cleaned !== item)
176
+ inside[key] = cleaned;
177
+ }
178
+ above.delete(value);
179
+ return value;
180
+ }
181
+ #get(target, key, receiver) {
182
+ const value = Reflect.get(target, key, receiver);
183
+ if (typeof value === "function") {
184
+ return typeof key === "string" && Array.isArray(target) && Object.hasOwn(this.#searches, key)
185
+ ? this.#searches[key]
186
+ : value;
187
+ }
188
+ if (typeof value !== "object" || value === null)
189
+ return value;
190
+ // A proxy has to hand out a frozen object's own values as they are.
191
+ if (!Object.isExtensible(target)) {
192
+ const own = Reflect.getOwnPropertyDescriptor(target, key);
193
+ if (own && !own.configurable && !own.writable)
194
+ return value;
195
+ }
196
+ return this.wrap(value);
197
+ }
198
+ #set(target, key, incoming) {
199
+ const notes = this.#notes;
200
+ if (notes === null)
201
+ throw new TypeError(OUTSIDE);
202
+ const value = this.#clean(incoming, undefined);
203
+ const had = Object.hasOwn(target, key);
204
+ const old = had ? target[key] : undefined;
205
+ if (had && Object.is(old, value))
206
+ return true;
207
+ if (!Array.isArray(target)) {
208
+ if (!Reflect.set(target, key, value))
209
+ return false;
210
+ notes.push({ target, key, had, value: old });
211
+ return true;
212
+ }
213
+ const length = target.length;
214
+ // Making an array shorter drops what was past its new end without a word.
215
+ const dropped = [];
216
+ if (key === "length" && typeof value === "number" && value < length) {
217
+ for (let i = value; i < length; i++) {
218
+ if (i in target)
219
+ dropped.push({ target, key: String(i), had: true, value: target[i], length });
220
+ }
221
+ }
222
+ if (!Reflect.set(target, key, value))
223
+ return false;
224
+ notes.push(...dropped, { target, key, had, value: old, length });
225
+ return true;
226
+ }
227
+ #delete(target, key) {
228
+ const notes = this.#notes;
229
+ if (notes === null)
230
+ throw new TypeError(OUTSIDE);
231
+ if (!Object.hasOwn(target, key))
232
+ return Reflect.deleteProperty(target, key);
233
+ const old = target[key];
234
+ const list = Array.isArray(target);
235
+ if (!list && !this.#orders.has(target))
236
+ this.#orders.set(target, Object.keys(target));
237
+ if (!Reflect.deleteProperty(target, key))
238
+ return false;
239
+ const note = { target, key, had: true, value: old };
240
+ if (list)
241
+ note.length = target.length;
242
+ notes.push(note);
243
+ return true;
244
+ }
245
+ #define(target, key, descriptor) {
246
+ const notes = this.#notes;
247
+ if (notes === null)
248
+ throw new TypeError(OUTSIDE);
249
+ const before = Reflect.getOwnPropertyDescriptor(target, key);
250
+ const cleaned = "value" in descriptor ? { ...descriptor, value: this.#clean(descriptor.value, undefined) } : descriptor;
251
+ if (!Reflect.defineProperty(target, key, cleaned))
252
+ return false;
253
+ notes.push({ target, key, descriptor: before });
254
+ return true;
255
+ }
256
+ /**
257
+ * A new object that a hook has just put in an array is still held by the
258
+ * hook as the object itself, while the array hands out its proxy. So
259
+ * looking for it in the array has to compare the objects underneath.
260
+ */
261
+ #search(name) {
262
+ const method = Array.prototype[name];
263
+ return function (...args) {
264
+ if (args.length > 0)
265
+ args[0] = plain(args[0]);
266
+ return method.apply(plain(this), args);
267
+ };
268
+ }
269
+ }
270
+ //# sourceMappingURL=tracked.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracked.js","sourceRoot":"","sources":["../../src/server/tracked.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;;GAcG;AAEH,iGAAiG;AACjG,MAAM,OAAO,GAAG,IAAI,OAAO,EAAkB,CAAC;AAQ9C,yGAAyG;AACzG,SAAS,aAAa,CAAC,KAAa;IAClC,MAAM,SAAS,GAAY,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IACxD,OAAO,SAAS,KAAK,MAAM,CAAC,SAAS,IAAI,SAAS,KAAK,IAAI,CAAC;AAC9D,CAAC;AAED,MAAM,QAAQ,GAAG,sCAAsC,CAAC;AACxD,MAAM,OAAO,GACX,mGAAmG,CAAC;AAEtG;;;;;;GAMG;AACH,MAAM,UAAU,KAAK,CAAI,KAAQ;IAC/B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC9D,OAAQ,OAAO,CAAC,GAAG,CAAC,KAAK,CAAmB,IAAI,KAAK,CAAC;AACxD,CAAC;AAED,MAAM,OAAO,OAAO;IAClB,4EAA4E;IAC5E,QAAQ,GAAG,IAAI,OAAO,EAAkB,CAAC;IACzC,sFAAsF;IACtF,MAAM,GAAkB,IAAI,CAAC;IAC7B;;;;OAIG;IACH,OAAO,GAAG,IAAI,GAAG,EAA0C,CAAC;IAC5D,QAAQ,CAA6C;IACrD,iFAAiF;IACjF,SAAS,CAAmE;IAE5E;QACE,IAAI,CAAC,QAAQ,GAAG;YACd,GAAG,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,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AAO,CAAC,wBAAwB,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAC7D,MAAM,OAAO,GAAG,OAAO,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,UAAU,EAAE,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,EAAE,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC;QACxH,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC;YAAE,OAAO,KAAK,CAAC;QAChE,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAC;QAChD,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;;OAIG;IACH,OAAO,CAAC,IAA4C;QAClD,MAAM,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,IAAI,CAAqD,CAAC;QACzF,OAAO,UAA2B,GAAG,IAAe;YAClD,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC;gBAAE,IAAI,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;YAC9C,OAAO,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;QACzC,CAAC,CAAC;IACJ,CAAC;CACF"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Helpers for worlds that are too big for one room. Cut the world into
3
+ * square cells, give each cell its own room, and hand players from room to
4
+ * room with `movePlayer` as they cross a border.
5
+ */
6
+ /**
7
+ * The id of the room responsible for a position, for a world cut into square
8
+ * cells `cellSize` units wide. Positions may be negative. The result is a
9
+ * valid room id, e.g. `overworld_3_-2`.
10
+ */
11
+ export declare function shardFor(x: number, y: number, cellSize: number, world?: string): string;
12
+ /** A cell of a world cut into squares: its column and row. */
13
+ export interface Cell {
14
+ /** Column: 0 holds x from 0 up to `cellSize`, -1 the column before it. */
15
+ cx: number;
16
+ /** Row: 0 holds y from 0 up to `cellSize`, -1 the row before it. */
17
+ cy: number;
18
+ }
19
+ /** The cell a shard id stands for, or undefined if it is not one of `world`'s. */
20
+ export declare function cellOf(shardId: string, world?: string): Cell | undefined;
package/dist/world.js ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Helpers for worlds that are too big for one room. Cut the world into
3
+ * square cells, give each cell its own room, and hand players from room to
4
+ * room with `movePlayer` as they cross a border.
5
+ */
6
+ /**
7
+ * The id of the room responsible for a position, for a world cut into square
8
+ * cells `cellSize` units wide. Positions may be negative. The result is a
9
+ * valid room id, e.g. `overworld_3_-2`.
10
+ */
11
+ export function shardFor(x, y, cellSize, world = "world") {
12
+ return `${world}_${Math.floor(x / cellSize)}_${Math.floor(y / cellSize)}`;
13
+ }
14
+ /** The cell a shard id stands for, or undefined if it is not one of `world`'s. */
15
+ export function cellOf(shardId, world = "world") {
16
+ const match = /^(.*)_(-?\d+)_(-?\d+)$/.exec(shardId);
17
+ if (!match || match[1] !== world)
18
+ return undefined;
19
+ return { cx: Number(match[2]), cy: Number(match[3]) };
20
+ }
21
+ //# sourceMappingURL=world.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"world.js","sourceRoot":"","sources":["../src/world.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;GAIG;AACH,MAAM,UAAU,QAAQ,CAAC,CAAS,EAAE,CAAS,EAAE,QAAgB,EAAE,KAAK,GAAG,OAAO;IAC9E,OAAO,GAAG,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,QAAQ,CAAC,EAAE,CAAC;AAC5E,CAAC;AAUD,kFAAkF;AAClF,MAAM,UAAU,MAAM,CAAC,OAAe,EAAE,KAAK,GAAG,OAAO;IACrD,MAAM,KAAK,GAAG,wBAAwB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACrD,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,KAAK;QAAE,OAAO,SAAS,CAAC;IACnD,OAAO,EAAE,EAAE,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACxD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,76 @@
1
1
  {
2
2
  "name": "tickflare",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Multiplayer game framework for Cloudflare Workers and Durable Objects",
5
+ "license": "MIT",
6
+ "homepage": "https://tickflare.gridpaper.dev",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Giamme/tickflare.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/Giamme/tickflare/issues"
13
+ },
14
+ "keywords": [
15
+ "cloudflare",
16
+ "cloudflare-workers",
17
+ "durable-objects",
18
+ "multiplayer",
19
+ "game-server",
20
+ "netcode",
21
+ "websocket",
22
+ "state-sync",
23
+ "lockstep",
24
+ "matchmaking"
25
+ ],
26
+ "type": "module",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/server/index.d.ts",
30
+ "import": "./dist/server/index.js",
31
+ "default": "./dist/server/index.js"
32
+ },
33
+ "./client": {
34
+ "types": "./dist/client/index.d.ts",
35
+ "import": "./dist/client/index.js",
36
+ "default": "./dist/client/index.js"
37
+ }
38
+ },
39
+ "files": [
40
+ "dist",
41
+ "src",
42
+ "tools",
43
+ "CHANGELOG.md"
44
+ ],
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "provenance": true
48
+ },
49
+ "engines": {
50
+ "node": ">=22"
51
+ },
52
+ "scripts": {
53
+ "dev": "npm run build:example && wrangler dev --config examples/tic-tac-toe/wrangler.jsonc",
54
+ "dev:arena": "npm run build:example && wrangler dev --config examples/arena/wrangler.jsonc",
55
+ "dev:skirmish": "npm run build:example && wrangler dev --config examples/skirmish/wrangler.jsonc",
56
+ "dev:ranked": "npm run build:example && wrangler dev --config examples/ranked/wrangler.jsonc",
57
+ "build": "tsc -p tsconfig.build.json",
58
+ "prepare": "npm run build",
59
+ "build:example": "esbuild src/client/index.ts --bundle --format=esm --outfile=examples/tic-tac-toe/public/tickflare-client.js && esbuild src/client/index.ts --bundle --format=esm --outfile=examples/arena/public/tickflare-client.js && esbuild src/client/index.ts --bundle --format=esm --outfile=examples/skirmish/public/tickflare-client.js && esbuild src/client/index.ts --bundle --format=esm --outfile=examples/ranked/public/tickflare-client.js",
60
+ "typecheck": "tsc --noEmit",
61
+ "test": "vitest run",
62
+ "docs:dev": "npm --prefix docs install && npm --prefix docs run dev",
63
+ "docs:build": "npm --prefix docs ci && npm --prefix docs run build"
64
+ },
65
+ "devDependencies": {
66
+ "@cloudflare/vitest-plugin": "^1.7.0",
67
+ "@cloudflare/workers-types": "^5.20261110.1",
68
+ "esbuild": "^0.28.2",
69
+ "typescript": "^7.0.2",
70
+ "vitest": "^5.1.0",
71
+ "wrangler": "^4.160.0"
72
+ },
73
+ "bin": {
74
+ "tickflare-rooms": "tools/rooms-report.mjs"
75
+ }
76
+ }