@codehz/ecs 0.3.7 → 0.3.9

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.
package/index.mjs ADDED
@@ -0,0 +1,1881 @@
1
+ //#region src/entity.ts
2
+ const COMPONENT_ID_MAX = 1023;
3
+ const ENTITY_ID_START = 1024;
4
+ /**
5
+ * Constants for relation ID encoding
6
+ */
7
+ const RELATION_SHIFT = 2 ** 42;
8
+ const WILDCARD_TARGET_ID = 0;
9
+ function relation(componentId, targetId) {
10
+ if (!isComponentId(componentId)) throw new Error("First argument must be a valid component ID");
11
+ let actualTargetId;
12
+ if (targetId === "*") actualTargetId = WILDCARD_TARGET_ID;
13
+ else {
14
+ if (!isEntityId(targetId) && !isComponentId(targetId)) throw new Error("Second argument must be a valid entity ID, component ID, or '*'");
15
+ actualTargetId = targetId;
16
+ }
17
+ return -(componentId * RELATION_SHIFT + actualTargetId);
18
+ }
19
+ /**
20
+ * Check if an ID is a component ID
21
+ */
22
+ function isComponentId(id) {
23
+ return id >= 1 && id <= COMPONENT_ID_MAX;
24
+ }
25
+ /**
26
+ * Check if an ID is an entity ID
27
+ */
28
+ function isEntityId(id) {
29
+ return id >= ENTITY_ID_START;
30
+ }
31
+ /**
32
+ * Check if an ID is a relation ID
33
+ */
34
+ function isRelationId(id) {
35
+ return id < 0;
36
+ }
37
+ /**
38
+ * Check if an ID is a wildcard relation id
39
+ */
40
+ function isWildcardRelationId(id) {
41
+ if (!isRelationId(id)) return false;
42
+ return -id % RELATION_SHIFT === WILDCARD_TARGET_ID;
43
+ }
44
+ /**
45
+ * Decode a relation ID into component and target IDs
46
+ * @param relationId The relation ID (must be negative)
47
+ * @returns Object with componentId, targetId, and relation type
48
+ */
49
+ function decodeRelationId(relationId) {
50
+ if (!isRelationId(relationId)) throw new Error("ID is not a relation ID");
51
+ const absId = -relationId;
52
+ const componentId = Math.floor(absId / RELATION_SHIFT);
53
+ const targetId = absId % RELATION_SHIFT;
54
+ if (targetId === WILDCARD_TARGET_ID) return {
55
+ componentId,
56
+ targetId,
57
+ type: "wildcard"
58
+ };
59
+ else if (isEntityId(targetId)) return {
60
+ componentId,
61
+ targetId,
62
+ type: "entity"
63
+ };
64
+ else if (isComponentId(targetId)) return {
65
+ componentId,
66
+ targetId,
67
+ type: "component"
68
+ };
69
+ else throw new Error("Invalid target ID in relation");
70
+ }
71
+ /**
72
+ * Get the string representation of an ID type
73
+ */
74
+ function getIdType(id) {
75
+ if (isComponentId(id)) return "component";
76
+ if (isEntityId(id)) return "entity";
77
+ if (isRelationId(id)) try {
78
+ const decoded = decodeRelationId(id);
79
+ if (!isComponentId(decoded.componentId) || decoded.type !== "wildcard" && !isEntityId(decoded.targetId) && !isComponentId(decoded.targetId)) return "invalid";
80
+ switch (decoded.type) {
81
+ case "entity": return "entity-relation";
82
+ case "component": return "component-relation";
83
+ case "wildcard": return "wildcard-relation";
84
+ }
85
+ } catch (error) {
86
+ return "invalid";
87
+ }
88
+ return "invalid";
89
+ }
90
+ /**
91
+ * Get detailed type information for an EntityId
92
+ * @param id The EntityId to analyze
93
+ * @returns Detailed type information including relation subtypes
94
+ */
95
+ function getDetailedIdType(id) {
96
+ if (isComponentId(id)) return { type: "component" };
97
+ if (isEntityId(id)) return { type: "entity" };
98
+ if (isRelationId(id)) try {
99
+ const decoded = decodeRelationId(id);
100
+ if (!isComponentId(decoded.componentId) || decoded.type !== "wildcard" && !isEntityId(decoded.targetId) && !isComponentId(decoded.targetId)) return { type: "invalid" };
101
+ let type;
102
+ switch (decoded.type) {
103
+ case "entity":
104
+ type = "entity-relation";
105
+ break;
106
+ case "component":
107
+ type = "component-relation";
108
+ break;
109
+ case "wildcard":
110
+ type = "wildcard-relation";
111
+ break;
112
+ }
113
+ return {
114
+ type,
115
+ componentId: decoded.componentId,
116
+ targetId: decoded.targetId
117
+ };
118
+ } catch (error) {
119
+ return { type: "invalid" };
120
+ }
121
+ return { type: "invalid" };
122
+ }
123
+ /**
124
+ * Entity ID Manager for automatic allocation and freelist recycling
125
+ */
126
+ var EntityIdManager = class {
127
+ nextId = ENTITY_ID_START;
128
+ freelist = /* @__PURE__ */ new Set();
129
+ /**
130
+ * Allocate a new entity ID
131
+ * Uses freelist if available, otherwise increments counter
132
+ */
133
+ allocate() {
134
+ if (this.freelist.size > 0) {
135
+ const id = this.freelist.values().next().value;
136
+ this.freelist.delete(id);
137
+ return id;
138
+ } else {
139
+ const id = this.nextId;
140
+ this.nextId++;
141
+ if (this.nextId >= Number.MAX_SAFE_INTEGER) throw new Error("Entity ID overflow: reached maximum safe integer");
142
+ return id;
143
+ }
144
+ }
145
+ /**
146
+ * Deallocate an entity ID, adding it to the freelist for reuse
147
+ * @param id The entity ID to deallocate
148
+ */
149
+ deallocate(id) {
150
+ if (!isEntityId(id)) throw new Error("Can only deallocate valid entity IDs");
151
+ if (id >= this.nextId) throw new Error("Cannot deallocate an ID that was never allocated");
152
+ this.freelist.add(id);
153
+ }
154
+ /**
155
+ * Get the current freelist size (for debugging/monitoring)
156
+ */
157
+ getFreelistSize() {
158
+ return this.freelist.size;
159
+ }
160
+ /**
161
+ * Get the next ID that would be allocated (for debugging)
162
+ */
163
+ getNextId() {
164
+ return this.nextId;
165
+ }
166
+ /**
167
+ * Serialize internal state for persistence.
168
+ * Returns a plain object representing allocator state. Values may be non-JSON-serializable.
169
+ */
170
+ serializeState() {
171
+ return {
172
+ nextId: this.nextId,
173
+ freelist: Array.from(this.freelist)
174
+ };
175
+ }
176
+ /**
177
+ * Restore internal state from a previously-serialized object.
178
+ * Overwrites the current nextId and freelist.
179
+ */
180
+ deserializeState(state) {
181
+ if (typeof state.nextId !== "number") throw new Error("Invalid state for EntityIdManager.deserializeState");
182
+ this.nextId = state.nextId;
183
+ this.freelist = new Set(state.freelist || []);
184
+ }
185
+ };
186
+ /**
187
+ * Component ID Manager for automatic allocation
188
+ * Components are typically registered once and not recycled
189
+ */
190
+ var ComponentIdAllocator = class {
191
+ nextId = 1;
192
+ /**
193
+ * Allocate a new component ID
194
+ * Increments counter sequentially from 1
195
+ */
196
+ allocate() {
197
+ if (this.nextId > COMPONENT_ID_MAX) throw new Error(`Component ID overflow: maximum ${COMPONENT_ID_MAX} components allowed`);
198
+ const id = this.nextId;
199
+ this.nextId++;
200
+ return id;
201
+ }
202
+ /**
203
+ * Get the next ID that would be allocated (for debugging)
204
+ */
205
+ getNextId() {
206
+ return this.nextId;
207
+ }
208
+ /**
209
+ * Check if more component IDs are available
210
+ */
211
+ hasAvailableIds() {
212
+ return this.nextId <= COMPONENT_ID_MAX;
213
+ }
214
+ };
215
+ const globalComponentIdAllocator = new ComponentIdAllocator();
216
+ const ComponentNames = /* @__PURE__ */ new Map();
217
+ const ComponentIdForNames = /* @__PURE__ */ new Map();
218
+ const ComponentOptions = /* @__PURE__ */ new Map();
219
+ /**
220
+ * Allocate a new component ID from the global allocator.
221
+ * @param nameOrOptions Optional name for the component (for serialization/debugging) or options object
222
+ * @returns The allocated component ID
223
+ * @example
224
+ * // Just a name
225
+ * const Position = component<Position>("Position");
226
+ *
227
+ * // With options
228
+ * const ChildOf = component({ exclusive: true, cascadeDelete: true });
229
+ *
230
+ * // With name and options
231
+ * const ChildOf = component({ name: "ChildOf", exclusive: true });
232
+ */
233
+ function component(nameOrOptions) {
234
+ const id = globalComponentIdAllocator.allocate();
235
+ let name;
236
+ let options;
237
+ if (typeof nameOrOptions === "string") name = nameOrOptions;
238
+ else if (typeof nameOrOptions === "object" && nameOrOptions !== null) {
239
+ options = nameOrOptions;
240
+ name = options.name;
241
+ }
242
+ if (name) {
243
+ if (ComponentIdForNames.has(name)) throw new Error(`Component name "${name}" is already registered`);
244
+ ComponentNames.set(id, name);
245
+ ComponentIdForNames.set(name, id);
246
+ }
247
+ if (options) ComponentOptions.set(id, options);
248
+ return id;
249
+ }
250
+ /**
251
+ * Get a component ID by its registered name
252
+ * @param name The component name
253
+ * @returns The component ID if found, undefined otherwise
254
+ */
255
+ function getComponentIdByName(name) {
256
+ return ComponentIdForNames.get(name);
257
+ }
258
+ /** Get a component name by its ID
259
+ * @param id The component ID
260
+ * @returns The component name if found, undefined otherwise
261
+ */
262
+ function getComponentNameById(id) {
263
+ return ComponentNames.get(id);
264
+ }
265
+ /**
266
+ * Check if a component is marked as exclusive
267
+ * @param id The component ID
268
+ * @returns true if the component is exclusive, false otherwise
269
+ */
270
+ function isExclusiveComponent(id) {
271
+ return ComponentOptions.get(id)?.exclusive ?? false;
272
+ }
273
+ /**
274
+ * Check if a component is marked as cascade delete
275
+ * @param id The component ID
276
+ * @returns true if the component is cascade delete, false otherwise
277
+ */
278
+ function isCascadeDeleteComponent(id) {
279
+ return ComponentOptions.get(id)?.cascadeDelete ?? false;
280
+ }
281
+ /**
282
+ * Check if a component is marked as dontFragment
283
+ * @param id The component ID
284
+ * @returns true if the component is dontFragment, false otherwise
285
+ */
286
+ function isDontFragmentComponent(id) {
287
+ return ComponentOptions.get(id)?.dontFragment ?? false;
288
+ }
289
+
290
+ //#endregion
291
+ //#region src/types.ts
292
+ function isOptionalEntityId(type) {
293
+ return typeof type === "object" && type !== null && "optional" in type;
294
+ }
295
+
296
+ //#endregion
297
+ //#region src/utils.ts
298
+ /**
299
+ * Utility functions for ECS library
300
+ */
301
+ /**
302
+ * Get a value from cache or compute and cache it if not present
303
+ * @param cache The cache map
304
+ * @param key The cache key
305
+ * @param compute Function to compute the value if not cached
306
+ * @returns The cached or computed value
307
+ */
308
+ function getOrComputeCache(cache, key, compute) {
309
+ let value = cache.get(key);
310
+ if (value === void 0) {
311
+ value = compute();
312
+ cache.set(key, value);
313
+ }
314
+ return value;
315
+ }
316
+ /**
317
+ * Get a value from cache or create and cache it if not present, allowing side effects during creation
318
+ * @param cache The cache map
319
+ * @param key The cache key
320
+ * @param create Function to create the value if not cached (can have side effects)
321
+ * @returns The cached or created value
322
+ */
323
+ function getOrCreateWithSideEffect(cache, key, create) {
324
+ let value = cache.get(key);
325
+ if (value === void 0) {
326
+ value = create();
327
+ cache.set(key, value);
328
+ }
329
+ return value;
330
+ }
331
+
332
+ //#endregion
333
+ //#region src/archetype.ts
334
+ /**
335
+ * Special value to represent missing component data
336
+ */
337
+ const MISSING_COMPONENT = Symbol("missing component");
338
+ /**
339
+ * Archetype class for ECS architecture
340
+ * Represents a group of entities that share the same set of components
341
+ * Optimized for fast iteration and component access
342
+ */
343
+ var Archetype = class {
344
+ /**
345
+ * The component types that define this archetype
346
+ */
347
+ componentTypes;
348
+ /**
349
+ * List of entities in this archetype
350
+ */
351
+ entities = [];
352
+ /**
353
+ * Component data storage - maps component type to array of component data
354
+ * Each array index corresponds to the entity index in the entities array
355
+ */
356
+ componentData = /* @__PURE__ */ new Map();
357
+ /**
358
+ * Reverse mapping from entity to its index in this archetype
359
+ */
360
+ entityToIndex = /* @__PURE__ */ new Map();
361
+ /**
362
+ * Reference to dontFragment relations storage from World
363
+ * This allows entities with different relation targets to share the same archetype
364
+ * Stored in World to avoid migration overhead when entities change archetypes
365
+ */
366
+ dontFragmentRelations;
367
+ /**
368
+ * Cache for pre-computed component data sources to avoid repeated calculations
369
+ * For regular components: data array
370
+ * For wildcards: matching relation types array
371
+ */
372
+ componentDataSourcesCache = /* @__PURE__ */ new Map();
373
+ /**
374
+ * Create a new archetype with the specified component types
375
+ * @param componentTypes The component types that define this archetype
376
+ * @param dontFragmentRelations Reference to the World's dontFragmentRelations storage
377
+ */
378
+ constructor(componentTypes, dontFragmentRelations) {
379
+ this.componentTypes = [...componentTypes].sort((a, b) => a - b);
380
+ this.dontFragmentRelations = dontFragmentRelations;
381
+ for (const componentType of this.componentTypes) this.componentData.set(componentType, []);
382
+ }
383
+ /**
384
+ * Get the number of entities in this archetype
385
+ */
386
+ get size() {
387
+ return this.entities.length;
388
+ }
389
+ /**
390
+ * Check if this archetype matches the given component types
391
+ * @param componentTypes The component types to check
392
+ */
393
+ matches(componentTypes) {
394
+ if (this.componentTypes.length !== componentTypes.length) return false;
395
+ const sortedTypes = [...componentTypes].sort((a, b) => a - b);
396
+ return this.componentTypes.every((type, index) => type === sortedTypes[index]);
397
+ }
398
+ /**
399
+ * Add an entity to this archetype with initial component data
400
+ * @param entityId The entity to add
401
+ * @param componentData Map of component type to component data (includes both regular and dontFragment components)
402
+ */
403
+ addEntity(entityId, componentData) {
404
+ if (this.entityToIndex.has(entityId)) throw new Error(`Entity ${entityId} is already in this archetype`);
405
+ const index = this.entities.length;
406
+ this.entities.push(entityId);
407
+ this.entityToIndex.set(entityId, index);
408
+ for (const componentType of this.componentTypes) {
409
+ const data = componentData.get(componentType);
410
+ this.getComponentData(componentType).push(data === void 0 ? MISSING_COMPONENT : data);
411
+ }
412
+ const dontFragmentData = /* @__PURE__ */ new Map();
413
+ for (const [componentType, data] of componentData) {
414
+ if (this.componentTypes.includes(componentType)) continue;
415
+ const detailedType = getDetailedIdType(componentType);
416
+ if ((detailedType.type === "entity-relation" || detailedType.type === "component-relation") && isDontFragmentComponent(detailedType.componentId)) dontFragmentData.set(componentType, data);
417
+ }
418
+ if (dontFragmentData.size > 0) this.dontFragmentRelations.set(entityId, dontFragmentData);
419
+ }
420
+ /**
421
+ * Get all component data for a specific entity
422
+ * @param entityId The entity to get data for
423
+ * @returns Map of component type to component data (includes both regular and dontFragment components)
424
+ */
425
+ getEntity(entityId) {
426
+ const index = this.entityToIndex.get(entityId);
427
+ if (index === void 0) return;
428
+ const entityData = /* @__PURE__ */ new Map();
429
+ for (const componentType of this.componentTypes) {
430
+ const data = this.getComponentData(componentType)[index];
431
+ entityData.set(componentType, data === MISSING_COMPONENT ? void 0 : data);
432
+ }
433
+ const dontFragmentData = this.dontFragmentRelations.get(entityId);
434
+ if (dontFragmentData) for (const [componentType, data] of dontFragmentData) entityData.set(componentType, data);
435
+ return entityData;
436
+ }
437
+ /**
438
+ * Dump all entities and their component data in this archetype
439
+ * @returns Array of objects with entity and component data (includes both regular and dontFragment components)
440
+ */
441
+ dump() {
442
+ const result = [];
443
+ for (let i = 0; i < this.entities.length; i++) {
444
+ const entity = this.entities[i];
445
+ const components = /* @__PURE__ */ new Map();
446
+ for (const componentType of this.componentTypes) {
447
+ const data = this.getComponentData(componentType)[i];
448
+ components.set(componentType, data === MISSING_COMPONENT ? void 0 : data);
449
+ }
450
+ const dontFragmentData = this.dontFragmentRelations.get(entity);
451
+ if (dontFragmentData) for (const [componentType, data] of dontFragmentData) components.set(componentType, data);
452
+ result.push({
453
+ entity,
454
+ components
455
+ });
456
+ }
457
+ return result;
458
+ }
459
+ /**
460
+ * Remove an entity from this archetype
461
+ * @param entityId The entity to remove
462
+ * @returns The component data of the removed entity (includes both regular and dontFragment components)
463
+ */
464
+ removeEntity(entityId) {
465
+ const index = this.entityToIndex.get(entityId);
466
+ if (index === void 0) return;
467
+ const removedData = /* @__PURE__ */ new Map();
468
+ for (const componentType of this.componentTypes) {
469
+ const dataArray = this.getComponentData(componentType);
470
+ removedData.set(componentType, dataArray[index]);
471
+ }
472
+ const dontFragmentData = this.dontFragmentRelations.get(entityId);
473
+ if (dontFragmentData) {
474
+ for (const [componentType, data] of dontFragmentData) removedData.set(componentType, data);
475
+ this.dontFragmentRelations.delete(entityId);
476
+ }
477
+ this.entityToIndex.delete(entityId);
478
+ const lastIndex = this.entities.length - 1;
479
+ if (index !== lastIndex) {
480
+ const lastEntity = this.entities[lastIndex];
481
+ this.entities[index] = lastEntity;
482
+ this.entityToIndex.set(lastEntity, index);
483
+ for (const componentType of this.componentTypes) {
484
+ const dataArray = this.getComponentData(componentType);
485
+ dataArray[index] = dataArray[lastIndex];
486
+ }
487
+ }
488
+ this.entities.pop();
489
+ for (const componentType of this.componentTypes) this.getComponentData(componentType).pop();
490
+ return removedData;
491
+ }
492
+ /**
493
+ * Check if an entity is in this archetype
494
+ * @param entityId The entity to check
495
+ */
496
+ exists(entityId) {
497
+ return this.entityToIndex.has(entityId);
498
+ }
499
+ get(entityId, componentType) {
500
+ const index = this.entityToIndex.get(entityId);
501
+ if (index === void 0) throw new Error(`Entity ${entityId} is not in this archetype`);
502
+ if (isWildcardRelationId(componentType)) {
503
+ const componentId = decodeRelationId(componentType).componentId;
504
+ const relations = [];
505
+ for (const relType of this.componentTypes) {
506
+ const relDetailed = getDetailedIdType(relType);
507
+ if ((relDetailed.type === "entity-relation" || relDetailed.type === "component-relation") && relDetailed.componentId === componentId) {
508
+ const dataArray = this.getComponentData(relType);
509
+ if (dataArray && dataArray[index] !== void 0) {
510
+ const data = dataArray[index];
511
+ relations.push([relDetailed.targetId, data === MISSING_COMPONENT ? void 0 : data]);
512
+ }
513
+ }
514
+ }
515
+ const dontFragmentData = this.dontFragmentRelations.get(entityId);
516
+ if (dontFragmentData) for (const [relType, data] of dontFragmentData) {
517
+ const relDetailed = getDetailedIdType(relType);
518
+ if ((relDetailed.type === "entity-relation" || relDetailed.type === "component-relation") && relDetailed.componentId === componentId) relations.push([relDetailed.targetId, data]);
519
+ }
520
+ return relations;
521
+ } else {
522
+ if (this.componentTypes.includes(componentType)) {
523
+ const data = this.getComponentData(componentType)[index];
524
+ return data === MISSING_COMPONENT ? void 0 : data;
525
+ }
526
+ const dontFragmentData = this.dontFragmentRelations.get(entityId);
527
+ if (dontFragmentData && dontFragmentData.has(componentType)) return dontFragmentData.get(componentType);
528
+ throw new Error(`Component type ${componentType} not found for entity ${entityId}`);
529
+ }
530
+ }
531
+ /**
532
+ * Set component data for a specific entity and component type
533
+ * @param entityId The entity
534
+ * @param componentType The component type
535
+ * @param data The component data
536
+ */
537
+ set(entityId, componentType, data) {
538
+ const index = this.entityToIndex.get(entityId);
539
+ if (index === void 0) throw new Error(`Entity ${entityId} is not in this archetype`);
540
+ if (this.componentData.has(componentType)) {
541
+ const dataArray = this.getComponentData(componentType);
542
+ dataArray[index] = data;
543
+ return;
544
+ }
545
+ const detailedType = getDetailedIdType(componentType);
546
+ if ((detailedType.type === "entity-relation" || detailedType.type === "component-relation") && isDontFragmentComponent(detailedType.componentId)) {
547
+ let dontFragmentData = this.dontFragmentRelations.get(entityId);
548
+ if (!dontFragmentData) {
549
+ dontFragmentData = /* @__PURE__ */ new Map();
550
+ this.dontFragmentRelations.set(entityId, dontFragmentData);
551
+ }
552
+ dontFragmentData.set(componentType, data);
553
+ return;
554
+ }
555
+ throw new Error(`Component type ${componentType} is not in this archetype`);
556
+ }
557
+ /**
558
+ * Get all entities in this archetype
559
+ */
560
+ getEntities() {
561
+ return this.entities;
562
+ }
563
+ /**
564
+ * Get the mapping of entities to their indices in this archetype
565
+ */
566
+ getEntityToIndexMap() {
567
+ return this.entityToIndex;
568
+ }
569
+ /**
570
+ * Get component data for all entities of a specific component type
571
+ * @param componentType The component type
572
+ */
573
+ getComponentData(componentType) {
574
+ const data = this.componentData.get(componentType);
575
+ if (!data) throw new Error(`Component type ${componentType} is not in this archetype`);
576
+ return data;
577
+ }
578
+ /**
579
+ * Get optional component data for all entities of a specific component type
580
+ * @param componentType The component type
581
+ * @returns An array of component data or undefined if not present
582
+ */
583
+ getOptionalComponentData(componentType) {
584
+ return this.componentData.get(componentType);
585
+ }
586
+ /**
587
+ * Helper: compute or return cached data sources for provided componentTypes
588
+ */
589
+ getCachedComponentDataSources(componentTypes) {
590
+ const cacheKey = this.buildCacheKey(componentTypes);
591
+ return getOrComputeCache(this.componentDataSourcesCache, cacheKey, () => componentTypes.map((compType) => this.getComponentDataSource(compType)));
592
+ }
593
+ /**
594
+ * Build cache key for component types
595
+ */
596
+ buildCacheKey(componentTypes) {
597
+ return componentTypes.map((id) => isOptionalEntityId(id) ? `opt(${id.optional})` : `${id}`).join(",");
598
+ }
599
+ /**
600
+ * Get data source for a single component type
601
+ */
602
+ getComponentDataSource(compType) {
603
+ const optional = isOptionalEntityId(compType);
604
+ const actualType = optional ? compType.optional : compType;
605
+ const detailedType = getDetailedIdType(actualType);
606
+ if (detailedType.type === "wildcard-relation") return this.getWildcardRelationDataSource(detailedType.componentId, optional);
607
+ else return optional ? this.getOptionalComponentData(actualType) : this.getComponentData(actualType);
608
+ }
609
+ /**
610
+ * Get data source for wildcard relations
611
+ */
612
+ getWildcardRelationDataSource(componentId, optional) {
613
+ const matchingRelations = this.componentTypes.filter((ct) => {
614
+ const detailedCt = getDetailedIdType(ct);
615
+ return (detailedCt.type === "entity-relation" || detailedCt.type === "component-relation") && detailedCt.componentId === componentId;
616
+ });
617
+ return optional ? matchingRelations.length > 0 ? matchingRelations : void 0 : matchingRelations;
618
+ }
619
+ /**
620
+ * Helper: build component tuples for a specific entity index using precomputed data sources
621
+ */
622
+ buildComponentsForIndex(componentTypes, componentDataSources, entityIndex) {
623
+ return componentDataSources.map((dataSource, i) => {
624
+ const compType = componentTypes[i];
625
+ return this.buildSingleComponent(compType, dataSource, entityIndex);
626
+ });
627
+ }
628
+ /**
629
+ * Build a single component value from its data source
630
+ */
631
+ buildSingleComponent(compType, dataSource, entityIndex) {
632
+ const optional = isOptionalEntityId(compType);
633
+ if (getIdType(optional ? compType.optional : compType) === "wildcard-relation") return this.buildWildcardRelationValue(dataSource, entityIndex, optional);
634
+ else return this.buildRegularComponentValue(dataSource, entityIndex, optional);
635
+ }
636
+ /**
637
+ * Build wildcard relation value from matching relations
638
+ */
639
+ buildWildcardRelationValue(dataSource, entityIndex, optional) {
640
+ if (dataSource === void 0) {
641
+ if (optional) return;
642
+ throw new Error(`No matching relations found for mandatory wildcard relation component type`);
643
+ }
644
+ const matchingRelations = dataSource;
645
+ const relations = [];
646
+ for (const relType of matchingRelations) {
647
+ const data = this.getComponentData(relType)[entityIndex];
648
+ const decodedRel = decodeRelationId(relType);
649
+ relations.push([decodedRel.targetId, data === MISSING_COMPONENT ? void 0 : data]);
650
+ }
651
+ return optional ? { value: relations } : relations;
652
+ }
653
+ /**
654
+ * Build regular component value from data source
655
+ */
656
+ buildRegularComponentValue(dataSource, entityIndex, optional) {
657
+ if (dataSource === void 0) {
658
+ if (optional) return;
659
+ throw new Error(`Component data not found for mandatory component type`);
660
+ }
661
+ const data = dataSource[entityIndex];
662
+ const result = data === MISSING_COMPONENT ? void 0 : data;
663
+ return optional ? { value: result } : result;
664
+ }
665
+ /**
666
+ * Get entities with their component data for specified component types
667
+ * Optimized for bulk component access with pre-computed indices
668
+ * @param componentTypes Array of component types to retrieve
669
+ * @returns Array of objects with entity and component data
670
+ */
671
+ getEntitiesWithComponents(componentTypes) {
672
+ const result = [];
673
+ this.forEachWithComponents(componentTypes, (entity, ...components) => {
674
+ result.push({
675
+ entity,
676
+ components
677
+ });
678
+ });
679
+ return result;
680
+ }
681
+ /**
682
+ * Iterate over entities with their component data for specified component types
683
+ * implemented as a generator returning each entity/components pair lazily
684
+ * @param componentTypes Array of component types to retrieve
685
+ */
686
+ *iterateWithComponents(componentTypes) {
687
+ const componentDataSources = this.getCachedComponentDataSources(componentTypes);
688
+ for (let entityIndex = 0; entityIndex < this.entities.length; entityIndex++) yield [this.entities[entityIndex], ...this.buildComponentsForIndex(componentTypes, componentDataSources, entityIndex)];
689
+ }
690
+ /**
691
+ * Iterate over entities with their component data for specified component types
692
+ * Optimized for bulk component access
693
+ * @param componentTypes Array of component types to retrieve
694
+ * @param callback Function called for each entity with its components
695
+ */
696
+ forEachWithComponents(componentTypes, callback) {
697
+ const componentDataSources = this.getCachedComponentDataSources(componentTypes);
698
+ for (let entityIndex = 0; entityIndex < this.entities.length; entityIndex++) {
699
+ const entity = this.entities[entityIndex];
700
+ callback(entity, ...this.buildComponentsForIndex(componentTypes, componentDataSources, entityIndex));
701
+ }
702
+ }
703
+ /**
704
+ * Iterate over all entities with their component data
705
+ * @param callback Function called for each entity with its component data
706
+ */
707
+ forEach(callback) {
708
+ for (let i = 0; i < this.entities.length; i++) {
709
+ const components = /* @__PURE__ */ new Map();
710
+ for (const componentType of this.componentTypes) {
711
+ const data = this.getComponentData(componentType)[i];
712
+ components.set(componentType, data === MISSING_COMPONENT ? void 0 : data);
713
+ }
714
+ callback(this.entities[i], components);
715
+ }
716
+ }
717
+ };
718
+
719
+ //#endregion
720
+ //#region src/changeset.ts
721
+ /**
722
+ * @internal Represents a set of component changes to be applied to an entity
723
+ */
724
+ var ComponentChangeset = class {
725
+ adds = /* @__PURE__ */ new Map();
726
+ removes = /* @__PURE__ */ new Set();
727
+ /**
728
+ * Add a component to the changeset
729
+ */
730
+ set(componentType, component$1) {
731
+ this.adds.set(componentType, component$1);
732
+ this.removes.delete(componentType);
733
+ }
734
+ /**
735
+ * Remove a component from the changeset
736
+ */
737
+ delete(componentType) {
738
+ this.removes.add(componentType);
739
+ this.adds.delete(componentType);
740
+ }
741
+ /**
742
+ * Check if the changeset has any changes
743
+ */
744
+ hasChanges() {
745
+ return this.adds.size > 0 || this.removes.size > 0;
746
+ }
747
+ /**
748
+ * Clear all changes
749
+ */
750
+ clear() {
751
+ this.adds.clear();
752
+ this.removes.clear();
753
+ }
754
+ /**
755
+ * Merge another changeset into this one
756
+ */
757
+ merge(other) {
758
+ for (const [componentType, component$1] of other.adds) {
759
+ this.adds.set(componentType, component$1);
760
+ this.removes.delete(componentType);
761
+ }
762
+ for (const componentType of other.removes) {
763
+ this.removes.add(componentType);
764
+ this.adds.delete(componentType);
765
+ }
766
+ }
767
+ /**
768
+ * Apply the changeset to existing components and return the final state
769
+ */
770
+ applyTo(existingComponents) {
771
+ for (const componentType of this.removes) existingComponents.delete(componentType);
772
+ for (const [componentType, component$1] of this.adds) existingComponents.set(componentType, component$1);
773
+ return existingComponents;
774
+ }
775
+ /**
776
+ * Get the final component types after applying the changeset
777
+ * @param existingComponentTypes - The current component types on the entity
778
+ * @returns The final component types or undefined if no changes
779
+ */
780
+ getFinalComponentTypes(existingComponentTypes) {
781
+ const finalComponentTypes = new Set(existingComponentTypes);
782
+ let changed = false;
783
+ for (const componentType of this.removes) {
784
+ if (!finalComponentTypes.has(componentType)) {
785
+ this.removes.delete(componentType);
786
+ continue;
787
+ }
788
+ changed = true;
789
+ finalComponentTypes.delete(componentType);
790
+ }
791
+ for (const componentType of this.adds.keys()) {
792
+ if (finalComponentTypes.has(componentType)) continue;
793
+ changed = true;
794
+ finalComponentTypes.add(componentType);
795
+ }
796
+ return changed ? Array.from(finalComponentTypes) : void 0;
797
+ }
798
+ };
799
+
800
+ //#endregion
801
+ //#region src/command-buffer.ts
802
+ /**
803
+ * Command buffer for deferred structural changes
804
+ */
805
+ var CommandBuffer = class {
806
+ commands = [];
807
+ executeEntityCommands;
808
+ /**
809
+ * Create a command buffer with an executor function
810
+ */
811
+ constructor(executeEntityCommands) {
812
+ this.executeEntityCommands = executeEntityCommands;
813
+ }
814
+ set(entityId, componentType, component$1) {
815
+ this.commands.push({
816
+ type: "set",
817
+ entityId,
818
+ componentType,
819
+ component: component$1
820
+ });
821
+ }
822
+ /**
823
+ * Remove a component from an entity (deferred)
824
+ */
825
+ remove(entityId, componentType) {
826
+ this.commands.push({
827
+ type: "delete",
828
+ entityId,
829
+ componentType
830
+ });
831
+ }
832
+ /**
833
+ * Destroy an entity (deferred)
834
+ */
835
+ delete(entityId) {
836
+ this.commands.push({
837
+ type: "destroy",
838
+ entityId
839
+ });
840
+ }
841
+ /**
842
+ * Execute all commands and clear the buffer
843
+ */
844
+ execute() {
845
+ const MAX_ITERATIONS = 100;
846
+ let iterations = 0;
847
+ while (this.commands.length > 0) {
848
+ if (iterations >= MAX_ITERATIONS) throw new Error("Command execution exceeded maximum iterations, possible infinite loop");
849
+ iterations++;
850
+ const currentCommands = [...this.commands];
851
+ this.commands = [];
852
+ const entityCommands = /* @__PURE__ */ new Map();
853
+ for (const cmd of currentCommands) {
854
+ if (!entityCommands.has(cmd.entityId)) entityCommands.set(cmd.entityId, []);
855
+ entityCommands.get(cmd.entityId).push(cmd);
856
+ }
857
+ for (const [entityId, commands] of entityCommands) this.executeEntityCommands(entityId, commands);
858
+ }
859
+ }
860
+ /**
861
+ * Get current commands (for testing)
862
+ */
863
+ getCommands() {
864
+ return [...this.commands];
865
+ }
866
+ /**
867
+ * Clear all commands
868
+ */
869
+ clear() {
870
+ this.commands = [];
871
+ }
872
+ };
873
+
874
+ //#endregion
875
+ //#region src/multi-map.ts
876
+ var MultiMap = class {
877
+ map = /* @__PURE__ */ new Map();
878
+ _valueCount = 0;
879
+ get valueCount() {
880
+ return this._valueCount;
881
+ }
882
+ get keyCount() {
883
+ return this.map.size;
884
+ }
885
+ hasKey(key) {
886
+ return this.map.has(key);
887
+ }
888
+ has(key, value) {
889
+ const set = this.map.get(key);
890
+ if (!set) return false;
891
+ if (arguments.length === 1) return true;
892
+ return set.has(value);
893
+ }
894
+ add(key, value) {
895
+ let set = this.map.get(key);
896
+ if (!set) {
897
+ set = /* @__PURE__ */ new Set();
898
+ this.map.set(key, set);
899
+ }
900
+ if (!set.has(value)) {
901
+ set.add(value);
902
+ this._valueCount++;
903
+ }
904
+ }
905
+ remove(key, value) {
906
+ const set = this.map.get(key);
907
+ if (!set) return false;
908
+ if (!set.has(value)) return false;
909
+ set.delete(value);
910
+ this._valueCount--;
911
+ if (set.size === 0) this.map.delete(key);
912
+ return true;
913
+ }
914
+ deleteKey(key) {
915
+ const set = this.map.get(key);
916
+ if (!set) return false;
917
+ this._valueCount -= set.size;
918
+ this.map.delete(key);
919
+ return true;
920
+ }
921
+ get(key) {
922
+ const set = this.map.get(key);
923
+ return set ? new Set(set) : /* @__PURE__ */ new Set();
924
+ }
925
+ *keys() {
926
+ yield* this.map.keys();
927
+ }
928
+ *values() {
929
+ for (const set of this.map.values()) for (const v of set) yield v;
930
+ }
931
+ [Symbol.iterator]() {
932
+ return this.entries();
933
+ }
934
+ *entries() {
935
+ for (const [k, set] of this.map.entries()) for (const v of set) yield [k, v];
936
+ }
937
+ clear() {
938
+ this.map.clear();
939
+ this._valueCount = 0;
940
+ }
941
+ };
942
+
943
+ //#endregion
944
+ //#region src/query-filter.ts
945
+ /**
946
+ * Serialize a QueryFilter into a deterministic string suitable for cache keys.
947
+ * Currently only serializes `negativeComponentTypes`.
948
+ */
949
+ function serializeQueryFilter(filter = {}) {
950
+ const negative = (filter.negativeComponentTypes || []).slice().sort((a, b) => a - b);
951
+ if (negative.length === 0) return "";
952
+ return `neg:${negative.join(",")}`;
953
+ }
954
+ /**
955
+ * Check if an archetype matches the given component types
956
+ */
957
+ function matchesComponentTypes(archetype, componentTypes) {
958
+ return componentTypes.every((type) => {
959
+ const detailedType = getDetailedIdType(type);
960
+ if (detailedType.type === "wildcard-relation") return archetype.componentTypes.some((archetypeType) => {
961
+ if (!isRelationId(archetypeType)) return false;
962
+ return decodeRelationId(archetypeType).componentId === detailedType.componentId;
963
+ });
964
+ else return archetype.componentTypes.includes(type);
965
+ });
966
+ }
967
+ /**
968
+ * Check if an archetype matches the filter conditions (only filtering logic)
969
+ */
970
+ function matchesFilter(archetype, filter) {
971
+ return (filter.negativeComponentTypes || []).every((type) => {
972
+ const detailedType = getDetailedIdType(type);
973
+ if (detailedType.type === "wildcard-relation") return !archetype.componentTypes.some((archetypeType) => {
974
+ if (!isRelationId(archetypeType)) return false;
975
+ return decodeRelationId(archetypeType).componentId === detailedType.componentId;
976
+ });
977
+ else return !archetype.componentTypes.includes(type);
978
+ });
979
+ }
980
+
981
+ //#endregion
982
+ //#region src/query.ts
983
+ /**
984
+ * Query class for efficient entity queries with cached archetypes
985
+ */
986
+ var Query = class {
987
+ world;
988
+ componentTypes;
989
+ filter;
990
+ cachedArchetypes = [];
991
+ isDisposed = false;
992
+ constructor(world, componentTypes, filter = {}) {
993
+ this.world = world;
994
+ this.componentTypes = [...componentTypes].sort((a, b) => a - b);
995
+ this.filter = filter;
996
+ this.updateCache();
997
+ world._registerQuery(this);
998
+ }
999
+ /**
1000
+ * Check if query is disposed and throw error if so
1001
+ */
1002
+ ensureNotDisposed() {
1003
+ if (this.isDisposed) throw new Error("Query has been disposed");
1004
+ }
1005
+ /**
1006
+ * Get all entities matching the query
1007
+ */
1008
+ getEntities() {
1009
+ this.ensureNotDisposed();
1010
+ const result = [];
1011
+ for (const archetype of this.cachedArchetypes) result.push(...archetype.getEntities());
1012
+ return result;
1013
+ }
1014
+ /**
1015
+ * Get entities with their component data
1016
+ * @param componentTypes Array of component types to retrieve
1017
+ * @returns Array of objects with entity and component data
1018
+ */
1019
+ getEntitiesWithComponents(componentTypes) {
1020
+ this.ensureNotDisposed();
1021
+ const result = [];
1022
+ for (const archetype of this.cachedArchetypes) {
1023
+ const entitiesWithData = archetype.getEntitiesWithComponents(componentTypes);
1024
+ result.push(...entitiesWithData);
1025
+ }
1026
+ return result;
1027
+ }
1028
+ /**
1029
+ * Iterate over entities with their component data
1030
+ * @param componentTypes Array of component types to retrieve
1031
+ * @param callback Function called for each entity with its components
1032
+ */
1033
+ forEach(componentTypes, callback) {
1034
+ this.ensureNotDisposed();
1035
+ for (const archetype of this.cachedArchetypes) archetype.forEachWithComponents(componentTypes, callback);
1036
+ }
1037
+ /**
1038
+ * Iterate over entities with their component data (generator)
1039
+ * @param componentTypes Array of component types to retrieve
1040
+ */
1041
+ *iterate(componentTypes) {
1042
+ this.ensureNotDisposed();
1043
+ for (const archetype of this.cachedArchetypes) yield* archetype.iterateWithComponents(componentTypes);
1044
+ }
1045
+ /**
1046
+ * Get component data arrays for all matching entities
1047
+ * @param componentType The component type to retrieve
1048
+ * @returns Array of component data for all matching entities
1049
+ */
1050
+ getComponentData(componentType) {
1051
+ this.ensureNotDisposed();
1052
+ const result = [];
1053
+ for (const archetype of this.cachedArchetypes) result.push(...archetype.getComponentData(componentType));
1054
+ return result;
1055
+ }
1056
+ /**
1057
+ * Update the cached archetypes
1058
+ * Called when new archetypes are created
1059
+ */
1060
+ updateCache() {
1061
+ if (this.isDisposed) return;
1062
+ this.cachedArchetypes = this.world.getMatchingArchetypes(this.componentTypes).filter((archetype) => matchesFilter(archetype, this.filter));
1063
+ }
1064
+ /**
1065
+ * Check if a new archetype matches this query and add to cache if it does
1066
+ */
1067
+ checkNewArchetype(archetype) {
1068
+ if (this.isDisposed) return;
1069
+ if (matchesComponentTypes(archetype, this.componentTypes) && matchesFilter(archetype, this.filter) && !this.cachedArchetypes.includes(archetype)) this.cachedArchetypes.push(archetype);
1070
+ }
1071
+ /**
1072
+ * Remove an archetype from the cached archetypes
1073
+ */
1074
+ removeArchetype(archetype) {
1075
+ if (this.isDisposed) return;
1076
+ const index = this.cachedArchetypes.indexOf(archetype);
1077
+ if (index !== -1) this.cachedArchetypes.splice(index, 1);
1078
+ }
1079
+ /**
1080
+ * Dispose the query and disconnect from world
1081
+ */
1082
+ /**
1083
+ * Request disposal of this query.
1084
+ * This will decrement the world's reference count for the query.
1085
+ * The query will only be fully disposed when the ref count reaches zero.
1086
+ */
1087
+ dispose() {
1088
+ this.world.releaseQuery(this);
1089
+ }
1090
+ /**
1091
+ * Internal full dispose called by World when refCount reaches zero.
1092
+ */
1093
+ _disposeInternal() {
1094
+ if (!this.isDisposed) {
1095
+ this.world._unregisterQuery(this);
1096
+ this.cachedArchetypes = [];
1097
+ this.isDisposed = true;
1098
+ }
1099
+ }
1100
+ /**
1101
+ * Symbol.dispose implementation for automatic resource management
1102
+ */
1103
+ [Symbol.dispose]() {
1104
+ this.dispose();
1105
+ }
1106
+ /**
1107
+ * Check if the query has been disposed
1108
+ */
1109
+ get disposed() {
1110
+ return this.isDisposed;
1111
+ }
1112
+ };
1113
+
1114
+ //#endregion
1115
+ //#region src/system-scheduler.ts
1116
+ /**
1117
+ * System Scheduler for managing system dependencies and execution order
1118
+ */
1119
+ var SystemScheduler = class {
1120
+ systems = /* @__PURE__ */ new Set();
1121
+ systemDependencies = /* @__PURE__ */ new Map();
1122
+ cachedExecutionOrder = null;
1123
+ /**
1124
+ * Add a system with optional dependencies
1125
+ * @param system The system to add
1126
+ * @param additionalDeps Additional dependencies for the system
1127
+ */
1128
+ addSystem(system, additionalDeps = []) {
1129
+ this.systems.add(system);
1130
+ for (const dep of system.dependencies || []) this.systems.add(dep);
1131
+ this.systemDependencies.set(system, new Set([...additionalDeps, ...system.dependencies || []]));
1132
+ this.cachedExecutionOrder = null;
1133
+ }
1134
+ /**
1135
+ * Get the execution order of systems based on dependencies
1136
+ * Uses topological sort
1137
+ */
1138
+ getExecutionOrder() {
1139
+ if (this.cachedExecutionOrder !== null) return this.cachedExecutionOrder;
1140
+ const result = [];
1141
+ const visited = /* @__PURE__ */ new Set();
1142
+ const visiting = /* @__PURE__ */ new Set();
1143
+ const visit = (system) => {
1144
+ if (visited.has(system)) return;
1145
+ if (visiting.has(system)) throw new Error("Circular dependency detected in system scheduling");
1146
+ visiting.add(system);
1147
+ for (const dep of this.systemDependencies.get(system) || []) visit(dep);
1148
+ visiting.delete(system);
1149
+ visited.add(system);
1150
+ result.push(system);
1151
+ };
1152
+ for (const system of this.systems) if (!visited.has(system)) visit(system);
1153
+ this.cachedExecutionOrder = result;
1154
+ return result;
1155
+ }
1156
+ update(...params) {
1157
+ const executionOrder = this.getExecutionOrder();
1158
+ const systemPromises = /* @__PURE__ */ new Map();
1159
+ for (const system of executionOrder) {
1160
+ const depPromises = Array.from(this.systemDependencies.get(system) || []).map((dep) => systemPromises.get(dep)).filter(Boolean);
1161
+ if (depPromises.length > 0) {
1162
+ const promise = Promise.all(depPromises).then(() => system.update(...params));
1163
+ systemPromises.set(system, promise);
1164
+ } else {
1165
+ const result = system.update(...params);
1166
+ if (result instanceof Promise) systemPromises.set(system, result);
1167
+ }
1168
+ }
1169
+ return Promise.all(systemPromises.values());
1170
+ }
1171
+ /**
1172
+ * Clear all systems and dependencies
1173
+ */
1174
+ clear() {
1175
+ this.systems.clear();
1176
+ this.cachedExecutionOrder = null;
1177
+ }
1178
+ };
1179
+
1180
+ //#endregion
1181
+ //#region src/world.ts
1182
+ /**
1183
+ * World class for ECS architecture
1184
+ * Manages entities, components, and systems
1185
+ */
1186
+ var World = class {
1187
+ /** Manages allocation and deallocation of entity IDs */
1188
+ entityIdManager = new EntityIdManager();
1189
+ /** Array of all archetypes in the world */
1190
+ archetypes = [];
1191
+ /** Maps archetype signatures (component type signatures) to archetype instances */
1192
+ archetypeBySignature = /* @__PURE__ */ new Map();
1193
+ /** Maps entity IDs to their current archetype */
1194
+ entityToArchetype = /* @__PURE__ */ new Map();
1195
+ /** Maps component types to arrays of archetypes that contain them */
1196
+ archetypesByComponent = /* @__PURE__ */ new Map();
1197
+ /** Tracks which entities reference each entity as a component type */
1198
+ entityReferences = /* @__PURE__ */ new Map();
1199
+ /** Storage for dontFragment relations - maps entity ID to a map of relation type to component data */
1200
+ dontFragmentRelations = /* @__PURE__ */ new Map();
1201
+ /** Array of all active queries for archetype change notifications */
1202
+ queries = [];
1203
+ /** Cache for queries keyed by component types and filter signatures */
1204
+ queryCache = /* @__PURE__ */ new Map();
1205
+ /** Schedules and executes systems in dependency order */
1206
+ systemScheduler = new SystemScheduler();
1207
+ /** Buffers structural changes for deferred execution */
1208
+ commandBuffer = new CommandBuffer((entityId, commands) => this.executeEntityCommands(entityId, commands));
1209
+ /** Stores lifecycle hooks for component and relation events */
1210
+ hooks = /* @__PURE__ */ new Map();
1211
+ /**
1212
+ * Create a new World.
1213
+ * If an optional snapshot object is provided (previously produced by `world.serialize()`),
1214
+ * the world will be restored from that snapshot. The snapshot may contain non-JSON values.
1215
+ */
1216
+ constructor(snapshot) {
1217
+ if (snapshot && typeof snapshot === "object") {
1218
+ if (snapshot.entityManager) this.entityIdManager.deserializeState(snapshot.entityManager);
1219
+ if (Array.isArray(snapshot.entities)) for (const entry of snapshot.entities) {
1220
+ const entityId = entry.id;
1221
+ const componentsArray = entry.components || [];
1222
+ const componentMap = /* @__PURE__ */ new Map();
1223
+ const componentTypes = [];
1224
+ for (const componentEntry of componentsArray) {
1225
+ const componentTypeRaw = componentEntry.type;
1226
+ let componentType;
1227
+ if (typeof componentTypeRaw === "number") componentType = componentTypeRaw;
1228
+ else if (typeof componentTypeRaw === "string") {
1229
+ const compId = getComponentIdByName(componentTypeRaw);
1230
+ if (compId === void 0) throw new Error(`Unknown component name in snapshot: ${componentTypeRaw}`);
1231
+ componentType = compId;
1232
+ } else if (typeof componentTypeRaw === "object" && componentTypeRaw !== null && typeof componentTypeRaw.component === "string") {
1233
+ const compId = getComponentIdByName(componentTypeRaw.component);
1234
+ if (compId === void 0) throw new Error(`Unknown component name in snapshot: ${componentTypeRaw.component}`);
1235
+ if (typeof componentTypeRaw.target === "string") {
1236
+ const targetCompId = getComponentIdByName(componentTypeRaw.target);
1237
+ if (targetCompId === void 0) throw new Error(`Unknown target component name in snapshot: ${componentTypeRaw.target}`);
1238
+ componentType = relation(compId, targetCompId);
1239
+ } else componentType = relation(compId, componentTypeRaw.target);
1240
+ } else throw new Error(`Invalid component type in snapshot: ${JSON.stringify(componentTypeRaw)}`);
1241
+ componentMap.set(componentType, componentEntry.value);
1242
+ componentTypes.push(componentType);
1243
+ }
1244
+ const archetype = this.ensureArchetype(componentTypes);
1245
+ archetype.addEntity(entityId, componentMap);
1246
+ this.entityToArchetype.set(entityId, archetype);
1247
+ for (const compType of componentTypes) {
1248
+ const detailedType = getDetailedIdType(compType);
1249
+ if (detailedType.type === "entity-relation") {
1250
+ const targetEntityId = detailedType.targetId;
1251
+ this.trackEntityReference(entityId, compType, targetEntityId);
1252
+ } else if (detailedType.type === "entity") this.trackEntityReference(entityId, compType, compType);
1253
+ }
1254
+ }
1255
+ }
1256
+ }
1257
+ /**
1258
+ * Generate a signature string for component types array
1259
+ * @returns A string signature for the component types
1260
+ */
1261
+ createArchetypeSignature(componentTypes) {
1262
+ return componentTypes.join(",");
1263
+ }
1264
+ /**
1265
+ * Create a new entity
1266
+ * @returns The ID of the newly created entity
1267
+ */
1268
+ new() {
1269
+ const entityId = this.entityIdManager.allocate();
1270
+ let emptyArchetype = this.ensureArchetype([]);
1271
+ emptyArchetype.addEntity(entityId, /* @__PURE__ */ new Map());
1272
+ this.entityToArchetype.set(entityId, emptyArchetype);
1273
+ return entityId;
1274
+ }
1275
+ /**
1276
+ * Destroy an entity and remove all its components (immediate execution)
1277
+ */
1278
+ destroyEntityImmediate(entityId) {
1279
+ const queue = [entityId];
1280
+ const visited = /* @__PURE__ */ new Set();
1281
+ while (queue.length > 0) {
1282
+ const cur = queue.shift();
1283
+ if (visited.has(cur)) continue;
1284
+ visited.add(cur);
1285
+ const archetype = this.entityToArchetype.get(cur);
1286
+ if (!archetype) continue;
1287
+ const componentReferences = Array.from(this.getEntityReferences(cur));
1288
+ for (const [sourceEntityId, componentType] of componentReferences) {
1289
+ const sourceArchetype = this.entityToArchetype.get(sourceEntityId);
1290
+ if (!sourceArchetype) continue;
1291
+ const detailedType = getDetailedIdType(componentType);
1292
+ if (detailedType.type === "entity-relation" && isCascadeDeleteComponent(detailedType.componentId)) {
1293
+ if (!visited.has(sourceEntityId)) queue.push(sourceEntityId);
1294
+ continue;
1295
+ }
1296
+ const currentComponents = /* @__PURE__ */ new Map();
1297
+ let removedComponent = sourceArchetype.get(sourceEntityId, componentType);
1298
+ for (const archetypeComponentType of sourceArchetype.componentTypes) if (archetypeComponentType !== componentType) {
1299
+ const componentData = sourceArchetype.get(sourceEntityId, archetypeComponentType);
1300
+ currentComponents.set(archetypeComponentType, componentData);
1301
+ }
1302
+ const newArchetype = this.ensureArchetype(currentComponents.keys());
1303
+ sourceArchetype.removeEntity(sourceEntityId);
1304
+ if (sourceArchetype.getEntities().length === 0) this.cleanupEmptyArchetype(sourceArchetype);
1305
+ newArchetype.addEntity(sourceEntityId, currentComponents);
1306
+ this.entityToArchetype.set(sourceEntityId, newArchetype);
1307
+ this.untrackEntityReference(sourceEntityId, componentType, cur);
1308
+ this.triggerLifecycleHooks(sourceEntityId, /* @__PURE__ */ new Map(), new Map([[componentType, removedComponent]]));
1309
+ }
1310
+ this.entityReferences.delete(cur);
1311
+ archetype.removeEntity(cur);
1312
+ if (archetype.getEntities().length === 0) this.cleanupEmptyArchetype(archetype);
1313
+ this.entityToArchetype.delete(cur);
1314
+ this.entityIdManager.deallocate(cur);
1315
+ }
1316
+ }
1317
+ /**
1318
+ * Check if an entity exists
1319
+ */
1320
+ exists(entityId) {
1321
+ return this.entityToArchetype.has(entityId);
1322
+ }
1323
+ set(entityId, componentType, component$1) {
1324
+ if (!this.exists(entityId)) throw new Error(`Entity ${entityId} does not exist`);
1325
+ const detailedType = getDetailedIdType(componentType);
1326
+ if (detailedType.type === "invalid") throw new Error(`Invalid component type: ${componentType}`);
1327
+ if (detailedType.type === "wildcard-relation") throw new Error(`Cannot directly add wildcard relation components: ${componentType}`);
1328
+ this.commandBuffer.set(entityId, componentType, component$1);
1329
+ }
1330
+ /**
1331
+ * Remove a component from an entity (deferred)
1332
+ */
1333
+ remove(entityId, componentType) {
1334
+ if (!this.exists(entityId)) throw new Error(`Entity ${entityId} does not exist`);
1335
+ if (getDetailedIdType(componentType).type === "invalid") throw new Error(`Invalid component type: ${componentType}`);
1336
+ this.commandBuffer.remove(entityId, componentType);
1337
+ }
1338
+ /**
1339
+ * Destroy an entity and remove all its components (deferred)
1340
+ */
1341
+ delete(entityId) {
1342
+ this.commandBuffer.delete(entityId);
1343
+ }
1344
+ /**
1345
+ * Check if an entity has a specific component
1346
+ */
1347
+ has(entityId, componentType) {
1348
+ const archetype = this.entityToArchetype.get(entityId);
1349
+ if (!archetype) return false;
1350
+ if (archetype.componentTypes.includes(componentType)) return true;
1351
+ const detailedType = getDetailedIdType(componentType);
1352
+ if ((detailedType.type === "entity-relation" || detailedType.type === "component-relation") && isDontFragmentComponent(detailedType.componentId)) return this.dontFragmentRelations.get(entityId)?.has(componentType) ?? false;
1353
+ return false;
1354
+ }
1355
+ get(entityId, componentType) {
1356
+ const archetype = this.entityToArchetype.get(entityId);
1357
+ if (!archetype) throw new Error(`Entity ${entityId} does not exist`);
1358
+ const detailedType = getDetailedIdType(componentType);
1359
+ if (detailedType.type !== "wildcard-relation") {
1360
+ const inArchetype = archetype.componentTypes.includes(componentType);
1361
+ const isDontFragment = (detailedType.type === "entity-relation" || detailedType.type === "component-relation") && isDontFragmentComponent(detailedType.componentId);
1362
+ if (!(inArchetype || isDontFragment && this.dontFragmentRelations.get(entityId)?.has(componentType))) throw new Error(`Entity ${entityId} does not have component ${componentType}. Use has() to check component existence before calling get().`);
1363
+ }
1364
+ return archetype.get(entityId, componentType);
1365
+ }
1366
+ /**
1367
+ * Register a system with optional dependencies
1368
+ */
1369
+ registerSystem(system, additionalDeps = []) {
1370
+ this.systemScheduler.addSystem(system, additionalDeps);
1371
+ }
1372
+ /**
1373
+ * Register a lifecycle hook for component or wildcard relation events
1374
+ */
1375
+ hook(componentType, hook) {
1376
+ if (!this.hooks.has(componentType)) this.hooks.set(componentType, /* @__PURE__ */ new Set());
1377
+ this.hooks.get(componentType).add(hook);
1378
+ if (hook.on_init !== void 0) this.archetypesByComponent.get(componentType)?.forEach((archetype) => {
1379
+ const entities = archetype.getEntityToIndexMap();
1380
+ const componentData = archetype.getComponentData(componentType);
1381
+ for (const [entity, index] of entities) {
1382
+ const data = componentData[index];
1383
+ const value = data === MISSING_COMPONENT ? void 0 : data;
1384
+ hook.on_init?.(entity, componentType, value);
1385
+ }
1386
+ });
1387
+ }
1388
+ /**
1389
+ * Unregister a lifecycle hook for component or wildcard relation events
1390
+ */
1391
+ unhook(componentType, hook) {
1392
+ const hooks = this.hooks.get(componentType);
1393
+ if (hooks) {
1394
+ hooks.delete(hook);
1395
+ if (hooks.size === 0) this.hooks.delete(componentType);
1396
+ }
1397
+ }
1398
+ /**
1399
+ * Mark a component as exclusive relation
1400
+ * @deprecated This method has been removed. Use component options instead: component({ exclusive: true })
1401
+ * @throws Always throws an error directing to the new API
1402
+ */
1403
+ setExclusive(componentId) {
1404
+ throw new Error("setExclusive has been removed. Use component options instead: component({ exclusive: true })");
1405
+ }
1406
+ /**
1407
+ * Mark a component as cascade-delete relation
1408
+ * @deprecated This method has been removed. Use component options instead: component({ cascadeDelete: true })
1409
+ * @throws Always throws an error directing to the new API
1410
+ */
1411
+ setCascadeDelete(componentId) {
1412
+ throw new Error("setCascadeDelete has been removed. Use component options instead: component({ cascadeDelete: true })");
1413
+ }
1414
+ /**
1415
+ * Update the world (run all systems in dependency order)
1416
+ * This function is synchronous when all systems are synchronous,
1417
+ * and asynchronous (returns a Promise) when any system is asynchronous.
1418
+ */
1419
+ update(...params) {
1420
+ const result = this.systemScheduler.update(...params);
1421
+ if (result instanceof Promise) return result.then(() => this.commandBuffer.execute());
1422
+ else this.commandBuffer.execute();
1423
+ }
1424
+ /**
1425
+ * Execute all deferred commands immediately without running systems
1426
+ */
1427
+ sync() {
1428
+ this.commandBuffer.execute();
1429
+ }
1430
+ /**
1431
+ * Create a cached query for efficient entity lookups
1432
+ * @returns A Query object for the specified component types and filter
1433
+ */
1434
+ createQuery(componentTypes, filter = {}) {
1435
+ const sortedTypes = [...componentTypes].sort((a, b) => a - b);
1436
+ const filterKey = serializeQueryFilter(filter);
1437
+ const key = `${this.createArchetypeSignature(sortedTypes)}${filterKey ? `|${filterKey}` : ""}`;
1438
+ const cached = this.queryCache.get(key);
1439
+ if (cached) {
1440
+ cached.refCount++;
1441
+ return cached.query;
1442
+ }
1443
+ const query = new Query(this, sortedTypes, filter);
1444
+ this.queryCache.set(key, {
1445
+ query,
1446
+ refCount: 1
1447
+ });
1448
+ return query;
1449
+ }
1450
+ /**
1451
+ * @internal Register a query for archetype update notifications
1452
+ */
1453
+ _registerQuery(query) {
1454
+ this.queries.push(query);
1455
+ }
1456
+ /**
1457
+ * @internal Unregister a query
1458
+ */
1459
+ _unregisterQuery(query) {
1460
+ const index = this.queries.indexOf(query);
1461
+ if (index !== -1) this.queries.splice(index, 1);
1462
+ }
1463
+ /**
1464
+ * Release a query reference obtained from createQuery.
1465
+ * Decrements the refCount and fully disposes the query when it reaches zero.
1466
+ */
1467
+ releaseQuery(query) {
1468
+ for (const [k, v] of this.queryCache.entries()) if (v.query === query) {
1469
+ v.refCount--;
1470
+ if (v.refCount <= 0) {
1471
+ this.queryCache.delete(k);
1472
+ this._unregisterQuery(query);
1473
+ v.query._disposeInternal();
1474
+ }
1475
+ return;
1476
+ }
1477
+ }
1478
+ /**
1479
+ * @internal Get archetypes that match specific component types (for internal use by queries)
1480
+ */
1481
+ getMatchingArchetypes(componentTypes) {
1482
+ if (componentTypes.length === 0) return [...this.archetypes];
1483
+ const regularComponents = [];
1484
+ const wildcardRelations = [];
1485
+ for (const componentType of componentTypes) {
1486
+ const detailedType = getDetailedIdType(componentType);
1487
+ if (detailedType.type === "wildcard-relation") wildcardRelations.push({
1488
+ componentId: detailedType.componentId,
1489
+ relationId: componentType
1490
+ });
1491
+ else regularComponents.push(componentType);
1492
+ }
1493
+ let matchingArchetypes = [];
1494
+ if (regularComponents.length > 0) {
1495
+ const sortedRegularTypes = [...regularComponents].sort((a, b) => a - b);
1496
+ if (sortedRegularTypes.length === 1) {
1497
+ const componentType = sortedRegularTypes[0];
1498
+ matchingArchetypes = this.archetypesByComponent.get(componentType) || [];
1499
+ } else {
1500
+ const archetypeLists = sortedRegularTypes.map((type) => this.archetypesByComponent.get(type) || []);
1501
+ const firstList = archetypeLists[0] || [];
1502
+ const intersection = /* @__PURE__ */ new Set();
1503
+ for (const archetype of firstList) {
1504
+ let hasAllComponents = true;
1505
+ for (let listIndex = 1; listIndex < archetypeLists.length; listIndex++) if (!archetypeLists[listIndex].includes(archetype)) {
1506
+ hasAllComponents = false;
1507
+ break;
1508
+ }
1509
+ if (hasAllComponents) intersection.add(archetype);
1510
+ }
1511
+ matchingArchetypes = Array.from(intersection);
1512
+ }
1513
+ } else matchingArchetypes = [...this.archetypes];
1514
+ for (const wildcard of wildcardRelations) matchingArchetypes = matchingArchetypes.filter((archetype) => archetype.componentTypes.some((archetypeType) => {
1515
+ if (!isRelationId(archetypeType)) return false;
1516
+ return decodeRelationId(archetypeType).componentId === wildcard.componentId;
1517
+ }));
1518
+ return matchingArchetypes;
1519
+ }
1520
+ query(componentTypes, includeComponents) {
1521
+ const matchingArchetypes = this.getMatchingArchetypes(componentTypes);
1522
+ if (includeComponents) {
1523
+ const result = [];
1524
+ for (const archetype of matchingArchetypes) {
1525
+ const entitiesWithData = archetype.getEntitiesWithComponents(componentTypes);
1526
+ result.push(...entitiesWithData);
1527
+ }
1528
+ return result;
1529
+ } else {
1530
+ const result = [];
1531
+ for (const archetype of matchingArchetypes) result.push(...archetype.getEntities());
1532
+ return result;
1533
+ }
1534
+ }
1535
+ /**
1536
+ * @internal Execute commands for a single entity (for internal use by CommandBuffer)
1537
+ * @returns ComponentChangeset describing the changes made
1538
+ */
1539
+ executeEntityCommands(entityId, commands) {
1540
+ const changeset = new ComponentChangeset();
1541
+ if (commands.some((cmd) => cmd.type === "destroy")) {
1542
+ this.destroyEntityImmediate(entityId);
1543
+ return changeset;
1544
+ }
1545
+ const currentArchetype = this.entityToArchetype.get(entityId);
1546
+ if (!currentArchetype) return changeset;
1547
+ this.processCommands(entityId, currentArchetype, commands, changeset);
1548
+ const removedComponents = this.applyChangeset(entityId, currentArchetype, changeset);
1549
+ this.updateEntityReferences(entityId, changeset);
1550
+ this.triggerLifecycleHooks(entityId, changeset.adds, removedComponents);
1551
+ return changeset;
1552
+ }
1553
+ /**
1554
+ * Process commands and populate the changeset
1555
+ */
1556
+ processCommands(entityId, currentArchetype, commands, changeset) {
1557
+ for (const command of commands) if (command.type === "set" && command.componentType) this.processSetCommand(entityId, currentArchetype, command.componentType, command.component, changeset);
1558
+ else if (command.type === "delete" && command.componentType) this.processDeleteCommand(entityId, currentArchetype, command.componentType, changeset);
1559
+ }
1560
+ /**
1561
+ * Process a set command, handling exclusive relations
1562
+ */
1563
+ processSetCommand(entityId, currentArchetype, componentType, component$1, changeset) {
1564
+ const detailedType = getDetailedIdType(componentType);
1565
+ if ((detailedType.type === "entity-relation" || detailedType.type === "component-relation") && isExclusiveComponent(detailedType.componentId)) this.removeExclusiveRelations(entityId, currentArchetype, detailedType.componentId, changeset);
1566
+ changeset.set(componentType, component$1);
1567
+ }
1568
+ /**
1569
+ * Remove all relations with the same base component (for exclusive relations)
1570
+ */
1571
+ removeExclusiveRelations(entityId, currentArchetype, baseComponentId, changeset) {
1572
+ for (const componentType of currentArchetype.componentTypes) if (this.isRelationWithComponent(componentType, baseComponentId)) changeset.delete(componentType);
1573
+ const entityData = currentArchetype.getEntity(entityId);
1574
+ if (entityData) for (const [componentType] of entityData) {
1575
+ if (currentArchetype.componentTypes.includes(componentType)) continue;
1576
+ if (this.isRelationWithComponent(componentType, baseComponentId)) changeset.delete(componentType);
1577
+ }
1578
+ }
1579
+ /**
1580
+ * Check if a component type is a relation with the given base component
1581
+ */
1582
+ isRelationWithComponent(componentType, baseComponentId) {
1583
+ const detailedType = getDetailedIdType(componentType);
1584
+ return (detailedType.type === "entity-relation" || detailedType.type === "component-relation") && detailedType.componentId === baseComponentId;
1585
+ }
1586
+ /**
1587
+ * Process a delete command, handling wildcard relations
1588
+ */
1589
+ processDeleteCommand(entityId, currentArchetype, componentType, changeset) {
1590
+ const detailedType = getDetailedIdType(componentType);
1591
+ if (detailedType.type === "wildcard-relation") this.removeWildcardRelations(entityId, currentArchetype, detailedType.componentId, changeset);
1592
+ else changeset.delete(componentType);
1593
+ }
1594
+ /**
1595
+ * Remove all relations matching a wildcard component ID
1596
+ */
1597
+ removeWildcardRelations(entityId, currentArchetype, baseComponentId, changeset) {
1598
+ for (const componentType of currentArchetype.componentTypes) if (this.isRelationWithComponent(componentType, baseComponentId)) changeset.delete(componentType);
1599
+ const entityData = currentArchetype.getEntity(entityId);
1600
+ if (entityData) for (const [componentType] of entityData) {
1601
+ if (currentArchetype.componentTypes.includes(componentType)) continue;
1602
+ if (this.isRelationWithComponent(componentType, baseComponentId)) changeset.delete(componentType);
1603
+ }
1604
+ }
1605
+ /**
1606
+ * Apply changeset to entity, moving to new archetype if needed
1607
+ * @returns Map of removed components with their data
1608
+ */
1609
+ applyChangeset(entityId, currentArchetype, changeset) {
1610
+ const currentEntityData = currentArchetype.getEntity(entityId);
1611
+ const allCurrentComponentTypes = currentEntityData ? Array.from(currentEntityData.keys()) : currentArchetype.componentTypes;
1612
+ const finalComponentTypes = changeset.getFinalComponentTypes(allCurrentComponentTypes);
1613
+ const removedComponents = /* @__PURE__ */ new Map();
1614
+ if (finalComponentTypes) this.moveEntityToNewArchetype(entityId, currentArchetype, finalComponentTypes, changeset, removedComponents);
1615
+ else this.updateEntityInSameArchetype(entityId, currentArchetype, changeset, removedComponents);
1616
+ return removedComponents;
1617
+ }
1618
+ /**
1619
+ * Move entity to a new archetype with updated components
1620
+ */
1621
+ moveEntityToNewArchetype(entityId, currentArchetype, finalComponentTypes, changeset, removedComponents) {
1622
+ const newArchetype = this.ensureArchetype(finalComponentTypes);
1623
+ const currentComponents = currentArchetype.removeEntity(entityId);
1624
+ for (const componentType of changeset.removes) removedComponents.set(componentType, currentComponents.get(componentType));
1625
+ newArchetype.addEntity(entityId, changeset.applyTo(currentComponents));
1626
+ this.entityToArchetype.set(entityId, newArchetype);
1627
+ if (currentArchetype.getEntities().length === 0) this.cleanupEmptyArchetype(currentArchetype);
1628
+ }
1629
+ /**
1630
+ * Update entity in same archetype (no archetype change needed)
1631
+ */
1632
+ updateEntityInSameArchetype(entityId, currentArchetype, changeset, removedComponents) {
1633
+ const currentComponents = currentArchetype.getEntity(entityId);
1634
+ const hasDontFragmentChanges = this.hasDontFragmentChanges(changeset);
1635
+ if (hasDontFragmentChanges) for (const componentType of changeset.removes) {
1636
+ const detailedType = getDetailedIdType(componentType);
1637
+ if ((detailedType.type === "entity-relation" || detailedType.type === "component-relation") && isDontFragmentComponent(detailedType.componentId)) removedComponents.set(componentType, currentComponents.get(componentType));
1638
+ }
1639
+ if (hasDontFragmentChanges) this.readdEntityWithUpdatedComponents(entityId, currentArchetype, currentComponents, changeset);
1640
+ else for (const [componentType, component$1] of changeset.adds) currentArchetype.set(entityId, componentType, component$1);
1641
+ }
1642
+ /**
1643
+ * Check if changeset contains dontFragment relation changes
1644
+ */
1645
+ hasDontFragmentChanges(changeset) {
1646
+ for (const componentType of changeset.removes) {
1647
+ const detailedType = getDetailedIdType(componentType);
1648
+ if ((detailedType.type === "entity-relation" || detailedType.type === "component-relation") && isDontFragmentComponent(detailedType.componentId)) return true;
1649
+ }
1650
+ for (const [componentType] of changeset.adds) {
1651
+ const detailedType = getDetailedIdType(componentType);
1652
+ if ((detailedType.type === "entity-relation" || detailedType.type === "component-relation") && isDontFragmentComponent(detailedType.componentId)) return true;
1653
+ }
1654
+ return false;
1655
+ }
1656
+ /**
1657
+ * Remove and re-add entity with updated components (for dontFragment changes)
1658
+ */
1659
+ readdEntityWithUpdatedComponents(entityId, archetype, currentComponents, changeset) {
1660
+ const newComponents = /* @__PURE__ */ new Map();
1661
+ for (const [ct, value] of currentComponents) if (!changeset.removes.has(ct)) newComponents.set(ct, value);
1662
+ for (const [ct, value] of changeset.adds) newComponents.set(ct, value);
1663
+ archetype.removeEntity(entityId);
1664
+ archetype.addEntity(entityId, newComponents);
1665
+ }
1666
+ /**
1667
+ * Update entity reference tracking based on changeset
1668
+ */
1669
+ updateEntityReferences(entityId, changeset) {
1670
+ for (const componentType of changeset.removes) {
1671
+ const detailedType = getDetailedIdType(componentType);
1672
+ if (detailedType.type === "entity-relation") this.untrackEntityReference(entityId, componentType, detailedType.targetId);
1673
+ else if (detailedType.type === "entity") this.untrackEntityReference(entityId, componentType, componentType);
1674
+ }
1675
+ for (const [componentType] of changeset.adds) {
1676
+ const detailedType = getDetailedIdType(componentType);
1677
+ if (detailedType.type === "entity-relation") this.trackEntityReference(entityId, componentType, detailedType.targetId);
1678
+ else if (detailedType.type === "entity") this.trackEntityReference(entityId, componentType, componentType);
1679
+ }
1680
+ }
1681
+ /**
1682
+ * Get or create an archetype for the given component types
1683
+ * Filters out dontFragment relations from the archetype signature
1684
+ * @returns The archetype for the given component types (excluding dontFragment relations)
1685
+ */
1686
+ ensureArchetype(componentTypes) {
1687
+ const sortedTypes = this.filterRegularComponentTypes(componentTypes).sort((a, b) => a - b);
1688
+ const hashKey = this.createArchetypeSignature(sortedTypes);
1689
+ return getOrCreateWithSideEffect(this.archetypeBySignature, hashKey, () => this.createNewArchetype(sortedTypes));
1690
+ }
1691
+ /**
1692
+ * Filter out dontFragment relations from component types
1693
+ */
1694
+ filterRegularComponentTypes(componentTypes) {
1695
+ const regularTypes = [];
1696
+ for (const componentType of componentTypes) {
1697
+ const detailedType = getDetailedIdType(componentType);
1698
+ if ((detailedType.type === "entity-relation" || detailedType.type === "component-relation") && isDontFragmentComponent(detailedType.componentId)) continue;
1699
+ regularTypes.push(componentType);
1700
+ }
1701
+ return regularTypes;
1702
+ }
1703
+ /**
1704
+ * Create a new archetype and register it with all tracking structures
1705
+ */
1706
+ createNewArchetype(componentTypes) {
1707
+ const newArchetype = new Archetype(componentTypes, this.dontFragmentRelations);
1708
+ this.archetypes.push(newArchetype);
1709
+ this.registerArchetypeInComponentIndex(newArchetype, componentTypes);
1710
+ this.notifyQueriesOfNewArchetype(newArchetype);
1711
+ return newArchetype;
1712
+ }
1713
+ /**
1714
+ * Register archetype in the component-to-archetype index
1715
+ */
1716
+ registerArchetypeInComponentIndex(archetype, componentTypes) {
1717
+ for (const componentType of componentTypes) {
1718
+ const archetypes = this.archetypesByComponent.get(componentType) || [];
1719
+ archetypes.push(archetype);
1720
+ this.archetypesByComponent.set(componentType, archetypes);
1721
+ }
1722
+ }
1723
+ /**
1724
+ * Notify all queries to check the new archetype
1725
+ */
1726
+ notifyQueriesOfNewArchetype(archetype) {
1727
+ for (const query of this.queries) query.checkNewArchetype(archetype);
1728
+ }
1729
+ /**
1730
+ * Add a component reference to the reverse index when an entity is used as a component type
1731
+ * @param sourceEntityId The entity that has the component
1732
+ * @param componentType The component type (which may be an entity ID used as component type)
1733
+ * @param targetEntityId The entity being used as component type
1734
+ */
1735
+ trackEntityReference(sourceEntityId, componentType, targetEntityId) {
1736
+ if (!this.entityReferences.has(targetEntityId)) this.entityReferences.set(targetEntityId, new MultiMap());
1737
+ this.entityReferences.get(targetEntityId).add(sourceEntityId, componentType);
1738
+ }
1739
+ /**
1740
+ * Remove a component reference from the reverse index
1741
+ * @param sourceEntityId The entity that has the component
1742
+ * @param componentType The component type
1743
+ * @param targetEntityId The entity being used as component type
1744
+ */
1745
+ untrackEntityReference(sourceEntityId, componentType, targetEntityId) {
1746
+ const references = this.entityReferences.get(targetEntityId);
1747
+ if (references) {
1748
+ references.remove(sourceEntityId, componentType);
1749
+ if (references.keyCount === 0) this.entityReferences.delete(targetEntityId);
1750
+ }
1751
+ }
1752
+ /**
1753
+ * Get all component references where a target entity is used as a component type
1754
+ * @param targetEntityId The target entity
1755
+ * @returns A MultiMap of sourceEntityId to componentTypes that reference the target entity
1756
+ */
1757
+ getEntityReferences(targetEntityId) {
1758
+ return this.entityReferences.get(targetEntityId) ?? new MultiMap();
1759
+ }
1760
+ /**
1761
+ * Remove an empty archetype from all internal data structures
1762
+ */
1763
+ cleanupEmptyArchetype(archetype) {
1764
+ if (archetype.getEntities().length > 0) return;
1765
+ this.removeArchetypeFromList(archetype);
1766
+ this.removeArchetypeFromSignatureMap(archetype);
1767
+ this.removeArchetypeFromComponentIndex(archetype);
1768
+ this.removeArchetypeFromQueries(archetype);
1769
+ }
1770
+ /**
1771
+ * Remove archetype from the main archetypes list
1772
+ */
1773
+ removeArchetypeFromList(archetype) {
1774
+ const index = this.archetypes.indexOf(archetype);
1775
+ if (index !== -1) this.archetypes.splice(index, 1);
1776
+ }
1777
+ /**
1778
+ * Remove archetype from the signature-to-archetype map
1779
+ */
1780
+ removeArchetypeFromSignatureMap(archetype) {
1781
+ const hashKey = this.createArchetypeSignature(archetype.componentTypes);
1782
+ this.archetypeBySignature.delete(hashKey);
1783
+ }
1784
+ /**
1785
+ * Remove archetype from the component-to-archetypes index
1786
+ */
1787
+ removeArchetypeFromComponentIndex(archetype) {
1788
+ for (const componentType of archetype.componentTypes) {
1789
+ const archetypes = this.archetypesByComponent.get(componentType);
1790
+ if (archetypes) {
1791
+ const compIndex = archetypes.indexOf(archetype);
1792
+ if (compIndex !== -1) {
1793
+ archetypes.splice(compIndex, 1);
1794
+ if (archetypes.length === 0) this.archetypesByComponent.delete(componentType);
1795
+ }
1796
+ }
1797
+ }
1798
+ }
1799
+ /**
1800
+ * Remove archetype from all queries
1801
+ */
1802
+ removeArchetypeFromQueries(archetype) {
1803
+ for (const query of this.queries) query.removeArchetype(archetype);
1804
+ }
1805
+ /**
1806
+ * Execute component lifecycle hooks for added and removed components
1807
+ */
1808
+ triggerLifecycleHooks(entityId, addedComponents, removedComponents) {
1809
+ for (const [componentType, component$1] of addedComponents) {
1810
+ const directHooks = this.hooks.get(componentType);
1811
+ if (directHooks) for (const lifecycleHook of directHooks) lifecycleHook.on_set?.(entityId, componentType, component$1);
1812
+ const detailedType = getDetailedIdType(componentType);
1813
+ if (detailedType.type === "entity-relation" || detailedType.type === "component-relation" || detailedType.type === "wildcard-relation") {
1814
+ const wildcardRelationId = relation(detailedType.componentId, "*");
1815
+ const wildcardHooks = this.hooks.get(wildcardRelationId);
1816
+ if (wildcardHooks) for (const lifecycleHook of wildcardHooks) lifecycleHook.on_set?.(entityId, componentType, component$1);
1817
+ }
1818
+ }
1819
+ for (const [componentType, component$1] of removedComponents) {
1820
+ const directHooks = this.hooks.get(componentType);
1821
+ if (directHooks) for (const lifecycleHook of directHooks) lifecycleHook.on_remove?.(entityId, componentType, component$1);
1822
+ const detailedType = getDetailedIdType(componentType);
1823
+ if (detailedType.type === "entity-relation" || detailedType.type === "component-relation" || detailedType.type === "wildcard-relation") {
1824
+ const wildcardRelationId = relation(detailedType.componentId, "*");
1825
+ const wildcardHooks = this.hooks.get(wildcardRelationId);
1826
+ if (wildcardHooks) for (const hook of wildcardHooks) hook.on_remove?.(entityId, componentType, component$1);
1827
+ }
1828
+ }
1829
+ }
1830
+ /**
1831
+ * Convert the world into a plain snapshot object.
1832
+ * This returns an in-memory structure and does not perform JSON stringification.
1833
+ * Component values are stored as-is (they may be non-JSON-serializable).
1834
+ */
1835
+ serialize() {
1836
+ const entities = [];
1837
+ for (const archetype of this.archetypes) {
1838
+ const dumpedEntities = archetype.dump();
1839
+ for (const { entity, components } of dumpedEntities) entities.push({
1840
+ id: entity,
1841
+ components: Array.from(components.entries()).map(([rawType, value]) => {
1842
+ const detailedType = getDetailedIdType(rawType);
1843
+ let type = rawType;
1844
+ let componentName;
1845
+ switch (detailedType.type) {
1846
+ case "component":
1847
+ type = getComponentNameById(rawType) || rawType;
1848
+ break;
1849
+ case "entity-relation":
1850
+ componentName = getComponentNameById(detailedType.componentId);
1851
+ if (componentName) type = {
1852
+ component: componentName,
1853
+ target: detailedType.targetId
1854
+ };
1855
+ break;
1856
+ case "component-relation":
1857
+ componentName = getComponentNameById(detailedType.componentId);
1858
+ if (componentName) type = {
1859
+ component: componentName,
1860
+ target: getComponentNameById(detailedType.targetId) || detailedType.targetId
1861
+ };
1862
+ break;
1863
+ }
1864
+ return {
1865
+ type,
1866
+ value: value === MISSING_COMPONENT ? void 0 : value
1867
+ };
1868
+ })
1869
+ });
1870
+ }
1871
+ return {
1872
+ version: 1,
1873
+ entityManager: this.entityIdManager.serializeState(),
1874
+ entities
1875
+ };
1876
+ }
1877
+ };
1878
+
1879
+ //#endregion
1880
+ export { Query, World, component, decodeRelationId, getComponentIdByName, getComponentNameById, isComponentId, isEntityId, isRelationId, isWildcardRelationId, relation };
1881
+ //# sourceMappingURL=index.mjs.map