@margoengine/ecs 0.0.0-stage → 1.0.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.
@@ -0,0 +1,278 @@
1
+ import { MargoError as e } from "@margoengine/math/errors";
2
+ import { hexColor as t } from "@margoengine/math/color";
3
+ //#region src/scripts.ts
4
+ var n = {
5
+ vec2: 2,
6
+ vec3: 3,
7
+ vec4: 4,
8
+ color: 4
9
+ }, r = [
10
+ "number",
11
+ "boolean",
12
+ "string",
13
+ "enum",
14
+ "entity",
15
+ "asset",
16
+ ...Object.keys(n)
17
+ ], i = [
18
+ "initialize",
19
+ "postInitialize",
20
+ "update",
21
+ "postUpdate",
22
+ "fixedUpdate",
23
+ "onEnable",
24
+ "onDisable",
25
+ "onAttributeChange",
26
+ "destroy",
27
+ "swap"
28
+ ], a = (e) => e.length <= 7 ? t(e) : void 0, o = (e, t, n) => /* @__PURE__ */ RangeError(`Invalid ${t.type} attribute ${e}: ${n}`);
29
+ function s(e, t, r) {
30
+ let { type: i, min: s = -Infinity, max: c = Infinity } = t;
31
+ if (i === "number") {
32
+ if (typeof r != "number" || !Number.isFinite(r)) throw o(e, t, "use a finite number");
33
+ if (r < s || r > c) throw o(e, t, `${r} is outside ${s}..${c}`);
34
+ return r;
35
+ }
36
+ if (i === "boolean") {
37
+ if (typeof r != "boolean") throw o(e, t, "use true or false");
38
+ return r;
39
+ }
40
+ if (i === "string") {
41
+ if (typeof r != "string") throw o(e, t, "use a string");
42
+ return r;
43
+ }
44
+ if (i === "enum") {
45
+ if (!t.options.includes(r)) throw o(e, t, `use one of ${t.options.join(", ")}`);
46
+ return r;
47
+ }
48
+ if (i === "entity") {
49
+ if (r !== null && !(Number.isInteger(r) && r >= 0)) throw o(e, t, "use an entity id or null");
50
+ return r;
51
+ }
52
+ if (i === "asset") {
53
+ if (r !== null && (typeof r != "string" || !r)) throw o(e, t, "use an asset id string or null");
54
+ return r;
55
+ }
56
+ let l = n[i], u = i === "color" && typeof r == "string" ? a(r) : r;
57
+ if (!(Array.isArray(u) || ArrayBuffer.isView(u)) || u.length !== l) throw o(e, t, `use ${l} numbers${i === "color" ? " or a #rrggbb string" : ""}`);
58
+ let d = Array.from(u), f = i === "color" ? Math.max(s, 0) : s, p = i === "color" ? Math.min(c, 1) : c;
59
+ for (let n of d) {
60
+ if (typeof n != "number" || !Number.isFinite(n)) throw o(e, t, "use finite numbers");
61
+ if (n < f || n > p) throw o(e, t, `${n} is outside ${f}..${p}`);
62
+ }
63
+ return d;
64
+ }
65
+ var c = (e, t) => Array.isArray(e) && Array.isArray(t) ? e.length === t.length && e.every((e, n) => e === t[n]) : e === t, l = (e) => Array.isArray(e) ? [...e] : e;
66
+ function u(e) {
67
+ switch (e.type) {
68
+ case "number": return 0;
69
+ case "boolean": return !1;
70
+ case "string": return "";
71
+ case "enum": return e.options[0];
72
+ case "color": return [
73
+ 1,
74
+ 1,
75
+ 1,
76
+ 1
77
+ ];
78
+ case "entity":
79
+ case "asset": return null;
80
+ default: return Array(n[e.type]).fill(0);
81
+ }
82
+ }
83
+ function d(e) {
84
+ if (!e || typeof e.name != "string" || !e.name) throw TypeError("Invalid script; give it a non-empty name");
85
+ let t = {};
86
+ for (let [n, i] of Object.entries(e.attributes ?? {})) {
87
+ if (!i || !r.includes(i.type)) throw TypeError(`Unknown attribute type for ${e.name}.${n}; use number, boolean, string, enum, vec2, vec3, vec4, color, entity or asset`);
88
+ if (i.type === "enum" && (!Array.isArray(i.options) || !i.options.length)) throw TypeError(`Enum attribute ${e.name}.${n} needs a non-empty options list`);
89
+ let a = {
90
+ ...i,
91
+ title: i.title ?? n
92
+ };
93
+ a.default = s(n, a, i.default === void 0 ? u(a) : i.default), t[n] = Object.freeze(a);
94
+ }
95
+ let n = {
96
+ name: e.name,
97
+ priority: e.priority ?? 0,
98
+ attributes: Object.freeze(t)
99
+ };
100
+ for (let t of i) if (e[t] !== void 0) {
101
+ if (typeof e[t] != "function") throw TypeError(`Script ${e.name} hook ${t} is not a function; pass a function or leave the hook out`);
102
+ n[t] = e[t];
103
+ }
104
+ return Object.freeze(n);
105
+ }
106
+ var f = class {
107
+ constructor(e, t = {}) {
108
+ this.world = e, this.options = t, this.types = /* @__PURE__ */ new Map(), this.all = [], this.byEntity = /* @__PURE__ */ new Map(), this.pending = [], this.seq = 0, this.errors = [], this.busy = !1, this.disposed = !1, this.store = { remove: (e) => this.removeAll(e) }, e.attach(this.store);
109
+ }
110
+ register(e) {
111
+ if (this.live(), this.types.has(e.name)) throw TypeError(`Script ${e.name} is already registered; use reload to replace it`);
112
+ return this.types.set(e.name, e), this;
113
+ }
114
+ get(e) {
115
+ return this.types.get(e);
116
+ }
117
+ schema() {
118
+ return [...this.types.values()].map((e) => ({
119
+ name: e.name,
120
+ priority: e.priority,
121
+ attributes: Object.entries(e.attributes).map(([e, t]) => JSON.parse(JSON.stringify({
122
+ name: e,
123
+ ...t
124
+ })))
125
+ }));
126
+ }
127
+ add(t, n, { values: r = {}, enabled: i = !0 } = {}) {
128
+ this.live(), this.world.check(t);
129
+ let a = typeof n == "string" ? n : n.name, o = this.types.get(a);
130
+ if (!o) throw new e("state", `Script ${a} is not registered; call register first`);
131
+ for (let e of Object.keys(r)) if (!(e in o.attributes)) throw RangeError(`Unknown attribute ${e} for script ${o.name}; declare it in attributes`);
132
+ let c = {
133
+ entity: t,
134
+ world: this.world,
135
+ type: o,
136
+ state: {},
137
+ attributes: {},
138
+ values: {},
139
+ seq: this.seq++,
140
+ dead: !1,
141
+ isInitialized: !1,
142
+ isEnabled: !!i
143
+ };
144
+ for (let [e, t] of Object.entries(o.attributes)) c.values[e] = s(e, t, e in r ? r[e] : t.default);
145
+ this.shape(c), Object.defineProperties(c, {
146
+ enabled: {
147
+ enumerable: !0,
148
+ get: () => c.isEnabled,
149
+ set: (e) => this.setEnabled(c, !!e)
150
+ },
151
+ initialized: {
152
+ enumerable: !0,
153
+ get: () => c.isInitialized
154
+ }
155
+ }), this.all.push(c), this.sortAll();
156
+ let l = this.byEntity.get(t);
157
+ return l ? l.push(c) : this.byEntity.set(t, [c]), this.pending.push(c), c;
158
+ }
159
+ on(e) {
160
+ return this.byEntity.get(e) ?? [];
161
+ }
162
+ remove(e, t) {
163
+ if (this.live(), typeof e != "number") return +!!this.kill(e);
164
+ let n = typeof t == "string" ? t : t?.name, r = (this.byEntity.get(e) ?? []).filter((e) => n === void 0 || e.type.name === n);
165
+ return this.pass(() => r.forEach((e) => this.kill(e))), r.length;
166
+ }
167
+ flush() {
168
+ this.live(), this.pass(() => {
169
+ for (;;) {
170
+ let e = this.pending.filter((e) => !e.dead && e.isEnabled);
171
+ if (!e.length) break;
172
+ this.pending = this.pending.filter((e) => !e.dead && !e.isEnabled), e.sort((e, t) => e.type.priority - t.type.priority || e.seq - t.seq);
173
+ for (let t of e) t.dead || t.isInitialized || (this.call(t, "onEnable"), t.isInitialized = !0, this.call(t, "initialize"));
174
+ for (let t of e) t.dead || this.call(t, "postInitialize");
175
+ }
176
+ });
177
+ }
178
+ update(e) {
179
+ this.step(e, ["update", "postUpdate"]);
180
+ }
181
+ fixedUpdate(e) {
182
+ this.step(e, ["fixedUpdate"]);
183
+ }
184
+ install(e, t = {}) {
185
+ return e.add("scripts.fixed", (e) => this.fixedUpdate(e.delta), { fixed: !0 }), e.add("scripts", (e) => this.update(e.delta), t), this;
186
+ }
187
+ reload(e, { reinitialize: t = !1 } = {}) {
188
+ this.live();
189
+ let n = this.types.get(e.name);
190
+ if (this.types.set(e.name, e), !n) return 0;
191
+ let r = 0;
192
+ return this.pass(() => {
193
+ for (let i of this.all.filter((e) => e.type === n)) {
194
+ let a = t && i.isInitialized;
195
+ a && (i.isEnabled && this.call(i, "onDisable"), this.call(i, "destroy"));
196
+ let o = i.values;
197
+ i.type = e, i.values = {};
198
+ for (let [t, n] of Object.entries(e.attributes)) try {
199
+ i.values[t] = t in o ? s(t, n, o[t]) : l(n.default);
200
+ } catch {
201
+ i.values[t] = l(n.default);
202
+ }
203
+ this.shape(i), a && (i.isInitialized = !1, i.state = {}, this.pending.push(i)), this.call(i, "swap", n), r++;
204
+ }
205
+ this.sortAll();
206
+ }), r;
207
+ }
208
+ [Symbol.dispose]() {
209
+ this.disposed || (this.disposed = !0, this.world.detach(this.store), this.pass(() => [...this.all].forEach((e) => this.kill(e))));
210
+ }
211
+ dispose() {
212
+ this[Symbol.dispose]();
213
+ }
214
+ live() {
215
+ if (this.disposed) throw new e("disposed", "Scripts is disposed; create a new Scripts");
216
+ }
217
+ sortAll() {
218
+ this.all.sort((e, t) => e.type.priority - t.type.priority || e.seq - t.seq);
219
+ }
220
+ shape(e) {
221
+ let t = {};
222
+ for (let [n, r] of Object.entries(e.type.attributes)) Object.defineProperty(t, n, {
223
+ enumerable: !0,
224
+ get: () => l(e.values[n]),
225
+ set: (t) => {
226
+ let i = s(n, r, t), a = e.values[n];
227
+ c(a, i) || (e.values[n] = i, e.isInitialized && !e.dead && this.pass(() => this.call(e, "onAttributeChange", n, l(i), l(a))));
228
+ }
229
+ });
230
+ e.attributes = Object.freeze(t);
231
+ }
232
+ setEnabled(e, t) {
233
+ e.dead || e.isEnabled === t || (e.isEnabled = t, e.isInitialized ? this.pass(() => this.call(e, t ? "onEnable" : "onDisable")) : t && !this.pending.includes(e) && this.pending.push(e));
234
+ }
235
+ kill(e) {
236
+ if (e.dead) return !1;
237
+ e.dead = !0, this.all = this.all.filter((t) => t !== e), this.pending = this.pending.filter((t) => t !== e);
238
+ let t = (this.byEntity.get(e.entity) ?? []).filter((t) => t !== e);
239
+ return t.length ? this.byEntity.set(e.entity, t) : this.byEntity.delete(e.entity), e.isInitialized &&= (this.pass(() => {
240
+ e.isEnabled && this.call(e, "onDisable"), this.call(e, "destroy");
241
+ }), !1), !0;
242
+ }
243
+ removeAll(e) {
244
+ this.pass(() => [...this.byEntity.get(e) ?? []].forEach((e) => this.kill(e)));
245
+ }
246
+ call(e, t, ...n) {
247
+ let r = e.type[t];
248
+ if (r) try {
249
+ r.apply(e, n);
250
+ } catch (n) {
251
+ this.options.onError ? this.options.onError(n, {
252
+ script: e,
253
+ hook: t
254
+ }) : this.errors.push(n);
255
+ }
256
+ }
257
+ step(e, t) {
258
+ if (this.live(), !Number.isFinite(e) || e < 0) throw RangeError("Invalid script delta; pass a finite number of seconds, 0 or more");
259
+ this.flush(), this.pass(() => {
260
+ for (let n of t) for (let t of [...this.all]) !t.dead && t.isEnabled && t.isInitialized && this.call(t, n, e);
261
+ });
262
+ }
263
+ pass(t) {
264
+ if (this.busy) return t();
265
+ this.busy = !0;
266
+ try {
267
+ t();
268
+ } finally {
269
+ this.busy = !1;
270
+ }
271
+ if (this.errors.length) {
272
+ let t = this.errors.length, n = new e("failed", `${t} script hook${t > 1 ? "s" : ""} threw; the first error is in cause, or pass onError to handle each`);
273
+ throw Object.defineProperty(n, "cause", { value: this.errors[0] }), this.errors = [], n;
274
+ }
275
+ }
276
+ };
277
+ //#endregion
278
+ export { f as Scripts, d as defineScript };
@@ -0,0 +1,34 @@
1
+ /** App-owned encoding for values that have no portable representation, such as asset references. */
2
+ export interface SnapshotValueCodec {
3
+ /** Stable wire name, unique in one codec list. */
4
+ name: string;
5
+ /** True for values owned by this codec. */
6
+ test(value: unknown): boolean;
7
+ /** Return supported portable data, not executable source. */
8
+ encode(value: unknown): unknown;
9
+ /** Reconstruct a value from portable data. Custom cycles must use app keys. */
10
+ decode(value: unknown): unknown;
11
+ }
12
+ /** Snapshot I/O limits and cancellation. */
13
+ export interface SnapshotOptions {
14
+ /** Abort asynchronous compression, decompression and hashing. Default none. */
15
+ signal?: AbortSignal;
16
+ /** Maximum packet and expanded text bytes. Default 64 MiB. */
17
+ maxBytes?: number;
18
+ /** App reference codecs. Default none. */
19
+ codecs?: readonly SnapshotValueCodec[];
20
+ }
21
+ /** Base64 text of `bytes`; uses the built-in encoder where the runtime has one (Node 26, current browsers). */
22
+ export declare function bytesToBase64(bytes: Uint8Array): string;
23
+ /** Bytes of canonical padded base64 `text`; throws SyntaxError on anything else, as the built-in strict decoder does. */
24
+ export declare function base64ToBytes(text: string): Uint8Array;
25
+ /** Lower-case hexadecimal text of `bytes`; uses the built-in encoder where the runtime has one. */
26
+ export declare function bytesToHex(bytes: Uint8Array): string;
27
+ /** Encode a portable identity graph, preserving cycles and shared buffers. */
28
+ export declare function encodeGraph(root: unknown, codecs?: readonly SnapshotValueCodec[]): string;
29
+ /** Decode a bounded graph without setting prototypes or evaluating code. */
30
+ export declare function decodeGraph(text: string, codecs?: readonly SnapshotValueCodec[]): unknown;
31
+ /** Validate I/O bounds before allocation. */
32
+ export declare function byteLimit(options: SnapshotOptions): number;
33
+ /** Compress/decompress with native bounded streams; cancellation rejects without partial state. */
34
+ export declare function transform(bytes: Uint8Array, decompress: boolean, options: SnapshotOptions): Promise<Uint8Array>;
@@ -0,0 +1,34 @@
1
+ import type { ComponentStore, Entity, World } from './index.js';
2
+ import { type SnapshotOptions } from './serialize-codec.js';
3
+ export type { SnapshotOptions, SnapshotValueCodec } from './serialize-codec.js';
4
+ /** Restore options. Entity mappings translate remote ids without resurrecting stale local handles. */
5
+ export interface SnapshotRestoreOptions extends SnapshotOptions {
6
+ /** Mapping returned by the previous restore. Default identity for the world's current ids. */
7
+ entities?: ReadonlyMap<Entity, Entity>;
8
+ }
9
+ /** Binary snapshots of named components and entity lifetime, independent of save or rendering packages. */
10
+ export declare class WorldSerializer {
11
+ readonly world: World;
12
+ private readonly stores;
13
+ /** @throws TypeError for empty selection, foreign stores, unsupported fields or duplicate codec names. */
14
+ constructor(world: World, components: Readonly<Record<string, ComponentStore>>);
15
+ /** Capture chosen fields, shared reference graphs, all live entity ids and component membership. */
16
+ snapshot(options?: SnapshotOptions): Promise<Uint8Array>;
17
+ /**
18
+ * Validate the complete packet before changing membership, then restore selected fields and entity lifetime.
19
+ * Surviving entities retain unselected components. Removed entities are destroyed. New entities get safe local ids.
20
+ * Return a fresh remote-to-local map for later snapshots/deltas and app-owned entity-reference fields.
21
+ * Observer exceptions propagate after their underlying mutation, as with Component.add.
22
+ * @throws TypeError for malformed packets, incompatible schemas, invalid mappings or unsupported values.
23
+ * @throws RangeError for byte limits, graph limits or insufficient entity capacity, before entity mutation.
24
+ */
25
+ restore(packet: Uint8Array, options?: SnapshotRestoreOptions): Promise<Map<Entity, Entity>>;
26
+ }
27
+ /** Create a baseline-checked binary delta, comparing fixed 256-character blocks using native string comparisons. */
28
+ export declare function createDelta(before: Uint8Array, after: Uint8Array, options?: SnapshotOptions): Promise<Uint8Array>;
29
+ /**
30
+ * Apply a delta to its exact baseline and return a complete snapshot. Both fingerprints are checked.
31
+ * For undo, createDelta(after,before) creates the inverse. No world mutation occurs here.
32
+ * @throws TypeError for corrupt, out-of-order or wrong-baseline deltas.
33
+ */
34
+ export declare function applyDelta(before: Uint8Array, delta: Uint8Array, options?: SnapshotOptions): Promise<Uint8Array>;