@codehz/ecs 0.5.1 → 0.5.2
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/{world.d.mts → builder.d.mts} +103 -465
- package/index.d.mts +1 -1
- package/index.mjs +1 -1
- package/package.json +1 -1
- package/testing.d.mts +2 -2
- package/testing.mjs +2 -2
- package/testing.mjs.map +1 -1
- package/world.mjs +1192 -1540
- package/world.mjs.map +1 -1
package/world.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"world.mjs","names":["actualTargetId: number","type: \"entity-relation\" | \"component-relation\" | \"wildcard-relation\"","ComponentIdForNames: Map<string, ComponentId<any>>","componentNames: (string | undefined)[]","name: string | undefined","options: ComponentOptions | undefined","result: Array<{\n entity: EntityId;\n components: Map<EntityId<any>, any>;\n }>","relations: [EntityId<unknown>, any][]","result: Array<{\n entity: EntityId;\n components: ComponentTuple<T>;\n }>","component","result: EntityId[]","result: Array<{\n entity: EntityId;\n components: ComponentTuple<T>;\n }>","result: T[]","targetId: EntityId<any>","componentsArray: SerializedComponent[]","componentTypes: EntityId<any>[]","queue: EntityId[]","component","requiredComponents: EntityId<any>[]","entities: EntityId[]","regularComponents: EntityId<any>[]","wildcardRelations: { componentId: ComponentId<any>; relationId: EntityId<any> }[]","matchingArchetypes: Archetype[]","result: Array<{\n entity: EntityId;\n components: any;\n }>","result: EntityId[]","regularTypes: EntityId<any>[]","result: any[]","entities: SerializedEntity[]"],"sources":["../src/bit-set.ts","../src/entity.ts","../src/types.ts","../src/utils.ts","../src/archetype.ts","../src/changeset.ts","../src/command-buffer.ts","../src/multi-map.ts","../src/query-filter.ts","../src/query.ts","../src/world.ts"],"sourcesContent":["export class BitSet {\n private data: Uint32Array;\n private _length: number;\n\n constructor(length: number) {\n this._length = length;\n const numWords = Math.ceil(length / 32);\n this.data = new Uint32Array(numWords);\n }\n\n get length(): number {\n return this._length;\n }\n\n has(index: number): boolean {\n if (index < 0 || index >= this._length) return false;\n const word = index >>> 5; // divide by 32\n const bit = index & 31;\n return ((this.data[word]! >>> bit) & 1) !== 0;\n }\n\n set(index: number): void {\n if (index < 0 || index >= this._length) return;\n const word = index >>> 5;\n const bit = index & 31;\n this.data[word]! |= 1 << bit;\n }\n\n clear(index: number): void {\n if (index < 0 || index >= this._length) return;\n const word = index >>> 5;\n const bit = index & 31;\n this.data[word]! &= ~(1 << bit);\n }\n\n // set a range [lo, hi] inclusive to 1\n setRange(lo: number, hi: number): void {\n if (lo > hi) return;\n if (lo < 0) lo = 0;\n if (hi >= this._length) hi = this._length - 1;\n\n const firstWord = lo >>> 5;\n const lastWord = hi >>> 5;\n const loBit = lo & 31;\n const hiBit = hi & 31;\n\n // helper to produce mask for [a..b] within a single 32-bit word\n const maskFor = (a: number, b: number) => {\n const width = b - a + 1;\n if (width <= 0) return 0 >>> 0;\n if (width >= 32) return 0xffffffff >>> 0;\n return (((1 << width) - 1) << a) >>> 0;\n };\n\n if (firstWord === lastWord) {\n const mask = maskFor(loBit, hiBit);\n this.data[firstWord]! = (this.data[firstWord]! | mask) >>> 0;\n return;\n }\n\n // first partial word\n const firstMask = maskFor(loBit, 31);\n this.data[firstWord]! = (this.data[firstWord]! | firstMask) >>> 0;\n\n // middle full words\n for (let w = firstWord + 1; w <= lastWord - 1; w++) {\n this.data[w] = 0xffffffff >>> 0;\n }\n\n // last partial word\n const lastMask = maskFor(0, hiBit);\n this.data[lastWord]! = (this.data[lastWord]! | lastMask) >>> 0;\n }\n\n // check whether any bit in [lo, hi] is zero (i.e. not set)\n anyClearInRange(lo: number, hi: number): boolean {\n if (lo > hi) return false;\n if (lo < 0) lo = 0;\n if (hi >= this._length) hi = this._length - 1;\n\n const firstWord = lo >>> 5;\n const lastWord = hi >>> 5;\n const loBit = lo & 31;\n const hiBit = hi & 31;\n\n const maskFor = (a: number, b: number) => {\n const width = b - a + 1;\n if (width <= 0) return 0 >>> 0;\n if (width >= 32) return 0xffffffff >>> 0;\n return (((1 << width) - 1) << a) >>> 0;\n };\n\n if (firstWord === lastWord) {\n const mask = maskFor(loBit, hiBit);\n const bits = (this.data[firstWord]! & mask) >>> 0;\n return bits !== mask >>> 0;\n }\n\n // first partial word: if any bit in the mask is clear -> return true\n const firstMask = maskFor(loBit, 31);\n if ((this.data[firstWord]! & firstMask) >>> 0 !== firstMask >>> 0) return true;\n\n // middle full words\n for (let w = firstWord + 1; w <= lastWord - 1; w++) {\n if (this.data[w] !== 0xffffffff >>> 0) return true;\n }\n\n // last partial word\n const lastMask = maskFor(0, hiBit);\n if ((this.data[lastWord]! & lastMask) >>> 0 !== lastMask >>> 0) return true;\n\n return false;\n }\n\n // reset all bits to zero\n reset(): void {\n this.data.fill(0);\n }\n\n *[Symbol.iterator](): IterableIterator<number> {\n for (let wordIndex = 0; wordIndex < this.data.length; wordIndex++) {\n let word = this.data[wordIndex]!;\n if (word === 0) continue;\n const baseIndex = wordIndex * 32;\n for (let bit = 0; bit < 32 && baseIndex + bit < this._length; bit++) {\n if (word & 1) {\n yield baseIndex + bit;\n }\n word >>>= 1;\n }\n }\n }\n}\n","import { BitSet } from \"./bit-set\";\n\n/**\n * Unique symbol brand for associating component type information with EntityId\n */\ndeclare const __componentTypeMarker: unique symbol;\n\n/**\n * Unique symbol brand for tagging the kind of EntityId (e.g., 'component', 'entity-relation')\n */\ndeclare const __entityIdTypeTag: unique symbol;\n\n/**\n * Entity ID type for ECS architecture\n * Based on 52-bit integers within safe integer range\n * - Component IDs: 1-1023\n * - Entity IDs: 1024+\n * - Relation IDs: negative numbers encoding component and entity associations\n */\nexport type EntityId<T = unknown, U = unknown> = number & {\n readonly [__componentTypeMarker]: T;\n readonly [__entityIdTypeTag]: U;\n};\n\nexport type ComponentId<T = void> = EntityId<T, \"component\">;\nexport type EntityRelationId<T = void> = EntityId<T, \"entity-relation\">;\nexport type ComponentRelationId<T = void> = EntityId<T, \"component-relation\">;\nexport type WildcardRelationId<T = void> = EntityId<T, \"wildcard-relation\">;\nexport type RelationId<T = void> = EntityRelationId<T> | ComponentRelationId<T> | WildcardRelationId<T>;\n\n/**\n * Constants for ID ranges\n */\nexport const INVALID_COMPONENT_ID = 0;\nexport const COMPONENT_ID_MAX = 1023;\nexport const ENTITY_ID_START = 1024;\n\n/**\n * Constants for relation ID encoding\n */\nexport const RELATION_SHIFT = 2 ** 42;\nexport const WILDCARD_TARGET_ID = 0;\n\n/**\n * Internal function to decode a relation ID into raw component and target IDs\n * @param id The EntityId to decode\n * @returns Object with componentId and targetId, or null if not a relation\n */\nfunction decodeRelationRaw(id: EntityId<any>): { componentId: number; targetId: number } | null {\n if (id >= 0) return null;\n const absId = -id;\n const componentId = Math.floor(absId / RELATION_SHIFT);\n const targetId = absId % RELATION_SHIFT;\n return { componentId, targetId };\n}\n\n/**\n * Check if a component ID is valid (1-1023)\n */\nfunction isValidComponentId(componentId: number): boolean {\n return componentId >= 1 && componentId <= COMPONENT_ID_MAX;\n}\n\n/**\n * Create a component ID\n * @param id Component identifier (1-1023)\n * @internal This function is for internal use and testing only. Use `component()` to create components.\n * @see component\n */\nexport function createComponentId<T = void>(id: number): ComponentId<T> {\n if (id < 1 || id > COMPONENT_ID_MAX) {\n throw new Error(`Component ID must be between 1 and ${COMPONENT_ID_MAX}`);\n }\n return id as ComponentId<T>;\n}\n\n/**\n * Create an entity ID\n * @param id Entity identifier (starting from 1024)\n */\nexport function createEntityId(id: number): EntityId {\n if (id < ENTITY_ID_START) {\n throw new Error(`Entity ID must be ${ENTITY_ID_START} or greater`);\n }\n return id as EntityId;\n}\n\n/**\n * Type for relation ID based on component and target types\n */\ntype RelationIdType<T, R> =\n R extends ComponentId<infer U>\n ? U extends void\n ? ComponentRelationId<T>\n : ComponentRelationId<T extends void ? U : T>\n : R extends EntityId<any>\n ? EntityRelationId<T>\n : never;\n\n/**\n * Create a relation ID by associating a component with another ID (entity or component)\n * @param componentId The component ID (0-1023)\n * @param targetId The target ID (entity, component, or '*' for wildcard)\n */\nexport function relation<T>(componentId: ComponentId<T>, targetId: \"*\"): WildcardRelationId<T>;\nexport function relation<T, R extends EntityId<any>>(componentId: ComponentId<T>, targetId: R): RelationIdType<T, R>;\nexport function relation<T>(componentId: ComponentId<T>, targetId: EntityId<any> | \"*\"): EntityId<any> {\n if (!isComponentId(componentId)) {\n throw new Error(\"First argument must be a valid component ID\");\n }\n\n let actualTargetId: number;\n if (targetId === \"*\") {\n actualTargetId = WILDCARD_TARGET_ID;\n } else {\n if (!isEntityId(targetId) && !isComponentId(targetId)) {\n throw new Error(\"Second argument must be a valid entity ID, component ID, or '*'\");\n }\n actualTargetId = targetId;\n }\n\n // Encode: negative number with component_id * 2^42 + target_id\n return -(componentId * RELATION_SHIFT + actualTargetId) as EntityId<any>;\n}\n\n/**\n * Check if an ID is a component ID\n */\nexport function isComponentId<T>(id: EntityId<T>): id is ComponentId<T> {\n return id >= 1 && id <= COMPONENT_ID_MAX;\n}\n\n/**\n * Check if an ID is an entity ID\n */\nexport function isEntityId<T>(id: EntityId<T>): id is EntityId<T> {\n return id >= ENTITY_ID_START;\n}\n\n/**\n * Check if an ID is a relation ID\n */\nexport function isRelationId<T>(id: EntityId<T>): id is RelationId<T> {\n return id < 0;\n}\n\n/**\n * Check if an ID is a wildcard relation id\n */\nexport function isWildcardRelationId<T>(id: EntityId<T>): id is WildcardRelationId<T> {\n const decoded = decodeRelationRaw(id);\n return decoded !== null && decoded.targetId === WILDCARD_TARGET_ID;\n}\n\n/**\n * Decode a relation ID into component and target IDs\n * @param relationId The relation ID (must be negative)\n * @returns Object with componentId, targetId, and relation type\n */\nexport function decodeRelationId(relationId: RelationId<any>): {\n componentId: ComponentId<any>;\n targetId: EntityId<any>;\n type: \"entity\" | \"component\" | \"wildcard\";\n} {\n const decoded = decodeRelationRaw(relationId);\n if (decoded === null) {\n throw new Error(\"ID is not a relation ID\");\n }\n\n const { componentId: rawComponentId, targetId: rawTargetId } = decoded;\n if (!isValidComponentId(rawComponentId)) {\n throw new Error(\"Invalid component ID in relation\");\n }\n\n const componentId = rawComponentId as ComponentId<any>;\n const targetId = rawTargetId as EntityId<any>;\n\n // Determine type based on targetId range\n if (targetId === WILDCARD_TARGET_ID) {\n return { componentId, targetId, type: \"wildcard\" };\n } else if (isEntityId(targetId)) {\n return { componentId, targetId, type: \"entity\" };\n } else if (isComponentId(targetId)) {\n return { componentId, targetId, type: \"component\" };\n } else {\n throw new Error(\"Invalid target ID in relation\");\n }\n}\n\n/**\n * Get the string representation of an ID type\n */\nexport function getIdType(\n id: EntityId<any>,\n): \"component\" | \"entity\" | \"entity-relation\" | \"component-relation\" | \"wildcard-relation\" | \"invalid\" {\n if (isComponentId(id)) return \"component\";\n if (isEntityId(id)) return \"entity\";\n\n if (isRelationId(id)) {\n try {\n const decoded = decodeRelationId(id);\n // Validate that componentId and targetId are valid (decodeRelationId already checks componentId)\n if (decoded.type !== \"wildcard\" && !isEntityId(decoded.targetId) && !isComponentId(decoded.targetId)) {\n return \"invalid\";\n }\n switch (decoded.type) {\n case \"entity\":\n return \"entity-relation\";\n case \"component\":\n return \"component-relation\";\n case \"wildcard\":\n return \"wildcard-relation\";\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (_error) {\n return \"invalid\"; // fallback for invalid relation IDs\n }\n }\n\n return \"invalid\"; // fallback for unknown/invalid IDs\n}\n\n/**\n * Get detailed type information for an EntityId\n * @param id The EntityId to analyze\n * @returns Detailed type information including relation subtypes\n */\nexport function getDetailedIdType(id: EntityId<any>):\n | {\n type: \"component\" | \"entity\" | \"invalid\";\n componentId?: never;\n targetId?: never;\n }\n | {\n type: \"entity-relation\" | \"wildcard-relation\";\n componentId: ComponentId<any>;\n targetId: EntityId<any>;\n }\n | {\n type: \"component-relation\";\n componentId: ComponentId<any>;\n targetId: ComponentId<any>;\n } {\n if (isComponentId(id)) {\n return { type: \"component\" };\n }\n\n if (isEntityId(id)) {\n return { type: \"entity\" };\n }\n\n if (isRelationId(id)) {\n try {\n const decoded = decodeRelationId(id);\n // Validate that targetId is valid (decodeRelationId already checks componentId)\n if (decoded.type !== \"wildcard\" && !isEntityId(decoded.targetId) && !isComponentId(decoded.targetId)) {\n return { type: \"invalid\" };\n }\n let type: \"entity-relation\" | \"component-relation\" | \"wildcard-relation\";\n\n switch (decoded.type) {\n case \"entity\":\n type = \"entity-relation\";\n break;\n case \"component\":\n type = \"component-relation\";\n break;\n case \"wildcard\":\n type = \"wildcard-relation\";\n break;\n }\n\n return {\n type,\n componentId: decoded.componentId,\n targetId: decoded.targetId as any,\n };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (_error) {\n // Invalid relation ID\n return { type: \"invalid\" };\n }\n }\n\n // Unknown/invalid ID\n return { type: \"invalid\" };\n}\n\n/**\n * Inspect an EntityId and return a human-readable string representation\n * @param id The EntityId to inspect\n * @returns A friendly string representation of the ID\n */\nexport function inspectEntityId(id: EntityId<any>): string {\n if (id === INVALID_COMPONENT_ID) {\n return \"Invalid Component ID (0)\";\n }\n\n if (isComponentId(id)) {\n return `Component ID (${id})`;\n }\n\n if (isEntityId(id)) {\n return `Entity ID (${id})`;\n }\n\n if (isRelationId(id)) {\n try {\n const decoded = decodeRelationId(id);\n // Validate that targetId is valid (decodeRelationId already checks componentId)\n if (decoded.type !== \"wildcard\" && !isEntityId(decoded.targetId) && !isComponentId(decoded.targetId)) {\n return `Invalid Relation ID (${id})`;\n }\n const componentStr = `Component ID (${decoded.componentId})`;\n const targetStr =\n decoded.type === \"entity\"\n ? `Entity ID (${decoded.targetId})`\n : decoded.type === \"component\"\n ? `Component ID (${decoded.targetId})`\n : \"Wildcard (*)\";\n return `Relation ID: ${componentStr} -> ${targetStr}`;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (_error) {\n return `Invalid Relation ID (${id})`;\n }\n }\n\n return `Unknown ID (${id})`;\n}\n\n/**\n * Entity ID Manager for automatic allocation and freelist recycling\n */\nexport class EntityIdManager {\n private nextId: number = ENTITY_ID_START;\n private freelist: Set<EntityId> = new Set();\n\n /**\n * Allocate a new entity ID\n * Uses freelist if available, otherwise increments counter\n */\n allocate(): EntityId {\n if (this.freelist.size > 0) {\n const id = this.freelist.values().next().value!;\n this.freelist.delete(id);\n return id;\n } else {\n const id = this.nextId;\n this.nextId++;\n // Check for overflow (though unlikely in practice)\n if (this.nextId >= Number.MAX_SAFE_INTEGER) {\n throw new Error(\"Entity ID overflow: reached maximum safe integer\");\n }\n return id as EntityId;\n }\n }\n\n /**\n * Deallocate an entity ID, adding it to the freelist for reuse\n * @param id The entity ID to deallocate\n */\n deallocate(id: EntityId<any>): void {\n if (!isEntityId(id)) {\n throw new Error(\"Can only deallocate valid entity IDs\");\n }\n if (id >= this.nextId) {\n throw new Error(\"Cannot deallocate an ID that was never allocated\");\n }\n this.freelist.add(id);\n }\n\n /**\n * Get the current freelist size (for debugging/monitoring)\n */\n getFreelistSize(): number {\n return this.freelist.size;\n }\n\n /**\n * Get the next ID that would be allocated (for debugging)\n */\n getNextId(): number {\n return this.nextId;\n }\n\n /**\n * Serialize internal state for persistence.\n * Returns a plain object representing allocator state. Values may be non-JSON-serializable.\n */\n serializeState(): { nextId: number; freelist: number[] } {\n return { nextId: this.nextId, freelist: Array.from(this.freelist) };\n }\n\n /**\n * Restore internal state from a previously-serialized object.\n * Overwrites the current nextId and freelist.\n */\n deserializeState(state: { nextId: number; freelist?: number[] }): void {\n if (typeof state.nextId !== \"number\") {\n throw new Error(\"Invalid state for EntityIdManager.deserializeState\");\n }\n this.nextId = state.nextId;\n this.freelist = new Set((state.freelist || []) as EntityId[]);\n }\n}\n\n/**\n * Component ID Manager for automatic allocation\n * Components are typically registered once and not recycled\n */\nexport class ComponentIdAllocator {\n private nextId: number = 1;\n\n /**\n * Allocate a new component ID\n * Increments counter sequentially from 1\n */\n allocate<T = void>(): ComponentId<T> {\n if (this.nextId > COMPONENT_ID_MAX) {\n throw new Error(`Component ID overflow: maximum ${COMPONENT_ID_MAX} components allowed`);\n }\n const id = this.nextId;\n this.nextId++;\n return id as ComponentId<T>;\n }\n\n /**\n * Get the next ID that would be allocated (for debugging)\n */\n getNextId(): number {\n return this.nextId;\n }\n\n /**\n * Check if more component IDs are available\n */\n hasAvailableIds(): boolean {\n return this.nextId <= COMPONENT_ID_MAX;\n }\n}\n\nconst globalComponentIdAllocator = new ComponentIdAllocator();\n\nconst ComponentIdForNames: Map<string, ComponentId<any>> = new Map();\n\n/**\n * Component options that define intrinsic properties\n */\nexport interface ComponentOptions {\n /**\n * Optional name for the component (for serialization/debugging)\n */\n name?: string;\n /**\n * If true, an entity can have at most one relation per base component.\n * When adding a new relation with the same base component, any existing relations\n * with that base component are automatically removed.\n * Only applicable to relation components.\n */\n exclusive?: boolean;\n /**\n * If true, when a relation target entity is deleted, all entities that reference\n * it through this component will also be deleted (cascade delete).\n * Only applicable to entity-relation components.\n */\n cascadeDelete?: boolean;\n /**\n * If true, relations with this component will not cause archetype fragmentation.\n * Entities with different target entities for this relation component will be stored\n * in the same archetype, preventing fragmentation when there are many different targets.\n * Only applicable to relation components.\n * Inspired by Flecs' DontFragment trait.\n */\n dontFragment?: boolean;\n}\n\n// Array for component names (Component ID range: 1-1023)\nconst componentNames: (string | undefined)[] = new Array(COMPONENT_ID_MAX + 1);\n\n// BitSets for fast component option checks (Component ID range: 1-1023)\nconst exclusiveFlags = new BitSet(COMPONENT_ID_MAX + 1);\nconst cascadeDeleteFlags = new BitSet(COMPONENT_ID_MAX + 1);\nconst dontFragmentFlags = new BitSet(COMPONENT_ID_MAX + 1);\n\n/**\n * Allocate a new component ID from the global allocator.\n * @param nameOrOptions Optional name for the component (for serialization/debugging) or options object\n * @returns The allocated component ID\n * @example\n * // Just a name\n * const Position = component<Position>(\"Position\");\n *\n * // With options\n * const ChildOf = component({ exclusive: true, cascadeDelete: true });\n *\n * // With name and options\n * const ChildOf = component({ name: \"ChildOf\", exclusive: true });\n */\nexport function component<T = void>(nameOrOptions?: string | ComponentOptions): ComponentId<T> {\n const id = globalComponentIdAllocator.allocate<T>();\n\n let name: string | undefined;\n let options: ComponentOptions | undefined;\n\n // Parse the parameter\n if (typeof nameOrOptions === \"string\") {\n name = nameOrOptions;\n } else if (typeof nameOrOptions === \"object\" && nameOrOptions !== null) {\n options = nameOrOptions;\n name = options.name;\n }\n\n // Register name if provided\n if (name) {\n if (ComponentIdForNames.has(name)) {\n throw new Error(`Component name \"${name}\" is already registered`);\n }\n\n componentNames[id] = name;\n ComponentIdForNames.set(name, id);\n }\n\n // Register options if provided\n if (options) {\n // Set bitset flags for fast lookup\n if (options.exclusive) exclusiveFlags.set(id);\n if (options.cascadeDelete) cascadeDeleteFlags.set(id);\n if (options.dontFragment) dontFragmentFlags.set(id);\n }\n\n return id;\n}\n\n/**\n * Get a component ID by its registered name\n * @param name The component name\n * @returns The component ID if found, undefined otherwise\n */\nexport function getComponentIdByName(name: string): ComponentId<any> | undefined {\n return ComponentIdForNames.get(name);\n}\n\n/** Get a component name by its ID\n * @param id The component ID\n * @returns The component name if found, undefined otherwise\n */\nexport function getComponentNameById(id: ComponentId<any>): string | undefined {\n return componentNames[id];\n}\n\n/**\n * Get component options by its ID\n * @param id The component ID\n * @returns The component options\n */\nexport function getComponentOptions(id: ComponentId<any>): ComponentOptions {\n if (!isComponentId(id)) {\n throw new Error(\"Invalid component ID\");\n }\n const hasName = componentNames[id] !== undefined;\n const hasExclusive = exclusiveFlags.has(id);\n const hasCascadeDelete = cascadeDeleteFlags.has(id);\n const hasDontFragment = dontFragmentFlags.has(id);\n return {\n name: hasName ? componentNames[id] : undefined,\n exclusive: hasExclusive ? true : undefined,\n cascadeDelete: hasCascadeDelete ? true : undefined,\n dontFragment: hasDontFragment ? true : undefined,\n };\n}\n\n/**\n * Check if a component is marked as exclusive\n * @param id The component ID\n * @returns true if the component is exclusive, false otherwise\n */\nexport function isExclusiveComponent(id: ComponentId<any>): boolean {\n return exclusiveFlags.has(id);\n}\n\n/**\n * Check if a component is marked as cascade delete\n * @param id The component ID\n * @returns true if the component is cascade delete, false otherwise\n */\nexport function isCascadeDeleteComponent(id: ComponentId<any>): boolean {\n return cascadeDeleteFlags.has(id);\n}\n\n/**\n * Check if a component is marked as dontFragment\n * @param id The component ID\n * @returns true if the component is dontFragment, false otherwise\n */\nexport function isDontFragmentComponent(id: ComponentId<any>): boolean {\n return dontFragmentFlags.has(id);\n}\n\n/**\n * Generic function to check relation flags with specific target conditions\n * @param id The entity/relation ID to check\n * @param flagBitSet The bitset for the flag\n * @param targetCondition Function to check target ID condition\n * @returns true if the condition is met, false otherwise\n */\nfunction checkRelationFlag(\n id: EntityId<any>,\n flagBitSet: BitSet,\n targetCondition: (targetId: number) => boolean,\n): boolean {\n const decoded = decodeRelationRaw(id);\n if (decoded === null) return false;\n const { componentId, targetId } = decoded;\n return isValidComponentId(componentId) && targetCondition(targetId) && flagBitSet.has(componentId);\n}\n\n/**\n * Check if a relation ID is a dontFragment relation (entity-relation or component-relation with dontFragment component)\n * This is an optimized function that avoids the overhead of getDetailedIdType\n * @param id The entity/relation ID to check\n * @returns true if this is a dontFragment relation, false otherwise\n */\nexport function isDontFragmentRelation(id: EntityId<any>): boolean {\n return checkRelationFlag(id, dontFragmentFlags, (targetId) => targetId !== WILDCARD_TARGET_ID);\n}\n\n/**\n * Check if an ID is a wildcard relation with dontFragment component\n * This is an optimized function for filtering archetype component types\n * @param id The entity/relation ID to check\n * @returns true if this is a wildcard relation with dontFragment component, false otherwise\n */\nexport function isDontFragmentWildcard(id: EntityId<any>): boolean {\n return checkRelationFlag(id, dontFragmentFlags, (targetId) => targetId === WILDCARD_TARGET_ID);\n}\n\n/**\n * Check if a relation ID is an exclusive relation (entity-relation or component-relation with exclusive component)\n * This avoids the full getDetailedIdType overhead for hot paths\n * @param id The entity/relation ID to check\n * @returns true if this is an exclusive relation, false otherwise\n */\nexport function isExclusiveRelation(id: EntityId<any>): boolean {\n return checkRelationFlag(id, exclusiveFlags, (targetId) => targetId !== WILDCARD_TARGET_ID);\n}\n\n/**\n * Check if a relation ID is a wildcard relation with exclusive component\n */\nexport function isExclusiveWildcard(id: EntityId<any>): boolean {\n return checkRelationFlag(id, exclusiveFlags, (targetId) => targetId === WILDCARD_TARGET_ID);\n}\n\n/**\n * Check if a relation ID is a cascade delete entity-relation\n * This is an optimized function that avoids the overhead of getDetailedIdType\n * Note: Cascade delete only applies to entity-relations (not component-relations or wildcards)\n * @param id The entity/relation ID to check\n * @returns true if this is an entity-relation with cascade delete, false otherwise\n */\nexport function isCascadeDeleteRelation(id: EntityId<any>): boolean {\n return checkRelationFlag(\n id,\n cascadeDeleteFlags,\n (targetId) => targetId !== WILDCARD_TARGET_ID && targetId >= ENTITY_ID_START,\n );\n}\n\n/**\n * Get the componentId from a relation ID without fully decoding the relation.\n * Returns undefined for non-relation IDs or invalid component IDs.\n */\nexport function getComponentIdFromRelationId<T>(id: EntityId<T>): ComponentId<T> | undefined {\n const decoded = decodeRelationRaw(id);\n if (decoded === null || !isValidComponentId(decoded.componentId)) return undefined;\n return decoded.componentId as ComponentId<T>;\n}\n\n/**\n * Get the targetId from a relation ID without fully decoding the relation.\n * Returns undefined for non-relation IDs.\n */\nexport function getTargetIdFromRelationId(id: EntityId<any>): EntityId<any> | undefined {\n const decoded = decodeRelationRaw(id);\n return decoded?.targetId as EntityId<any>;\n}\n\n/**\n * Check if an ID is an entity-relation (relation targeting an entity, not a component or wildcard)\n */\nexport function isEntityRelation(id: EntityId<any>): boolean {\n const decoded = decodeRelationRaw(id);\n return decoded !== null && decoded.targetId >= ENTITY_ID_START;\n}\n\n/**\n * Check if an ID is a component-relation (relation targeting a component)\n */\nexport function isComponentRelation(id: EntityId<any>): boolean {\n const decoded = decodeRelationRaw(id);\n return decoded !== null && isValidComponentId(decoded.targetId);\n}\n\n/**\n * Check if an ID is any type of relation (entity, component, or wildcard)\n */\nexport function isAnyRelation(id: EntityId<any>): boolean {\n return id < 0;\n}\n","import type { EntityId, WildcardRelationId } from \"./entity\";\n\n/**\n * Hook types for component lifecycle events\n */\nexport interface LifecycleHook<T = unknown> {\n /**\n * Called when a component is added to an entity\n */\n on_init?: (entityId: EntityId, componentType: EntityId<T>, component: T) => void;\n /**\n * Called when a component is added to an entity\n */\n on_set?: (entityId: EntityId, componentType: EntityId<T>, component: T) => void;\n /**\n * Called when a component is deleted from an entity\n */\n on_remove?: (entityId: EntityId, componentType: EntityId<T>, component: T) => void;\n}\n\nexport interface MultiLifecycleHook<T extends readonly ComponentType<any>[]> {\n on_init?: (entityId: EntityId, componentTypes: T, components: ComponentTuple<T>) => void;\n on_set?: (entityId: EntityId, componentTypes: T, components: ComponentTuple<T>) => void;\n on_remove?: (entityId: EntityId, componentTypes: T, components: ComponentTuple<T>) => void;\n}\n\nexport type ComponentType<T> = EntityId<T> | OptionalEntityId<T>;\n\nexport type OptionalEntityId<T> = { optional: EntityId<T> };\n\nexport function isOptionalEntityId<T>(type: ComponentType<T>): type is OptionalEntityId<T> {\n return typeof type === \"object\" && type !== null && \"optional\" in type;\n}\n\nexport type ComponentTypeToData<T> = T extends { optional: infer U }\n ? { value: ComponentTypeToData<U> } | undefined\n : T extends WildcardRelationId<infer U>\n ? [EntityId<unknown>, U][]\n : T extends EntityId<infer U>\n ? U\n : never;\n\n/**\n * Type helper for component tuples extracted from EntityId array\n */\nexport type ComponentTuple<T extends readonly ComponentType<any>[]> = {\n readonly [K in keyof T]: ComponentTypeToData<T[K]>;\n};\n","/**\n * Utility functions for ECS library\n */\n\n/**\n * Get a value from cache or compute and cache it if not present\n * @param cache The cache map\n * @param key The cache key\n * @param compute Function to compute the value if not cached\n * @returns The cached or computed value\n */\nexport function getOrComputeCache<K, V>(cache: Map<K, V>, key: K, compute: () => V): V {\n let value = cache.get(key);\n if (value === undefined) {\n value = compute();\n cache.set(key, value);\n }\n return value;\n}\n\n/**\n * Get a value from cache or create and cache it if not present, allowing side effects during creation\n * @param cache The cache map\n * @param key The cache key\n * @param create Function to create the value if not cached (can have side effects)\n * @returns The cached or created value\n */\nexport function getOrCreateWithSideEffect<K, V>(cache: Map<K, V>, key: K, create: () => V): V {\n let value = cache.get(key);\n if (value === undefined) {\n value = create();\n cache.set(key, value);\n }\n return value;\n}\n","import type { EntityId, WildcardRelationId } from \"./entity\";\nimport {\n getComponentIdFromRelationId,\n getDetailedIdType,\n getIdType,\n getTargetIdFromRelationId,\n isDontFragmentComponent,\n isWildcardRelationId,\n} from \"./entity\";\nimport { isOptionalEntityId, type ComponentTuple, type ComponentType } from \"./types\";\nimport { getOrComputeCache } from \"./utils\";\n\n/**\n * Special value to represent missing component data\n */\nexport const MISSING_COMPONENT = Symbol(\"missing component\");\n\n/**\n * Archetype class for ECS architecture\n * Represents a group of entities that share the same set of components\n * Optimized for fast iteration and component access\n */\nexport class Archetype {\n /**\n * The component types that define this archetype\n */\n public readonly componentTypes: EntityId<any>[];\n\n /**\n * List of entities in this archetype\n */\n private entities: EntityId[] = [];\n\n /**\n * Component data storage - maps component type to array of component data\n * Each array index corresponds to the entity index in the entities array\n */\n private componentData: Map<EntityId<any>, any[]> = new Map();\n\n /**\n * Reverse mapping from entity to its index in this archetype\n */\n private entityToIndex: Map<EntityId, number> = new Map();\n\n /**\n * Reference to dontFragment relations storage from World\n * This allows entities with different relation targets to share the same archetype\n * Stored in World to avoid migration overhead when entities change archetypes\n */\n private dontFragmentRelations: Map<EntityId, Map<EntityId<any>, any>>;\n\n /**\n * Cache for pre-computed component data sources to avoid repeated calculations\n * For regular components: data array\n * For wildcards: matching relation types array\n */\n private componentDataSourcesCache: Map<string, (any[] | EntityId<any>[] | undefined)[]> = new Map();\n\n /**\n * Create a new archetype with the specified component types\n * @param componentTypes The component types that define this archetype\n * @param dontFragmentRelations Reference to the World's dontFragmentRelations storage\n */\n constructor(componentTypes: EntityId<any>[], dontFragmentRelations: Map<EntityId, Map<EntityId<any>, any>>) {\n this.componentTypes = [...componentTypes].sort((a, b) => a - b); // Sort for consistent ordering\n this.dontFragmentRelations = dontFragmentRelations;\n\n // Initialize component data arrays\n for (const componentType of this.componentTypes) {\n this.componentData.set(componentType, []);\n }\n }\n\n /**\n * Get the number of entities in this archetype\n */\n get size(): number {\n return this.entities.length;\n }\n\n /**\n * Check if this archetype matches the given component types\n * @param componentTypes The component types to check\n */\n matches(componentTypes: EntityId<any>[]): boolean {\n if (this.componentTypes.length !== componentTypes.length) {\n return false;\n }\n const sortedTypes = [...componentTypes].sort((a, b) => a - b);\n return this.componentTypes.every((type, index) => type === sortedTypes[index]);\n }\n\n /**\n * Add an entity to this archetype with initial component data\n * @param entityId The entity to add\n * @param componentData Map of component type to component data (includes both regular and dontFragment components)\n */\n addEntity(entityId: EntityId, componentData: Map<EntityId<any>, any>): void {\n if (this.entityToIndex.has(entityId)) {\n throw new Error(`Entity ${entityId} is already in this archetype`);\n }\n\n const index = this.entities.length;\n this.entities.push(entityId);\n this.entityToIndex.set(entityId, index);\n\n // Add component data for regular components (those in the archetype signature)\n for (const componentType of this.componentTypes) {\n const data = componentData.get(componentType);\n this.getComponentData(componentType).push(!componentData.has(componentType) ? MISSING_COMPONENT : data);\n }\n\n // Add dontFragment relations separately\n const dontFragmentData = new Map<EntityId<any>, any>();\n for (const [componentType, data] of componentData) {\n // Skip if already added as regular component\n if (this.componentTypes.includes(componentType)) {\n continue;\n }\n\n // Check if this is a dontFragment relation\n const detailedType = getDetailedIdType(componentType);\n if (\n (detailedType.type === \"entity-relation\" || detailedType.type === \"component-relation\") &&\n isDontFragmentComponent(detailedType.componentId!)\n ) {\n dontFragmentData.set(componentType, data);\n }\n }\n\n if (dontFragmentData.size > 0) {\n this.dontFragmentRelations.set(entityId, dontFragmentData);\n }\n }\n\n /**\n * Get all component data for a specific entity\n * @param entityId The entity to get data for\n * @returns Map of component type to component data (includes both regular and dontFragment components)\n */\n getEntity(entityId: EntityId): Map<EntityId<any>, any> | undefined {\n const index = this.entityToIndex.get(entityId);\n if (index === undefined) {\n return undefined;\n }\n\n const entityData = new Map<EntityId<any>, any>();\n for (const componentType of this.componentTypes) {\n const dataArray = this.getComponentData(componentType);\n const data = dataArray[index];\n entityData.set(componentType, data === MISSING_COMPONENT ? undefined : data);\n }\n\n // Add dontFragment relations\n const dontFragmentData = this.dontFragmentRelations.get(entityId);\n if (dontFragmentData) {\n for (const [componentType, data] of dontFragmentData) {\n entityData.set(componentType, data);\n }\n }\n\n return entityData;\n }\n\n /**\n * Dump all entities and their component data in this archetype\n * @returns Array of objects with entity and component data (includes both regular and dontFragment components)\n */\n dump(): Array<{\n entity: EntityId;\n components: Map<EntityId<any>, any>;\n }> {\n const result: Array<{\n entity: EntityId;\n components: Map<EntityId<any>, any>;\n }> = [];\n\n for (let i = 0; i < this.entities.length; i++) {\n const entity = this.entities[i]!;\n const components = new Map<EntityId<any>, any>();\n for (const componentType of this.componentTypes) {\n const dataArray = this.getComponentData(componentType);\n const data = dataArray[i];\n components.set(componentType, data === MISSING_COMPONENT ? undefined : data);\n }\n\n // Add dontFragment relations\n const dontFragmentData = this.dontFragmentRelations.get(entity);\n if (dontFragmentData) {\n for (const [componentType, data] of dontFragmentData) {\n components.set(componentType, data);\n }\n }\n\n result.push({ entity, components });\n }\n\n return result;\n }\n\n /**\n * Remove an entity from this archetype\n * @param entityId The entity to remove\n * @returns The component data of the removed entity (includes both regular and dontFragment components)\n */\n removeEntity(entityId: EntityId): Map<EntityId<any>, any> | undefined {\n const index = this.entityToIndex.get(entityId);\n if (index === undefined) {\n return undefined;\n }\n\n // Extract component data before removal\n const removedData = new Map<EntityId<any>, any>();\n for (const componentType of this.componentTypes) {\n const dataArray = this.getComponentData(componentType);\n removedData.set(componentType, dataArray[index]);\n }\n\n // Include dontFragment relations in removed data\n const dontFragmentData = this.dontFragmentRelations.get(entityId);\n if (dontFragmentData) {\n for (const [componentType, data] of dontFragmentData) {\n removedData.set(componentType, data);\n }\n this.dontFragmentRelations.delete(entityId);\n }\n\n this.entityToIndex.delete(entityId);\n\n // Use swap-and-pop strategy for O(1) removal instead of O(n) splice\n const lastIndex = this.entities.length - 1;\n if (index !== lastIndex) {\n // Swap with last entity\n const lastEntity = this.entities[lastIndex]!;\n this.entities[index] = lastEntity;\n this.entityToIndex.set(lastEntity, index);\n\n // Swap component data for all components\n for (const componentType of this.componentTypes) {\n const dataArray = this.getComponentData(componentType);\n dataArray[index] = dataArray[lastIndex];\n }\n }\n\n // Remove the last element (now O(1))\n this.entities.pop();\n for (const componentType of this.componentTypes) {\n this.getComponentData(componentType).pop();\n }\n\n return removedData;\n }\n\n /**\n * Check if an entity is in this archetype\n * @param entityId The entity to check\n */\n exists(entityId: EntityId): boolean {\n return this.entityToIndex.has(entityId);\n }\n\n /**\n * Get component data for a specific entity and wildcard relation type\n * Returns an array of all matching relation instances\n * @param entityId The entity\n * @param componentType The wildcard relation type\n */\n get<T>(entityId: EntityId, componentType: WildcardRelationId<T>): [EntityId<unknown>, any][];\n /**\n * Get component data for a specific entity and component type\n * @param entityId The entity\n * @param componentType The component type\n */\n get<T>(entityId: EntityId, componentType: EntityId<T>): T;\n get<T>(entityId: EntityId, componentType: EntityId<T> | WildcardRelationId<T>): T | [EntityId<unknown>, any][] {\n const index = this.entityToIndex.get(entityId);\n if (index === undefined) {\n throw new Error(`Entity ${entityId} is not in this archetype`);\n }\n\n if (isWildcardRelationId(componentType)) {\n const componentId = getComponentIdFromRelationId(componentType);\n const relations: [EntityId<unknown>, any][] = [];\n\n // Check regular archetype components\n for (const relType of this.componentTypes) {\n const relDetailed = getDetailedIdType(relType);\n if (\n (relDetailed.type === \"entity-relation\" || relDetailed.type === \"component-relation\") &&\n relDetailed.componentId === componentId\n ) {\n const dataArray = this.getComponentData(relType);\n if (dataArray && dataArray[index] !== undefined) {\n const data = dataArray[index];\n relations.push([relDetailed.targetId, data === MISSING_COMPONENT ? undefined : data]);\n }\n }\n }\n\n // Check dontFragment relations\n const dontFragmentData = this.dontFragmentRelations.get(entityId);\n if (dontFragmentData) {\n for (const [relType, data] of dontFragmentData) {\n const relDetailed = getDetailedIdType(relType);\n if (\n (relDetailed.type === \"entity-relation\" || relDetailed.type === \"component-relation\") &&\n relDetailed.componentId === componentId\n ) {\n relations.push([relDetailed.targetId, data]);\n }\n }\n }\n\n return relations;\n } else {\n // First check if it's in the archetype signature\n if (this.componentTypes.includes(componentType)) {\n const data = this.getComponentData(componentType)[index]!;\n if (data === MISSING_COMPONENT) {\n throw new Error(`Component type ${componentType} not found for entity ${entityId}`);\n }\n return data as T;\n }\n\n // Check dontFragment relations\n const dontFragmentData = this.dontFragmentRelations.get(entityId);\n if (dontFragmentData && dontFragmentData.has(componentType)) {\n return dontFragmentData.get(componentType);\n }\n\n throw new Error(`Component type ${componentType} not found for entity ${entityId}`);\n }\n }\n\n /**\n * Get optional component data for a specific entity and component type\n * @param entityId The entity\n * @param componentType The component type\n * @returns { value: T } if component exists, undefined otherwise\n */\n getOptional<T>(entityId: EntityId, componentType: EntityId<T>): { value: T } | undefined {\n const index = this.entityToIndex.get(entityId);\n if (index === undefined) {\n throw new Error(`Entity ${entityId} is not in this archetype`);\n }\n\n // First check if it's in the archetype signature\n if (this.componentTypes.includes(componentType)) {\n const data = this.getComponentData(componentType)[index]!;\n if (data === MISSING_COMPONENT) {\n return undefined;\n }\n return { value: data as T };\n }\n\n // Check dontFragment relations\n const dontFragmentData = this.dontFragmentRelations.get(entityId);\n if (dontFragmentData && dontFragmentData.has(componentType)) {\n return { value: dontFragmentData.get(componentType) };\n }\n\n return undefined;\n }\n\n /**\n * Set component data for a specific entity and component type\n * @param entityId The entity\n * @param componentType The component type\n * @param data The component data\n */\n set<T>(entityId: EntityId, componentType: EntityId<T>, data: T): void {\n const index = this.entityToIndex.get(entityId);\n if (index === undefined) {\n throw new Error(`Entity ${entityId} is not in this archetype`);\n }\n\n // Check if it's in the archetype signature\n if (this.componentData.has(componentType)) {\n const dataArray = this.getComponentData(componentType);\n dataArray[index] = data;\n return;\n }\n\n // Check if it's a dontFragment relation\n const detailedType = getDetailedIdType(componentType);\n if (\n (detailedType.type === \"entity-relation\" || detailedType.type === \"component-relation\") &&\n isDontFragmentComponent(detailedType.componentId!)\n ) {\n let dontFragmentData = this.dontFragmentRelations.get(entityId);\n if (!dontFragmentData) {\n dontFragmentData = new Map();\n this.dontFragmentRelations.set(entityId, dontFragmentData);\n }\n dontFragmentData.set(componentType, data);\n return;\n }\n\n throw new Error(`Component type ${componentType} is not in this archetype`);\n }\n\n /**\n * Get all entities in this archetype\n */\n getEntities(): EntityId[] {\n return this.entities;\n }\n\n /**\n * Get the mapping of entities to their indices in this archetype\n */\n getEntityToIndexMap(): Map<EntityId, number> {\n return this.entityToIndex;\n }\n\n /**\n * Get component data for all entities of a specific component type\n * @param componentType The component type\n */\n getComponentData<T>(componentType: EntityId<T>): T[] {\n const data = this.componentData.get(componentType);\n if (!data) {\n throw new Error(`Component type ${componentType} is not in this archetype`);\n }\n return data;\n }\n\n /**\n * Get optional component data for all entities of a specific component type\n * @param componentType The component type\n * @returns An array of component data or undefined if not present\n */\n getOptionalComponentData<T>(componentType: EntityId<T>): T[] | undefined {\n return this.componentData.get(componentType);\n }\n\n /**\n * Helper: compute or return cached data sources for provided componentTypes\n */\n private getCachedComponentDataSources<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n ): (any[] | EntityId<any>[] | undefined)[] {\n const cacheKey = this.buildCacheKey(componentTypes);\n return getOrComputeCache(this.componentDataSourcesCache, cacheKey, () =>\n componentTypes.map((compType) => this.getComponentDataSource(compType)),\n );\n }\n\n /**\n * Build cache key for component types\n */\n private buildCacheKey(componentTypes: readonly ComponentType<any>[]): string {\n return componentTypes.map((id) => (isOptionalEntityId(id) ? `opt(${id.optional})` : `${id}`)).join(\",\");\n }\n\n /**\n * Get data source for a single component type\n */\n private getComponentDataSource(compType: ComponentType<any>): any[] | EntityId<any>[] | undefined {\n const optional = isOptionalEntityId(compType);\n const actualType = optional ? compType.optional : compType;\n const detailedType = getDetailedIdType(actualType);\n\n if (detailedType.type === \"wildcard-relation\") {\n return this.getWildcardRelationDataSource(detailedType.componentId, optional);\n } else {\n return optional ? this.getOptionalComponentData(actualType) : this.getComponentData(actualType);\n }\n }\n\n /**\n * Get data source for wildcard relations\n */\n private getWildcardRelationDataSource(componentId: EntityId<any>, optional: boolean): EntityId<any>[] | undefined {\n const matchingRelations = this.componentTypes.filter((ct) => {\n const detailedCt = getDetailedIdType(ct);\n return (\n (detailedCt.type === \"entity-relation\" || detailedCt.type === \"component-relation\") &&\n detailedCt.componentId === componentId\n );\n });\n\n return optional ? (matchingRelations.length > 0 ? matchingRelations : undefined) : matchingRelations;\n }\n\n /**\n * Helper: build component tuples for a specific entity index using precomputed data sources\n */\n private buildComponentsForIndex<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n componentDataSources: (any[] | EntityId<any>[] | undefined)[],\n entityIndex: number,\n entityId: EntityId,\n ): ComponentTuple<T> {\n return componentDataSources.map((dataSource, i) => {\n const compType = componentTypes[i]!;\n return this.buildSingleComponent(compType, dataSource, entityIndex, entityId);\n }) as ComponentTuple<T>;\n }\n\n /**\n * Build a single component value from its data source\n */\n private buildSingleComponent(\n compType: ComponentType<any>,\n dataSource: any[] | EntityId<any>[] | undefined,\n entityIndex: number,\n entityId: EntityId,\n ): any {\n const optional = isOptionalEntityId(compType);\n const actualType = optional ? compType.optional : compType;\n\n if (getIdType(actualType) === \"wildcard-relation\") {\n return this.buildWildcardRelationValue(\n actualType as WildcardRelationId<any>,\n dataSource,\n entityIndex,\n entityId,\n optional,\n );\n } else {\n return this.buildRegularComponentValue(dataSource, entityIndex, optional);\n }\n }\n\n /**\n * Build wildcard relation value from matching relations\n */\n private buildWildcardRelationValue(\n wildcardRelationType: WildcardRelationId<any>,\n dataSource: any[] | EntityId<any>[] | undefined,\n entityIndex: number,\n entityId: EntityId,\n optional: boolean,\n ): any {\n const matchingRelations = (dataSource as EntityId<any>[]) || [];\n const relations: [EntityId<unknown>, any][] = [];\n\n // Add regular archetype relations\n for (const relType of matchingRelations) {\n const dataArray = this.getComponentData(relType);\n const data = dataArray[entityIndex];\n const targetId = getTargetIdFromRelationId(relType)!;\n relations.push([targetId, data === MISSING_COMPONENT ? undefined : data]);\n }\n\n // Add dontFragment relations for this entity\n // Get the component ID from the wildcard relation type\n const targetComponentId = getComponentIdFromRelationId(wildcardRelationType);\n\n const dontFragmentData = this.dontFragmentRelations.get(entityId);\n if (dontFragmentData) {\n // Check dontFragment relations for matching component ID\n for (const [relType, data] of dontFragmentData) {\n const relDetailed = getDetailedIdType(relType);\n if (\n (relDetailed.type === \"entity-relation\" || relDetailed.type === \"component-relation\") &&\n relDetailed.componentId === targetComponentId\n ) {\n relations.push([relDetailed.targetId, data]);\n }\n }\n }\n\n // If no relations found and not optional, this entity doesn't match\n if (relations.length === 0) {\n if (!optional) {\n const componentId = getComponentIdFromRelationId(wildcardRelationType);\n throw new Error(\n `No matching relations found for mandatory wildcard relation component ${componentId} on entity ${entityId}`,\n );\n }\n // For optional, return undefined when there are no relations\n return undefined;\n }\n\n return optional ? { value: relations } : relations;\n }\n\n /**\n * Build regular component value from data source\n */\n private buildRegularComponentValue(\n dataSource: any[] | EntityId<any>[] | undefined,\n entityIndex: number,\n optional: boolean,\n ): any {\n if (dataSource === undefined) {\n if (optional) {\n return undefined;\n }\n throw new Error(`Component data not found for mandatory component type`);\n }\n\n const dataArray = dataSource as any[];\n const data = dataArray[entityIndex];\n const result = data === MISSING_COMPONENT ? undefined : data;\n\n return optional ? { value: result } : result;\n }\n\n /**\n * Get entities with their component data for specified component types\n * Optimized for bulk component access with pre-computed indices\n * @param componentTypes Array of component types to retrieve\n * @returns Array of objects with entity and component data\n */\n getEntitiesWithComponents<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n ): Array<{\n entity: EntityId;\n components: ComponentTuple<T>;\n }> {\n const result: Array<{\n entity: EntityId;\n components: ComponentTuple<T>;\n }> = [];\n\n this.forEachWithComponents(componentTypes, (entity, ...components) => {\n result.push({ entity, components });\n });\n\n return result;\n }\n\n /**\n * Iterate over entities with their component data for specified component types\n * implemented as a generator returning each entity/components pair lazily\n * @param componentTypes Array of component types to retrieve\n */\n *iterateWithComponents<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n ): IterableIterator<[EntityId, ...ComponentTuple<T>]> {\n // Reuse the same pre-caching and data access logic as forEachWithComponents\n const componentDataSources = this.getCachedComponentDataSources(componentTypes);\n\n for (let entityIndex = 0; entityIndex < this.entities.length; entityIndex++) {\n const entity = this.entities[entityIndex]!;\n\n const components = this.buildComponentsForIndex(componentTypes, componentDataSources, entityIndex, entity);\n\n yield [entity, ...components];\n }\n }\n\n /**\n * Iterate over entities with their component data for specified component types\n * Optimized for bulk component access\n * @param componentTypes Array of component types to retrieve\n * @param callback Function called for each entity with its components\n */\n forEachWithComponents<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n callback: (entity: EntityId, ...components: ComponentTuple<T>) => void,\n ): void {\n // Create a cache key from component types\n const componentDataSources = this.getCachedComponentDataSources(componentTypes);\n\n for (let entityIndex = 0; entityIndex < this.entities.length; entityIndex++) {\n const entity = this.entities[entityIndex]!;\n\n // Direct array access for each component type using pre-cached sources\n const components = this.buildComponentsForIndex(componentTypes, componentDataSources, entityIndex, entity);\n\n callback(entity, ...components);\n }\n }\n\n /**\n * Iterate over all entities with their component data\n * @param callback Function called for each entity with its component data\n */\n forEach(callback: (entityId: EntityId, components: Map<EntityId<any>, any>) => void): void {\n for (let i = 0; i < this.entities.length; i++) {\n const components = new Map<EntityId<any>, any>();\n for (const componentType of this.componentTypes) {\n const data = this.getComponentData(componentType)[i];\n components.set(componentType, data === MISSING_COMPONENT ? undefined : data);\n }\n callback(this.entities[i]!, components);\n }\n }\n\n /**\n * Check if any entity in this archetype has a relation matching the given component ID\n * This includes both regular relations in componentTypes and dontFragment relations\n * @param componentId The component ID to match\n * @returns true if any entity has a matching relation\n */\n hasRelationWithComponentId(componentId: EntityId<any>): boolean {\n // Check regular archetype components\n for (const componentType of this.componentTypes) {\n const detailedType = getDetailedIdType(componentType);\n if (\n (detailedType.type === \"entity-relation\" || detailedType.type === \"component-relation\") &&\n detailedType.componentId === componentId\n ) {\n return true;\n }\n }\n\n // Check dontFragment relations for any entity in this archetype\n for (const entityId of this.entities) {\n const entityDontFragmentRelations = this.dontFragmentRelations.get(entityId);\n if (entityDontFragmentRelations) {\n for (const relationType of entityDontFragmentRelations.keys()) {\n const detailedType = getDetailedIdType(relationType);\n if (\n (detailedType.type === \"entity-relation\" || detailedType.type === \"component-relation\") &&\n detailedType.componentId === componentId\n ) {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n}\n","import type { EntityId } from \"./entity\";\n\n/**\n * @internal Represents a set of component changes to be applied to an entity\n */\nexport class ComponentChangeset {\n readonly adds = new Map<EntityId<any>, any>();\n readonly removes = new Set<EntityId<any>>();\n\n /**\n * Add a component to the changeset\n */\n set<T>(componentType: EntityId<T>, component: T): void {\n this.adds.set(componentType, component);\n this.removes.delete(componentType); // Remove from removes if it was going to be removed\n }\n\n /**\n * Remove a component from the changeset\n */\n delete<T>(componentType: EntityId<T>): void {\n this.removes.add(componentType);\n this.adds.delete(componentType); // Remove from adds if it was going to be added\n }\n\n /**\n * Check if the changeset has any changes\n */\n hasChanges(): boolean {\n return this.adds.size > 0 || this.removes.size > 0;\n }\n\n /**\n * Clear all changes\n */\n clear(): void {\n this.adds.clear();\n this.removes.clear();\n }\n\n /**\n * Merge another changeset into this one\n */\n merge(other: ComponentChangeset): void {\n // Merge additions\n for (const [componentType, component] of other.adds) {\n this.adds.set(componentType, component);\n this.removes.delete(componentType);\n }\n // Merge removals\n for (const componentType of other.removes) {\n this.removes.add(componentType);\n this.adds.delete(componentType);\n }\n }\n\n /**\n * Apply the changeset to existing components and return the final state\n */\n applyTo(existingComponents: Map<EntityId<any>, any>): Map<EntityId<any>, any> {\n // Apply removals\n for (const componentType of this.removes) {\n existingComponents.delete(componentType);\n }\n\n // Apply additions/updates\n for (const [componentType, component] of this.adds) {\n existingComponents.set(componentType, component);\n }\n\n return existingComponents;\n }\n\n /**\n * Get the final component types after applying the changeset\n * @param existingComponentTypes - The current component types on the entity\n * @returns The final component types or undefined if no changes\n */\n getFinalComponentTypes(existingComponentTypes: EntityId<any>[]): EntityId<any>[] | undefined {\n const finalComponentTypes = new Set<EntityId<any>>(existingComponentTypes);\n let changed = false;\n\n // Apply removals\n for (const componentType of this.removes) {\n if (!finalComponentTypes.has(componentType)) {\n this.removes.delete(componentType);\n continue; // Component not present, skip\n }\n changed = true;\n finalComponentTypes.delete(componentType);\n }\n\n // Apply additions\n for (const componentType of this.adds.keys()) {\n if (finalComponentTypes.has(componentType)) {\n continue; // Component already present, skip\n }\n changed = true;\n finalComponentTypes.add(componentType);\n }\n\n return changed ? Array.from(finalComponentTypes) : undefined;\n }\n}\n","import type { EntityId } from \"./entity\";\n\n/**\n * Command for deferred execution\n */\nexport interface Command {\n type: \"set\" | \"delete\" | \"destroy\";\n entityId: EntityId;\n componentType?: EntityId<any>;\n component?: any;\n}\n\n/**\n * Command buffer for deferred structural changes\n */\nexport class CommandBuffer {\n private commands: Command[] = [];\n private executeEntityCommands: (entityId: EntityId, commands: Command[]) => void;\n\n /**\n * Create a command buffer with an executor function\n */\n constructor(executeEntityCommands: (entityId: EntityId, commands: Command[]) => void) {\n this.executeEntityCommands = executeEntityCommands;\n }\n\n /**\n * Add a component to an entity (deferred)\n */\n set(entityId: EntityId, componentType: EntityId<void>): void;\n set<T>(entityId: EntityId, componentType: EntityId<T>, component: NoInfer<T>): void;\n set(entityId: EntityId, componentType: EntityId, component?: any): void {\n this.commands.push({ type: \"set\", entityId, componentType, component });\n }\n\n /**\n * Remove a component from an entity (deferred)\n */\n remove<T>(entityId: EntityId, componentType: EntityId<T>): void {\n this.commands.push({ type: \"delete\", entityId, componentType });\n }\n\n /**\n * Destroy an entity (deferred)\n */\n delete(entityId: EntityId): void {\n this.commands.push({ type: \"destroy\", entityId });\n }\n\n /**\n * Execute all commands and clear the buffer\n */\n execute(): void {\n const MAX_ITERATIONS = 100;\n let iterations = 0;\n\n while (this.commands.length > 0) {\n if (iterations >= MAX_ITERATIONS) {\n throw new Error(\"Command execution exceeded maximum iterations, possible infinite loop\");\n }\n iterations++;\n\n const currentCommands = [...this.commands];\n this.commands = [];\n\n // Group commands by entity\n const entityCommands = new Map<EntityId, Command[]>();\n for (const cmd of currentCommands) {\n if (!entityCommands.has(cmd.entityId)) {\n entityCommands.set(cmd.entityId, []);\n }\n entityCommands.get(cmd.entityId)!.push(cmd);\n }\n\n // Process each entity's commands with optimization\n for (const [entityId, commands] of entityCommands) {\n this.executeEntityCommands(entityId, commands);\n }\n }\n }\n\n /**\n * Get current commands (for testing)\n */\n getCommands(): Command[] {\n return [...this.commands];\n }\n\n /**\n * Clear all commands\n */\n clear(): void {\n this.commands = [];\n }\n}\n","// A lightweight generic MultiMap implementation backed by Map<K, Set<V>>.\n// Provides usual operations: add, remove, get, has, keys, values, entries,\n// clear, deleteKey and size accessors.\n\nclass MultiMap<K, V> {\n private map: Map<K, Set<V>> = new Map();\n\n // Number of value entries across all keys (not number of keys).\n private _valueCount = 0;\n\n get valueCount(): number {\n return this._valueCount;\n }\n\n get keyCount(): number {\n return this.map.size;\n }\n\n hasKey(key: K): boolean {\n return this.map.has(key);\n }\n\n has(key: K, value?: V): boolean {\n const set = this.map.get(key);\n if (!set) return false;\n if (arguments.length === 1) return true;\n return set.has(value as V);\n }\n\n add(key: K, value: V): void {\n let set = this.map.get(key);\n if (!set) {\n set = new Set();\n this.map.set(key, set);\n }\n if (!set.has(value)) {\n set.add(value);\n this._valueCount++;\n }\n }\n\n // Remove a specific value for a key. Returns true if removed.\n remove(key: K, value: V): boolean {\n const set = this.map.get(key);\n if (!set) return false;\n if (!set.has(value)) return false;\n set.delete(value);\n this._valueCount--;\n if (set.size === 0) this.map.delete(key);\n return true;\n }\n\n // Delete entire key and all its values. Returns true if key existed.\n deleteKey(key: K): boolean {\n const set = this.map.get(key);\n if (!set) return false;\n this._valueCount -= set.size;\n this.map.delete(key);\n return true;\n }\n\n get(key: K): Set<V> {\n const set = this.map.get(key);\n return set ? new Set(set) : new Set();\n }\n\n // iterate keys, values and entries (key -> Set copy)\n *keys(): IterableIterator<K> {\n yield* this.map.keys();\n }\n\n *values(): IterableIterator<V> {\n for (const set of this.map.values()) {\n for (const v of set) yield v;\n }\n }\n\n [Symbol.iterator](): IterableIterator<[K, V]> {\n return this.entries();\n }\n\n *entries(): IterableIterator<[K, V]> {\n for (const [k, set] of this.map.entries()) {\n for (const v of set) yield [k, v];\n }\n }\n\n clear(): void {\n this.map.clear();\n this._valueCount = 0;\n }\n}\n\nexport { MultiMap };\nexport type { MultiMap as MultiMapType };\n","import type { Archetype } from \"./archetype\";\nimport type { EntityId } from \"./entity\";\nimport { getComponentIdFromRelationId, getDetailedIdType, isRelationId } from \"./entity\";\n\n/**\n * Filter options for queries\n */\nexport interface QueryFilter {\n negativeComponentTypes?: EntityId<any>[];\n}\n\n/**\n * Serialize a QueryFilter into a deterministic string suitable for cache keys.\n * Currently only serializes `negativeComponentTypes`.\n */\nexport function serializeQueryFilter(filter: QueryFilter = {}): string {\n const negative = (filter.negativeComponentTypes || []).slice().sort((a, b) => a - b);\n if (negative.length === 0) return \"\";\n return `neg:${negative.join(\",\")}`;\n}\n\n/**\n * Check if an archetype matches the given component types\n */\nexport function matchesComponentTypes(archetype: Archetype, componentTypes: EntityId<any>[]): boolean {\n return componentTypes.every((type) => {\n const detailedType = getDetailedIdType(type);\n if (detailedType.type === \"wildcard-relation\") {\n // For wildcard relations, check if archetype contains the component relation\n return archetype.componentTypes.some((archetypeType) => {\n if (!isRelationId(archetypeType)) return false;\n const componentId = getComponentIdFromRelationId(archetypeType);\n return componentId === detailedType.componentId;\n });\n } else {\n // For regular components, check direct inclusion\n return archetype.componentTypes.includes(type);\n }\n });\n}\n\n/**\n * Check if an archetype matches the filter conditions (only filtering logic)\n */\nexport function matchesFilter(archetype: Archetype, filter: QueryFilter): boolean {\n const negativeTypes = filter.negativeComponentTypes || [];\n return negativeTypes.every((type) => {\n const detailedType = getDetailedIdType(type);\n if (detailedType.type === \"wildcard-relation\") {\n // For wildcard relations in negative filter, exclude archetypes that contain ANY relation with the same component\n return !archetype.componentTypes.some((archetypeType) => {\n if (!isRelationId(archetypeType)) return false;\n const componentId = getComponentIdFromRelationId(archetypeType);\n return componentId === detailedType.componentId;\n });\n } else {\n // For regular components, check direct exclusion\n return !archetype.componentTypes.includes(type);\n }\n });\n}\n","import type { Archetype } from \"./archetype\";\nimport type { EntityId, WildcardRelationId } from \"./entity\";\nimport { getDetailedIdType } from \"./entity\";\nimport { matchesComponentTypes, matchesFilter, type QueryFilter } from \"./query-filter\";\nimport type { ComponentTuple, ComponentType } from \"./types\";\nimport type { World } from \"./world\";\n\n/**\n * Query class for efficient entity queries with cached archetypes\n */\nexport class Query {\n private world: World;\n private componentTypes: EntityId<any>[];\n private filter: QueryFilter;\n private cachedArchetypes: Archetype[] = [];\n private isDisposed = false;\n\n constructor(world: World, componentTypes: EntityId<any>[], filter: QueryFilter = {}) {\n this.world = world;\n this.componentTypes = [...componentTypes].sort((a, b) => a - b);\n this.filter = filter;\n this.updateCache();\n // Register with world for archetype updates\n world._registerQuery(this);\n }\n\n /**\n * Check if query is disposed and throw error if so\n */\n private ensureNotDisposed(): void {\n if (this.isDisposed) {\n throw new Error(\"Query has been disposed\");\n }\n }\n\n /**\n * Get all entities matching the query\n */\n getEntities(): EntityId[] {\n this.ensureNotDisposed();\n const result: EntityId[] = [];\n\n // Check if any component types are wildcard relations\n const hasWildcardRelations = this.componentTypes.some((ct) => {\n const detailed = getDetailedIdType(ct);\n return detailed.type === \"wildcard-relation\";\n });\n\n // If there are wildcard relations, we need to filter entities that actually have them\n // This is necessary for dontFragment components where an archetype can contain entities\n // with and without the relation\n if (hasWildcardRelations) {\n for (const archetype of this.cachedArchetypes) {\n for (const entity of archetype.getEntities()) {\n // Check if entity has all required wildcard relations\n let hasAllRelations = true;\n for (const componentType of this.componentTypes) {\n const detailed = getDetailedIdType(componentType);\n if (detailed.type === \"wildcard-relation\") {\n // Check if entity has at least one relation matching this wildcard\n const relations = archetype.get(entity, componentType as WildcardRelationId<any>);\n if (!relations || relations.length === 0) {\n hasAllRelations = false;\n break;\n }\n }\n }\n if (hasAllRelations) {\n result.push(entity);\n }\n }\n }\n } else {\n // No wildcard relations, can just return all entities from matching archetypes\n for (const archetype of this.cachedArchetypes) {\n result.push(...archetype.getEntities());\n }\n }\n\n return result;\n }\n\n /**\n * Get entities with their component data\n * @param componentTypes Array of component types to retrieve\n * @returns Array of objects with entity and component data\n */\n getEntitiesWithComponents<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n ): Array<{\n entity: EntityId;\n components: ComponentTuple<T>;\n }> {\n this.ensureNotDisposed();\n\n const result: Array<{\n entity: EntityId;\n components: ComponentTuple<T>;\n }> = [];\n\n for (const archetype of this.cachedArchetypes) {\n const entitiesWithData = archetype.getEntitiesWithComponents(componentTypes);\n result.push(...entitiesWithData);\n }\n\n return result;\n }\n\n /**\n * Iterate over entities with their component data\n * @param componentTypes Array of component types to retrieve\n * @param callback Function called for each entity with its components\n */\n forEach<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n callback: (entity: EntityId, ...components: ComponentTuple<T>) => void,\n ): void {\n this.ensureNotDisposed();\n\n for (const archetype of this.cachedArchetypes) {\n archetype.forEachWithComponents(componentTypes, callback);\n }\n }\n\n /**\n * Iterate over entities with their component data (generator)\n * @param componentTypes Array of component types to retrieve\n */\n *iterate<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n ): IterableIterator<[EntityId, ...ComponentTuple<T>]> {\n this.ensureNotDisposed();\n\n for (const archetype of this.cachedArchetypes) {\n yield* archetype.iterateWithComponents(componentTypes);\n }\n }\n\n /**\n * Get component data arrays for all matching entities\n * @param componentType The component type to retrieve\n * @returns Array of component data for all matching entities\n */\n getComponentData<T>(componentType: EntityId<T>): T[] {\n this.ensureNotDisposed();\n\n const result: T[] = [];\n for (const archetype of this.cachedArchetypes) {\n result.push(...archetype.getComponentData(componentType));\n }\n return result;\n }\n\n /**\n * Update the cached archetypes\n * Called when new archetypes are created\n */\n updateCache(): void {\n if (this.isDisposed) return;\n\n this.cachedArchetypes = this.world\n .getMatchingArchetypes(this.componentTypes)\n .filter((archetype: Archetype) => matchesFilter(archetype, this.filter));\n }\n\n /**\n * Check if a new archetype matches this query and add to cache if it does\n */\n checkNewArchetype(archetype: Archetype): void {\n if (this.isDisposed) return;\n if (\n matchesComponentTypes(archetype, this.componentTypes) &&\n matchesFilter(archetype, this.filter) &&\n !this.cachedArchetypes.includes(archetype)\n ) {\n this.cachedArchetypes.push(archetype);\n }\n }\n\n /**\n * Remove an archetype from the cached archetypes\n */\n removeArchetype(archetype: Archetype): void {\n if (this.isDisposed) return;\n const index = this.cachedArchetypes.indexOf(archetype);\n if (index !== -1) {\n this.cachedArchetypes.splice(index, 1);\n }\n }\n\n /**\n * Dispose the query and disconnect from world\n */\n /**\n * Request disposal of this query.\n * This will decrement the world's reference count for the query.\n * The query will only be fully disposed when the ref count reaches zero.\n */\n dispose(): void {\n // Ask the world to release this query (decrement refcount and fully dispose when zero)\n this.world.releaseQuery(this);\n }\n\n /**\n * Internal full dispose called by World when refCount reaches zero.\n */\n _disposeInternal(): void {\n if (!this.isDisposed) {\n // Unregister from world (remove from notification list)\n this.world._unregisterQuery(this);\n this.cachedArchetypes = [];\n this.isDisposed = true;\n }\n }\n\n /**\n * Symbol.dispose implementation for automatic resource management\n */\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n /**\n * Check if the query has been disposed\n */\n get disposed(): boolean {\n return this.isDisposed;\n }\n}\n","import { Archetype, MISSING_COMPONENT } from \"./archetype\";\nimport { ComponentChangeset } from \"./changeset\";\nimport { CommandBuffer, type Command } from \"./command-buffer\";\nimport type { ComponentId, EntityId, WildcardRelationId } from \"./entity\";\nimport {\n EntityIdManager,\n getComponentIdByName,\n getComponentIdFromRelationId,\n getComponentNameById,\n getDetailedIdType,\n getTargetIdFromRelationId,\n isCascadeDeleteRelation,\n isDontFragmentComponent,\n isDontFragmentRelation,\n isDontFragmentWildcard,\n isEntityRelation,\n isExclusiveComponent,\n isWildcardRelationId,\n relation,\n} from \"./entity\";\nimport { MultiMap } from \"./multi-map\";\nimport { Query } from \"./query\";\nimport { serializeQueryFilter, type QueryFilter } from \"./query-filter\";\nimport type { ComponentTuple, ComponentType, LifecycleHook, MultiLifecycleHook } from \"./types\";\nimport { isOptionalEntityId } from \"./types\";\nimport { getOrCreateWithSideEffect } from \"./utils\";\n\n// -----------------------------------------------------------------------------\n// Serialization helpers for IDs\n// -----------------------------------------------------------------------------\n\nexport type SerializedEntityId = number | string | { component: string; target: number | string | \"*\" };\n\n/**\n * Encode an internal EntityId into a SerializedEntityId for snapshots\n */\nfunction encodeEntityId(id: EntityId<any>): SerializedEntityId {\n const detailed = getDetailedIdType(id);\n switch (detailed.type) {\n case \"component\": {\n const name = getComponentNameById(id as ComponentId);\n if (!name) {\n // Warn if component doesn't have a name; keep numeric fallback\n console.warn(`Component ID ${id} has no registered name, serializing as number`);\n }\n return name || (id as number);\n }\n case \"entity-relation\": {\n const componentName = getComponentNameById(detailed.componentId);\n if (!componentName) {\n console.warn(`Component ID ${detailed.componentId} in relation has no registered name`);\n }\n return { component: componentName || (detailed.componentId as number).toString(), target: detailed.targetId! };\n }\n case \"component-relation\": {\n const componentName = getComponentNameById(detailed.componentId);\n const targetName = getComponentNameById(detailed.targetId! as ComponentId);\n if (!componentName) {\n console.warn(`Component ID ${detailed.componentId} in relation has no registered name`);\n }\n if (!targetName) {\n console.warn(`Target component ID ${detailed.targetId} in relation has no registered name`);\n }\n return {\n component: componentName || (detailed.componentId as number).toString(),\n target: targetName || (detailed.targetId as number),\n };\n }\n case \"wildcard-relation\": {\n const componentName = getComponentNameById(detailed.componentId);\n if (!componentName) {\n console.warn(`Component ID ${detailed.componentId} in relation has no registered name`);\n }\n return { component: componentName || (detailed.componentId as number).toString(), target: \"*\" };\n }\n default:\n return id as number;\n }\n}\n\n/**\n * Decode a SerializedEntityId back into an internal EntityId\n */\nfunction decodeSerializedId(sid: SerializedEntityId): EntityId<any> {\n if (typeof sid === \"number\") {\n return sid as EntityId<any>;\n }\n if (typeof sid === \"string\") {\n const id = getComponentIdByName(sid);\n if (id === undefined) {\n const num = parseInt(sid, 10);\n if (!isNaN(num)) return num as EntityId<any>;\n throw new Error(`Unknown component name in snapshot: ${sid}`);\n }\n return id;\n }\n if (typeof sid === \"object\" && sid !== null && typeof sid.component === \"string\") {\n let compId = getComponentIdByName(sid.component);\n if (compId === undefined) {\n const num = parseInt(sid.component, 10);\n if (!isNaN(num)) compId = num as ComponentId;\n }\n if (compId === undefined) {\n throw new Error(`Unknown component name in snapshot: ${sid.component}`);\n }\n\n if (sid.target === \"*\") {\n return relation(compId, \"*\");\n }\n\n let targetId: EntityId<any>;\n if (typeof sid.target === \"string\") {\n const tid = getComponentIdByName(sid.target);\n if (tid === undefined) {\n const num = parseInt(sid.target, 10);\n if (!isNaN(num)) targetId = num as EntityId<any>;\n else throw new Error(`Unknown target component name in snapshot: ${sid.target}`);\n } else {\n targetId = tid;\n }\n } else {\n targetId = sid.target as EntityId<any>;\n }\n return relation(compId, targetId as any);\n }\n throw new Error(`Invalid ID in snapshot: ${JSON.stringify(sid)}`);\n}\n\n/**\n * World class for ECS architecture\n * Manages entities and components\n */\nexport class World {\n // Core data structures for entity and archetype management\n /** Manages allocation and deallocation of entity IDs */\n private entityIdManager = new EntityIdManager();\n\n /** Array of all archetypes in the world */\n private archetypes: Archetype[] = [];\n\n /** Maps archetype signatures (component type signatures) to archetype instances */\n private archetypeBySignature = new Map<string, Archetype>();\n\n /** Maps entity IDs to their current archetype */\n private entityToArchetype = new Map<EntityId, Archetype>();\n\n /** Maps component types to arrays of archetypes that contain them */\n private archetypesByComponent = new Map<EntityId<any>, Archetype[]>();\n\n /** Tracks which entities reference each entity as a component type */\n private entityReferences = new Map<EntityId, MultiMap<EntityId, EntityId>>();\n\n /** Storage for dontFragment relations - maps entity ID to a map of relation type to component data */\n private dontFragmentRelations: Map<EntityId, Map<EntityId<any>, any>> = new Map();\n\n // Query management\n /** Array of all active queries for archetype change notifications */\n private queries: Query[] = [];\n\n /** Cache for queries keyed by component types and filter signatures */\n private queryCache = new Map<string, { query: Query; refCount: number }>();\n\n // Command execution\n /** Buffers structural changes for deferred execution */\n private commandBuffer = new CommandBuffer((entityId, commands) => this.executeEntityCommands(entityId, commands));\n\n // Lifecycle and configuration\n /** Stores lifecycle hooks for component and relation events */\n private hooks = new Map<EntityId<any>, Set<LifecycleHook<any>>>();\n\n /** Stores multi-component lifecycle hooks */\n private multiHooks: Set<{\n componentTypes: readonly ComponentType<any>[];\n requiredComponents: EntityId<any>[];\n hook: MultiLifecycleHook<any>;\n }> = new Set();\n\n /**\n * Create a new World.\n * If an optional snapshot object is provided (previously produced by `world.serialize()`),\n * the world will be restored from that snapshot. The snapshot may contain non-JSON values.\n */\n constructor(snapshot?: SerializedWorld) {\n // If snapshot provided, restore world state\n if (snapshot && typeof snapshot === \"object\") {\n if (snapshot.entityManager) {\n this.entityIdManager.deserializeState(snapshot.entityManager);\n }\n\n // Restore entities and their components\n if (Array.isArray(snapshot.entities)) {\n for (const entry of snapshot.entities) {\n const entityId = decodeSerializedId(entry.id);\n const componentsArray: SerializedComponent[] = entry.components || [];\n\n const componentMap = new Map<EntityId<any>, any>();\n const componentTypes: EntityId<any>[] = [];\n\n for (const componentEntry of componentsArray) {\n const componentType = decodeSerializedId(componentEntry.type);\n componentMap.set(componentType, componentEntry.value);\n componentTypes.push(componentType);\n }\n\n const archetype = this.ensureArchetype(componentTypes);\n archetype.addEntity(entityId, componentMap);\n this.entityToArchetype.set(entityId, archetype);\n\n // Update reverse index based on component types\n for (const compType of componentTypes) {\n const detailedType = getDetailedIdType(compType);\n if (detailedType.type === \"entity-relation\") {\n const targetEntityId = detailedType.targetId!;\n this.trackEntityReference(entityId, compType, targetEntityId);\n } else if (detailedType.type === \"entity\") {\n this.trackEntityReference(entityId, compType, compType);\n }\n }\n }\n }\n }\n }\n\n /**\n * Generate a signature string for component types array\n * @returns A string signature for the component types\n */\n private createArchetypeSignature(componentTypes: EntityId<any>[]): string {\n return componentTypes.join(\",\");\n }\n\n /**\n * Create a new entity\n * @returns The ID of the newly created entity\n */\n new<T = void>(): EntityId<T> {\n const entityId = this.entityIdManager.allocate();\n // Create empty archetype for entities with no components\n let emptyArchetype = this.ensureArchetype([]);\n emptyArchetype.addEntity(entityId, new Map());\n this.entityToArchetype.set(entityId, emptyArchetype);\n return entityId as EntityId<T>;\n }\n\n /**\n * Destroy an entity and remove all its components (immediate execution)\n */\n private destroyEntityImmediate(entityId: EntityId): void {\n // Implement BFS-style cascade deletion for entity relations where cascade is enabled\n const queue: EntityId[] = [entityId];\n const visited = new Set<EntityId>();\n\n while (queue.length > 0) {\n const cur = queue.shift()!;\n if (visited.has(cur)) continue;\n visited.add(cur);\n\n const archetype = this.entityToArchetype.get(cur);\n if (!archetype) {\n continue; // Entity doesn't exist\n }\n\n // Collect references to this entity and iterate\n const componentReferences = Array.from(this.getEntityReferences(cur));\n for (const [sourceEntityId, componentType] of componentReferences) {\n // For each referencing entity, decide whether to cascade delete or simply remove the component\n const sourceArchetype = this.entityToArchetype.get(sourceEntityId);\n if (!sourceArchetype) continue;\n\n // Cascade only applies to entity relations (not component-relation)\n if (isCascadeDeleteRelation(componentType)) {\n // Enqueue the referencing entity for deletion (cascade)\n if (!visited.has(sourceEntityId)) {\n queue.push(sourceEntityId);\n }\n continue;\n }\n\n // Non-cascade behavior: remove the relation component from the source entity\n this.removeComponentImmediate(sourceEntityId, componentType, cur);\n }\n\n // Clean up the reverse index for this entity\n this.entityReferences.delete(cur);\n\n // Remove the entity itself\n archetype.removeEntity(cur);\n this.entityToArchetype.delete(cur);\n\n this.cleanupArchetypesReferencingEntity(cur);\n this.entityIdManager.deallocate(cur);\n }\n }\n\n /**\n * Check if an entity exists\n */\n exists(entityId: EntityId): boolean {\n return this.entityToArchetype.has(entityId);\n }\n\n /**\n * Add a component to an entity (deferred)\n */\n set(entityId: EntityId, componentType: EntityId<void>): void;\n set<T>(entityId: EntityId, componentType: EntityId<T>, component: NoInfer<T>): void;\n set(entityId: EntityId, componentType: EntityId, component?: any): void {\n if (!this.exists(entityId)) {\n throw new Error(`Entity ${entityId} does not exist`);\n }\n\n // Validate component type\n const detailedType = getDetailedIdType(componentType);\n if (detailedType.type === \"invalid\") {\n throw new Error(`Invalid component type: ${componentType}`);\n }\n if (detailedType.type === \"wildcard-relation\") {\n throw new Error(`Cannot directly add wildcard relation components: ${componentType}`);\n }\n\n this.commandBuffer.set(entityId, componentType, component);\n }\n\n /**\n * Remove a component from an entity (deferred)\n */\n remove<T>(entityId: EntityId, componentType: EntityId<T>): void {\n if (!this.exists(entityId)) {\n throw new Error(`Entity ${entityId} does not exist`);\n }\n\n // Validate component type\n const detailedType = getDetailedIdType(componentType);\n if (detailedType.type === \"invalid\") {\n throw new Error(`Invalid component type: ${componentType}`);\n }\n\n this.commandBuffer.remove(entityId, componentType);\n }\n\n /**\n * Destroy an entity and remove all its components (deferred)\n */\n delete(entityId: EntityId): void {\n this.commandBuffer.delete(entityId);\n }\n\n /**\n * Check if an entity has a specific component\n */\n has<T>(entityId: EntityId, componentType: EntityId<T>): boolean {\n const archetype = this.entityToArchetype.get(entityId);\n if (!archetype) {\n return false;\n }\n\n // Check regular archetype components\n if (archetype.componentTypes.includes(componentType)) {\n return true;\n }\n\n if (isDontFragmentRelation(componentType)) {\n return this.dontFragmentRelations.get(entityId)?.has(componentType) ?? false;\n }\n\n return false;\n }\n\n /**\n * Get component data for a specific entity and wildcard relation type\n * Returns an array of all matching relation instances\n * @param entityId The entity\n * @param componentType The wildcard relation type\n * @returns Array of [targetEntityId, componentData] pairs for all matching relations\n */\n get<T>(entityId: EntityId, componentType: WildcardRelationId<T>): [EntityId<unknown>, T][];\n /**\n * Get component data for a specific entity and component type\n * @param entityId The entity\n * @param componentType The component type\n * @returns The component data\n */\n get<T>(entityId: EntityId, componentType: EntityId<T>): T;\n get<T>(entityId: EntityId, componentType: EntityId<T> | WildcardRelationId<T>): T | [EntityId<unknown>, any][] {\n const archetype = this.entityToArchetype.get(entityId);\n if (!archetype) {\n throw new Error(`Entity ${entityId} does not exist`);\n }\n\n // Check if entity has the component before attempting to get it\n // Note: undefined is a valid component value, so we cannot use undefined to check existence\n // Skip check for wildcard relations (componentType >= 0 means not a relation)\n if (componentType >= 0 || componentType % 2 ** 42 !== 0) {\n // Not a wildcard relation - check existence\n const inArchetype = archetype.componentTypes.includes(componentType);\n const hasDontFragment = isDontFragmentRelation(componentType);\n\n // For dontFragment relations, check if it exists in the dontFragmentRelations storage\n const hasComponent =\n inArchetype || (hasDontFragment && this.dontFragmentRelations.get(entityId)?.has(componentType));\n\n if (!hasComponent) {\n throw new Error(\n `Entity ${entityId} does not have component ${componentType}. Use has() to check component existence before calling get().`,\n );\n }\n }\n\n return archetype.get(entityId, componentType);\n }\n\n /**\n * Get optional component data for a specific entity and component type\n * @param entityId The entity\n * @param componentType The component type\n * @returns { value: T } if component exists, undefined otherwise\n */\n getOptional<T>(entityId: EntityId, componentType: EntityId<T>): { value: T } | undefined {\n const archetype = this.entityToArchetype.get(entityId);\n if (!archetype) {\n throw new Error(`Entity ${entityId} does not exist`);\n }\n\n if (isWildcardRelationId(componentType)) {\n return undefined;\n }\n\n return archetype.getOptional(entityId, componentType);\n }\n\n /**\n * Register a lifecycle hook for component or wildcard relation events\n */\n hook<T>(componentType: EntityId<T>, hook: LifecycleHook<T>): void;\n hook<const T extends readonly ComponentType<any>[]>(componentTypes: T, hook: MultiLifecycleHook<T>): void;\n hook(\n componentTypesOrSingle: EntityId<any> | readonly ComponentType<any>[],\n hook: LifecycleHook<any> | MultiLifecycleHook<any>,\n ): void {\n if (Array.isArray(componentTypesOrSingle)) {\n // Multi-component hook\n const componentTypes = componentTypesOrSingle as readonly ComponentType<any>[];\n const requiredComponents: EntityId<any>[] = [];\n for (const ct of componentTypes) {\n if (!isOptionalEntityId(ct)) {\n requiredComponents.push(ct as EntityId<any>);\n }\n }\n\n const entry = {\n componentTypes,\n requiredComponents,\n hook: hook as MultiLifecycleHook<any>,\n };\n this.multiHooks.add(entry);\n\n // Handle on_init for existing entities\n const multiHook = hook as MultiLifecycleHook<any>;\n if (multiHook.on_init !== undefined) {\n const matchingArchetypes = this.getMatchingArchetypes(requiredComponents);\n for (const archetype of matchingArchetypes) {\n for (const entityId of archetype.getEntities()) {\n const components = this.collectMultiHookComponents(entityId, componentTypes);\n multiHook.on_init(entityId, componentTypes, components);\n }\n }\n }\n } else {\n // Single-component hook\n const componentType = componentTypesOrSingle as EntityId<any>;\n if (!this.hooks.has(componentType)) {\n this.hooks.set(componentType, new Set());\n }\n this.hooks.get(componentType)!.add(hook as LifecycleHook<any>);\n\n const singleHook = hook as LifecycleHook<any>;\n if (singleHook.on_init !== undefined) {\n this.archetypesByComponent.get(componentType)?.forEach((archetype) => {\n const entities = archetype.getEntityToIndexMap();\n const componentData = archetype.getComponentData<any>(componentType);\n for (const [entity, index] of entities) {\n const data = componentData[index];\n const value = data === MISSING_COMPONENT ? undefined : data;\n singleHook.on_init?.(entity, componentType, value);\n }\n });\n }\n }\n }\n\n /**\n * Unregister a lifecycle hook for component or wildcard relation events\n */\n unhook<T>(componentType: EntityId<T>, hook: LifecycleHook<T>): void;\n unhook<const T extends readonly ComponentType<any>[]>(componentTypes: T, hook: MultiLifecycleHook<T>): void;\n unhook(\n componentTypesOrSingle: EntityId<any> | readonly ComponentType<any>[],\n hook: LifecycleHook<any> | MultiLifecycleHook<any>,\n ): void {\n if (Array.isArray(componentTypesOrSingle)) {\n // Multi-component hook\n for (const entry of this.multiHooks) {\n if (entry.hook === hook) {\n this.multiHooks.delete(entry);\n break;\n }\n }\n } else {\n // Single-component hook\n const componentType = componentTypesOrSingle as EntityId<any>;\n const hooks = this.hooks.get(componentType);\n if (hooks) {\n hooks.delete(hook as LifecycleHook<any>);\n if (hooks.size === 0) {\n this.hooks.delete(componentType);\n }\n }\n }\n }\n\n /**\n * Execute all deferred commands immediately\n */\n sync(): void {\n this.commandBuffer.execute();\n }\n\n /**\n * Create a cached query for efficient entity lookups\n * @returns A Query object for the specified component types and filter\n */\n createQuery(componentTypes: EntityId<any>[], filter: QueryFilter = {}): Query {\n // Build a deterministic key for the query (component types sorted + filter negative components sorted)\n const sortedTypes = [...componentTypes].sort((a, b) => a - b);\n const filterKey = serializeQueryFilter(filter);\n const key = `${this.createArchetypeSignature(sortedTypes)}${filterKey ? `|${filterKey}` : \"\"}`;\n\n const cached = this.queryCache.get(key);\n if (cached) {\n cached.refCount++;\n return cached.query;\n }\n\n const query = new Query(this, sortedTypes, filter);\n this.queryCache.set(key, { query, refCount: 1 });\n return query;\n }\n\n /**\n * Create an EntityBuilder for convenient entity creation.\n * @returns EntityBuilder\n */\n spawn(): EntityBuilder {\n return new EntityBuilder(this);\n }\n\n /**\n * Spawn multiple entities using an EntityBuilder configuration callback\n * @param count number of entities\n * @param configure builder configuration callback\n * @returns Created entity IDs\n */\n spawnMany(count: number, configure: (builder: EntityBuilder, index: number) => EntityBuilder): EntityId[] {\n const entities: EntityId[] = [];\n for (let i = 0; i < count; i++) {\n const builder = new EntityBuilder(this);\n entities.push(configure(builder, i).build());\n }\n return entities;\n }\n\n /**\n * @internal Register a query for archetype update notifications\n */\n _registerQuery(query: Query): void {\n this.queries.push(query);\n }\n\n /**\n * @internal Unregister a query\n */\n _unregisterQuery(query: Query): void {\n const index = this.queries.indexOf(query);\n if (index !== -1) {\n this.queries.splice(index, 1);\n }\n }\n\n /**\n * Release a query reference obtained from createQuery.\n * Decrements the refCount and fully disposes the query when it reaches zero.\n */\n releaseQuery(query: Query): void {\n for (const [k, v] of this.queryCache.entries()) {\n if (v.query === query) {\n v.refCount--;\n if (v.refCount <= 0) {\n this.queryCache.delete(k);\n this._unregisterQuery(query);\n // Fully dispose the query (will unregister it from notification list)\n v.query._disposeInternal();\n }\n return;\n }\n }\n }\n\n /**\n * @internal Get archetypes that match specific component types (for internal use by queries)\n */\n getMatchingArchetypes(componentTypes: EntityId<any>[]): Archetype[] {\n if (componentTypes.length === 0) {\n return [...this.archetypes];\n }\n\n // Separate regular components from wildcard relations\n const regularComponents: EntityId<any>[] = [];\n const wildcardRelations: { componentId: ComponentId<any>; relationId: EntityId<any> }[] = [];\n\n for (const componentType of componentTypes) {\n if (isWildcardRelationId(componentType)) {\n const componentId = getComponentIdFromRelationId(componentType);\n if (componentId !== undefined) {\n wildcardRelations.push({\n componentId,\n relationId: componentType,\n });\n }\n } else {\n regularComponents.push(componentType);\n }\n }\n\n // Get archetypes for regular components\n let matchingArchetypes: Archetype[] = [];\n\n if (regularComponents.length > 0) {\n const sortedRegularTypes = [...regularComponents].sort((a, b) => a - b);\n\n if (sortedRegularTypes.length === 1) {\n const componentType = sortedRegularTypes[0]!;\n matchingArchetypes = this.archetypesByComponent.get(componentType) || [];\n } else {\n // Multi-component query - find intersection of archetypes\n const archetypeLists = sortedRegularTypes.map((type) => this.archetypesByComponent.get(type) || []);\n const firstList = archetypeLists[0] || [];\n const intersection = new Set<Archetype>();\n\n // Find archetypes that contain all required components\n for (const archetype of firstList) {\n let hasAllComponents = true;\n for (let listIndex = 1; listIndex < archetypeLists.length; listIndex++) {\n const otherList = archetypeLists[listIndex]!;\n if (!otherList.includes(archetype)) {\n hasAllComponents = false;\n break;\n }\n }\n if (hasAllComponents) {\n intersection.add(archetype);\n }\n }\n\n matchingArchetypes = Array.from(intersection);\n }\n } else {\n // No regular components, start with all archetypes\n matchingArchetypes = [...this.archetypes];\n }\n\n // Filter by wildcard relations\n for (const wildcard of wildcardRelations) {\n // For dontFragment components, check if wildcard marker is in archetypesByComponent\n if (isDontFragmentComponent(wildcard.componentId)) {\n // Use the wildcard marker for efficient lookup\n const archetypesWithMarker = this.archetypesByComponent.get(wildcard.relationId) || [];\n\n if (matchingArchetypes.length === 0) {\n // No regular components, use all archetypes with the wildcard marker\n matchingArchetypes = archetypesWithMarker;\n } else {\n // Filter to only include archetypes that have the wildcard marker\n matchingArchetypes = matchingArchetypes.filter((archetype) => archetypesWithMarker.includes(archetype));\n }\n } else {\n // For regular (non-dontFragment) relations, fall back to entity-level checking\n // This is necessary because non-dontFragment relations are in the archetype signature\n matchingArchetypes = matchingArchetypes.filter((archetype) =>\n archetype.hasRelationWithComponentId(wildcard.componentId),\n );\n }\n }\n\n return matchingArchetypes;\n }\n\n /**\n * Query entities with specific components\n * @returns Array of entity IDs that have all the specified components\n */\n query(componentTypes: EntityId<any>[]): EntityId[];\n query<const T extends readonly EntityId<any>[]>(\n componentTypes: T,\n includeComponents: true,\n ): Array<{\n entity: EntityId;\n components: ComponentTuple<T>;\n }>;\n query(\n componentTypes: EntityId<any>[],\n includeComponents?: boolean,\n ):\n | EntityId[]\n | Array<{\n entity: EntityId;\n components: any;\n }> {\n const matchingArchetypes = this.getMatchingArchetypes(componentTypes);\n\n if (includeComponents) {\n const result: Array<{\n entity: EntityId;\n components: any;\n }> = [];\n\n for (const archetype of matchingArchetypes) {\n const entitiesWithData = archetype.getEntitiesWithComponents(componentTypes as EntityId<any>[]);\n result.push(...entitiesWithData);\n }\n\n return result;\n } else {\n const result: EntityId[] = [];\n for (const archetype of matchingArchetypes) {\n result.push(...archetype.getEntities());\n }\n return result;\n }\n }\n\n /**\n * @internal Execute commands for a single entity (for internal use by CommandBuffer)\n * @returns ComponentChangeset describing the changes made\n */\n executeEntityCommands(entityId: EntityId, commands: Command[]): ComponentChangeset {\n const changeset = new ComponentChangeset();\n\n // Handle entity destruction\n if (commands.some((cmd) => cmd.type === \"destroy\")) {\n this.destroyEntityImmediate(entityId);\n return changeset;\n }\n\n const currentArchetype = this.entityToArchetype.get(entityId);\n if (!currentArchetype) {\n return changeset;\n }\n\n // Process commands to build changeset\n this.processCommands(entityId, currentArchetype, commands, changeset);\n\n // Apply changes to entity\n const removedComponents = this.applyChangeset(entityId, currentArchetype, changeset);\n\n // Update entity reference tracking\n this.updateEntityReferences(entityId, changeset);\n\n // Trigger lifecycle hooks\n this.triggerLifecycleHooks(entityId, changeset.adds, removedComponents);\n\n return changeset;\n }\n\n /**\n * Process commands and populate the changeset\n */\n private processCommands(\n entityId: EntityId,\n currentArchetype: Archetype,\n commands: Command[],\n changeset: ComponentChangeset,\n ): void {\n for (const command of commands) {\n if (command.type === \"set\" && command.componentType) {\n this.processSetCommand(entityId, currentArchetype, command.componentType, command.component, changeset);\n } else if (command.type === \"delete\" && command.componentType) {\n this.processDeleteCommand(entityId, currentArchetype, command.componentType, changeset);\n }\n }\n }\n\n /**\n * Process a set command, handling exclusive relations\n */\n private processSetCommand(\n entityId: EntityId,\n currentArchetype: Archetype,\n componentType: EntityId<any>,\n component: any,\n changeset: ComponentChangeset,\n ): void {\n // Extract componentId if it's a relation (fast path)\n const componentId = getComponentIdFromRelationId(componentType);\n if (componentId !== undefined) {\n // Handle exclusive relations by removing existing relations with the same base component\n if (componentId !== undefined && isExclusiveComponent(componentId)) {\n this.removeExclusiveRelations(entityId, currentArchetype, componentId, changeset);\n }\n\n // For dontFragment relations, ensure wildcard marker is in archetype signature\n if (componentId !== undefined && isDontFragmentComponent(componentId)) {\n const wildcardMarker = relation(componentId, \"*\");\n // Add wildcard marker to changeset if not already in archetype\n if (!currentArchetype.componentTypes.includes(wildcardMarker)) {\n changeset.set(wildcardMarker, undefined);\n }\n }\n }\n\n changeset.set(componentType, component);\n }\n\n /**\n * Remove all relations with the same base component (for exclusive relations)\n */\n private removeExclusiveRelations(\n entityId: EntityId,\n currentArchetype: Archetype,\n baseComponentId: ComponentId<any>,\n changeset: ComponentChangeset,\n ): void {\n // Check archetype components\n for (const componentType of currentArchetype.componentTypes) {\n if (this.isRelationWithComponent(componentType, baseComponentId)) {\n changeset.delete(componentType);\n }\n }\n\n // Check dontFragment relations\n const entityData = currentArchetype.getEntity(entityId);\n if (entityData) {\n for (const [componentType] of entityData) {\n if (currentArchetype.componentTypes.includes(componentType)) continue;\n if (this.isRelationWithComponent(componentType, baseComponentId)) {\n changeset.delete(componentType);\n }\n }\n }\n }\n\n private isRelationWithComponent(componentType: EntityId<any>, baseComponentId: ComponentId<any>): boolean {\n const componentId = getComponentIdFromRelationId(componentType);\n // componentId is defined only for relations (negative IDs), and excludes wildcards by matching baseComponentId\n return componentId === baseComponentId;\n }\n\n /**\n * Process a delete command, handling wildcard relations\n */\n private processDeleteCommand(\n entityId: EntityId,\n currentArchetype: Archetype,\n componentType: EntityId<any>,\n changeset: ComponentChangeset,\n ): void {\n const componentId = getComponentIdFromRelationId(componentType);\n\n if (isWildcardRelationId(componentType) && componentId !== undefined) {\n this.removeWildcardRelations(entityId, currentArchetype, componentId, changeset);\n } else {\n changeset.delete(componentType);\n\n // If removing a dontFragment relation, check if we should remove the wildcard marker\n if (componentId !== undefined && isDontFragmentComponent(componentId)) {\n // Check if there are any other dontFragment relations with the same component ID\n const wildcardMarker = relation(componentId, \"*\");\n const entityData = currentArchetype.getEntity(entityId);\n let hasOtherRelations = false;\n\n if (entityData) {\n for (const [otherComponentType] of entityData) {\n if (otherComponentType === componentType) continue; // Skip the one being removed\n if (otherComponentType === wildcardMarker) continue; // Skip wildcard marker itself\n if (changeset.removes.has(otherComponentType)) continue; // Skip if also being removed\n\n const otherComponentId = getComponentIdFromRelationId(otherComponentType);\n if (otherComponentId === componentId) {\n hasOtherRelations = true;\n break;\n }\n }\n }\n\n // If no other relations exist, remove the wildcard marker\n if (!hasOtherRelations) {\n changeset.delete(wildcardMarker);\n }\n }\n }\n }\n\n /**\n * Remove all relations matching a wildcard component ID\n */\n private removeWildcardRelations(\n entityId: EntityId,\n currentArchetype: Archetype,\n baseComponentId: ComponentId<any>,\n changeset: ComponentChangeset,\n ): void {\n // Check archetype components\n for (const componentType of currentArchetype.componentTypes) {\n if (this.isRelationWithComponent(componentType, baseComponentId)) {\n changeset.delete(componentType);\n }\n }\n\n // Check dontFragment relations\n const entityData = currentArchetype.getEntity(entityId);\n if (entityData) {\n for (const [componentType] of entityData) {\n if (currentArchetype.componentTypes.includes(componentType)) continue;\n if (this.isRelationWithComponent(componentType, baseComponentId)) {\n changeset.delete(componentType);\n }\n }\n }\n\n // If removing dontFragment relations, also remove the wildcard marker\n if (isDontFragmentComponent(baseComponentId)) {\n const wildcardMarker = relation(baseComponentId, \"*\");\n changeset.delete(wildcardMarker);\n }\n }\n\n /**\n * Remove a single component from an entity immediately, handling dontFragment relations correctly.\n * Used by destroyEntityImmediate for non-cascade relation cleanup.\n */\n private removeComponentImmediate(entityId: EntityId, componentType: EntityId<any>, targetEntityId: EntityId): void {\n const sourceArchetype = this.entityToArchetype.get(entityId);\n if (!sourceArchetype) return;\n\n // Build changeset for removing this component\n const changeset = new ComponentChangeset();\n const componentId = getComponentIdFromRelationId(componentType);\n\n changeset.delete(componentType);\n\n // If removing a dontFragment relation, check if we should remove the wildcard marker\n if (componentId !== undefined && isDontFragmentComponent(componentId)) {\n const wildcardMarker = relation(componentId, \"*\");\n const entityData = sourceArchetype.getEntity(entityId);\n let hasOtherRelations = false;\n\n if (entityData) {\n for (const [otherComponentType] of entityData) {\n if (otherComponentType === componentType) continue;\n // Skip wildcard marker itself\n if (otherComponentType === wildcardMarker) continue;\n const otherComponentId = getComponentIdFromRelationId(otherComponentType);\n if (otherComponentId === componentId) {\n hasOtherRelations = true;\n break;\n }\n }\n }\n\n if (!hasOtherRelations) {\n changeset.delete(wildcardMarker);\n }\n }\n\n // Get removed component value before applying changeset\n const removedComponent = sourceArchetype.get(entityId, componentType);\n\n // Apply changeset using existing logic\n this.applyChangeset(entityId, sourceArchetype, changeset);\n\n // Remove from component reverse index\n this.untrackEntityReference(entityId, componentType, targetEntityId);\n\n // Trigger component removed hooks\n this.triggerLifecycleHooks(entityId, new Map(), new Map([[componentType, removedComponent]]));\n }\n\n /**\n * Apply changeset to entity, moving to new archetype if needed\n * @returns Map of removed components with their data\n */\n private applyChangeset(\n entityId: EntityId,\n currentArchetype: Archetype,\n changeset: ComponentChangeset,\n ): Map<EntityId<any>, any> {\n const currentEntityData = currentArchetype.getEntity(entityId);\n const allCurrentComponentTypes = currentEntityData\n ? Array.from(currentEntityData.keys())\n : currentArchetype.componentTypes;\n\n const finalComponentTypes = changeset.getFinalComponentTypes(allCurrentComponentTypes);\n const removedComponents = new Map<EntityId<any>, any>();\n\n if (finalComponentTypes) {\n // Check if archetype-affecting components actually changed\n // (dontFragment components don't affect archetype signature)\n const currentRegularTypes = this.filterRegularComponentTypes(allCurrentComponentTypes);\n const finalRegularTypes = this.filterRegularComponentTypes(finalComponentTypes);\n const archetypeChanged = !this.areComponentTypesEqual(currentRegularTypes, finalRegularTypes);\n\n if (archetypeChanged) {\n // Move to new archetype (regular components changed)\n this.moveEntityToNewArchetype(entityId, currentArchetype, finalComponentTypes, changeset, removedComponents);\n } else {\n // Only dontFragment components changed, stay in same archetype\n this.updateEntityInSameArchetype(entityId, currentArchetype, changeset, removedComponents);\n }\n } else {\n // Update in same archetype\n this.updateEntityInSameArchetype(entityId, currentArchetype, changeset, removedComponents);\n }\n\n return removedComponents;\n }\n\n /**\n * Move entity to a new archetype with updated components\n */\n private moveEntityToNewArchetype(\n entityId: EntityId,\n currentArchetype: Archetype,\n finalComponentTypes: EntityId<any>[],\n changeset: ComponentChangeset,\n removedComponents: Map<EntityId<any>, any>,\n ): void {\n const newArchetype = this.ensureArchetype(finalComponentTypes);\n const currentComponents = currentArchetype.removeEntity(entityId)!;\n\n // Track removed components\n for (const componentType of changeset.removes) {\n removedComponents.set(componentType, currentComponents.get(componentType));\n }\n\n // Add to new archetype with updated components\n newArchetype.addEntity(entityId, changeset.applyTo(currentComponents));\n this.entityToArchetype.set(entityId, newArchetype);\n }\n\n /**\n * Update entity in same archetype (no archetype change needed)\n */\n private updateEntityInSameArchetype(\n entityId: EntityId,\n currentArchetype: Archetype,\n changeset: ComponentChangeset,\n removedComponents: Map<EntityId<any>, any>,\n ): void {\n // Process dontFragment relation changes directly on World's storage\n this.applyDontFragmentChanges(entityId, changeset, removedComponents);\n\n // Direct update for regular components in archetype\n for (const [componentType, component] of changeset.adds) {\n if (isDontFragmentRelation(componentType)) {\n continue;\n }\n currentArchetype.set(entityId, componentType, component);\n }\n }\n\n /**\n * Apply dontFragment relation changes directly to World's storage\n * This is much more efficient than the removeEntity + addEntity approach\n */\n private applyDontFragmentChanges(\n entityId: EntityId,\n changeset: ComponentChangeset,\n removedComponents: Map<EntityId<any>, any>,\n ): void {\n // Get or create the entity's dontFragment relations map\n let entityRelations = this.dontFragmentRelations.get(entityId);\n\n for (const componentType of changeset.removes) {\n if (isDontFragmentRelation(componentType)) {\n if (entityRelations) {\n const removedValue = entityRelations.get(componentType);\n if (removedValue !== undefined || entityRelations.has(componentType)) {\n removedComponents.set(componentType, removedValue);\n entityRelations.delete(componentType);\n }\n }\n }\n }\n\n for (const [componentType, component] of changeset.adds) {\n if (isDontFragmentRelation(componentType)) {\n if (!entityRelations) {\n entityRelations = new Map();\n this.dontFragmentRelations.set(entityId, entityRelations);\n }\n entityRelations.set(componentType, component);\n }\n }\n\n // Clean up empty map\n if (entityRelations && entityRelations.size === 0) {\n this.dontFragmentRelations.delete(entityId);\n }\n }\n\n /**\n * Update entity reference tracking based on changeset\n */\n private updateEntityReferences(entityId: EntityId, changeset: ComponentChangeset): void {\n // Remove references for removed components\n for (const componentType of changeset.removes) {\n if (isEntityRelation(componentType)) {\n const targetId = getTargetIdFromRelationId(componentType)!;\n this.untrackEntityReference(entityId, componentType, targetId);\n } else if (componentType >= 1024) {\n // Entity used as component type\n this.untrackEntityReference(entityId, componentType, componentType);\n }\n }\n\n // Add references for added components\n for (const [componentType] of changeset.adds) {\n if (isEntityRelation(componentType)) {\n const targetId = getTargetIdFromRelationId(componentType)!;\n this.trackEntityReference(entityId, componentType, targetId);\n } else if (componentType >= 1024) {\n // Entity used as component type\n this.trackEntityReference(entityId, componentType, componentType);\n }\n }\n }\n\n /**\n * Get or create an archetype for the given component types\n * Filters out dontFragment relations from the archetype signature\n * @returns The archetype for the given component types (excluding dontFragment relations)\n */\n private ensureArchetype(componentTypes: Iterable<EntityId<any>>): Archetype {\n const regularTypes = this.filterRegularComponentTypes(componentTypes);\n const sortedTypes = regularTypes.sort((a, b) => a - b);\n const hashKey = this.createArchetypeSignature(sortedTypes);\n\n return getOrCreateWithSideEffect(this.archetypeBySignature, hashKey, () => this.createNewArchetype(sortedTypes));\n }\n\n /**\n * Compare two arrays of component types for equality (order-independent)\n */\n private areComponentTypesEqual(types1: EntityId<any>[], types2: EntityId<any>[]): boolean {\n if (types1.length !== types2.length) return false;\n const sorted1 = [...types1].sort((a, b) => a - b);\n const sorted2 = [...types2].sort((a, b) => a - b);\n return sorted1.every((v, i) => v === sorted2[i]);\n }\n\n /**\n * Filter out dontFragment relations from component types, but keep wildcard markers\n */\n private filterRegularComponentTypes(componentTypes: Iterable<EntityId<any>>): EntityId<any>[] {\n const regularTypes: EntityId<any>[] = [];\n\n for (const componentType of componentTypes) {\n // Keep wildcard markers for dontFragment components (they mark the archetype)\n if (isDontFragmentWildcard(componentType)) {\n regularTypes.push(componentType);\n continue;\n }\n\n // Skip specific dontFragment relations from archetype signature\n if (isDontFragmentRelation(componentType)) {\n continue;\n }\n\n regularTypes.push(componentType);\n }\n\n return regularTypes;\n }\n\n /**\n * Create a new archetype and register it with all tracking structures\n */\n private createNewArchetype(componentTypes: EntityId<any>[]): Archetype {\n const newArchetype = new Archetype(componentTypes, this.dontFragmentRelations);\n this.archetypes.push(newArchetype);\n\n // Register archetype in component index\n this.registerArchetypeInComponentIndex(newArchetype, componentTypes);\n\n // Notify queries about new archetype\n this.notifyQueriesOfNewArchetype(newArchetype);\n\n return newArchetype;\n }\n\n /**\n * Register archetype in the component-to-archetype index\n */\n private registerArchetypeInComponentIndex(archetype: Archetype, componentTypes: EntityId<any>[]): void {\n for (const componentType of componentTypes) {\n const archetypes = this.archetypesByComponent.get(componentType) || [];\n archetypes.push(archetype);\n this.archetypesByComponent.set(componentType, archetypes);\n }\n }\n\n /**\n * Notify all queries to check the new archetype\n */\n private notifyQueriesOfNewArchetype(archetype: Archetype): void {\n for (const query of this.queries) {\n query.checkNewArchetype(archetype);\n }\n }\n\n /**\n * Add a component reference to the reverse index when an entity is used as a component type\n * @param sourceEntityId The entity that has the component\n * @param componentType The component type (which may be an entity ID used as component type)\n * @param targetEntityId The entity being used as component type\n */\n private trackEntityReference(sourceEntityId: EntityId, componentType: EntityId, targetEntityId: EntityId): void {\n if (!this.entityReferences.has(targetEntityId)) {\n this.entityReferences.set(targetEntityId, new MultiMap());\n }\n this.entityReferences.get(targetEntityId)!.add(sourceEntityId, componentType);\n }\n\n /**\n * Remove a component reference from the reverse index\n * @param sourceEntityId The entity that has the component\n * @param componentType The component type\n * @param targetEntityId The entity being used as component type\n */\n private untrackEntityReference(sourceEntityId: EntityId, componentType: EntityId, targetEntityId: EntityId): void {\n const references = this.entityReferences.get(targetEntityId);\n if (references) {\n references.remove(sourceEntityId, componentType);\n if (references.keyCount === 0) {\n this.entityReferences.delete(targetEntityId);\n }\n }\n }\n\n /**\n * Get all component references where a target entity is used as a component type\n * @param targetEntityId The target entity\n * @returns A MultiMap of sourceEntityId to componentTypes that reference the target entity\n */\n private getEntityReferences(targetEntityId: EntityId): Iterable<[EntityId, EntityId]> {\n return this.entityReferences.get(targetEntityId) ?? new MultiMap();\n }\n\n /**\n * Check if an archetype's signature references a specific entity\n * (via entity-relation targeting the entity, or using entity as component type)\n */\n private archetypeReferencesEntity(archetype: Archetype, entityId: EntityId): boolean {\n for (const componentType of archetype.componentTypes) {\n if (componentType === entityId) {\n return true;\n }\n if (isEntityRelation(componentType)) {\n const targetId = getTargetIdFromRelationId(componentType);\n if (targetId === entityId) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Cleanup empty archetypes that reference a specific deleted entity\n * Only removes archetypes whose component types reference the entity\n */\n private cleanupArchetypesReferencingEntity(entityId: EntityId): void {\n for (let i = this.archetypes.length - 1; i >= 0; i--) {\n const archetype = this.archetypes[i]!;\n if (archetype.getEntities().length === 0 && this.archetypeReferencesEntity(archetype, entityId)) {\n this.removeArchetypeFromList(archetype);\n this.removeArchetypeFromSignatureMap(archetype);\n this.removeArchetypeFromComponentIndex(archetype);\n this.removeArchetypeFromQueries(archetype);\n }\n }\n }\n\n /**\n * Remove archetype from the main archetypes list\n */\n private removeArchetypeFromList(archetype: Archetype): void {\n const index = this.archetypes.indexOf(archetype);\n if (index !== -1) {\n this.archetypes.splice(index, 1);\n }\n }\n\n /**\n * Remove archetype from the signature-to-archetype map\n */\n private removeArchetypeFromSignatureMap(archetype: Archetype): void {\n const hashKey = this.createArchetypeSignature(archetype.componentTypes);\n this.archetypeBySignature.delete(hashKey);\n }\n\n /**\n * Remove archetype from the component-to-archetypes index\n */\n private removeArchetypeFromComponentIndex(archetype: Archetype): void {\n for (const componentType of archetype.componentTypes) {\n const archetypes = this.archetypesByComponent.get(componentType);\n if (archetypes) {\n const compIndex = archetypes.indexOf(archetype);\n if (compIndex !== -1) {\n archetypes.splice(compIndex, 1);\n if (archetypes.length === 0) {\n this.archetypesByComponent.delete(componentType);\n }\n }\n }\n }\n }\n\n /**\n * Remove archetype from all queries\n */\n private removeArchetypeFromQueries(archetype: Archetype): void {\n for (const query of this.queries) {\n query.removeArchetype(archetype);\n }\n }\n\n /**\n * Execute component lifecycle hooks for added and removed components\n */\n private triggerLifecycleHooks(\n entityId: EntityId,\n addedComponents: Map<EntityId<any>, any>,\n removedComponents: Map<EntityId<any>, any>,\n ): void {\n // Trigger component added hooks\n for (const [componentType, component] of addedComponents) {\n // Trigger direct component hooks\n const directHooks = this.hooks.get(componentType);\n if (directHooks) {\n for (const lifecycleHook of directHooks) {\n lifecycleHook.on_set?.(entityId, componentType, component);\n }\n }\n\n const componentId = getComponentIdFromRelationId(componentType);\n if (componentId !== undefined) {\n const wildcardRelationId = relation(componentId, \"*\");\n const wildcardHooks = this.hooks.get(wildcardRelationId);\n if (wildcardHooks) {\n for (const lifecycleHook of wildcardHooks) {\n lifecycleHook.on_set?.(entityId, componentType, component);\n }\n }\n }\n }\n\n // Trigger component removed hooks\n for (const [componentType, component] of removedComponents) {\n // Trigger direct component hooks\n const directHooks = this.hooks.get(componentType);\n if (directHooks) {\n for (const lifecycleHook of directHooks) {\n lifecycleHook.on_remove?.(entityId, componentType, component);\n }\n }\n\n const componentId = getComponentIdFromRelationId(componentType);\n if (componentId !== undefined) {\n const wildcardRelationId = relation(componentId, \"*\");\n const wildcardHooks = this.hooks.get(wildcardRelationId);\n if (wildcardHooks) {\n for (const hook of wildcardHooks) {\n hook.on_remove?.(entityId, componentType, component);\n }\n }\n }\n }\n\n // Trigger multi-component hooks\n this.triggerMultiComponentHooks(entityId, addedComponents, removedComponents);\n }\n\n /**\n * Trigger multi-component hooks based on changes\n */\n private triggerMultiComponentHooks(\n entityId: EntityId,\n addedComponents: Map<EntityId<any>, any>,\n removedComponents: Map<EntityId<any>, any>,\n ): void {\n for (const entry of this.multiHooks) {\n const { componentTypes, requiredComponents, hook } = entry;\n\n // Check if any of the required components were added\n let anyRequiredAdded = false;\n for (const reqComp of requiredComponents) {\n if (addedComponents.has(reqComp)) {\n anyRequiredAdded = true;\n break;\n }\n }\n\n // Check if any of the required components were removed\n let anyRequiredRemoved = false;\n for (const reqComp of requiredComponents) {\n if (removedComponents.has(reqComp)) {\n anyRequiredRemoved = true;\n break;\n }\n }\n\n // Handle on_set: trigger if any required component was added and entity has all required components now\n if (anyRequiredAdded && hook.on_set) {\n const hasAllRequired = this.entityHasAllComponents(entityId, requiredComponents);\n if (hasAllRequired) {\n const components = this.collectMultiHookComponents(entityId, componentTypes);\n hook.on_set(entityId, componentTypes, components);\n }\n }\n\n // Handle on_remove: trigger if any required component was removed and entity had all required components before removal\n if (anyRequiredRemoved && hook.on_remove) {\n // Check if entity had all required components before removal\n const hadAllRequiredBefore = this.entityHadAllComponentsBefore(entityId, requiredComponents, removedComponents);\n if (hadAllRequiredBefore) {\n // Collect components snapshot from before removal\n const components = this.collectMultiHookComponentsWithRemoved(entityId, componentTypes, removedComponents);\n hook.on_remove(entityId, componentTypes, components);\n }\n }\n }\n }\n\n /**\n * Check if entity currently has all required components\n */\n private entityHasAllComponents(entityId: EntityId, requiredComponents: EntityId<any>[]): boolean {\n for (const reqComp of requiredComponents) {\n if (!this.has(entityId, reqComp)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Check if entity had all required components before removal\n */\n private entityHadAllComponentsBefore(\n entityId: EntityId,\n requiredComponents: EntityId<any>[],\n removedComponents: Map<EntityId<any>, any>,\n ): boolean {\n for (const reqComp of requiredComponents) {\n // Component was either present before (and now removed) or still present\n const wasRemoved = removedComponents.has(reqComp);\n const stillHas = this.has(entityId, reqComp);\n if (!wasRemoved && !stillHas) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Collect component values for multi-component hook (current state)\n */\n private collectMultiHookComponents(entityId: EntityId, componentTypes: readonly ComponentType<any>[]): any[] {\n const result: any[] = [];\n for (const ct of componentTypes) {\n if (isOptionalEntityId(ct)) {\n const optionalId = ct.optional;\n result.push(this.getOptional(entityId, optionalId));\n } else {\n result.push(this.get(entityId, ct as EntityId<any>));\n }\n }\n return result;\n }\n\n /**\n * Collect component values for multi-component hook with removed components (snapshot before removal)\n */\n private collectMultiHookComponentsWithRemoved(\n entityId: EntityId,\n componentTypes: readonly ComponentType<any>[],\n removedComponents: Map<EntityId<any>, any>,\n ): any[] {\n const result: any[] = [];\n for (const ct of componentTypes) {\n if (isOptionalEntityId(ct)) {\n const optionalId = ct.optional;\n if (removedComponents.has(optionalId)) {\n result.push({ value: removedComponents.get(optionalId) });\n } else {\n result.push(this.getOptional(entityId, optionalId));\n }\n } else {\n const compId = ct as EntityId<any>;\n if (removedComponents.has(compId)) {\n result.push(removedComponents.get(compId));\n } else {\n result.push(this.get(entityId, compId));\n }\n }\n }\n return result;\n }\n\n /**\n * Convert the world into a plain snapshot object.\n * This returns an in-memory structure and does not perform JSON stringification.\n * Component values are stored as-is (they may be non-JSON-serializable).\n */\n serialize(): SerializedWorld {\n const entities: SerializedEntity[] = [];\n\n for (const archetype of this.archetypes) {\n const dumpedEntities = archetype.dump();\n for (const { entity, components } of dumpedEntities) {\n entities.push({\n id: encodeEntityId(entity),\n components: Array.from(components.entries()).map(([rawType, value]) => ({\n type: encodeEntityId(rawType),\n value: value === MISSING_COMPONENT ? undefined : value,\n })),\n });\n }\n }\n\n return {\n version: 1,\n entityManager: this.entityIdManager.serializeState(),\n entities,\n };\n }\n}\n\nexport type SerializedWorld = {\n version: number;\n entityManager: any;\n entities: SerializedEntity[];\n};\n\nexport type SerializedEntity = {\n id: SerializedEntityId;\n components: SerializedComponent[];\n};\n\nexport type SerializedComponent = {\n type: SerializedEntityId;\n value: any;\n};\n\n// =============================================================================\n// EntityBuilder - Fluent Entity Creation (moved from testing utilities)\n// =============================================================================\n\n/**\n * A component definition for entity building, supporting both regular components and relations\n */\nexport type ComponentDef<T = unknown> =\n | { type: \"component\"; id: EntityId<T>; value: T }\n | { type: \"relation\"; componentId: ComponentId<T>; targetId: EntityId<any>; value: T };\n\nexport class EntityBuilder {\n private world: World;\n private components: ComponentDef[] = [];\n\n constructor(world: World) {\n this.world = world;\n }\n\n with<T>(componentId: EntityId<T>, value: T): this {\n this.components.push({ type: \"component\", id: componentId, value });\n return this;\n }\n\n withTag(componentId: EntityId<void>): this {\n this.components.push({ type: \"component\", id: componentId, value: undefined as void });\n return this;\n }\n\n withRelation<T>(componentId: ComponentId<T>, targetEntity: EntityId<any>, value: T): this {\n this.components.push({ type: \"relation\", componentId, targetId: targetEntity, value });\n return this;\n }\n\n withRelationTag(componentId: ComponentId<void>, targetEntity: EntityId<any>): this {\n this.components.push({ type: \"relation\", componentId, targetId: targetEntity, value: undefined as void });\n return this;\n }\n\n /**\n * Create an entity and enqueue components to be applied. This method\n * does NOT call `world.sync()` automatically; callers must invoke\n * `world.sync()` to apply deferred commands.\n * (Previously auto-synced; now a breaking change — buildDeferred() removed.)\n */\n build(): EntityId {\n const entity = this.world.new();\n\n for (const def of this.components) {\n if (def.type === \"component\") {\n this.world.set(entity, def.id, def.value as any);\n } else {\n const relationId = relation(def.componentId, def.targetId);\n this.world.set(entity, relationId,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AAO;;CAGT,aAAgB,aAA6B,cAA6B,OAAgB;AACxF,OAAK,WAAW,KAAK;GAAE,MAAM;GAAY;GAAa,UAAU;GAAc;GAAO,CAAC;AACtF,SAAO;;CAGT,gBAAgB,aAAgC,cAAmC;AACjF,OAAK,WAAW,KAAK;GAAE,MAAM;GAAY;GAAa,UAAU;GAAc,OAAO;GAAmB,CAAC;AACzG,SAAO;;;;;;;;CAST,QAAkB;EAChB,MAAM,SAAS,KAAK,MAAM,KAAK;AAE/B,OAAK,MAAM,OAAO,KAAK,WACrB,KAAI,IAAI,SAAS,YACf,MAAK,MAAM,IAAI,QAAQ,IAAI,IAAI,IAAI,MAAa;OAC3C;GACL,MAAM,aAAa,SAAS,IAAI,aAAa,IAAI,SAAS;AAC1D,QAAK,MAAM,IAAI,QAAQ,YAAY,IAAI,MAAa;;AAIxD,SAAO"}
|
|
1
|
+
{"version":3,"file":"world.mjs","names":["actualTargetId: number","type: \"entity-relation\" | \"component-relation\" | \"wildcard-relation\"","ComponentIdForNames: Map<string, ComponentId<any>>","componentNames: (string | undefined)[]","name: string | undefined","options: ComponentOptions | undefined","component","result: EntityId[]","result","result: Array<{\n entity: EntityId;\n components: ComponentTuple<T>;\n }>","result: T[]","relations: [EntityId<unknown>, any][]","relations: [EntityId<unknown>, any][]","result: Array<{ entity: EntityId; components: ComponentTuple<T> }>","targetId: EntityId<any>","component","regularTypes: EntityId<any>[]","component","componentsArray: SerializedComponent[]","componentTypes: EntityId<any>[]","queue: EntityId[]","component","requiredComponents: EntityId<any>[]","entry: MultiHookEntry","entities: EntityId[]","regularComponents: EntityId<any>[]","wildcardRelations: { componentId: ComponentId<any>; relationId: EntityId<any> }[]","result: Array<{ entity: EntityId; components: any }>","result: EntityId[]","entities: SerializedEntity[]"],"sources":["../src/core/entity-types.ts","../src/core/entity-relation.ts","../src/core/entity-manager.ts","../src/utils/bit-set.ts","../src/core/component-registry.ts","../src/core/builder.ts","../src/commands/changeset.ts","../src/commands/command-buffer.ts","../src/query/filter.ts","../src/query/query.ts","../src/utils/utils.ts","../src/core/types.ts","../src/core/archetype-helpers.ts","../src/core/archetype.ts","../src/core/serialization.ts","../src/core/world-commands.ts","../src/core/world-hooks.ts","../src/utils/multi-map.ts","../src/core/world-references.ts","../src/core/world.ts"],"sourcesContent":["/**\n * Unique symbol brand for associating component type information with EntityId\n */\ndeclare const __componentTypeMarker: unique symbol;\n\n/**\n * Unique symbol brand for tagging the kind of EntityId (e.g., 'component', 'entity-relation')\n */\ndeclare const __entityIdTypeTag: unique symbol;\n\n/**\n * Entity ID type for ECS architecture\n * Based on 52-bit integers within safe integer range\n * - Component IDs: 1-1023\n * - Entity IDs: 1024+\n * - Relation IDs: negative numbers encoding component and entity associations\n */\nexport type EntityId<T = unknown, U = unknown> = number & {\n readonly [__componentTypeMarker]: T;\n readonly [__entityIdTypeTag]: U;\n};\n\nexport type ComponentId<T = void> = EntityId<T, \"component\">;\nexport type EntityRelationId<T = void> = EntityId<T, \"entity-relation\">;\nexport type ComponentRelationId<T = void> = EntityId<T, \"component-relation\">;\nexport type WildcardRelationId<T = void> = EntityId<T, \"wildcard-relation\">;\nexport type RelationId<T = void> = EntityRelationId<T> | ComponentRelationId<T> | WildcardRelationId<T>;\n\n/**\n * Constants for ID ranges\n */\nexport const INVALID_COMPONENT_ID = 0;\nexport const COMPONENT_ID_MAX = 1023;\nexport const ENTITY_ID_START = 1024;\n\n/**\n * Constants for relation ID encoding\n */\nexport const RELATION_SHIFT = 2 ** 42;\nexport const WILDCARD_TARGET_ID = 0;\n\n/**\n * Check if a component ID is valid (1-1023)\n */\nexport function isValidComponentId(componentId: number): boolean {\n return componentId >= 1 && componentId <= COMPONENT_ID_MAX;\n}\n\n/**\n * Check if an ID is a component ID\n */\nexport function isComponentId<T>(id: EntityId<T>): id is ComponentId<T> {\n return id >= 1 && id <= COMPONENT_ID_MAX;\n}\n\n/**\n * Check if an ID is an entity ID\n */\nexport function isEntityId<T>(id: EntityId<T>): id is EntityId<T> {\n return id >= ENTITY_ID_START;\n}\n\n/**\n * Check if an ID is a relation ID\n */\nexport function isRelationId<T>(id: EntityId<T>): id is RelationId<T> {\n return id < 0;\n}\n\n/**\n * Create a component ID\n * @param id Component identifier (1-1023)\n * @internal This function is for internal use and testing only. Use `component()` to create components.\n * @see component\n */\nexport function createComponentId<T = void>(id: number): ComponentId<T> {\n if (id < 1 || id > COMPONENT_ID_MAX) {\n throw new Error(`Component ID must be between 1 and ${COMPONENT_ID_MAX}`);\n }\n return id as ComponentId<T>;\n}\n\n/**\n * Create an entity ID\n * @param id Entity identifier (starting from 1024)\n */\nexport function createEntityId(id: number): EntityId {\n if (id < ENTITY_ID_START) {\n throw new Error(`Entity ID must be ${ENTITY_ID_START} or greater`);\n }\n return id as EntityId;\n}\n","import type {\n ComponentId,\n ComponentRelationId,\n EntityId,\n EntityRelationId,\n RelationId,\n WildcardRelationId,\n} from \"./entity-types\";\nimport {\n ENTITY_ID_START,\n isComponentId,\n isEntityId,\n isValidComponentId,\n RELATION_SHIFT,\n WILDCARD_TARGET_ID,\n} from \"./entity-types\";\n\n/**\n * Internal function to decode a relation ID into raw component and target IDs\n * @param id The EntityId to decode\n * @returns Object with componentId and targetId, or null if not a relation\n */\nexport function decodeRelationRaw(id: EntityId<any>): { componentId: number; targetId: number } | null {\n if (id >= 0) return null;\n const absId = -id;\n const componentId = Math.floor(absId / RELATION_SHIFT);\n const targetId = absId % RELATION_SHIFT;\n return { componentId, targetId };\n}\n\n/**\n * Type for relation ID based on component and target types\n */\ntype RelationIdType<T, R> =\n R extends ComponentId<infer U>\n ? U extends void\n ? ComponentRelationId<T>\n : ComponentRelationId<T extends void ? U : T>\n : R extends EntityId<any>\n ? EntityRelationId<T>\n : never;\n\n/**\n * Create a relation ID by associating a component with another ID (entity or component)\n * @param componentId The component ID (0-1023)\n * @param targetId The target ID (entity, component, or '*' for wildcard)\n */\nexport function relation<T>(componentId: ComponentId<T>, targetId: \"*\"): WildcardRelationId<T>;\nexport function relation<T, R extends EntityId<any>>(componentId: ComponentId<T>, targetId: R): RelationIdType<T, R>;\nexport function relation<T>(componentId: ComponentId<T>, targetId: EntityId<any> | \"*\"): EntityId<any> {\n if (!isComponentId(componentId)) {\n throw new Error(\"First argument must be a valid component ID\");\n }\n\n let actualTargetId: number;\n if (targetId === \"*\") {\n actualTargetId = WILDCARD_TARGET_ID;\n } else {\n if (!isEntityId(targetId) && !isComponentId(targetId)) {\n throw new Error(\"Second argument must be a valid entity ID, component ID, or '*'\");\n }\n actualTargetId = targetId;\n }\n\n // Encode: negative number with component_id * 2^42 + target_id\n return -(componentId * RELATION_SHIFT + actualTargetId) as EntityId<any>;\n}\n\n/**\n * Check if an ID is a wildcard relation id\n */\nexport function isWildcardRelationId<T>(id: EntityId<T>): id is WildcardRelationId<T> {\n const decoded = decodeRelationRaw(id);\n return decoded !== null && decoded.targetId === WILDCARD_TARGET_ID;\n}\n\n/**\n * Decode a relation ID into component and target IDs\n * @param relationId The relation ID (must be negative)\n * @returns Object with componentId, targetId, and relation type\n */\nexport function decodeRelationId(relationId: RelationId<any>): {\n componentId: ComponentId<any>;\n targetId: EntityId<any>;\n type: \"entity\" | \"component\" | \"wildcard\";\n} {\n const decoded = decodeRelationRaw(relationId);\n if (decoded === null) {\n throw new Error(\"ID is not a relation ID\");\n }\n\n const { componentId: rawComponentId, targetId: rawTargetId } = decoded;\n if (!isValidComponentId(rawComponentId)) {\n throw new Error(\"Invalid component ID in relation\");\n }\n\n const componentId = rawComponentId as ComponentId<any>;\n const targetId = rawTargetId as EntityId<any>;\n\n // Determine type based on targetId range\n if (targetId === WILDCARD_TARGET_ID) {\n return { componentId, targetId, type: \"wildcard\" };\n } else if (isEntityId(targetId)) {\n return { componentId, targetId, type: \"entity\" };\n } else if (isComponentId(targetId)) {\n return { componentId, targetId, type: \"component\" };\n } else {\n throw new Error(\"Invalid target ID in relation\");\n }\n}\n\n/**\n * Get the string representation of an ID type\n */\nexport function getIdType(\n id: EntityId<any>,\n): \"component\" | \"entity\" | \"entity-relation\" | \"component-relation\" | \"wildcard-relation\" | \"invalid\" {\n if (isComponentId(id)) return \"component\";\n if (isEntityId(id)) return \"entity\";\n\n if (id < 0) {\n try {\n const decoded = decodeRelationId(id as RelationId<any>);\n // Validate that componentId and targetId are valid (decodeRelationId already checks componentId)\n if (decoded.type !== \"wildcard\" && !isEntityId(decoded.targetId) && !isComponentId(decoded.targetId)) {\n return \"invalid\";\n }\n switch (decoded.type) {\n case \"entity\":\n return \"entity-relation\";\n case \"component\":\n return \"component-relation\";\n case \"wildcard\":\n return \"wildcard-relation\";\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (_error) {\n return \"invalid\"; // fallback for invalid relation IDs\n }\n }\n\n return \"invalid\"; // fallback for unknown/invalid IDs\n}\n\n/**\n * Get detailed type information for an EntityId\n * @param id The EntityId to analyze\n * @returns Detailed type information including relation subtypes\n */\nexport function getDetailedIdType(id: EntityId<any>):\n | {\n type: \"component\" | \"entity\" | \"invalid\";\n componentId?: never;\n targetId?: never;\n }\n | {\n type: \"entity-relation\" | \"wildcard-relation\";\n componentId: ComponentId<any>;\n targetId: EntityId<any>;\n }\n | {\n type: \"component-relation\";\n componentId: ComponentId<any>;\n targetId: ComponentId<any>;\n } {\n if (isComponentId(id)) {\n return { type: \"component\" };\n }\n\n if (isEntityId(id)) {\n return { type: \"entity\" };\n }\n\n if (id < 0) {\n try {\n const decoded = decodeRelationId(id as RelationId<any>);\n // Validate that targetId is valid (decodeRelationId already checks componentId)\n if (decoded.type !== \"wildcard\" && !isEntityId(decoded.targetId) && !isComponentId(decoded.targetId)) {\n return { type: \"invalid\" };\n }\n let type: \"entity-relation\" | \"component-relation\" | \"wildcard-relation\";\n\n switch (decoded.type) {\n case \"entity\":\n type = \"entity-relation\";\n break;\n case \"component\":\n type = \"component-relation\";\n break;\n case \"wildcard\":\n type = \"wildcard-relation\";\n break;\n }\n\n return {\n type,\n componentId: decoded.componentId,\n targetId: decoded.targetId as any,\n };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (_error) {\n // Invalid relation ID\n return { type: \"invalid\" };\n }\n }\n\n // Unknown/invalid ID\n return { type: \"invalid\" };\n}\n\n/**\n * Inspect an EntityId and return a human-readable string representation\n * @param id The EntityId to inspect\n * @returns A friendly string representation of the ID\n */\nexport function inspectEntityId(id: EntityId<any>): string {\n if (id === 0) {\n return \"Invalid Component ID (0)\";\n }\n\n if (isComponentId(id)) {\n return `Component ID (${id})`;\n }\n\n if (isEntityId(id)) {\n return `Entity ID (${id})`;\n }\n\n if (id < 0) {\n try {\n const decoded = decodeRelationId(id as RelationId<any>);\n // Validate that targetId is valid (decodeRelationId already checks componentId)\n if (decoded.type !== \"wildcard\" && !isEntityId(decoded.targetId) && !isComponentId(decoded.targetId)) {\n return `Invalid Relation ID (${id})`;\n }\n const componentStr = `Component ID (${decoded.componentId})`;\n const targetStr =\n decoded.type === \"entity\"\n ? `Entity ID (${decoded.targetId})`\n : decoded.type === \"component\"\n ? `Component ID (${decoded.targetId})`\n : \"Wildcard (*)\";\n return `Relation ID: ${componentStr} -> ${targetStr}`;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (_error) {\n return `Invalid Relation ID (${id})`;\n }\n }\n\n return `Unknown ID (${id})`;\n}\n\n/**\n * Get the componentId from a relation ID without fully decoding the relation.\n * Returns undefined for non-relation IDs or invalid component IDs.\n */\nexport function getComponentIdFromRelationId<T>(id: EntityId<T>): ComponentId<T> | undefined {\n const decoded = decodeRelationRaw(id);\n if (decoded === null || !isValidComponentId(decoded.componentId)) return undefined;\n return decoded.componentId as ComponentId<T>;\n}\n\n/**\n * Get the targetId from a relation ID without fully decoding the relation.\n * Returns undefined for non-relation IDs.\n */\nexport function getTargetIdFromRelationId(id: EntityId<any>): EntityId<any> | undefined {\n const decoded = decodeRelationRaw(id);\n return decoded?.targetId as EntityId<any>;\n}\n\n/**\n * Check if an ID is an entity-relation (relation targeting an entity, not a component or wildcard)\n */\nexport function isEntityRelation(id: EntityId<any>): boolean {\n const decoded = decodeRelationRaw(id);\n return decoded !== null && decoded.targetId >= ENTITY_ID_START;\n}\n\n/**\n * Check if an ID is a component-relation (relation targeting a component)\n */\nexport function isComponentRelation(id: EntityId<any>): boolean {\n const decoded = decodeRelationRaw(id);\n return decoded !== null && isValidComponentId(decoded.targetId);\n}\n\n/**\n * Check if an ID is any type of relation (entity, component, or wildcard)\n */\nexport function isAnyRelation(id: EntityId<any>): boolean {\n return id < 0;\n}\n","import type { ComponentId, EntityId } from \"./entity-types\";\nimport { COMPONENT_ID_MAX, ENTITY_ID_START, isEntityId } from \"./entity-types\";\n\n/**\n * Entity ID Manager for automatic allocation and freelist recycling\n */\nexport class EntityIdManager {\n private nextId: number = ENTITY_ID_START;\n private freelist: Set<EntityId> = new Set();\n\n /**\n * Allocate a new entity ID\n * Uses freelist if available, otherwise increments counter\n */\n allocate(): EntityId {\n if (this.freelist.size > 0) {\n const id = this.freelist.values().next().value!;\n this.freelist.delete(id);\n return id;\n } else {\n const id = this.nextId;\n this.nextId++;\n // Check for overflow (though unlikely in practice)\n if (this.nextId >= Number.MAX_SAFE_INTEGER) {\n throw new Error(\"Entity ID overflow: reached maximum safe integer\");\n }\n return id as EntityId;\n }\n }\n\n /**\n * Deallocate an entity ID, adding it to the freelist for reuse\n * @param id The entity ID to deallocate\n */\n deallocate(id: EntityId<any>): void {\n if (!isEntityId(id)) {\n throw new Error(\"Can only deallocate valid entity IDs\");\n }\n if (id >= this.nextId) {\n throw new Error(\"Cannot deallocate an ID that was never allocated\");\n }\n this.freelist.add(id);\n }\n\n /**\n * Get the current freelist size (for debugging/monitoring)\n */\n getFreelistSize(): number {\n return this.freelist.size;\n }\n\n /**\n * Get the next ID that would be allocated (for debugging)\n */\n getNextId(): number {\n return this.nextId;\n }\n\n /**\n * Serialize internal state for persistence.\n * Returns a plain object representing allocator state. Values may be non-JSON-serializable.\n */\n serializeState(): { nextId: number; freelist: number[] } {\n return { nextId: this.nextId, freelist: Array.from(this.freelist) };\n }\n\n /**\n * Restore internal state from a previously-serialized object.\n * Overwrites the current nextId and freelist.\n */\n deserializeState(state: { nextId: number; freelist?: number[] }): void {\n if (typeof state.nextId !== \"number\") {\n throw new Error(\"Invalid state for EntityIdManager.deserializeState\");\n }\n this.nextId = state.nextId;\n this.freelist = new Set((state.freelist || []) as EntityId[]);\n }\n}\n\n/**\n * Component ID Manager for automatic allocation\n * Components are typically registered once and not recycled\n */\nexport class ComponentIdAllocator {\n private nextId: number = 1;\n\n /**\n * Allocate a new component ID\n * Increments counter sequentially from 1\n */\n allocate<T = void>(): ComponentId<T> {\n if (this.nextId > COMPONENT_ID_MAX) {\n throw new Error(`Component ID overflow: maximum ${COMPONENT_ID_MAX} components allowed`);\n }\n const id = this.nextId;\n this.nextId++;\n return id as ComponentId<T>;\n }\n\n /**\n * Get the next ID that would be allocated (for debugging)\n */\n getNextId(): number {\n return this.nextId;\n }\n\n /**\n * Check if more component IDs are available\n */\n hasAvailableIds(): boolean {\n return this.nextId <= COMPONENT_ID_MAX;\n }\n}\n","export class BitSet {\n private data: Uint32Array;\n private _length: number;\n\n constructor(length: number) {\n this._length = length;\n const numWords = Math.ceil(length / 32);\n this.data = new Uint32Array(numWords);\n }\n\n get length(): number {\n return this._length;\n }\n\n has(index: number): boolean {\n if (index < 0 || index >= this._length) return false;\n const word = index >>> 5; // divide by 32\n const bit = index & 31;\n return ((this.data[word]! >>> bit) & 1) !== 0;\n }\n\n set(index: number): void {\n if (index < 0 || index >= this._length) return;\n const word = index >>> 5;\n const bit = index & 31;\n this.data[word]! |= 1 << bit;\n }\n\n clear(index: number): void {\n if (index < 0 || index >= this._length) return;\n const word = index >>> 5;\n const bit = index & 31;\n this.data[word]! &= ~(1 << bit);\n }\n\n // set a range [lo, hi] inclusive to 1\n setRange(lo: number, hi: number): void {\n if (lo > hi) return;\n if (lo < 0) lo = 0;\n if (hi >= this._length) hi = this._length - 1;\n\n const firstWord = lo >>> 5;\n const lastWord = hi >>> 5;\n const loBit = lo & 31;\n const hiBit = hi & 31;\n\n // helper to produce mask for [a..b] within a single 32-bit word\n const maskFor = (a: number, b: number) => {\n const width = b - a + 1;\n if (width <= 0) return 0 >>> 0;\n if (width >= 32) return 0xffffffff >>> 0;\n return (((1 << width) - 1) << a) >>> 0;\n };\n\n if (firstWord === lastWord) {\n const mask = maskFor(loBit, hiBit);\n this.data[firstWord]! = (this.data[firstWord]! | mask) >>> 0;\n return;\n }\n\n // first partial word\n const firstMask = maskFor(loBit, 31);\n this.data[firstWord]! = (this.data[firstWord]! | firstMask) >>> 0;\n\n // middle full words\n for (let w = firstWord + 1; w <= lastWord - 1; w++) {\n this.data[w] = 0xffffffff >>> 0;\n }\n\n // last partial word\n const lastMask = maskFor(0, hiBit);\n this.data[lastWord]! = (this.data[lastWord]! | lastMask) >>> 0;\n }\n\n // check whether any bit in [lo, hi] is zero (i.e. not set)\n anyClearInRange(lo: number, hi: number): boolean {\n if (lo > hi) return false;\n if (lo < 0) lo = 0;\n if (hi >= this._length) hi = this._length - 1;\n\n const firstWord = lo >>> 5;\n const lastWord = hi >>> 5;\n const loBit = lo & 31;\n const hiBit = hi & 31;\n\n const maskFor = (a: number, b: number) => {\n const width = b - a + 1;\n if (width <= 0) return 0 >>> 0;\n if (width >= 32) return 0xffffffff >>> 0;\n return (((1 << width) - 1) << a) >>> 0;\n };\n\n if (firstWord === lastWord) {\n const mask = maskFor(loBit, hiBit);\n const bits = (this.data[firstWord]! & mask) >>> 0;\n return bits !== mask >>> 0;\n }\n\n // first partial word: if any bit in the mask is clear -> return true\n const firstMask = maskFor(loBit, 31);\n if ((this.data[firstWord]! & firstMask) >>> 0 !== firstMask >>> 0) return true;\n\n // middle full words\n for (let w = firstWord + 1; w <= lastWord - 1; w++) {\n if (this.data[w] !== 0xffffffff >>> 0) return true;\n }\n\n // last partial word\n const lastMask = maskFor(0, hiBit);\n if ((this.data[lastWord]! & lastMask) >>> 0 !== lastMask >>> 0) return true;\n\n return false;\n }\n\n // reset all bits to zero\n reset(): void {\n this.data.fill(0);\n }\n\n *[Symbol.iterator](): IterableIterator<number> {\n for (let wordIndex = 0; wordIndex < this.data.length; wordIndex++) {\n let word = this.data[wordIndex]!;\n if (word === 0) continue;\n const baseIndex = wordIndex * 32;\n for (let bit = 0; bit < 32 && baseIndex + bit < this._length; bit++) {\n if (word & 1) {\n yield baseIndex + bit;\n }\n word >>>= 1;\n }\n }\n }\n}\n","import { BitSet } from \"../utils/bit-set\";\nimport { ComponentIdAllocator } from \"./entity-manager\";\nimport { decodeRelationRaw } from \"./entity-relation\";\nimport type { ComponentId, EntityId } from \"./entity-types\";\nimport {\n COMPONENT_ID_MAX,\n ENTITY_ID_START,\n isComponentId,\n isValidComponentId,\n WILDCARD_TARGET_ID,\n} from \"./entity-types\";\n\nconst globalComponentIdAllocator = new ComponentIdAllocator();\n\nconst ComponentIdForNames: Map<string, ComponentId<any>> = new Map();\n\n/**\n * Component options that define intrinsic properties\n */\nexport interface ComponentOptions {\n /**\n * Optional name for the component (for serialization/debugging)\n */\n name?: string;\n /**\n * If true, an entity can have at most one relation per base component.\n * When adding a new relation with the same base component, any existing relations\n * with that base component are automatically removed.\n * Only applicable to relation components.\n */\n exclusive?: boolean;\n /**\n * If true, when a relation target entity is deleted, all entities that reference\n * it through this component will also be deleted (cascade delete).\n * Only applicable to entity-relation components.\n */\n cascadeDelete?: boolean;\n /**\n * If true, relations with this component will not cause archetype fragmentation.\n * Entities with different target entities for this relation component will be stored\n * in the same archetype, preventing fragmentation when there are many different targets.\n * Only applicable to relation components.\n * Inspired by Flecs' DontFragment trait.\n */\n dontFragment?: boolean;\n}\n\n// Array for component names (Component ID range: 1-1023)\nconst componentNames: (string | undefined)[] = new Array(COMPONENT_ID_MAX + 1);\n\n// BitSets for fast component option checks (Component ID range: 1-1023)\nconst exclusiveFlags = new BitSet(COMPONENT_ID_MAX + 1);\nconst cascadeDeleteFlags = new BitSet(COMPONENT_ID_MAX + 1);\nconst dontFragmentFlags = new BitSet(COMPONENT_ID_MAX + 1);\n\n/**\n * Allocate a new component ID from the global allocator.\n * @param nameOrOptions Optional name for the component (for serialization/debugging) or options object\n * @returns The allocated component ID\n * @example\n * // Just a name\n * const Position = component<Position>(\"Position\");\n *\n * // With options\n * const ChildOf = component({ exclusive: true, cascadeDelete: true });\n *\n * // With name and options\n * const ChildOf = component({ name: \"ChildOf\", exclusive: true });\n */\nexport function component<T = void>(nameOrOptions?: string | ComponentOptions): ComponentId<T> {\n const id = globalComponentIdAllocator.allocate<T>();\n\n let name: string | undefined;\n let options: ComponentOptions | undefined;\n\n // Parse the parameter\n if (typeof nameOrOptions === \"string\") {\n name = nameOrOptions;\n } else if (typeof nameOrOptions === \"object\" && nameOrOptions !== null) {\n options = nameOrOptions;\n name = options.name;\n }\n\n // Register name if provided\n if (name) {\n if (ComponentIdForNames.has(name)) {\n throw new Error(`Component name \"${name}\" is already registered`);\n }\n\n componentNames[id] = name;\n ComponentIdForNames.set(name, id);\n }\n\n // Register options if provided\n if (options) {\n // Set bitset flags for fast lookup\n if (options.exclusive) exclusiveFlags.set(id);\n if (options.cascadeDelete) cascadeDeleteFlags.set(id);\n if (options.dontFragment) dontFragmentFlags.set(id);\n }\n\n return id;\n}\n\n/**\n * Get a component ID by its registered name\n * @param name The component name\n * @returns The component ID if found, undefined otherwise\n */\nexport function getComponentIdByName(name: string): ComponentId<any> | undefined {\n return ComponentIdForNames.get(name);\n}\n\n/** Get a component name by its ID\n * @param id The component ID\n * @returns The component name if found, undefined otherwise\n */\nexport function getComponentNameById(id: ComponentId<any>): string | undefined {\n return componentNames[id];\n}\n\n/**\n * Get component options by its ID\n * @param id The component ID\n * @returns The component options\n */\nexport function getComponentOptions(id: ComponentId<any>): ComponentOptions {\n if (!isComponentId(id)) {\n throw new Error(\"Invalid component ID\");\n }\n const hasName = componentNames[id] !== undefined;\n const hasExclusive = exclusiveFlags.has(id);\n const hasCascadeDelete = cascadeDeleteFlags.has(id);\n const hasDontFragment = dontFragmentFlags.has(id);\n return {\n name: hasName ? componentNames[id] : undefined,\n exclusive: hasExclusive ? true : undefined,\n cascadeDelete: hasCascadeDelete ? true : undefined,\n dontFragment: hasDontFragment ? true : undefined,\n };\n}\n\n/**\n * Check if a component is marked as exclusive\n * @param id The component ID\n * @returns true if the component is exclusive, false otherwise\n */\nexport function isExclusiveComponent(id: ComponentId<any>): boolean {\n return exclusiveFlags.has(id);\n}\n\n/**\n * Check if a component is marked as cascade delete\n * @param id The component ID\n * @returns true if the component is cascade delete, false otherwise\n */\nexport function isCascadeDeleteComponent(id: ComponentId<any>): boolean {\n return cascadeDeleteFlags.has(id);\n}\n\n/**\n * Check if a component is marked as dontFragment\n * @param id The component ID\n * @returns true if the component is dontFragment, false otherwise\n */\nexport function isDontFragmentComponent(id: ComponentId<any>): boolean {\n return dontFragmentFlags.has(id);\n}\n\n/**\n * Generic function to check relation flags with specific target conditions\n * @param id The entity/relation ID to check\n * @param flagBitSet The bitset for the flag\n * @param targetCondition Function to check target ID condition\n * @returns true if the condition is met, false otherwise\n */\nfunction checkRelationFlag(\n id: EntityId<any>,\n flagBitSet: BitSet,\n targetCondition: (targetId: number) => boolean,\n): boolean {\n const decoded = decodeRelationRaw(id);\n if (decoded === null) return false;\n const { componentId, targetId } = decoded;\n return isValidComponentId(componentId) && targetCondition(targetId) && flagBitSet.has(componentId);\n}\n\n/**\n * Check if a relation ID is a dontFragment relation (entity-relation or component-relation with dontFragment component)\n * This is an optimized function that avoids the overhead of getDetailedIdType\n * @param id The entity/relation ID to check\n * @returns true if this is a dontFragment relation, false otherwise\n */\nexport function isDontFragmentRelation(id: EntityId<any>): boolean {\n return checkRelationFlag(id, dontFragmentFlags, (targetId) => targetId !== WILDCARD_TARGET_ID);\n}\n\n/**\n * Check if an ID is a wildcard relation with dontFragment component\n * This is an optimized function for filtering archetype component types\n * @param id The entity/relation ID to check\n * @returns true if this is a wildcard relation with dontFragment component, false otherwise\n */\nexport function isDontFragmentWildcard(id: EntityId<any>): boolean {\n return checkRelationFlag(id, dontFragmentFlags, (targetId) => targetId === WILDCARD_TARGET_ID);\n}\n\n/**\n * Check if a relation ID is an exclusive relation (entity-relation or component-relation with exclusive component)\n * This avoids the full getDetailedIdType overhead for hot paths\n * @param id The entity/relation ID to check\n * @returns true if this is an exclusive relation, false otherwise\n */\nexport function isExclusiveRelation(id: EntityId<any>): boolean {\n return checkRelationFlag(id, exclusiveFlags, (targetId) => targetId !== WILDCARD_TARGET_ID);\n}\n\n/**\n * Check if a relation ID is a wildcard relation with exclusive component\n */\nexport function isExclusiveWildcard(id: EntityId<any>): boolean {\n return checkRelationFlag(id, exclusiveFlags, (targetId) => targetId === WILDCARD_TARGET_ID);\n}\n\n/**\n * Check if a relation ID is a cascade delete entity-relation\n * This is an optimized function that avoids the overhead of getDetailedIdType\n * Note: Cascade delete only applies to entity-relations (not component-relations or wildcards)\n * @param id The entity/relation ID to check\n * @returns true if this is an entity-relation with cascade delete, false otherwise\n */\nexport function isCascadeDeleteRelation(id: EntityId<any>): boolean {\n return checkRelationFlag(\n id,\n cascadeDeleteFlags,\n (targetId) => targetId !== WILDCARD_TARGET_ID && targetId >= ENTITY_ID_START,\n );\n}\n","import type { ComponentId, EntityId } from \"./entity\";\nimport { relation } from \"./entity\";\nimport type { World } from \"./world\";\n\n// =============================================================================\n// EntityBuilder - Fluent Entity Creation (moved from testing utilities)\n// =============================================================================\n\n/**\n * A component definition for entity building, supporting both regular components and relations\n */\nexport type ComponentDef<T = unknown> =\n | { type: \"component\"; id: EntityId<T>; value: T }\n | { type: \"relation\"; componentId: ComponentId<T>; targetId: EntityId<any>; value: T };\n\nexport class EntityBuilder {\n private world: World;\n private components: ComponentDef[] = [];\n\n constructor(world: World) {\n this.world = world;\n }\n\n with<T>(componentId: EntityId<T>, value: T): this {\n this.components.push({ type: \"component\", id: componentId, value });\n return this;\n }\n\n withTag(componentId: EntityId<void>): this {\n this.components.push({ type: \"component\", id: componentId, value: undefined as void });\n return this;\n }\n\n withRelation<T>(componentId: ComponentId<T>, targetEntity: EntityId<any>, value: T): this {\n this.components.push({ type: \"relation\", componentId, targetId: targetEntity, value });\n return this;\n }\n\n withRelationTag(componentId: ComponentId<void>, targetEntity: EntityId<any>): this {\n this.components.push({ type: \"relation\", componentId, targetId: targetEntity, value: undefined as void });\n return this;\n }\n\n /**\n * Create an entity and enqueue components to be applied. This method\n * does NOT call `world.sync()` automatically; callers must invoke\n * `world.sync()` to apply deferred commands.\n * (Previously auto-synced; now a breaking change — buildDeferred() removed.)\n */\n build(): EntityId {\n const entity = this.world.new();\n\n for (const def of this.components) {\n if (def.type === \"component\") {\n this.world.set(entity, def.id, def.value as any);\n } else {\n const relationId = relation(def.componentId, def.targetId);\n this.world.set(entity, relationId, def.value as any);\n }\n }\n\n return entity;\n }\n}\n","import type { EntityId } from \"../core/entity\";\n\n/**\n * @internal Represents a set of component changes to be applied to an entity\n */\nexport class ComponentChangeset {\n readonly adds = new Map<EntityId<any>, any>();\n readonly removes = new Set<EntityId<any>>();\n\n /**\n * Add a component to the changeset\n */\n set<T>(componentType: EntityId<T>, component: T): void {\n this.adds.set(componentType, component);\n this.removes.delete(componentType); // Remove from removes if it was going to be removed\n }\n\n /**\n * Remove a component from the changeset\n */\n delete<T>(componentType: EntityId<T>): void {\n this.removes.add(componentType);\n this.adds.delete(componentType); // Remove from adds if it was going to be added\n }\n\n /**\n * Check if the changeset has any changes\n */\n hasChanges(): boolean {\n return this.adds.size > 0 || this.removes.size > 0;\n }\n\n /**\n * Clear all changes\n */\n clear(): void {\n this.adds.clear();\n this.removes.clear();\n }\n\n /**\n * Merge another changeset into this one\n */\n merge(other: ComponentChangeset): void {\n // Merge additions\n for (const [componentType, component] of other.adds) {\n this.adds.set(componentType, component);\n this.removes.delete(componentType);\n }\n // Merge removals\n for (const componentType of other.removes) {\n this.removes.add(componentType);\n this.adds.delete(componentType);\n }\n }\n\n /**\n * Apply the changeset to existing components and return the final state\n */\n applyTo(existingComponents: Map<EntityId<any>, any>): Map<EntityId<any>, any> {\n // Apply removals\n for (const componentType of this.removes) {\n existingComponents.delete(componentType);\n }\n\n // Apply additions/updates\n for (const [componentType, component] of this.adds) {\n existingComponents.set(componentType, component);\n }\n\n return existingComponents;\n }\n\n /**\n * Get the final component types after applying the changeset\n * @param existingComponentTypes - The current component types on the entity\n * @returns The final component types or undefined if no changes\n */\n getFinalComponentTypes(existingComponentTypes: EntityId<any>[]): EntityId<any>[] | undefined {\n const finalComponentTypes = new Set<EntityId<any>>(existingComponentTypes);\n let changed = false;\n\n // Apply removals\n for (const componentType of this.removes) {\n if (!finalComponentTypes.has(componentType)) {\n this.removes.delete(componentType);\n continue; // Component not present, skip\n }\n changed = true;\n finalComponentTypes.delete(componentType);\n }\n\n // Apply additions\n for (const componentType of this.adds.keys()) {\n if (finalComponentTypes.has(componentType)) {\n continue; // Component already present, skip\n }\n changed = true;\n finalComponentTypes.add(componentType);\n }\n\n return changed ? Array.from(finalComponentTypes) : undefined;\n }\n}\n","import type { EntityId } from \"../core/entity\";\n\n/**\n * Command for deferred execution\n */\nexport interface Command {\n type: \"set\" | \"delete\" | \"destroy\";\n entityId: EntityId;\n componentType?: EntityId<any>;\n component?: any;\n}\n\n/**\n * Command buffer for deferred structural changes\n */\nexport class CommandBuffer {\n private commands: Command[] = [];\n private executeEntityCommands: (entityId: EntityId, commands: Command[]) => void;\n\n /**\n * Create a command buffer with an executor function\n */\n constructor(executeEntityCommands: (entityId: EntityId, commands: Command[]) => void) {\n this.executeEntityCommands = executeEntityCommands;\n }\n\n /**\n * Add a component to an entity (deferred)\n */\n set(entityId: EntityId, componentType: EntityId<void>): void;\n set<T>(entityId: EntityId, componentType: EntityId<T>, component: NoInfer<T>): void;\n set(entityId: EntityId, componentType: EntityId, component?: any): void {\n this.commands.push({ type: \"set\", entityId, componentType, component });\n }\n\n /**\n * Remove a component from an entity (deferred)\n */\n remove<T>(entityId: EntityId, componentType: EntityId<T>): void {\n this.commands.push({ type: \"delete\", entityId, componentType });\n }\n\n /**\n * Destroy an entity (deferred)\n */\n delete(entityId: EntityId): void {\n this.commands.push({ type: \"destroy\", entityId });\n }\n\n /**\n * Execute all commands and clear the buffer\n */\n execute(): void {\n const MAX_ITERATIONS = 100;\n let iterations = 0;\n\n while (this.commands.length > 0) {\n if (iterations >= MAX_ITERATIONS) {\n throw new Error(\"Command execution exceeded maximum iterations, possible infinite loop\");\n }\n iterations++;\n\n const currentCommands = [...this.commands];\n this.commands = [];\n\n // Group commands by entity\n const entityCommands = new Map<EntityId, Command[]>();\n for (const cmd of currentCommands) {\n if (!entityCommands.has(cmd.entityId)) {\n entityCommands.set(cmd.entityId, []);\n }\n entityCommands.get(cmd.entityId)!.push(cmd);\n }\n\n // Process each entity's commands with optimization\n for (const [entityId, commands] of entityCommands) {\n this.executeEntityCommands(entityId, commands);\n }\n }\n }\n\n /**\n * Get current commands (for testing)\n */\n getCommands(): Command[] {\n return [...this.commands];\n }\n\n /**\n * Clear all commands\n */\n clear(): void {\n this.commands = [];\n }\n}\n","import type { Archetype } from \"../core/archetype\";\nimport type { EntityId } from \"../core/entity\";\nimport { getComponentIdFromRelationId, getDetailedIdType, isRelationId } from \"../core/entity\";\n\n/**\n * Filter options for queries\n */\nexport interface QueryFilter {\n negativeComponentTypes?: EntityId<any>[];\n}\n\n/**\n * Serialize a QueryFilter into a deterministic string suitable for cache keys.\n * Currently only serializes `negativeComponentTypes`.\n */\nexport function serializeQueryFilter(filter: QueryFilter = {}): string {\n const negative = (filter.negativeComponentTypes || []).slice().sort((a, b) => a - b);\n if (negative.length === 0) return \"\";\n return `neg:${negative.join(\",\")}`;\n}\n\n/**\n * Check if an archetype matches the given component types\n */\nexport function matchesComponentTypes(archetype: Archetype, componentTypes: EntityId<any>[]): boolean {\n return componentTypes.every((type) => {\n const detailedType = getDetailedIdType(type);\n if (detailedType.type === \"wildcard-relation\") {\n // For wildcard relations, check if archetype contains the component relation\n return archetype.componentTypes.some((archetypeType) => {\n if (!isRelationId(archetypeType)) return false;\n const componentId = getComponentIdFromRelationId(archetypeType);\n return componentId === detailedType.componentId;\n });\n } else {\n // For regular components, check direct inclusion\n return archetype.componentTypes.includes(type);\n }\n });\n}\n\n/**\n * Check if an archetype matches the filter conditions (only filtering logic)\n */\nexport function matchesFilter(archetype: Archetype, filter: QueryFilter): boolean {\n const negativeTypes = filter.negativeComponentTypes || [];\n return negativeTypes.every((type) => {\n const detailedType = getDetailedIdType(type);\n if (detailedType.type === \"wildcard-relation\") {\n // For wildcard relations in negative filter, exclude archetypes that contain ANY relation with the same component\n return !archetype.componentTypes.some((archetypeType) => {\n if (!isRelationId(archetypeType)) return false;\n const componentId = getComponentIdFromRelationId(archetypeType);\n return componentId === detailedType.componentId;\n });\n } else {\n // For regular components, check direct exclusion\n return !archetype.componentTypes.includes(type);\n }\n });\n}\n","import type { Archetype } from \"../core/archetype\";\nimport type { EntityId, WildcardRelationId } from \"../core/entity\";\nimport { getDetailedIdType } from \"../core/entity\";\nimport type { ComponentTuple, ComponentType } from \"../core/types\";\nimport type { World } from \"../core/world\";\nimport { matchesComponentTypes, matchesFilter, type QueryFilter } from \"./filter\";\n\n/**\n * Query class for efficient entity queries with cached archetypes\n */\nexport class Query {\n private world: World;\n private componentTypes: EntityId<any>[];\n private filter: QueryFilter;\n private cachedArchetypes: Archetype[] = [];\n private isDisposed = false;\n /** Cached wildcard component types for faster entity filtering */\n private wildcardTypes: WildcardRelationId<any>[];\n\n constructor(world: World, componentTypes: EntityId<any>[], filter: QueryFilter = {}) {\n this.world = world;\n this.componentTypes = [...componentTypes].sort((a, b) => a - b);\n this.filter = filter;\n // Pre-compute wildcard types once\n this.wildcardTypes = this.componentTypes.filter(\n (ct) => getDetailedIdType(ct).type === \"wildcard-relation\",\n ) as WildcardRelationId<any>[];\n this.updateCache();\n // Register with world for archetype updates\n world._registerQuery(this);\n }\n\n /**\n * Check if query is disposed and throw error if so\n */\n private ensureNotDisposed(): void {\n if (this.isDisposed) {\n throw new Error(\"Query has been disposed\");\n }\n }\n\n /**\n * Get all entities matching the query\n */\n getEntities(): EntityId[] {\n this.ensureNotDisposed();\n\n // Fast path: no wildcard relations\n if (this.wildcardTypes.length === 0) {\n const result: EntityId[] = [];\n for (const archetype of this.cachedArchetypes) {\n result.push(...archetype.getEntities());\n }\n return result;\n }\n\n // Slow path: need to filter entities that actually have wildcard relations\n // This is necessary for dontFragment components where an archetype can contain\n // entities with and without the relation\n const result: EntityId[] = [];\n for (const archetype of this.cachedArchetypes) {\n for (const entity of archetype.getEntities()) {\n if (this.entityHasAllWildcards(archetype, entity)) {\n result.push(entity);\n }\n }\n }\n return result;\n }\n\n /**\n * Check if entity has all required wildcard relations\n */\n private entityHasAllWildcards(archetype: Archetype, entity: EntityId): boolean {\n for (const wildcardType of this.wildcardTypes) {\n const relations = archetype.get(entity, wildcardType);\n if (!relations || relations.length === 0) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Get entities with their component data\n * @param componentTypes Array of component types to retrieve\n * @returns Array of objects with entity and component data\n */\n getEntitiesWithComponents<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n ): Array<{\n entity: EntityId;\n components: ComponentTuple<T>;\n }> {\n this.ensureNotDisposed();\n\n const result: Array<{\n entity: EntityId;\n components: ComponentTuple<T>;\n }> = [];\n\n for (const archetype of this.cachedArchetypes) {\n const entitiesWithData = archetype.getEntitiesWithComponents(componentTypes);\n result.push(...entitiesWithData);\n }\n\n return result;\n }\n\n /**\n * Iterate over entities with their component data\n * @param componentTypes Array of component types to retrieve\n * @param callback Function called for each entity with its components\n */\n forEach<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n callback: (entity: EntityId, ...components: ComponentTuple<T>) => void,\n ): void {\n this.ensureNotDisposed();\n\n for (const archetype of this.cachedArchetypes) {\n archetype.forEachWithComponents(componentTypes, callback);\n }\n }\n\n /**\n * Iterate over entities with their component data (generator)\n * @param componentTypes Array of component types to retrieve\n */\n *iterate<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n ): IterableIterator<[EntityId, ...ComponentTuple<T>]> {\n this.ensureNotDisposed();\n\n for (const archetype of this.cachedArchetypes) {\n yield* archetype.iterateWithComponents(componentTypes);\n }\n }\n\n /**\n * Get component data arrays for all matching entities\n * @param componentType The component type to retrieve\n * @returns Array of component data for all matching entities\n */\n getComponentData<T>(componentType: EntityId<T>): T[] {\n this.ensureNotDisposed();\n\n const result: T[] = [];\n for (const archetype of this.cachedArchetypes) {\n result.push(...archetype.getComponentData(componentType));\n }\n return result;\n }\n\n /**\n * Update the cached archetypes\n * Called when new archetypes are created\n */\n updateCache(): void {\n if (this.isDisposed) return;\n\n this.cachedArchetypes = this.world\n .getMatchingArchetypes(this.componentTypes)\n .filter((archetype: Archetype) => matchesFilter(archetype, this.filter));\n }\n\n /**\n * Check if a new archetype matches this query and add to cache if it does\n */\n checkNewArchetype(archetype: Archetype): void {\n if (this.isDisposed) return;\n if (\n matchesComponentTypes(archetype, this.componentTypes) &&\n matchesFilter(archetype, this.filter) &&\n !this.cachedArchetypes.includes(archetype)\n ) {\n this.cachedArchetypes.push(archetype);\n }\n }\n\n /**\n * Remove an archetype from the cached archetypes\n */\n removeArchetype(archetype: Archetype): void {\n if (this.isDisposed) return;\n const index = this.cachedArchetypes.indexOf(archetype);\n if (index !== -1) {\n this.cachedArchetypes.splice(index, 1);\n }\n }\n\n /**\n * Request disposal of this query.\n * This will decrement the world's reference count for the query.\n * The query will only be fully disposed when the ref count reaches zero.\n */\n dispose(): void {\n // Ask the world to release this query (decrement refcount and fully dispose when zero)\n this.world.releaseQuery(this);\n }\n\n /**\n * Internal full dispose called by World when refCount reaches zero.\n */\n _disposeInternal(): void {\n if (!this.isDisposed) {\n // Unregister from world (remove from notification list)\n this.world._unregisterQuery(this);\n this.cachedArchetypes = [];\n this.isDisposed = true;\n }\n }\n\n /**\n * Symbol.dispose implementation for automatic resource management\n */\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n /**\n * Check if the query has been disposed\n */\n get disposed(): boolean {\n return this.isDisposed;\n }\n}\n","/**\n * Utility functions for ECS library\n */\n\n/**\n * Get a value from cache or compute and cache it if not present\n * @param cache The cache map\n * @param key The cache key\n * @param compute Function to compute the value if not cached\n * @returns The cached or computed value\n */\nexport function getOrComputeCache<K, V>(cache: Map<K, V>, key: K, compute: () => V): V {\n let value = cache.get(key);\n if (value === undefined) {\n value = compute();\n cache.set(key, value);\n }\n return value;\n}\n\n/**\n * Get a value from cache or create and cache it if not present, allowing side effects during creation\n * @param cache The cache map\n * @param key The cache key\n * @param create Function to create the value if not cached (can have side effects)\n * @returns The cached or created value\n */\nexport function getOrCreateWithSideEffect<K, V>(cache: Map<K, V>, key: K, create: () => V): V {\n let value = cache.get(key);\n if (value === undefined) {\n value = create();\n cache.set(key, value);\n }\n return value;\n}\n","import type { EntityId, WildcardRelationId } from \"./entity\";\n\n/**\n * Hook types for component lifecycle events\n */\nexport interface LifecycleHook<T = unknown> {\n /**\n * Called when a component is added to an entity\n */\n on_init?: (entityId: EntityId, componentType: EntityId<T>, component: T) => void;\n /**\n * Called when a component is added to an entity\n */\n on_set?: (entityId: EntityId, componentType: EntityId<T>, component: T) => void;\n /**\n * Called when a component is deleted from an entity\n */\n on_remove?: (entityId: EntityId, componentType: EntityId<T>, component: T) => void;\n}\n\nexport interface MultiLifecycleHook<T extends readonly ComponentType<any>[]> {\n on_init?: (entityId: EntityId, componentTypes: T, components: ComponentTuple<T>) => void;\n on_set?: (entityId: EntityId, componentTypes: T, components: ComponentTuple<T>) => void;\n on_remove?: (entityId: EntityId, componentTypes: T, components: ComponentTuple<T>) => void;\n}\n\nexport type ComponentType<T> = EntityId<T> | OptionalEntityId<T>;\n\nexport type OptionalEntityId<T> = { optional: EntityId<T> };\n\nexport function isOptionalEntityId<T>(type: ComponentType<T>): type is OptionalEntityId<T> {\n return typeof type === \"object\" && type !== null && \"optional\" in type;\n}\n\nexport type ComponentTypeToData<T> = T extends { optional: infer U }\n ? { value: ComponentTypeToData<U> } | undefined\n : T extends WildcardRelationId<infer U>\n ? [EntityId<unknown>, U][]\n : T extends EntityId<infer U>\n ? U\n : never;\n\n/**\n * Type helper for component tuples extracted from EntityId array\n */\nexport type ComponentTuple<T extends readonly ComponentType<any>[]> = {\n readonly [K in keyof T]: ComponentTypeToData<T[K]>;\n};\n","import { MISSING_COMPONENT } from \"./archetype\";\nimport type { ComponentId, EntityId, WildcardRelationId } from \"./entity\";\nimport { getComponentIdFromRelationId, getDetailedIdType, getIdType, getTargetIdFromRelationId } from \"./entity\";\nimport { isOptionalEntityId, type ComponentType } from \"./types\";\n\ntype DetailedIdType = ReturnType<typeof getDetailedIdType>;\n\ntype RelationDetailedType =\n | { type: \"entity-relation\"; componentId: ComponentId<any>; targetId: EntityId<any> }\n | { type: \"component-relation\"; componentId: ComponentId<any>; targetId: ComponentId<any> };\n\n/**\n * Check if a detailed type represents a relation (entity or component)\n */\nexport function isRelationType(detailedType: DetailedIdType): detailedType is RelationDetailedType {\n return detailedType.type === \"entity-relation\" || detailedType.type === \"component-relation\";\n}\n\n/**\n * Check if a component type matches a given component ID for relations\n */\nexport function matchesRelationComponentId(componentType: EntityId<any>, componentId: EntityId<any>): boolean {\n const detailedType = getDetailedIdType(componentType);\n return isRelationType(detailedType) && detailedType.componentId === componentId;\n}\n\n/**\n * Find all relations in dontFragment data that match a component ID\n */\nexport function findMatchingDontFragmentRelations(\n dontFragmentData: Map<EntityId<any>, any> | undefined,\n componentId: EntityId<any>,\n): [EntityId<unknown>, any][] {\n const relations: [EntityId<unknown>, any][] = [];\n if (!dontFragmentData) return relations;\n\n for (const [relType, data] of dontFragmentData) {\n const relDetailed = getDetailedIdType(relType);\n if (isRelationType(relDetailed) && relDetailed.componentId === componentId) {\n relations.push([relDetailed.targetId, data]);\n }\n }\n return relations;\n}\n\n/**\n * Build cache key for component types\n */\nexport function buildCacheKey(componentTypes: readonly ComponentType<any>[]): string {\n return componentTypes.map((id) => (isOptionalEntityId(id) ? `opt(${id.optional})` : `${id}`)).join(\",\");\n}\n\n/**\n * Get data source for wildcard relations from component types\n */\nexport function getWildcardRelationDataSource(\n componentTypes: EntityId<any>[],\n componentId: EntityId<any>,\n optional: boolean,\n): EntityId<any>[] | undefined {\n const matchingRelations = componentTypes.filter((ct) => matchesRelationComponentId(ct, componentId));\n return optional ? (matchingRelations.length > 0 ? matchingRelations : undefined) : matchingRelations;\n}\n\n/**\n * Build wildcard relation value from matching relations\n */\nexport function buildWildcardRelationValue(\n wildcardRelationType: WildcardRelationId<any>,\n matchingRelations: EntityId<any>[] | undefined,\n getDataAtIndex: (relType: EntityId<any>) => any,\n dontFragmentData: Map<EntityId<any>, any> | undefined,\n entityId: EntityId,\n optional: boolean,\n): any {\n const relations: [EntityId<unknown>, any][] = [];\n const targetComponentId = getComponentIdFromRelationId(wildcardRelationType);\n\n // Add regular archetype relations\n for (const relType of matchingRelations || []) {\n const data = getDataAtIndex(relType);\n const targetId = getTargetIdFromRelationId(relType)!;\n relations.push([targetId, data === MISSING_COMPONENT ? undefined : data]);\n }\n\n // Add dontFragment relations\n if (targetComponentId !== undefined) {\n relations.push(...findMatchingDontFragmentRelations(dontFragmentData, targetComponentId));\n }\n\n if (relations.length === 0) {\n if (!optional) {\n const componentId = getComponentIdFromRelationId(wildcardRelationType);\n throw new Error(\n `No matching relations found for mandatory wildcard relation component ${componentId} on entity ${entityId}`,\n );\n }\n return undefined;\n }\n\n return optional ? { value: relations } : relations;\n}\n\n/**\n * Build regular component value from data source\n */\nexport function buildRegularComponentValue(dataSource: any[] | undefined, entityIndex: number, optional: boolean): any {\n if (dataSource === undefined) {\n if (optional) return undefined;\n throw new Error(`Component data not found for mandatory component type`);\n }\n\n const data = dataSource[entityIndex];\n const result = data === MISSING_COMPONENT ? undefined : data;\n return optional ? { value: result } : result;\n}\n\n/**\n * Build a single component value based on its type\n */\nexport function buildSingleComponent(\n compType: ComponentType<any>,\n dataSource: any[] | EntityId<any>[] | undefined,\n entityIndex: number,\n entityId: EntityId,\n getComponentData: (type: EntityId<any>) => any[],\n dontFragmentRelations: Map<EntityId, Map<EntityId<any>, any>>,\n): any {\n const optional = isOptionalEntityId(compType);\n const actualType = optional ? compType.optional : compType;\n\n if (getIdType(actualType) === \"wildcard-relation\") {\n return buildWildcardRelationValue(\n actualType as WildcardRelationId<any>,\n dataSource as EntityId<any>[] | undefined,\n (relType) => getComponentData(relType)[entityIndex],\n dontFragmentRelations.get(entityId),\n entityId,\n optional,\n );\n } else {\n return buildRegularComponentValue(dataSource as any[] | undefined, entityIndex, optional);\n }\n}\n","import { getOrComputeCache } from \"../utils/utils\";\nimport {\n buildCacheKey,\n buildSingleComponent,\n findMatchingDontFragmentRelations,\n getWildcardRelationDataSource,\n isRelationType,\n} from \"./archetype-helpers\";\nimport type { EntityId, WildcardRelationId } from \"./entity\";\nimport {\n getComponentIdFromRelationId,\n getDetailedIdType,\n getIdType,\n isDontFragmentComponent,\n isWildcardRelationId,\n} from \"./entity\";\nimport { isOptionalEntityId, type ComponentTuple, type ComponentType } from \"./types\";\n\n/**\n * Special value to represent missing component data\n */\nexport const MISSING_COMPONENT = Symbol(\"missing component\");\n\n/**\n * Archetype class for ECS architecture\n * Represents a group of entities that share the same set of components\n * Optimized for fast iteration and component access\n */\nexport class Archetype {\n /**\n * The component types that define this archetype\n */\n public readonly componentTypes: EntityId<any>[];\n\n /**\n * List of entities in this archetype\n */\n private entities: EntityId[] = [];\n\n /**\n * Component data storage - maps component type to array of component data\n * Each array index corresponds to the entity index in the entities array\n */\n private componentData: Map<EntityId<any>, any[]> = new Map();\n\n /**\n * Reverse mapping from entity to its index in this archetype\n */\n private entityToIndex: Map<EntityId, number> = new Map();\n\n /**\n * Reference to dontFragment relations storage from World\n * This allows entities with different relation targets to share the same archetype\n * Stored in World to avoid migration overhead when entities change archetypes\n */\n private dontFragmentRelations: Map<EntityId, Map<EntityId<any>, any>>;\n\n /**\n * Cache for pre-computed component data sources to avoid repeated calculations\n */\n private componentDataSourcesCache: Map<string, (any[] | EntityId<any>[] | undefined)[]> = new Map();\n\n constructor(componentTypes: EntityId<any>[], dontFragmentRelations: Map<EntityId, Map<EntityId<any>, any>>) {\n this.componentTypes = [...componentTypes].sort((a, b) => a - b);\n this.dontFragmentRelations = dontFragmentRelations;\n\n for (const componentType of this.componentTypes) {\n this.componentData.set(componentType, []);\n }\n }\n\n get size(): number {\n return this.entities.length;\n }\n\n matches(componentTypes: EntityId<any>[]): boolean {\n if (this.componentTypes.length !== componentTypes.length) return false;\n const sortedTypes = [...componentTypes].sort((a, b) => a - b);\n return this.componentTypes.every((type, index) => type === sortedTypes[index]);\n }\n\n addEntity(entityId: EntityId, componentData: Map<EntityId<any>, any>): void {\n if (this.entityToIndex.has(entityId)) {\n throw new Error(`Entity ${entityId} is already in this archetype`);\n }\n\n const index = this.entities.length;\n this.entities.push(entityId);\n this.entityToIndex.set(entityId, index);\n\n // Add component data for regular components\n for (const componentType of this.componentTypes) {\n const data = componentData.get(componentType);\n this.getComponentData(componentType).push(!componentData.has(componentType) ? MISSING_COMPONENT : data);\n }\n\n // Add dontFragment relations separately\n this.addDontFragmentRelations(entityId, componentData);\n }\n\n private addDontFragmentRelations(entityId: EntityId, componentData: Map<EntityId<any>, any>): void {\n const dontFragmentData = new Map<EntityId<any>, any>();\n\n for (const [componentType, data] of componentData) {\n if (this.componentTypes.includes(componentType)) continue;\n\n const detailedType = getDetailedIdType(componentType);\n if (isRelationType(detailedType) && isDontFragmentComponent(detailedType.componentId!)) {\n dontFragmentData.set(componentType, data);\n }\n }\n\n if (dontFragmentData.size > 0) {\n this.dontFragmentRelations.set(entityId, dontFragmentData);\n }\n }\n\n getEntity(entityId: EntityId): Map<EntityId<any>, any> | undefined {\n const index = this.entityToIndex.get(entityId);\n if (index === undefined) return undefined;\n\n const entityData = new Map<EntityId<any>, any>();\n\n // Add regular components\n for (const componentType of this.componentTypes) {\n const data = this.getComponentData(componentType)[index];\n entityData.set(componentType, data === MISSING_COMPONENT ? undefined : data);\n }\n\n // Add dontFragment relations\n const dontFragmentData = this.dontFragmentRelations.get(entityId);\n if (dontFragmentData) {\n for (const [componentType, data] of dontFragmentData) {\n entityData.set(componentType, data);\n }\n }\n\n return entityData;\n }\n\n dump(): Array<{ entity: EntityId; components: Map<EntityId<any>, any> }> {\n return this.entities.map((entity, i) => {\n const components = new Map<EntityId<any>, any>();\n\n for (const componentType of this.componentTypes) {\n const data = this.getComponentData(componentType)[i];\n components.set(componentType, data === MISSING_COMPONENT ? undefined : data);\n }\n\n const dontFragmentData = this.dontFragmentRelations.get(entity);\n if (dontFragmentData) {\n for (const [componentType, data] of dontFragmentData) {\n components.set(componentType, data);\n }\n }\n\n return { entity, components };\n });\n }\n\n removeEntity(entityId: EntityId): Map<EntityId<any>, any> | undefined {\n const index = this.entityToIndex.get(entityId);\n if (index === undefined) return undefined;\n\n // Extract component data before removal\n const removedData = new Map<EntityId<any>, any>();\n for (const componentType of this.componentTypes) {\n removedData.set(componentType, this.getComponentData(componentType)[index]);\n }\n\n // Include dontFragment relations\n const dontFragmentData = this.dontFragmentRelations.get(entityId);\n if (dontFragmentData) {\n for (const [componentType, data] of dontFragmentData) {\n removedData.set(componentType, data);\n }\n this.dontFragmentRelations.delete(entityId);\n }\n\n this.entityToIndex.delete(entityId);\n\n // Swap-and-pop for O(1) removal\n const lastIndex = this.entities.length - 1;\n if (index !== lastIndex) {\n const lastEntity = this.entities[lastIndex]!;\n this.entities[index] = lastEntity;\n this.entityToIndex.set(lastEntity, index);\n\n for (const componentType of this.componentTypes) {\n const dataArray = this.getComponentData(componentType);\n dataArray[index] = dataArray[lastIndex];\n }\n }\n\n this.entities.pop();\n for (const componentType of this.componentTypes) {\n this.getComponentData(componentType).pop();\n }\n\n return removedData;\n }\n\n exists(entityId: EntityId): boolean {\n return this.entityToIndex.has(entityId);\n }\n\n get<T>(entityId: EntityId, componentType: WildcardRelationId<T>): [EntityId<unknown>, any][];\n get<T>(entityId: EntityId, componentType: EntityId<T>): T;\n get<T>(entityId: EntityId, componentType: EntityId<T> | WildcardRelationId<T>): T | [EntityId<unknown>, any][] {\n const index = this.entityToIndex.get(entityId);\n if (index === undefined) {\n throw new Error(`Entity ${entityId} is not in this archetype`);\n }\n\n if (isWildcardRelationId(componentType)) {\n return this.getWildcardRelations(entityId, index, componentType);\n }\n\n return this.getRegularComponent(entityId, index, componentType);\n }\n\n private getWildcardRelations<T>(\n entityId: EntityId,\n index: number,\n componentType: WildcardRelationId<T>,\n ): [EntityId<unknown>, any][] {\n const componentId = getComponentIdFromRelationId(componentType);\n const relations: [EntityId<unknown>, any][] = [];\n\n // Check regular archetype components\n for (const relType of this.componentTypes) {\n const relDetailed = getDetailedIdType(relType);\n if (isRelationType(relDetailed) && relDetailed.componentId === componentId) {\n const dataArray = this.getComponentData(relType);\n if (dataArray && dataArray[index] !== undefined) {\n const data = dataArray[index];\n relations.push([relDetailed.targetId, data === MISSING_COMPONENT ? undefined : data]);\n }\n }\n }\n\n // Check dontFragment relations\n if (componentId !== undefined) {\n relations.push(...findMatchingDontFragmentRelations(this.dontFragmentRelations.get(entityId), componentId));\n }\n\n return relations;\n }\n\n private getRegularComponent<T>(entityId: EntityId, index: number, componentType: EntityId<T>): T {\n if (this.componentTypes.includes(componentType)) {\n const data = this.getComponentData(componentType)[index]!;\n if (data === MISSING_COMPONENT) {\n throw new Error(`Component type ${componentType} not found for entity ${entityId}`);\n }\n return data as T;\n }\n\n const dontFragmentData = this.dontFragmentRelations.get(entityId);\n if (dontFragmentData?.has(componentType)) {\n return dontFragmentData.get(componentType);\n }\n\n throw new Error(`Component type ${componentType} not found for entity ${entityId}`);\n }\n\n getOptional<T>(entityId: EntityId, componentType: EntityId<T>): { value: T } | undefined {\n const index = this.entityToIndex.get(entityId);\n if (index === undefined) {\n throw new Error(`Entity ${entityId} is not in this archetype`);\n }\n\n if (this.componentTypes.includes(componentType)) {\n const data = this.getComponentData(componentType)[index]!;\n if (data === MISSING_COMPONENT) return undefined;\n return { value: data as T };\n }\n\n const dontFragmentData = this.dontFragmentRelations.get(entityId);\n if (dontFragmentData?.has(componentType)) {\n return { value: dontFragmentData.get(componentType) };\n }\n\n return undefined;\n }\n\n set<T>(entityId: EntityId, componentType: EntityId<T>, data: T): void {\n const index = this.entityToIndex.get(entityId);\n if (index === undefined) {\n throw new Error(`Entity ${entityId} is not in this archetype`);\n }\n\n if (this.componentData.has(componentType)) {\n this.getComponentData(componentType)[index] = data;\n return;\n }\n\n const detailedType = getDetailedIdType(componentType);\n if (isRelationType(detailedType) && isDontFragmentComponent(detailedType.componentId!)) {\n let dontFragmentData = this.dontFragmentRelations.get(entityId);\n if (!dontFragmentData) {\n dontFragmentData = new Map();\n this.dontFragmentRelations.set(entityId, dontFragmentData);\n }\n dontFragmentData.set(componentType, data);\n return;\n }\n\n throw new Error(`Component type ${componentType} is not in this archetype`);\n }\n\n getEntities(): EntityId[] {\n return this.entities;\n }\n\n getEntityToIndexMap(): Map<EntityId, number> {\n return this.entityToIndex;\n }\n\n getComponentData<T>(componentType: EntityId<T>): T[] {\n const data = this.componentData.get(componentType);\n if (!data) {\n throw new Error(`Component type ${componentType} is not in this archetype`);\n }\n return data;\n }\n\n getOptionalComponentData<T>(componentType: EntityId<T>): T[] | undefined {\n return this.componentData.get(componentType);\n }\n\n private getCachedComponentDataSources<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n ): (any[] | EntityId<any>[] | undefined)[] {\n const cacheKey = buildCacheKey(componentTypes);\n return getOrComputeCache(this.componentDataSourcesCache, cacheKey, () =>\n componentTypes.map((compType) => this.getComponentDataSource(compType)),\n );\n }\n\n private getComponentDataSource(compType: ComponentType<any>): any[] | EntityId<any>[] | undefined {\n const optional = isOptionalEntityId(compType);\n const actualType = optional ? compType.optional : compType;\n const idType = getIdType(actualType);\n\n if (idType === \"wildcard-relation\") {\n const componentId = getComponentIdFromRelationId(actualType)!;\n return getWildcardRelationDataSource(this.componentTypes, componentId, optional);\n }\n\n return optional ? this.getOptionalComponentData(actualType) : this.getComponentData(actualType);\n }\n\n private buildComponentsForIndex<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n componentDataSources: (any[] | EntityId<any>[] | undefined)[],\n entityIndex: number,\n entityId: EntityId,\n ): ComponentTuple<T> {\n return componentDataSources.map((dataSource, i) =>\n buildSingleComponent(\n componentTypes[i]!,\n dataSource,\n entityIndex,\n entityId,\n (type) => this.getComponentData(type),\n this.dontFragmentRelations,\n ),\n ) as ComponentTuple<T>;\n }\n\n getEntitiesWithComponents<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n ): Array<{ entity: EntityId; components: ComponentTuple<T> }> {\n const result: Array<{ entity: EntityId; components: ComponentTuple<T> }> = [];\n this.forEachWithComponents(componentTypes, (entity, ...components) => {\n result.push({ entity, components });\n });\n return result;\n }\n\n *iterateWithComponents<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n ): IterableIterator<[EntityId, ...ComponentTuple<T>]> {\n const componentDataSources = this.getCachedComponentDataSources(componentTypes);\n\n for (let entityIndex = 0; entityIndex < this.entities.length; entityIndex++) {\n const entity = this.entities[entityIndex]!;\n const components = this.buildComponentsForIndex(componentTypes, componentDataSources, entityIndex, entity);\n yield [entity, ...components];\n }\n }\n\n forEachWithComponents<const T extends readonly ComponentType<any>[]>(\n componentTypes: T,\n callback: (entity: EntityId, ...components: ComponentTuple<T>) => void,\n ): void {\n const componentDataSources = this.getCachedComponentDataSources(componentTypes);\n\n for (let entityIndex = 0; entityIndex < this.entities.length; entityIndex++) {\n const entity = this.entities[entityIndex]!;\n const components = this.buildComponentsForIndex(componentTypes, componentDataSources, entityIndex, entity);\n callback(entity, ...components);\n }\n }\n\n forEach(callback: (entityId: EntityId, components: Map<EntityId<any>, any>) => void): void {\n for (let i = 0; i < this.entities.length; i++) {\n const components = new Map<EntityId<any>, any>();\n for (const componentType of this.componentTypes) {\n const data = this.getComponentData(componentType)[i];\n components.set(componentType, data === MISSING_COMPONENT ? undefined : data);\n }\n callback(this.entities[i]!, components);\n }\n }\n\n hasRelationWithComponentId(componentId: EntityId<any>): boolean {\n // Check regular archetype components\n for (const componentType of this.componentTypes) {\n const detailedType = getDetailedIdType(componentType);\n if (isRelationType(detailedType) && detailedType.componentId === componentId) {\n return true;\n }\n }\n\n // Check dontFragment relations\n for (const entityId of this.entities) {\n const entityDontFragmentRelations = this.dontFragmentRelations.get(entityId);\n if (entityDontFragmentRelations) {\n for (const relationType of entityDontFragmentRelations.keys()) {\n const detailedType = getDetailedIdType(relationType);\n if (isRelationType(detailedType) && detailedType.componentId === componentId) {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n}\n","import type { ComponentId, EntityId } from \"./entity\";\nimport { getComponentIdByName, getComponentNameById, getDetailedIdType, relation } from \"./entity\";\n\n// -----------------------------------------------------------------------------\n// Serialization helpers for IDs\n// -----------------------------------------------------------------------------\n\nexport type SerializedEntityId = number | string | { component: string; target: number | string | \"*\" };\n\nexport type SerializedWorld = {\n version: number;\n entityManager: any;\n entities: SerializedEntity[];\n};\n\nexport type SerializedEntity = {\n id: SerializedEntityId;\n components: SerializedComponent[];\n};\n\nexport type SerializedComponent = {\n type: SerializedEntityId;\n value: any;\n};\n\n/**\n * Encode an internal EntityId into a SerializedEntityId for snapshots\n */\nexport function encodeEntityId(id: EntityId<any>): SerializedEntityId {\n const detailed = getDetailedIdType(id);\n switch (detailed.type) {\n case \"component\": {\n const name = getComponentNameById(id as ComponentId);\n if (!name) {\n // Warn if component doesn't have a name; keep numeric fallback\n console.warn(`Component ID ${id} has no registered name, serializing as number`);\n }\n return name || (id as number);\n }\n case \"entity-relation\": {\n const componentName = getComponentNameById(detailed.componentId);\n if (!componentName) {\n console.warn(`Component ID ${detailed.componentId} in relation has no registered name`);\n }\n return { component: componentName || (detailed.componentId as number).toString(), target: detailed.targetId! };\n }\n case \"component-relation\": {\n const componentName = getComponentNameById(detailed.componentId);\n const targetName = getComponentNameById(detailed.targetId! as ComponentId);\n if (!componentName) {\n console.warn(`Component ID ${detailed.componentId} in relation has no registered name`);\n }\n if (!targetName) {\n console.warn(`Target component ID ${detailed.targetId} in relation has no registered name`);\n }\n return {\n component: componentName || (detailed.componentId as number).toString(),\n target: targetName || (detailed.targetId as number),\n };\n }\n case \"wildcard-relation\": {\n const componentName = getComponentNameById(detailed.componentId);\n if (!componentName) {\n console.warn(`Component ID ${detailed.componentId} in relation has no registered name`);\n }\n return { component: componentName || (detailed.componentId as number).toString(), target: \"*\" };\n }\n default:\n return id as number;\n }\n}\n\n/**\n * Decode a SerializedEntityId back into an internal EntityId\n */\nexport function decodeSerializedId(sid: SerializedEntityId): EntityId<any> {\n if (typeof sid === \"number\") {\n return sid as EntityId<any>;\n }\n if (typeof sid === \"string\") {\n const id = getComponentIdByName(sid);\n if (id === undefined) {\n const num = parseInt(sid, 10);\n if (!isNaN(num)) return num as EntityId<any>;\n throw new Error(`Unknown component name in snapshot: ${sid}`);\n }\n return id;\n }\n if (typeof sid === \"object\" && sid !== null && typeof sid.component === \"string\") {\n let compId = getComponentIdByName(sid.component);\n if (compId === undefined) {\n const num = parseInt(sid.component, 10);\n if (!isNaN(num)) compId = num as ComponentId;\n }\n if (compId === undefined) {\n throw new Error(`Unknown component name in snapshot: ${sid.component}`);\n }\n\n if (sid.target === \"*\") {\n return relation(compId, \"*\");\n }\n\n let targetId: EntityId<any>;\n if (typeof sid.target === \"string\") {\n const tid = getComponentIdByName(sid.target);\n if (tid === undefined) {\n const num = parseInt(sid.target, 10);\n if (!isNaN(num)) targetId = num as EntityId<any>;\n else throw new Error(`Unknown target component name in snapshot: ${sid.target}`);\n } else {\n targetId = tid;\n }\n } else {\n targetId = sid.target as EntityId<any>;\n }\n return relation(compId, targetId as any);\n }\n throw new Error(`Invalid ID in snapshot: ${JSON.stringify(sid)}`);\n}\n","import type { ComponentChangeset } from \"../commands/changeset\";\nimport type { Command } from \"../commands/command-buffer\";\nimport type { Archetype } from \"./archetype\";\nimport {\n getComponentIdFromRelationId,\n isDontFragmentComponent,\n isDontFragmentRelation,\n isDontFragmentWildcard,\n isWildcardRelationId,\n relation,\n type ComponentId,\n type EntityId,\n} from \"./entity\";\n\nexport interface CommandProcessorContext {\n dontFragmentRelations: Map<EntityId, Map<EntityId<any>, any>>;\n ensureArchetype: (componentTypes: Iterable<EntityId<any>>) => Archetype;\n}\n\nexport function processCommands(\n entityId: EntityId,\n currentArchetype: Archetype,\n commands: Command[],\n changeset: ComponentChangeset,\n handleExclusiveRelation: (entityId: EntityId, archetype: Archetype, componentId: ComponentId<any>) => void,\n): void {\n for (const command of commands) {\n if (command.type === \"set\" && command.componentType) {\n processSetCommand(\n entityId,\n currentArchetype,\n command.componentType,\n command.component,\n changeset,\n handleExclusiveRelation,\n );\n } else if (command.type === \"delete\" && command.componentType) {\n processDeleteCommand(entityId, currentArchetype, command.componentType, changeset);\n }\n }\n}\n\nfunction processSetCommand(\n entityId: EntityId,\n currentArchetype: Archetype,\n componentType: EntityId<any>,\n component: any,\n changeset: ComponentChangeset,\n handleExclusiveRelation: (entityId: EntityId, archetype: Archetype, componentId: ComponentId<any>) => void,\n): void {\n // Extract componentId if it's a relation (fast path)\n const componentId = getComponentIdFromRelationId(componentType);\n if (componentId !== undefined) {\n // Handle exclusive relations by removing existing relations with the same base component\n handleExclusiveRelation(entityId, currentArchetype, componentId);\n\n // For dontFragment relations, ensure wildcard marker is in archetype signature\n if (isDontFragmentComponent(componentId)) {\n const wildcardMarker = relation(componentId, \"*\");\n // Add wildcard marker to changeset if not already in archetype\n if (!currentArchetype.componentTypes.includes(wildcardMarker)) {\n changeset.set(wildcardMarker, undefined);\n }\n }\n }\n\n changeset.set(componentType, component);\n}\n\nfunction processDeleteCommand(\n entityId: EntityId,\n currentArchetype: Archetype,\n componentType: EntityId<any>,\n changeset: ComponentChangeset,\n): void {\n const componentId = getComponentIdFromRelationId(componentType);\n\n if (isWildcardRelationId(componentType) && componentId !== undefined) {\n removeWildcardRelations(entityId, currentArchetype, componentId, changeset);\n } else {\n changeset.delete(componentType);\n maybeRemoveWildcardMarker(entityId, currentArchetype, componentType, componentId, changeset);\n }\n}\n\nexport function removeMatchingRelations(\n entityId: EntityId,\n archetype: Archetype,\n baseComponentId: ComponentId<any>,\n changeset: ComponentChangeset,\n): void {\n // Check archetype components\n for (const componentType of archetype.componentTypes) {\n if (getComponentIdFromRelationId(componentType) === baseComponentId) {\n changeset.delete(componentType);\n }\n }\n\n // Check dontFragment relations stored on entity\n const entityData = archetype.getEntity(entityId);\n if (entityData) {\n for (const [componentType] of entityData) {\n if (archetype.componentTypes.includes(componentType)) continue;\n if (getComponentIdFromRelationId(componentType) === baseComponentId) {\n changeset.delete(componentType);\n }\n }\n }\n}\n\nfunction removeWildcardRelations(\n entityId: EntityId,\n currentArchetype: Archetype,\n baseComponentId: ComponentId<any>,\n changeset: ComponentChangeset,\n): void {\n removeMatchingRelations(entityId, currentArchetype, baseComponentId, changeset);\n\n // If removing dontFragment relations, also remove the wildcard marker\n if (isDontFragmentComponent(baseComponentId)) {\n changeset.delete(relation(baseComponentId, \"*\"));\n }\n}\n\nexport function maybeRemoveWildcardMarker(\n entityId: EntityId,\n archetype: Archetype,\n removedComponentType: EntityId<any>,\n componentId: ComponentId<any> | undefined,\n changeset: ComponentChangeset,\n): void {\n if (componentId === undefined || !isDontFragmentComponent(componentId)) {\n return;\n }\n\n const wildcardMarker = relation(componentId, \"*\");\n const entityData = archetype.getEntity(entityId);\n if (!entityData) {\n changeset.delete(wildcardMarker);\n return;\n }\n\n // Check if there are any other relations with the same component ID\n for (const [otherComponentType] of entityData) {\n if (otherComponentType === removedComponentType) continue;\n if (otherComponentType === wildcardMarker) continue;\n if (changeset.removes.has(otherComponentType)) continue;\n\n if (getComponentIdFromRelationId(otherComponentType) === componentId) {\n return; // Found another relation, keep the marker\n }\n }\n\n changeset.delete(wildcardMarker);\n}\n\nexport function applyChangeset(\n ctx: CommandProcessorContext,\n entityId: EntityId,\n currentArchetype: Archetype,\n changeset: ComponentChangeset,\n entityToArchetype: Map<EntityId, Archetype>,\n): Map<EntityId<any>, any> {\n const currentEntityData = currentArchetype.getEntity(entityId);\n const allCurrentComponentTypes = currentEntityData\n ? Array.from(currentEntityData.keys())\n : currentArchetype.componentTypes;\n\n const finalComponentTypes = changeset.getFinalComponentTypes(allCurrentComponentTypes);\n const removedComponents = new Map<EntityId<any>, any>();\n\n if (finalComponentTypes) {\n // Check if archetype-affecting components actually changed\n // (dontFragment components don't affect archetype signature)\n const currentRegularTypes = filterRegularComponentTypes(allCurrentComponentTypes);\n const finalRegularTypes = filterRegularComponentTypes(finalComponentTypes);\n const archetypeChanged = !areComponentTypesEqual(currentRegularTypes, finalRegularTypes);\n\n if (archetypeChanged) {\n // Move to new archetype (regular components changed)\n moveEntityToNewArchetype(\n ctx,\n entityId,\n currentArchetype,\n finalComponentTypes,\n changeset,\n removedComponents,\n entityToArchetype,\n );\n } else {\n // Only dontFragment components changed, stay in same archetype\n updateEntityInSameArchetype(ctx, entityId, currentArchetype, changeset, removedComponents);\n }\n } else {\n // Update in same archetype\n updateEntityInSameArchetype(ctx, entityId, currentArchetype, changeset, removedComponents);\n }\n\n return removedComponents;\n}\n\nfunction moveEntityToNewArchetype(\n ctx: CommandProcessorContext,\n entityId: EntityId,\n currentArchetype: Archetype,\n finalComponentTypes: EntityId<any>[],\n changeset: ComponentChangeset,\n removedComponents: Map<EntityId<any>, any>,\n entityToArchetype: Map<EntityId, Archetype>,\n): void {\n const newArchetype = ctx.ensureArchetype(finalComponentTypes);\n const currentComponents = currentArchetype.removeEntity(entityId)!;\n\n // Track removed components\n for (const componentType of changeset.removes) {\n removedComponents.set(componentType, currentComponents.get(componentType));\n }\n\n // Add to new archetype with updated components\n newArchetype.addEntity(entityId, changeset.applyTo(currentComponents));\n entityToArchetype.set(entityId, newArchetype);\n}\n\nfunction updateEntityInSameArchetype(\n ctx: CommandProcessorContext,\n entityId: EntityId,\n currentArchetype: Archetype,\n changeset: ComponentChangeset,\n removedComponents: Map<EntityId<any>, any>,\n): void {\n // Process dontFragment relation changes directly on World's storage\n applyDontFragmentChanges(ctx.dontFragmentRelations, entityId, changeset, removedComponents);\n\n // Direct update for regular components in archetype\n for (const [componentType, component] of changeset.adds) {\n if (isDontFragmentRelation(componentType)) {\n continue;\n }\n currentArchetype.set(entityId, componentType, component);\n }\n}\n\nfunction applyDontFragmentChanges(\n dontFragmentRelations: Map<EntityId, Map<EntityId<any>, any>>,\n entityId: EntityId,\n changeset: ComponentChangeset,\n removedComponents: Map<EntityId<any>, any>,\n): void {\n // Get or create the entity's dontFragment relations map\n let entityRelations = dontFragmentRelations.get(entityId);\n\n for (const componentType of changeset.removes) {\n if (isDontFragmentRelation(componentType)) {\n if (entityRelations) {\n const removedValue = entityRelations.get(componentType);\n if (removedValue !== undefined || entityRelations.has(componentType)) {\n removedComponents.set(componentType, removedValue);\n entityRelations.delete(componentType);\n }\n }\n }\n }\n\n for (const [componentType, component] of changeset.adds) {\n if (isDontFragmentRelation(componentType)) {\n if (!entityRelations) {\n entityRelations = new Map();\n dontFragmentRelations.set(entityId, entityRelations);\n }\n entityRelations.set(componentType, component);\n }\n }\n\n // Clean up empty map\n if (entityRelations && entityRelations.size === 0) {\n dontFragmentRelations.delete(entityId);\n }\n}\n\nexport function filterRegularComponentTypes(componentTypes: Iterable<EntityId<any>>): EntityId<any>[] {\n const regularTypes: EntityId<any>[] = [];\n\n for (const componentType of componentTypes) {\n // Keep wildcard markers for dontFragment components (they mark the archetype)\n if (isDontFragmentWildcard(componentType)) {\n regularTypes.push(componentType);\n continue;\n }\n\n // Skip specific dontFragment relations from archetype signature\n if (isDontFragmentRelation(componentType)) {\n continue;\n }\n\n regularTypes.push(componentType);\n }\n\n return regularTypes;\n}\n\nexport function areComponentTypesEqual(types1: EntityId<any>[], types2: EntityId<any>[]): boolean {\n if (types1.length !== types2.length) return false;\n const sorted1 = [...types1].sort((a, b) => a - b);\n const sorted2 = [...types2].sort((a, b) => a - b);\n return sorted1.every((v, i) => v === sorted2[i]);\n}\n","import { getComponentIdFromRelationId, relation, type EntityId } from \"./entity\";\nimport type { ComponentType, LifecycleHook, MultiLifecycleHook } from \"./types\";\nimport { isOptionalEntityId } from \"./types\";\n\nexport type HooksMap = Map<EntityId<any>, Set<LifecycleHook<any>>>;\n\nexport interface MultiHookEntry {\n componentTypes: readonly ComponentType<any>[];\n requiredComponents: EntityId<any>[];\n hook: MultiLifecycleHook<any>;\n}\n\nexport interface HooksContext {\n hooks: HooksMap;\n multiHooks: Set<MultiHookEntry>;\n has: (entityId: EntityId, componentType: EntityId<any>) => boolean;\n get: <T>(entityId: EntityId, componentType: EntityId<T>) => T;\n getOptional: <T>(entityId: EntityId, componentType: EntityId<T>) => { value: T } | undefined;\n}\n\nexport function triggerLifecycleHooks(\n ctx: HooksContext,\n entityId: EntityId,\n addedComponents: Map<EntityId<any>, any>,\n removedComponents: Map<EntityId<any>, any>,\n): void {\n invokeHooksForComponents(ctx.hooks, entityId, addedComponents, \"on_set\");\n invokeHooksForComponents(ctx.hooks, entityId, removedComponents, \"on_remove\");\n triggerMultiComponentHooks(ctx, entityId, addedComponents, removedComponents);\n}\n\nfunction invokeHooksForComponents(\n hooks: HooksMap,\n entityId: EntityId,\n components: Map<EntityId<any>, any>,\n hookType: \"on_set\" | \"on_remove\",\n): void {\n for (const [componentType, component] of components) {\n // Trigger direct component hooks\n const directHooks = hooks.get(componentType);\n if (directHooks) {\n for (const hook of directHooks) {\n hook[hookType]?.(entityId, componentType, component);\n }\n }\n\n // Trigger wildcard relation hooks\n const componentId = getComponentIdFromRelationId(componentType);\n if (componentId !== undefined) {\n const wildcardHooks = hooks.get(relation(componentId, \"*\"));\n if (wildcardHooks) {\n for (const hook of wildcardHooks) {\n hook[hookType]?.(entityId, componentType, component);\n }\n }\n }\n }\n}\n\nfunction triggerMultiComponentHooks(\n ctx: HooksContext,\n entityId: EntityId,\n addedComponents: Map<EntityId<any>, any>,\n removedComponents: Map<EntityId<any>, any>,\n): void {\n for (const { componentTypes, requiredComponents, hook } of ctx.multiHooks) {\n const anyRequiredAdded = requiredComponents.some((c) => addedComponents.has(c));\n const anyRequiredRemoved = requiredComponents.some((c) => removedComponents.has(c));\n\n // Handle on_set: trigger if any required component was added and entity has all required components now\n if (anyRequiredAdded && hook.on_set && entityHasAllComponents(ctx, entityId, requiredComponents)) {\n hook.on_set(entityId, componentTypes, collectMultiHookComponents(ctx, entityId, componentTypes));\n }\n\n // Handle on_remove: trigger if any required component was removed and entity had all required components before\n if (\n anyRequiredRemoved &&\n hook.on_remove &&\n entityHadAllComponentsBefore(ctx, entityId, requiredComponents, removedComponents)\n ) {\n hook.on_remove(\n entityId,\n componentTypes,\n collectMultiHookComponentsWithRemoved(ctx, entityId, componentTypes, removedComponents),\n );\n }\n }\n}\n\nfunction entityHasAllComponents(ctx: HooksContext, entityId: EntityId, requiredComponents: EntityId<any>[]): boolean {\n return requiredComponents.every((c) => ctx.has(entityId, c));\n}\n\nfunction entityHadAllComponentsBefore(\n ctx: HooksContext,\n entityId: EntityId,\n requiredComponents: EntityId<any>[],\n removedComponents: Map<EntityId<any>, any>,\n): boolean {\n return requiredComponents.every((c) => removedComponents.has(c) || ctx.has(entityId, c));\n}\n\nexport function collectMultiHookComponents(\n ctx: HooksContext,\n entityId: EntityId,\n componentTypes: readonly ComponentType<any>[],\n): any[] {\n return componentTypes.map((ct) =>\n isOptionalEntityId(ct) ? ctx.getOptional(entityId, ct.optional) : ctx.get(entityId, ct as EntityId<any>),\n );\n}\n\nfunction collectMultiHookComponentsWithRemoved(\n ctx: HooksContext,\n entityId: EntityId,\n componentTypes: readonly ComponentType<any>[],\n removedComponents: Map<EntityId<any>, any>,\n): any[] {\n return componentTypes.map((ct) => {\n if (isOptionalEntityId(ct)) {\n const optionalId = ct.optional;\n return removedComponents.has(optionalId)\n ? { value: removedComponents.get(optionalId) }\n : ctx.getOptional(entityId, optionalId);\n }\n const compId = ct as EntityId<any>;\n return removedComponents.has(compId) ? removedComponents.get(compId) : ctx.get(entityId, compId);\n });\n}\n","// A lightweight generic MultiMap implementation backed by Map<K, Set<V>>.\n// Provides usual operations: add, remove, get, has, keys, values, entries,\n// clear, deleteKey and size accessors.\n\nclass MultiMap<K, V> {\n private map: Map<K, Set<V>> = new Map();\n\n // Number of value entries across all keys (not number of keys).\n private _valueCount = 0;\n\n get valueCount(): number {\n return this._valueCount;\n }\n\n get keyCount(): number {\n return this.map.size;\n }\n\n hasKey(key: K): boolean {\n return this.map.has(key);\n }\n\n has(key: K, value?: V): boolean {\n const set = this.map.get(key);\n if (!set) return false;\n if (arguments.length === 1) return true;\n return set.has(value as V);\n }\n\n add(key: K, value: V): void {\n let set = this.map.get(key);\n if (!set) {\n set = new Set();\n this.map.set(key, set);\n }\n if (!set.has(value)) {\n set.add(value);\n this._valueCount++;\n }\n }\n\n // Remove a specific value for a key. Returns true if removed.\n remove(key: K, value: V): boolean {\n const set = this.map.get(key);\n if (!set) return false;\n if (!set.has(value)) return false;\n set.delete(value);\n this._valueCount--;\n if (set.size === 0) this.map.delete(key);\n return true;\n }\n\n // Delete entire key and all its values. Returns true if key existed.\n deleteKey(key: K): boolean {\n const set = this.map.get(key);\n if (!set) return false;\n this._valueCount -= set.size;\n this.map.delete(key);\n return true;\n }\n\n get(key: K): Set<V> {\n const set = this.map.get(key);\n return set ? new Set(set) : new Set();\n }\n\n // iterate keys, values and entries (key -> Set copy)\n *keys(): IterableIterator<K> {\n yield* this.map.keys();\n }\n\n *values(): IterableIterator<V> {\n for (const set of this.map.values()) {\n for (const v of set) yield v;\n }\n }\n\n [Symbol.iterator](): IterableIterator<[K, V]> {\n return this.entries();\n }\n\n *entries(): IterableIterator<[K, V]> {\n for (const [k, set] of this.map.entries()) {\n for (const v of set) yield [k, v];\n }\n }\n\n clear(): void {\n this.map.clear();\n this._valueCount = 0;\n }\n}\n\nexport { MultiMap };\nexport type { MultiMap as MultiMapType };\n","import { MultiMap } from \"../utils/multi-map\";\nimport type { EntityId } from \"./entity\";\n\nexport type EntityReferencesMap = Map<EntityId, MultiMap<EntityId, EntityId>>;\n\nexport function trackEntityReference(\n entityReferences: EntityReferencesMap,\n sourceEntityId: EntityId,\n componentType: EntityId,\n targetEntityId: EntityId,\n): void {\n if (!entityReferences.has(targetEntityId)) {\n entityReferences.set(targetEntityId, new MultiMap());\n }\n entityReferences.get(targetEntityId)!.add(sourceEntityId, componentType);\n}\n\nexport function untrackEntityReference(\n entityReferences: EntityReferencesMap,\n sourceEntityId: EntityId,\n componentType: EntityId,\n targetEntityId: EntityId,\n): void {\n const references = entityReferences.get(targetEntityId);\n if (references) {\n references.remove(sourceEntityId, componentType);\n if (references.keyCount === 0) {\n entityReferences.delete(targetEntityId);\n }\n }\n}\n\nexport function getEntityReferences(\n entityReferences: EntityReferencesMap,\n targetEntityId: EntityId,\n): Iterable<[EntityId, EntityId]> {\n return entityReferences.get(targetEntityId) ?? new MultiMap();\n}\n","import { ComponentChangeset } from \"../commands/changeset\";\nimport { CommandBuffer, type Command } from \"../commands/command-buffer\";\nimport { serializeQueryFilter, type QueryFilter } from \"../query/filter\";\nimport { Query } from \"../query/query\";\nimport { getOrCreateWithSideEffect } from \"../utils/utils\";\nimport { Archetype, MISSING_COMPONENT } from \"./archetype\";\nimport { EntityBuilder } from \"./builder\";\nimport type { ComponentId, EntityId, WildcardRelationId } from \"./entity\";\nimport {\n EntityIdManager,\n getComponentIdFromRelationId,\n getDetailedIdType,\n getTargetIdFromRelationId,\n isCascadeDeleteRelation,\n isDontFragmentRelation,\n isEntityRelation,\n isExclusiveComponent,\n isWildcardRelationId,\n} from \"./entity\";\nimport type { SerializedComponent, SerializedEntity, SerializedWorld } from \"./serialization\";\nimport { decodeSerializedId, encodeEntityId } from \"./serialization\";\nimport type { ComponentTuple, ComponentType, LifecycleHook, MultiLifecycleHook } from \"./types\";\nimport { isOptionalEntityId } from \"./types\";\nimport {\n applyChangeset,\n filterRegularComponentTypes,\n maybeRemoveWildcardMarker,\n processCommands,\n removeMatchingRelations,\n} from \"./world-commands\";\nimport {\n collectMultiHookComponents,\n triggerLifecycleHooks,\n type HooksContext,\n type MultiHookEntry,\n} from \"./world-hooks\";\nimport {\n getEntityReferences,\n trackEntityReference,\n untrackEntityReference,\n type EntityReferencesMap,\n} from \"./world-references\";\n\n/**\n * World class for ECS architecture\n * Manages entities and components\n */\nexport class World {\n // Core data structures for entity and archetype management\n private entityIdManager = new EntityIdManager();\n private archetypes: Archetype[] = [];\n private archetypeBySignature = new Map<string, Archetype>();\n private entityToArchetype = new Map<EntityId, Archetype>();\n private archetypesByComponent = new Map<EntityId<any>, Archetype[]>();\n private entityReferences: EntityReferencesMap = new Map();\n private dontFragmentRelations: Map<EntityId, Map<EntityId<any>, any>> = new Map();\n\n // Query management\n private queries: Query[] = [];\n private queryCache = new Map<string, { query: Query; refCount: number }>();\n\n // Command execution\n private commandBuffer = new CommandBuffer((entityId, commands) => this.executeEntityCommands(entityId, commands));\n\n // Lifecycle hooks\n private hooks = new Map<EntityId<any>, Set<LifecycleHook<any>>>();\n private multiHooks: Set<MultiHookEntry> = new Set();\n\n constructor(snapshot?: SerializedWorld) {\n if (snapshot && typeof snapshot === \"object\") {\n this.deserializeSnapshot(snapshot);\n }\n }\n\n private deserializeSnapshot(snapshot: SerializedWorld): void {\n if (snapshot.entityManager) {\n this.entityIdManager.deserializeState(snapshot.entityManager);\n }\n\n if (Array.isArray(snapshot.entities)) {\n for (const entry of snapshot.entities) {\n const entityId = decodeSerializedId(entry.id);\n const componentsArray: SerializedComponent[] = entry.components || [];\n\n const componentMap = new Map<EntityId<any>, any>();\n const componentTypes: EntityId<any>[] = [];\n\n for (const componentEntry of componentsArray) {\n const componentType = decodeSerializedId(componentEntry.type);\n componentMap.set(componentType, componentEntry.value);\n componentTypes.push(componentType);\n }\n\n const archetype = this.ensureArchetype(componentTypes);\n archetype.addEntity(entityId, componentMap);\n this.entityToArchetype.set(entityId, archetype);\n\n for (const compType of componentTypes) {\n const detailedType = getDetailedIdType(compType);\n if (detailedType.type === \"entity-relation\") {\n trackEntityReference(this.entityReferences, entityId, compType, detailedType.targetId!);\n } else if (detailedType.type === \"entity\") {\n trackEntityReference(this.entityReferences, entityId, compType, compType);\n }\n }\n }\n }\n }\n\n private createArchetypeSignature(componentTypes: EntityId<any>[]): string {\n return componentTypes.join(\",\");\n }\n\n new<T = void>(): EntityId<T> {\n const entityId = this.entityIdManager.allocate();\n let emptyArchetype = this.ensureArchetype([]);\n emptyArchetype.addEntity(entityId, new Map());\n this.entityToArchetype.set(entityId, emptyArchetype);\n return entityId as EntityId<T>;\n }\n\n private destroyEntityImmediate(entityId: EntityId): void {\n const queue: EntityId[] = [entityId];\n const visited = new Set<EntityId>();\n\n while (queue.length > 0) {\n const cur = queue.shift()!;\n if (visited.has(cur)) continue;\n visited.add(cur);\n\n const archetype = this.entityToArchetype.get(cur);\n if (!archetype) continue;\n\n const componentReferences = Array.from(getEntityReferences(this.entityReferences, cur));\n for (const [sourceEntityId, componentType] of componentReferences) {\n const sourceArchetype = this.entityToArchetype.get(sourceEntityId);\n if (!sourceArchetype) continue;\n\n if (isCascadeDeleteRelation(componentType)) {\n if (!visited.has(sourceEntityId)) {\n queue.push(sourceEntityId);\n }\n continue;\n }\n\n this.removeComponentImmediate(sourceEntityId, componentType, cur);\n }\n\n this.entityReferences.delete(cur);\n archetype.removeEntity(cur);\n this.entityToArchetype.delete(cur);\n this.cleanupArchetypesReferencingEntity(cur);\n this.entityIdManager.deallocate(cur);\n }\n }\n\n exists(entityId: EntityId): boolean {\n return this.entityToArchetype.has(entityId);\n }\n\n set(entityId: EntityId, componentType: EntityId<void>): void;\n set<T>(entityId: EntityId, componentType: EntityId<T>, component: NoInfer<T>): void;\n set(entityId: EntityId, componentType: EntityId, component?: any): void {\n if (!this.exists(entityId)) {\n throw new Error(`Entity ${entityId} does not exist`);\n }\n\n const detailedType = getDetailedIdType(componentType);\n if (detailedType.type === \"invalid\") {\n throw new Error(`Invalid component type: ${componentType}`);\n }\n if (detailedType.type === \"wildcard-relation\") {\n throw new Error(`Cannot directly add wildcard relation components: ${componentType}`);\n }\n\n this.commandBuffer.set(entityId, componentType, component);\n }\n\n remove<T>(entityId: EntityId, componentType: EntityId<T>): void {\n if (!this.exists(entityId)) {\n throw new Error(`Entity ${entityId} does not exist`);\n }\n\n const detailedType = getDetailedIdType(componentType);\n if (detailedType.type === \"invalid\") {\n throw new Error(`Invalid component type: ${componentType}`);\n }\n\n this.commandBuffer.remove(entityId, componentType);\n }\n\n delete(entityId: EntityId): void {\n this.commandBuffer.delete(entityId);\n }\n\n has<T>(entityId: EntityId, componentType: EntityId<T>): boolean {\n const archetype = this.entityToArchetype.get(entityId);\n if (!archetype) return false;\n\n if (archetype.componentTypes.includes(componentType)) return true;\n\n if (isDontFragmentRelation(componentType)) {\n return this.dontFragmentRelations.get(entityId)?.has(componentType) ?? false;\n }\n\n return false;\n }\n\n get<T>(entityId: EntityId, componentType: WildcardRelationId<T>): [EntityId<unknown>, T][];\n get<T>(entityId: EntityId, componentType: EntityId<T>): T;\n get<T>(entityId: EntityId, componentType: EntityId<T> | WildcardRelationId<T>): T | [EntityId<unknown>, any][] {\n const archetype = this.entityToArchetype.get(entityId);\n if (!archetype) {\n throw new Error(`Entity ${entityId} does not exist`);\n }\n\n if (componentType >= 0 || componentType % 2 ** 42 !== 0) {\n const inArchetype = archetype.componentTypes.includes(componentType);\n const hasDontFragment = isDontFragmentRelation(componentType);\n const hasComponent =\n inArchetype || (hasDontFragment && this.dontFragmentRelations.get(entityId)?.has(componentType));\n\n if (!hasComponent) {\n throw new Error(\n `Entity ${entityId} does not have component ${componentType}. Use has() to check component existence before calling get().`,\n );\n }\n }\n\n return archetype.get(entityId, componentType);\n }\n\n getOptional<T>(entityId: EntityId, componentType: EntityId<T>): { value: T } | undefined {\n const archetype = this.entityToArchetype.get(entityId);\n if (!archetype) {\n throw new Error(`Entity ${entityId} does not exist`);\n }\n\n if (isWildcardRelationId(componentType)) return undefined;\n\n return archetype.getOptional(entityId, componentType);\n }\n\n hook<T>(componentType: EntityId<T>, hook: LifecycleHook<T>): void;\n hook<const T extends readonly ComponentType<any>[]>(componentTypes: T, hook: MultiLifecycleHook<T>): void;\n hook(\n componentTypesOrSingle: EntityId<any> | readonly ComponentType<any>[],\n hook: LifecycleHook<any> | MultiLifecycleHook<any>,\n ): void {\n if (Array.isArray(componentTypesOrSingle)) {\n const componentTypes = componentTypesOrSingle as readonly ComponentType<any>[];\n const requiredComponents: EntityId<any>[] = [];\n for (const ct of componentTypes) {\n if (!isOptionalEntityId(ct)) {\n requiredComponents.push(ct as EntityId<any>);\n }\n }\n\n const entry: MultiHookEntry = {\n componentTypes,\n requiredComponents,\n hook: hook as MultiLifecycleHook<any>,\n };\n this.multiHooks.add(entry);\n\n const multiHook = hook as MultiLifecycleHook<any>;\n if (multiHook.on_init !== undefined) {\n const matchingArchetypes = this.getMatchingArchetypes(requiredComponents);\n for (const archetype of matchingArchetypes) {\n for (const entityId of archetype.getEntities()) {\n const components = collectMultiHookComponents(this.createHooksContext(), entityId, componentTypes);\n multiHook.on_init(entityId, componentTypes, components);\n }\n }\n }\n } else {\n const componentType = componentTypesOrSingle as EntityId<any>;\n if (!this.hooks.has(componentType)) {\n this.hooks.set(componentType, new Set());\n }\n this.hooks.get(componentType)!.add(hook as LifecycleHook<any>);\n\n const singleHook = hook as LifecycleHook<any>;\n if (singleHook.on_init !== undefined) {\n this.archetypesByComponent.get(componentType)?.forEach((archetype) => {\n const entities = archetype.getEntityToIndexMap();\n const componentData = archetype.getComponentData<any>(componentType);\n for (const [entity, index] of entities) {\n const data = componentData[index];\n const value = data === MISSING_COMPONENT ? undefined : data;\n singleHook.on_init?.(entity, componentType, value);\n }\n });\n }\n }\n }\n\n unhook<T>(componentType: EntityId<T>, hook: LifecycleHook<T>): void;\n unhook<const T extends readonly ComponentType<any>[]>(componentTypes: T, hook: MultiLifecycleHook<T>): void;\n unhook(\n componentTypesOrSingle: EntityId<any> | readonly ComponentType<any>[],\n hook: LifecycleHook<any> | MultiLifecycleHook<any>,\n ): void {\n if (Array.isArray(componentTypesOrSingle)) {\n for (const entry of this.multiHooks) {\n if (entry.hook === hook) {\n this.multiHooks.delete(entry);\n break;\n }\n }\n } else {\n const componentType = componentTypesOrSingle as EntityId<any>;\n const hooks = this.hooks.get(componentType);\n if (hooks) {\n hooks.delete(hook as LifecycleHook<any>);\n if (hooks.size === 0) {\n this.hooks.delete(componentType);\n }\n }\n }\n }\n\n sync(): void {\n this.commandBuffer.execute();\n }\n\n createQuery(componentTypes: EntityId<any>[], filter: QueryFilter = {}): Query {\n const sortedTypes = [...componentTypes].sort((a, b) => a - b);\n const filterKey = serializeQueryFilter(filter);\n const key = `${this.createArchetypeSignature(sortedTypes)}${filterKey ? `|${filterKey}` : \"\"}`;\n\n const cached = this.queryCache.get(key);\n if (cached) {\n cached.refCount++;\n return cached.query;\n }\n\n const query = new Query(this, sortedTypes, filter);\n this.queryCache.set(key, { query, refCount: 1 });\n return query;\n }\n\n spawn(): EntityBuilder {\n return new EntityBuilder(this);\n }\n\n spawnMany(count: number, configure: (builder: EntityBuilder, index: number) => EntityBuilder): EntityId[] {\n const entities: EntityId[] = [];\n for (let i = 0; i < count; i++) {\n const builder = new EntityBuilder(this);\n entities.push(configure(builder, i).build());\n }\n return entities;\n }\n\n _registerQuery(query: Query): void {\n this.queries.push(query);\n }\n\n _unregisterQuery(query: Query): void {\n const index = this.queries.indexOf(query);\n if (index !== -1) {\n this.queries.splice(index, 1);\n }\n }\n\n releaseQuery(query: Query): void {\n for (const [k, v] of this.queryCache.entries()) {\n if (v.query === query) {\n v.refCount--;\n if (v.refCount <= 0) {\n this.queryCache.delete(k);\n this._unregisterQuery(query);\n v.query._disposeInternal();\n }\n return;\n }\n }\n }\n\n getMatchingArchetypes(componentTypes: EntityId<any>[]): Archetype[] {\n if (componentTypes.length === 0) {\n return [...this.archetypes];\n }\n\n const regularComponents: EntityId<any>[] = [];\n const wildcardRelations: { componentId: ComponentId<any>; relationId: EntityId<any> }[] = [];\n\n for (const componentType of componentTypes) {\n if (isWildcardRelationId(componentType)) {\n const componentId = getComponentIdFromRelationId(componentType);\n if (componentId !== undefined) {\n wildcardRelations.push({ componentId, relationId: componentType });\n }\n } else {\n regularComponents.push(componentType);\n }\n }\n\n let matchingArchetypes = this.getArchetypesWithComponents(regularComponents);\n\n for (const { componentId, relationId } of wildcardRelations) {\n const archetypesWithMarker = this.archetypesByComponent.get(relationId) || [];\n matchingArchetypes =\n matchingArchetypes.length === 0\n ? archetypesWithMarker\n : matchingArchetypes.filter(\n (a) => archetypesWithMarker.includes(a) || a.hasRelationWithComponentId(componentId),\n );\n }\n\n return matchingArchetypes;\n }\n\n private getArchetypesWithComponents(componentTypes: EntityId<any>[]): Archetype[] {\n if (componentTypes.length === 0) return [...this.archetypes];\n if (componentTypes.length === 1) return this.archetypesByComponent.get(componentTypes[0]!) || [];\n\n const archetypeLists = componentTypes.map((type) => this.archetypesByComponent.get(type) || []);\n const firstList = archetypeLists[0]!;\n return firstList.filter((archetype) => archetypeLists.slice(1).every((list) => list.includes(archetype)));\n }\n\n query(componentTypes: EntityId<any>[]): EntityId[];\n query<const T extends readonly EntityId<any>[]>(\n componentTypes: T,\n includeComponents: true,\n ): Array<{ entity: EntityId; components: ComponentTuple<T> }>;\n query(\n componentTypes: EntityId<any>[],\n includeComponents?: boolean,\n ): EntityId[] | Array<{ entity: EntityId; components: any }> {\n const matchingArchetypes = this.getMatchingArchetypes(componentTypes);\n\n if (includeComponents) {\n const result: Array<{ entity: EntityId; components: any }> = [];\n for (const archetype of matchingArchetypes) {\n result.push(...archetype.getEntitiesWithComponents(componentTypes as EntityId<any>[]));\n }\n return result;\n } else {\n const result: EntityId[] = [];\n for (const archetype of matchingArchetypes) {\n result.push(...archetype.getEntities());\n }\n return result;\n }\n }\n\n executeEntityCommands(entityId: EntityId, commands: Command[]): ComponentChangeset {\n const changeset = new ComponentChangeset();\n\n if (commands.some((cmd) => cmd.type === \"destroy\")) {\n this.destroyEntityImmediate(entityId);\n return changeset;\n }\n\n const currentArchetype = this.entityToArchetype.get(entityId);\n if (!currentArchetype) return changeset;\n\n processCommands(entityId, currentArchetype, commands, changeset, (eid, arch, compId) => {\n if (isExclusiveComponent(compId)) {\n removeMatchingRelations(eid, arch, compId, changeset);\n }\n });\n\n const removedComponents = applyChangeset(\n { dontFragmentRelations: this.dontFragmentRelations, ensureArchetype: (ct) => this.ensureArchetype(ct) },\n entityId,\n currentArchetype,\n changeset,\n this.entityToArchetype,\n );\n\n this.updateEntityReferences(entityId, changeset);\n triggerLifecycleHooks(this.createHooksContext(), entityId, changeset.adds, removedComponents);\n\n return changeset;\n }\n\n private createHooksContext(): HooksContext {\n return {\n hooks: this.hooks,\n multiHooks: this.multiHooks,\n has: (eid, ct) => this.has(eid, ct),\n get: (eid, ct) => this.get(eid, ct),\n getOptional: (eid, ct) => this.getOptional(eid, ct),\n };\n }\n\n private removeComponentImmediate(entityId: EntityId, componentType: EntityId<any>, targetEntityId: EntityId): void {\n const sourceArchetype = this.entityToArchetype.get(entityId);\n if (!sourceArchetype) return;\n\n const changeset = new ComponentChangeset();\n changeset.delete(componentType);\n maybeRemoveWildcardMarker(\n entityId,\n sourceArchetype,\n componentType,\n getComponentIdFromRelationId(componentType),\n changeset,\n );\n\n const removedComponent = sourceArchetype.get(entityId, componentType);\n applyChangeset(\n { dontFragmentRelations: this.dontFragmentRelations, ensureArchetype: (ct) => this.ensureArchetype(ct) },\n entityId,\n sourceArchetype,\n changeset,\n this.entityToArchetype,\n );\n untrackEntityReference(this.entityReferences, entityId, componentType, targetEntityId);\n triggerLifecycleHooks(this.createHooksContext(), entityId, new Map(), new Map([[componentType, removedComponent]]));\n }\n\n private updateEntityReferences(entityId: EntityId, changeset: ComponentChangeset): void {\n for (const componentType of changeset.removes) {\n if (isEntityRelation(componentType)) {\n const targetId = getTargetIdFromRelationId(componentType)!;\n untrackEntityReference(this.entityReferences, entityId, componentType, targetId);\n } else if (componentType >= 1024) {\n untrackEntityReference(this.entityReferences, entityId, componentType, componentType);\n }\n }\n\n for (const [componentType] of changeset.adds) {\n if (isEntityRelation(componentType)) {\n const targetId = getTargetIdFromRelationId(componentType)!;\n trackEntityReference(this.entityReferences, entityId, componentType, targetId);\n } else if (componentType >= 1024) {\n trackEntityReference(this.entityReferences, entityId, componentType, componentType);\n }\n }\n }\n\n private ensureArchetype(componentTypes: Iterable<EntityId<any>>): Archetype {\n const regularTypes = filterRegularComponentTypes(componentTypes);\n const sortedTypes = regularTypes.sort((a, b) => a - b);\n const hashKey = this.createArchetypeSignature(sortedTypes);\n\n return getOrCreateWithSideEffect(this.archetypeBySignature, hashKey, () => this.createNewArchetype(sortedTypes));\n }\n\n private createNewArchetype(componentTypes: EntityId<any>[]): Archetype {\n const newArchetype = new Archetype(componentTypes, this.dontFragmentRelations);\n this.archetypes.push(newArchetype);\n\n for (const componentType of componentTypes) {\n const archetypes = this.archetypesByComponent.get(componentType) || [];\n archetypes.push(newArchetype);\n this.archetypesByComponent.set(componentType, archetypes);\n }\n\n for (const query of this.queries) {\n query.checkNewArchetype(newArchetype);\n }\n\n return newArchetype;\n }\n\n private archetypeReferencesEntity(archetype: Archetype, entityId: EntityId): boolean {\n return archetype.componentTypes.some(\n (ct) => ct === entityId || (isEntityRelation(ct) && getTargetIdFromRelationId(ct) === entityId),\n );\n }\n\n private cleanupArchetypesReferencingEntity(entityId: EntityId): void {\n for (let i = this.archetypes.length - 1; i >= 0; i--) {\n const archetype = this.archetypes[i]!;\n if (archetype.getEntities().length === 0 && this.archetypeReferencesEntity(archetype, entityId)) {\n this.removeArchetype(archetype);\n }\n }\n }\n\n private removeArchetype(archetype: Archetype): void {\n const index = this.archetypes.indexOf(archetype);\n if (index !== -1) {\n this.archetypes.splice(index, 1);\n }\n\n this.archetypeBySignature.delete(this.createArchetypeSignature(archetype.componentTypes));\n\n for (const componentType of archetype.componentTypes) {\n const archetypes = this.archetypesByComponent.get(componentType);\n if (archetypes) {\n const compIndex = archetypes.indexOf(archetype);\n if (compIndex !== -1) {\n archetypes.splice(compIndex, 1);\n if (archetypes.length === 0) {\n this.archetypesByComponent.delete(componentType);\n }\n }\n }\n }\n\n for (const query of this.queries) {\n query.removeArchetype(archetype);\n }\n }\n\n serialize(): SerializedWorld {\n const entities: SerializedEntity[] = [];\n\n for (const archetype of this.archetypes) {\n const dumpedEntities = archetype.dump();\n for (const { entity, components } of dumpedEntities) {\n entities.push({\n id: encodeEntityId(entity),\n components: Array.from(components.entries()).map(([rawType, value]) => ({\n type: encodeEntityId(rawType),\n value: value === MISSING_COMPONENT ? undefined : value,\n })),\n });\n }\n }\n\n return {\n version: 1,\n entityManager: this.entityIdManager.serializeState(),\n entities,\n };\n }\n}\n"],"mappings":";AAgCA,MAAa,mBAAmB;AAChC,MAAa,kBAAkB;;;;AAK/B,MAAa,iBAAiB,KAAK;AACnC,MAAa,qBAAqB;;;;AAKlC,SAAgB,mBAAmB,aAA8B;AAC/D,QAAO,eAAe,KAAK,eAAe;;;;;AAM5C,SAAgB,cAAiB,IAAuC;AACtE,QAAO,MAAM,KAAK,MAAM;;;;;AAM1B,SAAgB,WAAc,IAAoC;AAChE,QAAO,MAAM;;;;;AAMf,SAAgB,aAAgB,IAAsC;AACpE,QAAO,KAAK;;;;;;;;;;AC5Cd,SAAgB,kBAAkB,IAAqE;AACrG,KAAI,MAAM,EAAG,QAAO;CACpB,MAAM,QAAQ,CAAC;AAGf,QAAO;EAAE,aAFW,KAAK,MAAM,QAAQ,eAAe;EAEhC,UADL,QAAQ;EACO;;AAsBlC,SAAgB,SAAY,aAA6B,UAA8C;AACrG,KAAI,CAAC,cAAc,YAAY,CAC7B,OAAM,IAAI,MAAM,8CAA8C;CAGhE,IAAIA;AACJ,KAAI,aAAa,IACf,kBAAiB;MACZ;AACL,MAAI,CAAC,WAAW,SAAS,IAAI,CAAC,cAAc,SAAS,CACnD,OAAM,IAAI,MAAM,kEAAkE;AAEpF,mBAAiB;;AAInB,QAAO,EAAE,cAAc,iBAAiB;;;;;AAM1C,SAAgB,qBAAwB,IAA8C;CACpF,MAAM,UAAU,kBAAkB,GAAG;AACrC,QAAO,YAAY,QAAQ,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