@nano133/nanoterra 0.1.0 → 0.3.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 (106) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/README.md +269 -12
  3. package/ai/SPEC.md +7 -2
  4. package/dist/admin/adapters/d1.d.ts +27 -0
  5. package/dist/admin/adapters/d1.js +73 -0
  6. package/dist/admin/adapters/firestore.d.ts +40 -0
  7. package/dist/admin/adapters/firestore.js +53 -0
  8. package/dist/admin/amount.d.ts +5 -0
  9. package/dist/admin/amount.js +11 -0
  10. package/dist/admin/conformance.d.ts +132 -0
  11. package/dist/admin/conformance.js +467 -0
  12. package/dist/admin/guard.d.ts +38 -0
  13. package/dist/admin/guard.js +57 -0
  14. package/dist/admin/handler.d.ts +63 -0
  15. package/dist/admin/handler.js +170 -0
  16. package/dist/admin/http.d.ts +17 -0
  17. package/dist/admin/http.js +76 -0
  18. package/dist/admin/index.d.ts +13 -0
  19. package/dist/admin/index.js +14 -0
  20. package/dist/admin/memory.d.ts +32 -0
  21. package/dist/admin/memory.js +40 -0
  22. package/dist/admin/panel/api.d.ts +11 -0
  23. package/dist/admin/panel/api.js +33 -0
  24. package/dist/admin/panel/dom.d.ts +7 -0
  25. package/dist/admin/panel/dom.js +33 -0
  26. package/dist/admin/panel/gameCard.d.ts +4 -0
  27. package/dist/admin/panel/gameCard.js +56 -0
  28. package/dist/admin/panel/index.d.ts +10 -0
  29. package/dist/admin/panel/index.js +13 -0
  30. package/dist/admin/panel/mount.d.ts +30 -0
  31. package/dist/admin/panel/mount.js +147 -0
  32. package/dist/admin/panel/shelf.d.ts +24 -0
  33. package/dist/admin/panel/shelf.js +271 -0
  34. package/dist/admin/panel/shelfData.d.ts +37 -0
  35. package/dist/admin/panel/shelfData.js +68 -0
  36. package/dist/admin/panel/signins.d.ts +6 -0
  37. package/dist/admin/panel/signins.js +69 -0
  38. package/dist/admin/store.d.ts +121 -0
  39. package/dist/admin/store.js +3 -0
  40. package/dist/admin/summary.d.ts +39 -0
  41. package/dist/admin/summary.js +85 -0
  42. package/dist/admin/switches.d.ts +58 -0
  43. package/dist/admin/switches.js +61 -0
  44. package/dist/character/bases/bee.js +7 -5
  45. package/dist/character/bases/spec.d.ts +7 -0
  46. package/dist/character/create.d.ts +15 -0
  47. package/dist/character/create.js +69 -2
  48. package/dist/character/ctx.d.ts +12 -2
  49. package/dist/character/index.d.ts +2 -0
  50. package/dist/character/index.js +2 -0
  51. package/dist/character/make.js +2 -1
  52. package/dist/character/preview.d.ts +32 -0
  53. package/dist/character/preview.js +112 -0
  54. package/dist/character/sockets.d.ts +37 -0
  55. package/dist/character/sockets.js +66 -0
  56. package/dist/looks/change.d.ts +8 -4
  57. package/dist/looks/change.js +25 -3
  58. package/dist/looks/index.d.ts +3 -3
  59. package/dist/looks/index.js +2 -2
  60. package/dist/looks/json.d.ts +2 -2
  61. package/dist/looks/json.js +6 -4
  62. package/dist/looks/look.d.ts +29 -3
  63. package/dist/looks/look.js +60 -4
  64. package/dist/model/check.d.ts +59 -0
  65. package/dist/model/check.js +681 -0
  66. package/dist/model/index.d.ts +2 -0
  67. package/dist/model/index.js +5 -0
  68. package/dist/model/limits.d.ts +103 -0
  69. package/dist/model/limits.js +132 -0
  70. package/package.json +11 -3
  71. package/src/admin/adapters/d1.ts +94 -0
  72. package/src/admin/adapters/firestore.ts +78 -0
  73. package/src/admin/amount.ts +14 -0
  74. package/src/admin/conformance.ts +605 -0
  75. package/src/admin/guard.ts +86 -0
  76. package/src/admin/handler.ts +200 -0
  77. package/src/admin/http.ts +74 -0
  78. package/src/admin/index.ts +21 -0
  79. package/src/admin/memory.ts +59 -0
  80. package/src/admin/panel/api.ts +37 -0
  81. package/src/admin/panel/dom.ts +31 -0
  82. package/src/admin/panel/gameCard.ts +63 -0
  83. package/src/admin/panel/index.ts +18 -0
  84. package/src/admin/panel/mount.ts +227 -0
  85. package/src/admin/panel/shelf.ts +361 -0
  86. package/src/admin/panel/shelfData.ts +87 -0
  87. package/src/admin/panel/signins.ts +68 -0
  88. package/src/admin/panel/style.css +551 -0
  89. package/src/admin/store.ts +98 -0
  90. package/src/admin/summary.ts +103 -0
  91. package/src/admin/switches.ts +74 -0
  92. package/src/character/bases/bee.ts +7 -5
  93. package/src/character/bases/spec.ts +4 -0
  94. package/src/character/create.ts +73 -2
  95. package/src/character/ctx.ts +17 -2
  96. package/src/character/index.ts +2 -0
  97. package/src/character/make.ts +2 -1
  98. package/src/character/preview.ts +148 -0
  99. package/src/character/sockets.ts +81 -0
  100. package/src/looks/change.ts +25 -6
  101. package/src/looks/index.ts +3 -3
  102. package/src/looks/json.ts +6 -4
  103. package/src/looks/look.ts +66 -5
  104. package/src/model/check.ts +624 -0
  105. package/src/model/index.ts +5 -0
  106. package/src/model/limits.ts +193 -0
@@ -0,0 +1,148 @@
1
+ import * as THREE from "three";
2
+ import { createCharacter, type Character } from "./create.js";
3
+ import type { LookRecord } from "./record.js";
4
+
5
+ // A picture of a look on the real character, for the Shelf of /admin (or any page): the character is built and dressed once, one frame is
6
+ // drawn with ONE shared offscreen WebGL renderer, and the picture (a PNG data URL) is kept by the look's text, so the same look is drawn
7
+ // once. Pictures are drawn one at a time. With no WebGL, `render` answers null and the page keeps its flat picture.
8
+ //
9
+ // The Shelf (`@nano133/nanoterra/admin/panel`) has no Three.js: give it `previewPicture(load)`, where `load` imports your preview file
10
+ // dynamically, so this file loads only when the Shelf opens (the game starter's src/client/admin.ts does it).
11
+
12
+ /** What draws one look: the game's own character dressed in it (its hat, its models), or by default the package's character. */
13
+ export type PreviewBody<L> = {
14
+ object: THREE.Object3D;
15
+ /** Puts the look on. A promise waits (a model that loads). */
16
+ dress(look: L): void | Promise<void>;
17
+ /** Frees what the body made. */
18
+ dispose(): void;
19
+ };
20
+
21
+ export type LookPreviewOptions<L> = {
22
+ /** The picture's side in CSS pixels (default 112); it is drawn at twice that for a sharp screen. */
23
+ size?: number;
24
+ /** A body for the next picture. Left out: the package's character in `record` (else the island's first look), its shirt in the look's body colour. */
25
+ body?: () => PreviewBody<L>;
26
+ /** The record of the default body. */
27
+ record?: LookRecord;
28
+ /** The background (default: none, a clear picture). */
29
+ background?: THREE.ColorRepresentation | null;
30
+ /** The key of a look in the cache (default: its JSON text). */
31
+ key?: (look: L) => string;
32
+ };
33
+
34
+ export type LookPreview<L> = {
35
+ /** A PNG data URL of the look on the character, or null when the page has no WebGL or the drawing failed. */
36
+ render(look: L): Promise<string | null>;
37
+ /** How many pictures are kept. */
38
+ readonly cached: number;
39
+ /** Frees the renderer (and its WebGL context) and the cache. `render` answers null after it. */
40
+ dispose(): void;
41
+ };
42
+
43
+ /** The look as the starter's looks.json has it: a body colour that paints the shirt (the body when there is no top). */
44
+ type ColourLook = { priceUsd?: number; change?: { body?: string } };
45
+
46
+ function defaultBody<L>(record: LookRecord | undefined): () => PreviewBody<L> {
47
+ return () => {
48
+ const c: Character = createCharacter({ record, reducedMotion: true });
49
+ return {
50
+ object: c.object,
51
+ dress(look) {
52
+ const body = (look as ColourLook).change?.body;
53
+ if (body && ((look as ColourLook).priceUsd ?? 1) > 0) c.setColors({ shirt: body });
54
+ },
55
+ dispose: () => c.dispose(),
56
+ };
57
+ };
58
+ }
59
+
60
+ /** A picture maker. Make one for a page and keep it: it holds one WebGL context while it lives. */
61
+ export function createLookPreview<L>(options: LookPreviewOptions<L> = {}): LookPreview<L> {
62
+ const size = options.size ?? 112;
63
+ const makeBody = options.body ?? defaultBody<L>(options.record);
64
+ const keyOf = options.key ?? ((l: L) => JSON.stringify(l));
65
+ const cache = new Map<string, Promise<string | null>>();
66
+ let renderer: THREE.WebGLRenderer | null = null;
67
+ let failed = false;
68
+ let disposed = false;
69
+ let queue: Promise<unknown> = Promise.resolve();
70
+
71
+ const scene = new THREE.Scene();
72
+ if (options.background != null) scene.background = new THREE.Color(options.background);
73
+ scene.add(new THREE.HemisphereLight("#ffffff", "#8a8f9e", 1.6));
74
+ const sun = new THREE.DirectionalLight("#ffffff", 1.6);
75
+ sun.position.set(2, 4, 5);
76
+ scene.add(sun);
77
+ const camera = new THREE.PerspectiveCamera(30, 1, 0.05, 50);
78
+
79
+ function getRenderer(): THREE.WebGLRenderer | null {
80
+ if (renderer || failed) return renderer;
81
+ try {
82
+ // three makes its own canvas (in a page); with no page or no WebGL this throws, and the answer is null.
83
+ renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
84
+ renderer.setPixelRatio(1);
85
+ renderer.setSize(size * 2, size * 2, false);
86
+ renderer.setClearColor(0x000000, 0);
87
+ } catch {
88
+ failed = true;
89
+ renderer = null;
90
+ }
91
+ return renderer;
92
+ }
93
+
94
+ async function draw(look: L): Promise<string | null> {
95
+ if (disposed) return null;
96
+ const r = getRenderer();
97
+ if (!r) return null;
98
+ const body = makeBody();
99
+ try {
100
+ await body.dress(look);
101
+ if (disposed) return null;
102
+ scene.add(body.object);
103
+ // Frame the whole character (with what it holds) from the front, a little from its right and above.
104
+ body.object.updateMatrixWorld(true);
105
+ const box = new THREE.Box3().setFromObject(body.object);
106
+ const sphere = box.getBoundingSphere(new THREE.Sphere());
107
+ const dir = new THREE.Vector3(-0.6, 0.15, 1).normalize();
108
+ const dist = sphere.radius / Math.sin(THREE.MathUtils.degToRad(camera.fov / 2)) * 1.02;
109
+ camera.position.copy(sphere.center).addScaledVector(dir, dist);
110
+ camera.lookAt(sphere.center);
111
+ camera.near = Math.max(0.01, dist - sphere.radius * 2);
112
+ camera.far = dist + sphere.radius * 2;
113
+ camera.updateProjectionMatrix();
114
+ r.render(scene, camera);
115
+ return r.domElement.toDataURL("image/png");
116
+ } catch {
117
+ return null;
118
+ } finally {
119
+ scene.remove(body.object);
120
+ body.dispose();
121
+ }
122
+ }
123
+
124
+ return {
125
+ render(look) {
126
+ if (disposed) return Promise.resolve(null);
127
+ const key = keyOf(look);
128
+ const hit = cache.get(key);
129
+ if (hit) return hit;
130
+ // One at a time: the renderer and the scene are shared.
131
+ const p = queue.then(() => draw(look));
132
+ queue = p.catch(() => null);
133
+ cache.set(key, p);
134
+ return p;
135
+ },
136
+ get cached() {
137
+ return cache.size;
138
+ },
139
+ dispose() {
140
+ if (disposed) return;
141
+ disposed = true;
142
+ cache.clear();
143
+ renderer?.dispose();
144
+ renderer?.forceContextLoss();
145
+ renderer = null;
146
+ },
147
+ };
148
+ }
@@ -0,0 +1,81 @@
1
+ import * as THREE from "three";
2
+ import type { BaseSpec } from "./bases/spec.js";
3
+ import { BUILD_FACTORS } from "./make.js";
4
+ import type { BoneName } from "./skeleton.js";
5
+
6
+ // The character's three attach points (sockets): the head, the right hand and the back. A socket is a THREE.Object3D on one bone of the
7
+ // island's skeleton, so a thing hung on it follows the walk, the run, the jump and the wave, and costs its own draws (a model of the game's,
8
+ // a .glb say). A worn thing that is merged into the body's geometry (ctx.ts `WornAdapter.add`) adds no draw and needs no socket.
9
+ //
10
+ // Each socket's place depends on the base and on the look (the build widens the body and moves the hands out; the head's size scales the
11
+ // head). `socketFrame` works it out; `createCharacter` keeps its sockets on the new bones after a rebuild (a new base, hair or clothes).
12
+
13
+ /** The names of the sockets. */
14
+ export const SOCKETS = ["head", "hand", "back"] as const;
15
+ export type SocketName = (typeof SOCKETS)[number];
16
+
17
+ /** Where a socket sits: its bone, and its place, turn and scale in that bone's space (the units of the character's own space). */
18
+ export type SocketFrame = { bone: BoneName; position: THREE.Vector3; quaternion: THREE.Quaternion; scale: THREE.Vector3 };
19
+
20
+ /** The head bone's rest height. */
21
+ const HEAD_BONE_Y = 1.5;
22
+ /** The chest bone's rest height. */
23
+ const CHEST_BONE_Y = 1.12;
24
+
25
+ /**
26
+ * The hand's hold: a hand item is modelled standing up (+Y), its grip at the origin, its front at +Z. The hand holds it pointing forward,
27
+ * as a torch is held out: the item's +Y along the character's forward (+Z), its front (+Z) up, its +X to the character's right (-X).
28
+ */
29
+ export const HAND_HOLD = Object.freeze(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 1).normalize(), Math.PI));
30
+
31
+ /** What `socketFrame` reads of a look: its build and its head's size. */
32
+ export type SocketLook = { build: keyof typeof BUILD_FACTORS; head: number };
33
+
34
+ /**
35
+ * A socket's frame on a base for a look.
36
+ * - "head": on the head bone, at the base's hat frame (`spec.hat`), scaled by the hat frame and the head's size: a thing made for the
37
+ * Classic's head, round the middle of the head (the game starter's hats are made so), fits every head.
38
+ * - "hand": on grip_R, in the middle of the right hand (the hands of a wide body are drawn further out than their bone), turned by
39
+ * `HAND_HOLD`.
40
+ * - "back": on the chest bone, on the back of the torso (`spec.back`, else the chest's height and the torso's radius there); its axes are the
41
+ * character's, so a back item is modelled with the side that touches the body at the origin and its bulk towards -Z.
42
+ */
43
+ export function socketFrame(spec: BaseSpec, look: SocketLook, name: SocketName): SocketFrame {
44
+ const t = BUILD_FACTORS[look.build] ?? BUILD_FACTORS.regular;
45
+ const hs = look.head;
46
+ if (name === "head") {
47
+ const h = spec.hat;
48
+ return {
49
+ bone: "head",
50
+ position: new THREE.Vector3(0, (h.y - HEAD_BONE_Y) * hs, (h.z ?? 0) * hs),
51
+ quaternion: new THREE.Quaternion(),
52
+ scale: new THREE.Vector3(h.s[0] * hs, h.s[1] * hs, h.s[2] * hs),
53
+ };
54
+ }
55
+ if (name === "hand") {
56
+ // limbs.ts draws the hand at 0.47 + 0.45 (torso - 1) + armOut from the middle; the bone stays at 0.47.
57
+ const out = 0.45 * (t.torso - 1) + (spec.limbs.armOut ?? 0);
58
+ const at = spec.handAt ?? [0, 0, 0];
59
+ return { bone: "grip_R", position: new THREE.Vector3(-out + at[0], at[1], at[2]), quaternion: HAND_HOLD.clone(), scale: new THREE.Vector3(1, 1, 1) };
60
+ }
61
+ if (name === "back") {
62
+ const y = spec.back?.y ?? CHEST_BONE_Y;
63
+ const z = spec.back?.z ?? -spec.torsoR(y) * t.torso;
64
+ return { bone: "chest", position: new THREE.Vector3(0, y - CHEST_BONE_Y, z), quaternion: new THREE.Quaternion(), scale: new THREE.Vector3(1, 1, 1) };
65
+ }
66
+ throw new TypeError(`@nano133/nanoterra: there is no socket ${JSON.stringify(name)} (the sockets are ${SOCKETS.join(", ")})`);
67
+ }
68
+
69
+ /** Puts a socket object on its bone (from `bones`) at its frame. The object keeps its children: a hung item moves with it. */
70
+ export function placeSocket(socket: THREE.Object3D, bones: Partial<Record<BoneName, THREE.Object3D>>, spec: BaseSpec, look: SocketLook, name: SocketName) {
71
+ const f = socketFrame(spec, look, name);
72
+ const bone = bones[f.bone];
73
+ if (!bone) throw new TypeError(`@nano133/nanoterra: the skeleton has no bone ${f.bone} for the socket ${name}`);
74
+ socket.position.copy(f.position);
75
+ socket.quaternion.copy(f.quaternion);
76
+ socket.scale.copy(f.scale);
77
+ bone.add(socket);
78
+ return socket;
79
+ }
80
+
81
+ export const isSocketName = (v: unknown): v is SocketName => typeof v === "string" && (SOCKETS as readonly string[]).includes(v);
@@ -1,28 +1,46 @@
1
- import type { Look, Problem } from "./look.js";
1
+ import { COLOR_PATTERN, cleanSlots, type Look, type Problem, type Slots } from "./look.js";
2
+
3
+ /** Whether two looks have the same slots: the same names with the same values, in any order. No slots and empty slots are the same; a colour is the same in upper and lower case. */
4
+ export function sameSlots(a: Slots | undefined, b: Slots | undefined): boolean {
5
+ const x = cleanSlots(a) ?? {};
6
+ const y = cleanSlots(b) ?? {};
7
+ const names = Object.keys(x);
8
+ if (names.length !== Object.keys(y).length) return false;
9
+ const norm = (v: string) => (COLOR_PATTERN.test(v) ? v.toLowerCase() : v);
10
+ return names.every((n) => Object.prototype.hasOwnProperty.call(y, n) && norm(x[n]) === norm(y[n]));
11
+ }
2
12
 
3
13
  // What a change of the list does, before it goes live. Owned looks are stored by id: a look that someone owns must stay in the file.
4
14
 
5
15
  /**
6
16
  * The mistakes that a new list would make for the players: an id that someone owns (a paid order gave it to them) is gone from the new
7
- * list. `owned` is every look id that any player owns. The free look is not owned by an order: it is every player's.
17
+ * list, or its slots changed (the game reads the slots of the id that a player owns, so a new slot changes what they own: add a new look instead).
18
+ * `owned` is every look id that any player owns. The free look is not owned by an order: it is every player's, and its slots may change.
19
+ * A change of a price, a name, a body colour or a hat on an owned look is allowed.
8
20
  */
9
21
  export function removalProblems(before: readonly Look[], after: readonly Look[], owned: Iterable<string>): Problem[] {
10
22
  const now = new Set(after.map((l) => l.id));
11
23
  const own = new Set(owned);
12
24
  const out: Problem[] = [];
25
+ const next = new Map(after.map((l, i) => [l.id, { look: l, place: i + 1 }]));
13
26
  for (const l of before) {
14
- if (now.has(l.id) || !own.has(l.id)) continue;
15
- out.push({ look: null, field: "id", message: `The look "${l.id}" (${l.name}) is owned by a player and is not in the new list. Keep it in the file; change its price if you do not want to sell it.` });
27
+ if (!own.has(l.id)) continue;
28
+ const kept = next.get(l.id);
29
+ if (!kept) {
30
+ out.push({ look: null, field: "id", message: `The look "${l.id}" (${l.name}) is owned by a player and is not in the new list. Keep it in the file; change its price if you do not want to sell it.` });
31
+ } else if (!sameSlots(l.slots, kept.look.slots)) {
32
+ out.push({ look: kept.place, field: "slots", message: `The slots of the look "${l.id}" (${l.name}) changed, and a player owns it. Keep its slots as they were, or add a new look with the new slots.` });
33
+ }
16
34
  }
17
35
  return out;
18
36
  }
19
37
 
20
- export type LookField = "name" | "priceUsd" | "body" | "hat" | "hatColor";
38
+ export type LookField = "name" | "priceUsd" | "body" | "hat" | "hatColor" | "slots";
21
39
 
22
40
  export type LooksDiff = {
23
41
  added: Look[];
24
42
  removed: Look[];
25
- /** Looks with the same id and a different name, price, colour or hat. */
43
+ /** Looks with the same id and a different name, price, colour, hat or slots. */
26
44
  changed: { id: string; before: Look; after: Look; fields: LookField[] }[];
27
45
  };
28
46
 
@@ -40,6 +58,7 @@ export function diffLooks(before: readonly Look[], after: readonly Look[]): Look
40
58
  if (a.change.body.toLowerCase() !== b.change.body.toLowerCase()) fields.push("body");
41
59
  if (a.change.hat !== b.change.hat) fields.push("hat");
42
60
  if ((a.change.hatColor ?? "").toLowerCase() !== (b.change.hatColor ?? "").toLowerCase()) fields.push("hatColor");
61
+ if (!sameSlots(a.slots, b.slots)) fields.push("slots");
43
62
  if (fields.length) diff.changed.push({ id: a.id, before: b, after: a, fields });
44
63
  }
45
64
  return diff;
@@ -1,7 +1,7 @@
1
- export { HATS, ID_PATTERN, COLOR_PATTERN, NAME_MAX, PRICE_MAX_USD, wholeCents, lookProblems, checkLooks, usdText } from "./look.js";
2
- export type { Hat, Look, Problem } from "./look.js";
1
+ export { HATS, ID_PATTERN, COLOR_PATTERN, NAME_MAX, PRICE_MAX_USD, SLOTS_MAX, SLOT_NAME_PATTERN, SLOT_WORD_PATTERN, RESERVED_SLOT_NAMES, wholeCents, lookProblems, checkLooks, cleanSlots, slotValueOk, usdText } from "./look.js";
2
+ export type { Hat, Look, Problem, Slots } from "./look.js";
3
3
  export { PRICE_LADDER, rungUsd, rungOf, priceText } from "./ladder.js";
4
4
  export type { Rung } from "./ladder.js";
5
- export { removalProblems, diffLooks } from "./change.js";
5
+ export { removalProblems, diffLooks, sameSlots } from "./change.js";
6
6
  export type { LooksDiff, LookField } from "./change.js";
7
7
  export { looksJson, slugId } from "./json.js";
package/src/looks/json.ts CHANGED
@@ -1,15 +1,17 @@
1
- import { ID_PATTERN, type Look } from "./look.js";
1
+ import { cleanSlots, ID_PATTERN, type Look } from "./look.js";
2
2
 
3
3
  /**
4
- * The text of looks.json for a list of looks: one look on each line, in the order id, name, priceUsd, change, as the game starter's
5
- * file is written, so a change of one look is a change of one line in a diff. It ends with a new line.
4
+ * The text of looks.json for a list of looks: one look on each line, in the order id, name, priceUsd, change (and slots, when the look has any), as the game
5
+ * starter's file is written, so a change of one look is a change of one line in a diff. A look with no slots is written exactly as before. It ends with a new line.
6
6
  */
7
7
  export function looksJson(looks: readonly Look[]): string {
8
8
  const row = (l: Look) => {
9
9
  const change = [`"body": ${JSON.stringify(l.change.body)}`];
10
10
  if (l.change.hat !== undefined) change.push(`"hat": ${JSON.stringify(l.change.hat)}`);
11
11
  if (l.change.hatColor !== undefined) change.push(`"hatColor": ${JSON.stringify(l.change.hatColor)}`);
12
- return ` { "id": ${JSON.stringify(l.id)}, "name": ${JSON.stringify(l.name)}, "priceUsd": ${l.priceUsd}, "change": { ${change.join(", ")} } }`;
12
+ const slots = cleanSlots(l.slots);
13
+ const tail = slots ? `, "slots": { ${Object.keys(slots).map((k) => `${JSON.stringify(k)}: ${JSON.stringify(slots[k])}`).join(", ")} }` : "";
14
+ return ` { "id": ${JSON.stringify(l.id)}, "name": ${JSON.stringify(l.name)}, "priceUsd": ${l.priceUsd}, "change": { ${change.join(", ")} }${tail} }`;
13
15
  };
14
16
  return `[\n${looks.map(row).join(",\n")}\n]\n`;
15
17
  }
package/src/looks/look.ts CHANGED
@@ -13,10 +13,27 @@ export type Look = {
13
13
  /** The price in US dollars with at most 2 decimals, for example 0.25. 0 means free for everyone. */
14
14
  priceUsd: number;
15
15
  change: { body: string; hat?: Hat; hatColor?: string };
16
+ /**
17
+ * What a game defines for itself: up to 8 slots, each a name and a value, that the game's own code reads ("wings": "ember", "trail": "#ffcf5a"). A name is 1 to 24
18
+ * lowercase letters, digits or dashes, starting with a letter; a value is a word (1 to 40 lowercase letters, digits or dashes) or a colour ("#rrggbb"). Optional: a look
19
+ * without `slots`, or with an empty one, is the same look. Because players own a look by its id, the slots of a look that someone owns must not change.
20
+ */
21
+ slots?: Slots;
16
22
  };
17
23
 
24
+ /** The slots of a look: names and values, words or colours. */
25
+ export type Slots = Record<string, string>;
26
+
18
27
  export const ID_PATTERN = /^[a-z0-9-]{1,40}$/;
19
28
  export const COLOR_PATTERN = /^#[0-9a-f]{6}$/i;
29
+ /** At most this many slots on a look. */
30
+ export const SLOTS_MAX = 8;
31
+ /** A slot's name: 1 to 24 lowercase letters, digits or dashes, starting with a letter. */
32
+ export const SLOT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,23}$/;
33
+ /** Names that a slot may not have: they mean something to an object (`constructor`, `prototype`). */
34
+ export const RESERVED_SLOT_NAMES: readonly string[] = ["constructor", "prototype"];
35
+ /** A slot's value that is a word: 1 to 40 lowercase letters, digits or dashes. (The other kind of value is a colour, COLOR_PATTERN.) */
36
+ export const SLOT_WORD_PATTERN = /^[a-z0-9-]{1,40}$/;
20
37
  export const NAME_MAX = 40;
21
38
  export const PRICE_MAX_USD = 1000;
22
39
 
@@ -24,14 +41,17 @@ export const PRICE_MAX_USD = 1000;
24
41
  export type Problem = {
25
42
  /** The place of the look in the list, from 1, or null for a mistake of the whole list. */
26
43
  look: number | null;
27
- /** The field: "list", "id", "name", "priceUsd", "change.body", "change.hat", "change.hatColor" or "free". */
44
+ /** The field: "list", "id", "name", "priceUsd", "change.body", "change.hat", "change.hatColor", "slots", "slots.<name>" or "free". (The change rules also use "slots" for a slot that changed on a look that players own.) */
28
45
  field: string;
29
46
  message: string;
30
47
  };
31
48
 
32
- /** Whether a price has no fraction of a cent. `Math.round(x * 100) === x * 100` is wrong for 0.07, 0.29 and 1.1 (floating point). */
49
+ /**
50
+ * Whether a price has no fraction of a cent. `Math.round(x * 100) === x * 100` is wrong for 0.07, 0.29 and 1.1 (floating point), and a tolerance is wrong the other way (0.300000001
51
+ * and 1e-9 would pass): a price is whole cents when it is exactly the number that its own two-decimal text names.
52
+ */
33
53
  export function wholeCents(usd: number): boolean {
34
- return Math.abs(usd * 100 - Math.round(usd * 100)) < 1e-6;
54
+ return typeof usd === "number" && Number.isFinite(usd) && Number(usd.toFixed(2)) === usd;
35
55
  }
36
56
 
37
57
  /** Every mistake in a list of looks (looks.json as it was read), in the order of the list. An empty array means the list is good. */
@@ -54,16 +74,57 @@ export function lookProblems(raw: unknown): Problem[] {
54
74
  if (typeof v.change?.body !== "string" || !COLOR_PATTERN.test(v.change.body)) add("change.body", '"change.body" must be a colour like "#4aa8ff"');
55
75
  if (v.change?.hat !== undefined && !(HATS as readonly unknown[]).includes(v.change.hat)) add("change.hat", `"change.hat" must be one of ${HATS.join(", ")}`);
56
76
  if (v.change?.hatColor !== undefined && (typeof v.change.hatColor !== "string" || !COLOR_PATTERN.test(v.change.hatColor))) add("change.hatColor", '"change.hatColor" must be a colour like "#1c6e4f"');
77
+ if (v.slots !== undefined) slotProblems(v.slots).forEach((s) => add(s.field, s.message));
57
78
  });
58
79
  if (!out.length && !free) out.push({ look: null, field: "free", message: "looks.json needs at least one free look (priceUsd 0): every player starts with it" });
59
80
  return out;
60
81
  }
61
82
 
83
+ /** Whether `v` is a plain object (not null, not a list, not a class instance). */
84
+ const isPlain = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v) && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
85
+
86
+ /** Whether a slot's value is good: a word or a colour. */
87
+ export const slotValueOk = (v: unknown): v is string => typeof v === "string" && (SLOT_WORD_PATTERN.test(v) || COLOR_PATTERN.test(v));
88
+
89
+ /** The mistakes in one look's `slots` (the look's own message is added by the caller): the field is "slots" or "slots.<name>". */
90
+ function slotProblems(slots: unknown): { field: string; message: string }[] {
91
+ if (!isPlain(slots)) return [{ field: "slots", message: '"slots" must be an object of names and values, like { "wings": "ember" }' }];
92
+ const names = Object.keys(slots);
93
+ const out: { field: string; message: string }[] = [];
94
+ if (names.length > SLOTS_MAX) out.push({ field: "slots", message: `"slots" can have at most ${SLOTS_MAX} slots (this one has ${names.length})` });
95
+ for (const name of names) {
96
+ if (!SLOT_NAME_PATTERN.test(name)) out.push({ field: `slots.${name}`, message: `the slot name "${name}" must be 1 to 24 lowercase letters, digits or dashes, starting with a letter` });
97
+ else if (RESERVED_SLOT_NAMES.includes(name)) out.push({ field: `slots.${name}`, message: `the slot name "${name}" is reserved: choose another` });
98
+ else if (!slotValueOk(slots[name])) out.push({ field: `slots.${name}`, message: `"slots.${name}" must be a word (1 to 40 lowercase letters, digits or dashes) or a colour like "#ffcf5a"` });
99
+ }
100
+ return out;
101
+ }
102
+
103
+ /**
104
+ * The slots as a clean copy, or undefined when there are none (an empty `slots` is the same as none). The creator's order of names is kept. A COLOUR is written in lower case
105
+ * ("#ffcf5a"), so the game always reads one text for one colour: a change of only the case of a colour is then no change at all, for the game as for the check.
106
+ */
107
+ export function cleanSlots(slots: Slots | undefined): Slots | undefined {
108
+ if (!slots) return undefined;
109
+ const names = Object.keys(slots);
110
+ return names.length ? Object.fromEntries(names.map((n) => [n, typeof slots[n] === "string" && COLOR_PATTERN.test(slots[n]) ? slots[n].toLowerCase() : slots[n]])) : undefined;
111
+ }
112
+
62
113
  /** The looks, or an Error that says the first mistake in plain words. The same words as the starter's `checkLooks`. */
63
- export function checkLooks(raw: unknown): Look[] {
114
+ export function checkLooks(rawInput: unknown): Look[] {
115
+ // One snapshot of the data is checked AND copied: a getter or a changing value cannot be good for the check and something else for the copy. (JSON cannot hold one.)
116
+ let raw: unknown = rawInput;
117
+ try {
118
+ raw = rawInput === undefined ? undefined : JSON.parse(JSON.stringify(rawInput));
119
+ } catch {
120
+ throw new Error("looks.json must be plain JSON data");
121
+ }
64
122
  const first = lookProblems(raw)[0];
65
123
  if (first) throw new Error(first.message);
66
- return (raw as Look[]).map((l) => ({ id: l.id, name: l.name, priceUsd: l.priceUsd, change: { body: l.change.body, hat: l.change.hat, hatColor: l.change.hatColor } }));
124
+ return (raw as Look[]).map((l) => {
125
+ const slots = cleanSlots(l.slots);
126
+ return { id: l.id, name: l.name, priceUsd: l.priceUsd, change: { body: l.change.body, hat: l.change.hat, hatColor: l.change.hatColor }, ...(slots ? { slots } : {}) };
127
+ });
67
128
  }
68
129
 
69
130
  /** "$0.25" */