aiecsjs 0.5.8 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/version.ts","../src/internal/bitmask.ts","../src/internal/errors.ts","../src/internal/world.ts","../src/internal/component.ts","../src/internal/entity.ts"],"names":["VERSION","createMask","wordCount","setBit","mask","bit","w","clearBit","testBit","cloneMask","src","out","i","maskHash","m","parts","isMaskZero","matches","withMask","anyMask","noneMask","anyHasBits","words","anyHit","wm","am","nm","listBits","word","ctz32","forEachSetBit","base","fn","wi","matchesEntityMask","entityMask","v","EcsError","message","DEFAULT_OPTIONS","DEFAULT_MAX_COMPONENTS","nextWorldId","worldRegistry","getWorldState","world","state","registerWorld","unregisterWorld","id","isWorldRegistered","resolveOptions","opts","o","indexBits","generationBits","maxComponents","maxByIndex","initialCapacity","maxEntities","createEmptyArchetype","maskWordCount","createWorld","options","resolved","generationCtor","generations","empty","makePublicWorld","destroyWorld","resetWorld","arch","storage","k","buf","getWorldSize","getWorldCapacity","ensureCapacity","needed","newCap","growEntityArrays","genCtor","newGen","newArch","newMask","info","growSoAColumns","soa","fields","f","old","newLen","next","findOrCreateArchetype","key","existing","collectBits","ensureArchetypeCapacity","bits","lsb","getOrRegisterComponentBit","readEntityMask","eid","writeEntityMask","tryGetComponentBit","isWorld","x","obj","nextComponentId","TYPE_CTOR","componentInfoById","defineComponent","schema","name","decl","type","vectorLen","t","len","ctor","defineTag","defineObjectComponent","factory","fac","getComponentInfo","component","addComponent","initial","isAliveInternal","prevMask","writeInitial","migrateEntity","fireAddObservers","notifyMaskChange","removeComponent","fireRemoveObservers","idx","clearSoAEntity","hasComponent","getComponent","setComponent","value","fireSetObservers","packedEid","col","val","arr","inst","target","clearAllEntityStorages","srcArchId","srcArch","destArchId","destArch","row","lastRow","moved","newRow","_dispatch","_maskChange","registerMaskChangeDispatch","prev","dispatchDestroyMaskChange","before","after","registerObserverDispatch","api","getComponentByInternalId","listAllComponents","DEFAULT_INDEX_BITS","DEFAULT_GENERATION_BITS","DEFAULT_INDEX_MASK","DEFAULT_GENERATION_MASK","packEid","gen","unpackIdx","unpackGen","createEntity","ensureEntityAtSlot","s","pos","last","destroyEntity","dispatchDestroyObservers","lazyObservers","cleanupRelationsOnDestroy","archId","entityExists","storedGen","refGen","getEntityIndex","getEntityGeneration","packEntity","index","generation","isEntity","_observersAPI","registerObserversAPI","_relationsCleanup","registerRelationsCleanup"],"mappings":"aAAO,IAAMA,CAAAA,CAAU,QCEhB,SAASC,CAAAA,CAAWC,CAAAA,CAAgC,CACzD,OAAO,IAAI,WAAA,CAAYA,CAAS,CAClC,CAEO,SAASC,CAAAA,CAAOC,CAAAA,CAAmBC,CAAAA,CAAmB,CAC3D,IAAMC,CAAAA,CAAID,IAAQ,CAAA,CAClBD,CAAAA,CAAKE,CAAC,CAAA,CAAA,CAAKF,CAAAA,CAAKE,CAAC,GAAK,CAAA,EAAM,CAAA,GAAMD,CAAAA,CAAM,EAAA,EAC1C,CAEO,SAASE,EAASH,CAAAA,CAAmBC,CAAAA,CAAmB,CAC7D,IAAMC,CAAAA,CAAID,CAAAA,GAAQ,EAClBD,CAAAA,CAAKE,CAAC,CAAA,CAAA,CAAKF,CAAAA,CAAKE,CAAC,CAAA,EAAK,GAAK,EAAE,CAAA,GAAMD,CAAAA,CAAM,EAAA,CAAA,EAC3C,CAEO,SAASG,EAAQJ,CAAAA,CAAmBC,CAAAA,CAAsB,CAC/D,IAAMC,CAAAA,CAAID,CAAAA,GAAQ,EAClB,OAAA,CAAA,CAASD,CAAAA,CAAKE,CAAC,CAAA,EAAK,CAAA,EAAM,CAAA,GAAMD,EAAM,EAAA,CAAA,IAAU,CAClD,CAOO,SAASI,CAAAA,CAAUC,CAAAA,CAA+B,CACvD,IAAMC,CAAAA,CAAM,IAAI,WAAA,CAAYD,CAAAA,CAAI,MAAM,EACtC,IAAA,IAASE,CAAAA,CAAI,CAAA,CA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AO6D,CAAa,CAC1C,CAOA,IAAI0F,CAAAA,CAAqC,IAAA,CAClC,SAASC,EAAAA,CAAqB/B,CAAAA,CAAyB,CAC5D8B,EAAgB9B,EAClB,CACA,SAASkB,EAAAA,EAA8B,CACrC,OAAKY,GACI,CAAE,wBAAA,CAA0B,IAAM,CAAC,CAAE,CAGhD,CAEA,IAAIE,CAAAA,CAAyE,IAAA,CACtE,SAASC,EAAAA,CAAyBtK,CAAAA,CAAsD,CAC7FqK,CAAAA,CAAoBrK,EACtB,CACA,SAASwJ,EAAAA,CAA0B3I,CAAAA,CAAmBwD,CAAAA,CAAqB,CACrEgG,CAAAA,EAAmBA,CAAAA,CAAkBxJ,CAAAA,CAAOwD,CAAG,EACrD","file":"chunk-Q2XLL6YG.cjs","sourcesContent":["export const VERSION = '0.5.9'\n","// Multi-word Uint32 bitmask helpers.\n\nexport function createMask(wordCount: number): Uint32Array {\n return new Uint32Array(wordCount)\n}\n\nexport function setBit(mask: Uint32Array, bit: number): void {\n const w = bit >>> 5\n mask[w] = (mask[w] ?? 0) | (1 << (bit & 31))\n}\n\nexport function clearBit(mask: Uint32Array, bit: number): void {\n const w = bit >>> 5\n mask[w] = (mask[w] ?? 0) & ~(1 << (bit & 31))\n}\n\nexport function testBit(mask: Uint32Array, bit: number): boolean {\n const w = bit >>> 5\n return ((mask[w] ?? 0) & (1 << (bit & 31))) !== 0\n}\n\nexport function copyMask(dst: Uint32Array, src: Uint32Array): void {\n const n = src.length\n for (let i = 0; i < n; i++) dst[i] = src[i] ?? 0\n}\n\nexport function cloneMask(src: Uint32Array): Uint32Array {\n const out = new Uint32Array(src.length)\n for (let i = 0; i < src.length; i++) out[i] = src[i] ?? 0\n return out\n}\n\nexport function maskEquals(a: Uint32Array, b: Uint32Array): boolean {\n const n = a.length\n if (b.length !== n) return false\n for (let i = 0; i < n; i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return false\n return true\n}\n\nexport function maskHash(m: Uint32Array): string {\n // Stable string key for Map lookups. Hex-joined.\n const parts: string[] = []\n for (let i = 0; i < m.length; i++) {\n parts.push((m[i] ?? 0).toString(16))\n }\n return parts.join(',')\n}\n\nexport function isMaskZero(m: Uint32Array): boolean {\n for (let i = 0; i < m.length; i++) if ((m[i] ?? 0) !== 0) return false\n return true\n}\n\nexport function unionMask(a: Uint32Array, b: Uint32Array): Uint32Array {\n const out = new Uint32Array(a.length)\n for (let i = 0; i < a.length; i++) out[i] = (a[i] ?? 0) | (b[i] ?? 0)\n return out\n}\n\n/**\n * Test whether an archetype's mask matches a query.\n * - withMask: all of these bits must be present\n * - anyMask: if anyHasBits, at least one of these bits must be present\n * - noneMask: none of these bits may be present\n */\nexport function matches(\n mask: Uint32Array,\n withMask: Uint32Array,\n anyMask: Uint32Array,\n noneMask: Uint32Array,\n anyHasBits: boolean,\n words: number,\n): boolean {\n let anyHit = !anyHasBits\n for (let w = 0; w < words; w++) {\n const m = mask[w] ?? 0\n const wm = withMask[w] ?? 0\n const am = anyMask[w] ?? 0\n const nm = noneMask[w] ?? 0\n if ((m & wm) !== wm) return false\n if ((m & nm) !== 0) return false\n if (!anyHit && (m & am) !== 0) anyHit = true\n }\n return anyHit\n}\n\nexport function listBits(mask: Uint32Array): number[] {\n const out: number[] = []\n for (let w = 0; w < mask.length; w++) {\n let word = mask[w] ?? 0\n while (word !== 0) {\n const bit = (w << 5) + ctz32(word)\n out.push(bit)\n word &= word - 1\n }\n }\n return out\n}\n\n// Iterate set bits in a slice of a larger Uint32Array starting at `base`.\n// Shared by destroy paths and storage cleanup so the bit-extraction maths\n// lives in exactly one place.\nexport function forEachSetBit(\n mask: Uint32Array,\n base: number,\n words: number,\n fn: (bit: number) => void,\n): void {\n for (let wi = 0; wi < words; wi++) {\n let word = mask[base + wi] ?? 0\n while (word !== 0) {\n const bit = (wi << 5) + ctz32(word)\n fn(bit)\n word &= word - 1\n }\n }\n}\n\n// Match a query against an entity's mask stored as a slice inside a larger\n// Uint32Array. Reading directly from the parent array avoids the temporary\n// Uint32Array allocation on every observer dispatch.\nexport function matchesEntityMask(\n entityMask: Uint32Array,\n base: number,\n words: number,\n withMask: Uint32Array,\n anyMask: Uint32Array,\n noneMask: Uint32Array,\n anyHasBits: boolean,\n): boolean {\n let anyHit = !anyHasBits\n for (let i = 0; i < words; i++) {\n const m = entityMask[base + i] ?? 0\n const wm = withMask[i] ?? 0\n const am = anyMask[i] ?? 0\n const nm = noneMask[i] ?? 0\n if ((m & wm) !== wm) return false\n if ((m & nm) !== 0) return false\n if (!anyHit && (m & am) !== 0) anyHit = true\n }\n return anyHit\n}\n\nfunction ctz32(v: number): number {\n // Count trailing zeros in a 32-bit integer (assumes v !== 0)\n return 31 - Math.clz32(v & -v)\n}\n","// aiecsjs/internal/errors — named error types for the core.\n\n/**\n * Thrown by core world/entity/component operations for invariant violations and\n * misuse (bad world options, a destroyed/unknown world, exhausted component\n * slots, capacity overflow). Carries the existing `aiecsjs: `-prefixed message.\n *\n * Catch this to distinguish an aiecsjs-originated failure from an unrelated\n * runtime error, instead of string-matching on the message. Mirrors the\n * {@link EntityNotAliveError} class style.\n *\n * @example\n * try {\n * createWorld({ indexBits: 99 })\n * } catch (err) {\n * if (err instanceof EcsError) {\n * // an aiecsjs invariant was violated\n * }\n * }\n */\nexport class EcsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'EcsError'\n }\n}\n","import { VERSION } from '../version.js'\nimport { cloneMask, copyMask, createMask, maskHash } from './bitmask.js'\nimport { EcsError } from './errors.js'\nimport type {\n ArchetypeState,\n ComponentInfo,\n FieldInfo,\n ResolvedWorldOptions,\n SoAColumns,\n World,\n WorldComponentStorage,\n WorldOptions,\n WorldState,\n} from './types.js'\n\nexport const WORLD_BRAND = Symbol.for('aiecsjs.world')\n\nconst DEFAULT_OPTIONS: Required<Omit<WorldOptions, 'buffer' | 'bufferByteOffset'>> = {\n initialCapacity: 1024,\n maxEntities: 1_000_000,\n indexBits: 24,\n generationBits: 8,\n}\n\nconst DEFAULT_MAX_COMPONENTS = 256\n\nlet nextWorldId = 1\nconst worldRegistry = new Map<number, WorldState>()\n\nexport function getWorldState(world: World): WorldState {\n const state = worldRegistry.get(world.id)\n if (!state) throw new EcsError(`aiecsjs: world ${world.id} is destroyed or unknown`)\n if (state.destroyed) throw new EcsError(`aiecsjs: world ${world.id} is destroyed`)\n return state\n}\n\nexport function registerWorld(state: WorldState): void {\n worldRegistry.set(state.id, state)\n}\n\nexport function unregisterWorld(id: number): void {\n worldRegistry.delete(id)\n}\n\nexport function isWorldRegistered(id: number): boolean {\n return worldRegistry.has(id)\n}\n\nfunction resolveOptions(opts: WorldOptions | undefined): ResolvedWorldOptions {\n const o = opts ?? {}\n const indexBits = o.indexBits ?? DEFAULT_OPTIONS.indexBits\n const generationBits = o.generationBits ?? DEFAULT_OPTIONS.generationBits\n const maxComponents = DEFAULT_MAX_COMPONENTS\n if (indexBits < 1 || indexBits > 24) {\n throw new EcsError('aiecsjs: indexBits must be in [1, 24]')\n }\n if (generationBits < 0 || generationBits > 16) {\n throw new EcsError('aiecsjs: generationBits must be in [0, 16]')\n }\n if (indexBits + generationBits > 32) {\n throw new EcsError(\n `aiecsjs: indexBits (${indexBits}) + generationBits (${generationBits}) must be <= 32`,\n )\n }\n const maxByIndex = 1 << indexBits\n const initialCapacity = Math.max(\n 1,\n Math.min(o.initialCapacity ?? DEFAULT_OPTIONS.initialCapacity, maxByIndex),\n )\n const maxEntities = Math.max(\n initialCapacity,\n Math.min(o.maxEntities ?? DEFAULT_OPTIONS.maxEntities, maxByIndex),\n )\n return {\n initialCapacity,\n maxEntities,\n indexBits,\n generationBits,\n indexMask: (1 << indexBits) - 1,\n generationMask: generationBits === 0 ? 0 : (1 << generationBits) - 1,\n maxComponents,\n maskWordCount: Math.ceil(maxComponents / 32),\n buffer: o.buffer ?? null,\n bufferByteOffset: o.bufferByteOffset ?? 0,\n }\n}\n\nexport function createEmptyArchetype(maskWordCount: number, maxComponents: number): ArchetypeState {\n return {\n id: 0,\n mask: createMask(maskWordCount),\n size: 0,\n capacity: 16,\n entities: new Uint32Array(16),\n entityRow: new Map<number, number>(),\n componentBits: [],\n edgeAdd: new Int32Array(maxComponents).fill(-1),\n edgeRemove: new Int32Array(maxComponents).fill(-1),\n }\n}\n\nexport function createWorld(options?: WorldOptions): World {\n const resolved = resolveOptions(options)\n const id = nextWorldId++\n\n const generationCtor = resolved.generationBits > 8 ? Uint16Array : Uint8Array\n const generations = new generationCtor(resolved.initialCapacity)\n\n const state: WorldState = {\n id,\n capacity: resolved.initialCapacity,\n version: VERSION,\n options: resolved,\n size: 0,\n nextFreshIndex: 1, // 0 reserved\n freeList: [],\n generations,\n destroyed: false,\n componentBitFor: new Map<number, number>(),\n componentInfoByBit: new Array(resolved.maxComponents).fill(null),\n componentStorageByBit: new Array(resolved.maxComponents).fill(null),\n nextComponentBit: 0,\n entityArchetype: new Uint32Array(resolved.initialCapacity),\n entityMask: new Uint32Array(resolved.initialCapacity * resolved.maskWordCount),\n archetypes: [],\n archetypeByMaskHash: new Map<string, number>(),\n queryVersion: 0,\n queries: [],\n queryMasks: new Map(),\n queryArchetypeCache: [],\n queryArchetypeStamp: [],\n bitToQueries: new Map<number, Set<number>>(),\n reactiveBuffers: new Map(),\n observers: [],\n relationStorage: new Map(),\n sab: resolved.buffer,\n readOnly: false,\n }\n\n // Seed archetype 0 (the empty mask)\n const empty = createEmptyArchetype(resolved.maskWordCount, resolved.maxComponents)\n empty.id = 0\n state.archetypes.push(empty)\n state.archetypeByMaskHash.set(maskHash(empty.mask), 0)\n\n registerWorld(state)\n return makePublicWorld(state)\n}\n\nexport function makePublicWorld(state: WorldState): World {\n return {\n id: state.id,\n get capacity() {\n return state.capacity\n },\n version: state.version,\n } as World\n}\n\nexport function destroyWorld(world: World): void {\n const state = worldRegistry.get(world.id)\n if (!state || state.destroyed) return\n state.destroyed = true\n // Clear large buffers to help GC. Post-dispose ops already throw via\n // getWorldState (state.destroyed), so releasing internal state can't regress\n // live behaviour; the capacity getter closure in makePublicWorld is the only\n // thing pinning `state`, so we must drop the big per-entity arrays here or\n // they survive as long as the (typically retained) public world handle.\n state.archetypes = []\n state.archetypeByMaskHash.clear()\n state.componentInfoByBit = []\n state.componentStorageByBit = []\n state.queries = []\n state.queryMasks.clear()\n state.queryArchetypeCache = []\n state.observers = []\n state.relationStorage.clear()\n state.reactiveBuffers.clear()\n // Release the remaining large per-entity arrays / indices that the original\n // \"clear large buffers\" pass left allocated (these dominate memory for big\n // worlds). Swap to length-0 instances rather than mutating in place.\n state.entityMask = new Uint32Array(0)\n state.entityArchetype = new Uint32Array(0)\n state.generations = new Uint8Array(0)\n state.freeList = []\n state.componentBitFor.clear()\n state.bitToQueries.clear()\n state.queryArchetypeStamp = []\n state.sab = null\n unregisterWorld(world.id)\n}\n\nexport function resetWorld(world: World): void {\n const state = getWorldState(world)\n // Keep capacity and registered components; clear entities and per-entity state.\n state.size = 0\n state.nextFreshIndex = 1\n state.freeList = []\n state.generations.fill(0)\n state.entityArchetype.fill(0)\n state.entityMask.fill(0)\n // Wipe archetype memberships but keep archetype graph for stability.\n for (const arch of state.archetypes) {\n arch.size = 0\n arch.entityRow.clear()\n }\n // Clear SoA columns and AoS instances; storage allocation is preserved.\n for (const storage of state.componentStorageByBit) {\n if (!storage) continue\n if (storage.kind === 'soa' && storage.soa) {\n for (const k of Object.keys(storage.soa)) {\n storage.soa[k]?.fill(0)\n }\n } else if (storage.kind === 'aos' && storage.aos) {\n storage.aos.fill(undefined as unknown as never)\n }\n }\n // Clear relation edges, exactly as destroyWorld does. relationStorage is keyed\n // by raw slot index; resetWorld restarts nextFreshIndex=1 and zeroes generations,\n // so recycled slots would otherwise inherit the prior occupant's relation edges\n // and data (C5). Storage is recreated lazily on the next addRelation.\n state.relationStorage.clear()\n state.queryVersion++\n for (const buf of state.reactiveBuffers.values()) {\n buf.entered.length = 0\n buf.exited.length = 0\n }\n}\n\nexport function getWorldSize(world: World): number {\n return getWorldState(world).size\n}\n\nexport function getWorldCapacity(world: World): number {\n return getWorldState(world).capacity\n}\n\n// --- Capacity growth ---\n\nexport function ensureCapacity(state: WorldState, needed: number): void {\n if (needed <= state.capacity) return\n if (needed > state.options.maxEntities) {\n throw new EcsError(\n `aiecsjs: requested capacity ${needed} exceeds maxEntities ${state.options.maxEntities}`,\n )\n }\n let newCap = state.capacity\n while (newCap < needed) newCap = Math.min(newCap * 2, state.options.maxEntities)\n growEntityArrays(state, newCap)\n}\n\nfunction growEntityArrays(state: WorldState, newCap: number): void {\n // generations\n const genCtor = state.generations.constructor as new (len: number) => Uint8Array | Uint16Array\n const newGen = new genCtor(newCap)\n ;(newGen as Uint8Array).set(state.generations as Uint8Array)\n state.generations = newGen\n\n // entityArchetype\n const newArch = new Uint32Array(newCap)\n newArch.set(state.entityArchetype)\n state.entityArchetype = newArch\n\n // entityMask\n const wordCount = state.options.maskWordCount\n const newMask = new Uint32Array(newCap * wordCount)\n newMask.set(state.entityMask)\n state.entityMask = newMask\n\n // Component storages (SoA columns + AoS arrays)\n for (const storage of state.componentStorageByBit) {\n if (!storage) continue\n if (storage.kind === 'soa' && storage.soa) {\n const info = state.componentInfoByBit[storage.bit]\n if (info) growSoAColumns(storage.soa, info.fields, newCap)\n } else if (storage.kind === 'aos' && storage.aos) {\n storage.aos.length = newCap\n }\n }\n\n state.capacity = newCap\n}\n\nfunction growSoAColumns(soa: SoAColumns, fields: FieldInfo[], newCap: number): void {\n for (const f of fields) {\n const old = soa[f.name]\n if (!old) continue\n const newLen = newCap * f.vectorLen\n if (old.length >= newLen) continue\n const next = new f.ctor(newLen)\n next.set(old)\n soa[f.name] = next\n }\n}\n\n// --- Archetype management ---\n\nexport function findOrCreateArchetype(\n state: WorldState,\n mask: Uint32Array,\n): { archId: number; created: boolean } {\n const key = maskHash(mask)\n const existing = state.archetypeByMaskHash.get(key)\n if (existing !== undefined) return { archId: existing, created: false }\n\n const id = state.archetypes.length\n const arch: ArchetypeState = {\n id,\n mask: cloneMask(mask),\n size: 0,\n capacity: 16,\n entities: new Uint32Array(16),\n entityRow: new Map<number, number>(),\n componentBits: collectBits(mask),\n edgeAdd: new Int32Array(state.options.maxComponents).fill(-1),\n edgeRemove: new Int32Array(state.options.maxComponents).fill(-1),\n }\n state.archetypes.push(arch)\n state.archetypeByMaskHash.set(key, id)\n state.queryVersion++\n return { archId: id, created: true }\n}\n\nexport function ensureArchetypeCapacity(arch: ArchetypeState, needed: number): void {\n if (needed <= arch.capacity) return\n let newCap = arch.capacity\n while (newCap < needed) newCap *= 2\n const next = new Uint32Array(newCap)\n next.set(arch.entities)\n arch.entities = next\n arch.capacity = newCap\n}\n\nfunction collectBits(mask: Uint32Array): number[] {\n const bits: number[] = []\n for (let w = 0; w < mask.length; w++) {\n let word = mask[w] ?? 0\n while (word !== 0) {\n const lsb = word & -word\n const bit = (w << 5) + (31 - Math.clz32(lsb))\n bits.push(bit)\n word &= word - 1\n }\n }\n return bits\n}\n\n// --- Component registration in a world ---\n\nexport function getOrRegisterComponentBit(state: WorldState, info: ComponentInfo): number {\n const existing = state.componentBitFor.get(info.id)\n if (existing !== undefined) return existing\n\n if (state.nextComponentBit >= state.options.maxComponents) {\n throw new EcsError(`aiecsjs: world reached maxComponents=${state.options.maxComponents}`)\n }\n const bit = state.nextComponentBit++\n state.componentBitFor.set(info.id, bit)\n state.componentInfoByBit[bit] = info\n\n // Create storage\n let storage: WorldComponentStorage\n if (info.kind === 'soa') {\n const soa: SoAColumns = {}\n for (const f of info.fields) {\n soa[f.name] = new f.ctor(state.capacity * f.vectorLen)\n }\n storage = { kind: 'soa', componentId: info.id, bit, soa }\n } else if (info.kind === 'aos') {\n storage = { kind: 'aos', componentId: info.id, bit, aos: new Array(state.capacity) }\n } else {\n storage = { kind: 'tag', componentId: info.id, bit }\n }\n state.componentStorageByBit[bit] = storage\n return bit\n}\n\n// Read a bitmask out of state.entityMask[] into a fresh Uint32Array.\nexport function readEntityMask(state: WorldState, eid: number): Uint32Array {\n const w = state.options.maskWordCount\n const out = new Uint32Array(w)\n const idx = eid & state.options.indexMask\n const base = idx * w\n for (let i = 0; i < w; i++) out[i] = state.entityMask[base + i] ?? 0\n return out\n}\n\nexport function writeEntityMask(state: WorldState, eid: number, mask: Uint32Array): void {\n const w = state.options.maskWordCount\n const idx = eid & state.options.indexMask\n const base = idx * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = mask[i] ?? 0\n}\n\n// Get the bit of a component within a world without registering.\nexport function tryGetComponentBit(state: WorldState, info: ComponentInfo): number | undefined {\n return state.componentBitFor.get(info.id)\n}\n\nexport function isWorld(x: unknown): x is World {\n if (!x || typeof x !== 'object') return false\n const obj = x as { id?: unknown; version?: unknown }\n if (typeof obj.id !== 'number') return false\n if (typeof obj.version !== 'string') return false\n return worldRegistry.has(obj.id)\n}\n","import { clearBit, cloneMask, forEachSetBit, setBit, testBit } from './bitmask.js'\nimport { isAliveInternal } from './entity.js'\nimport type {\n AoSComponent,\n ComponentInfo,\n ComponentInit,\n ComponentLike,\n EntityId,\n FieldInfo,\n SoAColumns,\n SoAComponent,\n SoAFieldDecl,\n SoAFieldType,\n SoASchema,\n TagComponent,\n TypedArrayConstructor,\n World,\n WorldComponentStorage,\n WorldState,\n} from './types.js'\nimport {\n ensureArchetypeCapacity,\n findOrCreateArchetype,\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n writeEntityMask,\n} from './world.js'\n\n// --- Component factories ---\n\nlet nextComponentId = 1\n\nconst TYPE_CTOR: Record<string, TypedArrayConstructor> = {\n i8: Int8Array,\n u8: Uint8Array,\n i16: Int16Array,\n u16: Uint16Array,\n i32: Int32Array,\n u32: Uint32Array,\n f32: Float32Array,\n f64: Float64Array,\n eid: Uint32Array,\n bool: Uint8Array,\n}\n\nconst componentInfoById = new Map<number, ComponentInfo>()\n\nexport function defineComponent<S extends SoASchema>(schema: S): SoAComponent<S> {\n const fields: FieldInfo[] = []\n for (const [name, decl] of Object.entries(schema) as [string, SoAFieldDecl][]) {\n let type: SoAFieldType\n let vectorLen = 1\n if (typeof decl === 'string') {\n type = decl\n } else if (Array.isArray(decl)) {\n const [t, len] = decl\n type = t\n vectorLen = len\n } else {\n throw new TypeError(`aiecsjs: invalid field declaration for \"${name}\"`)\n }\n const ctor = TYPE_CTOR[type]\n if (!ctor) throw new TypeError(`aiecsjs: unknown field type \"${type}\" for field \"${name}\"`)\n fields.push({\n name,\n type,\n vectorLen,\n ctor,\n bytesPerElement: ctor.BYTES_PER_ELEMENT,\n })\n }\n const id = nextComponentId++\n const info: ComponentInfo = { id, kind: 'soa', schema, fields, factory: null }\n componentInfoById.set(id, info)\n const handle: SoAComponent<S> = {\n __kind: 'soa',\n __id: id,\n __schema: schema,\n }\n return handle\n}\n\nexport function defineTag(): TagComponent {\n const id = nextComponentId++\n const info: ComponentInfo = { id, kind: 'tag', schema: null, fields: [], factory: null }\n componentInfoById.set(id, info)\n return { __kind: 'tag', __id: id }\n}\n\nexport function defineObjectComponent<T>(factory?: () => T): AoSComponent<T> {\n const id = nextComponentId++\n const fac = factory ?? (() => ({}) as T)\n const info: ComponentInfo = {\n id,\n kind: 'aos',\n schema: null,\n fields: [],\n factory: fac as () => unknown,\n }\n componentInfoById.set(id, info)\n return { __kind: 'aos', __id: id, __factory: fac }\n}\n\nexport function getComponentInfo(component: ComponentLike): ComponentInfo {\n const info = componentInfoById.get(component.__id)\n if (!info)\n throw new Error(\n 'aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)',\n )\n return info\n}\n\n// --- Component ops on entities ---\n\nexport function addComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n initial?: ComponentInit<C>,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) {\n throw new Error(`aiecsjs: addComponent on dead entity ${eid}`)\n }\n const info = getComponentInfo(component)\n const bit = getOrRegisterComponentBit(state, info)\n\n const prevMask = readEntityMask(state, eid)\n if (testBit(prevMask, bit)) {\n if (initial !== undefined) writeInitial(state, eid as number, component, initial)\n return\n }\n const newMask = cloneMask(prevMask)\n setBit(newMask, bit)\n migrateEntity(state, eid as number, newMask)\n\n writeInitial(state, eid as number, component, initial)\n\n fireAddObservers(state, eid, bit)\n notifyMaskChange(state, eid, bit, prevMask, newMask)\n}\n\nexport function removeComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) return\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return\n const prevMask = readEntityMask(state, eid)\n if (!testBit(prevMask, bit)) return\n\n // Write the new mask BEFORE firing observers so query-targeted observers\n // reading `state.entityMask` see the post-removal state (and thus correctly\n // detect \"entity left this query\"). Without this reorder, a query that\n // requires the removed component would still match during dispatch and the\n // remove observer would never fire. Component-targeted observers receive the\n // bit directly and don't depend on mask timing. addComponent already follows\n // this \"mutate then fire\" order; keeping removeComponent consistent.\n const newMask = cloneMask(prevMask)\n clearBit(newMask, bit)\n migrateEntity(state, eid as number, newMask)\n\n fireRemoveObservers(state, eid, bit)\n\n const idx = (eid as number) & state.options.indexMask\n const storage = state.componentStorageByBit[bit]\n if (storage?.kind === 'soa' && storage.soa) {\n clearSoAEntity(storage.soa, info.fields, idx)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[idx] = undefined\n }\n\n notifyMaskChange(state, eid, bit, prevMask, newMask)\n}\n\nexport function hasComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n): boolean {\n const state = getWorldState(world)\n if (!isAliveInternal(state, eid)) return false\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return false\n const mask = readEntityMask(state, eid)\n return testBit(mask, bit)\n}\n\nexport function getComponent<C extends ComponentLike>(\n world: World,\n eid: EntityId,\n component: C,\n): unknown {\n const state = getWorldState(world)\n if (!isAliveInternal(state, eid)) return undefined\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) return undefined\n const mask = readEntityMask(state, eid)\n if (!testBit(mask, bit)) return undefined\n const storage = state.componentStorageByBit[bit]\n if (!storage) return undefined\n if (storage.kind === 'soa') return storage.soa\n if (storage.kind === 'aos') {\n const idx = (eid as number) & state.options.indexMask\n return storage.aos?.[idx]\n }\n return true // tag\n}\n\nexport function setComponent<C extends ComponentLike, V>(\n world: World,\n eid: EntityId,\n component: C,\n value: V,\n): void {\n const state = getWorldState(world)\n if (state.readOnly) throw new Error('aiecsjs: cannot mutate a read-only world')\n if (!isAliveInternal(state, eid)) throw new Error(`aiecsjs: setComponent on dead entity ${eid}`)\n const info = getComponentInfo(component)\n const bit = tryGetComponentBit(state, info)\n if (bit === undefined) {\n // Adding via set\n addComponent(world, eid, component, value as ComponentInit<C>)\n return\n }\n const mask = readEntityMask(state, eid)\n if (!testBit(mask, bit)) {\n addComponent(world, eid, component, value as ComponentInit<C>)\n return\n }\n writeInitial(state, eid as number, component, value)\n fireSetObservers(state, eid, bit, value)\n}\n\n// --- Internals ---\n\nfunction writeInitial(\n state: WorldState,\n packedEid: number,\n component: ComponentLike,\n initial: unknown,\n): void {\n const info = getComponentInfo(component)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) return\n const storage = state.componentStorageByBit[bit]\n if (!storage) return\n // Unpack to raw index for storage access\n const idx = packedEid & state.options.indexMask\n if (info.kind === 'soa' && storage.soa) {\n if (initial == null) return\n const obj = initial as Record<string, unknown>\n for (const f of info.fields) {\n if (!(f.name in obj)) continue\n const col = storage.soa[f.name]\n if (!col) continue\n const val = obj[f.name]\n if (f.vectorLen === 1) {\n col[idx] = typeof val === 'boolean' ? (val ? 1 : 0) : Number(val)\n } else if (Array.isArray(val) || ArrayBuffer.isView(val)) {\n const base = idx * f.vectorLen\n const arr = val as ArrayLike<number>\n for (let i = 0; i < f.vectorLen; i++) col[base + i] = Number(arr[i] ?? 0)\n }\n }\n } else if (info.kind === 'aos' && storage.aos) {\n const factory = info.factory ?? (() => ({}))\n let inst = storage.aos[idx]\n if (inst === undefined) {\n inst = factory()\n storage.aos[idx] = inst\n }\n if (initial && typeof initial === 'object') {\n // SECURITY: do NOT use `Object.assign(inst, initial)` here. When `initial`\n // comes from `JSON.parse(untrustedBytes)` — e.g. via `fromJSON`,\n // `deserializeWorld`, or app code piping a bridge payload — the parsed\n // object can carry an OWN `__proto__` property, and `Object.assign` uses\n // [[Set]] semantics which would trigger the proto setter and clobber the\n // instance's prototype chain. Explicit own-key copy with a deny-list\n // closes the prototype-pollution path.\n const src = initial as Record<string, unknown>\n const target = inst as Record<string, unknown>\n for (const key of Object.keys(src)) {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue\n target[key] = src[key]\n }\n }\n }\n // tag: nothing\n}\n\nfunction clearSoAEntity(soa: SoAColumns, fields: FieldInfo[], eid: number): void {\n for (const f of fields) {\n const col = soa[f.name]\n if (!col) continue\n if (f.vectorLen === 1) {\n col[eid] = 0\n } else {\n const base = eid * f.vectorLen\n for (let i = 0; i < f.vectorLen; i++) col[base + i] = 0\n }\n }\n}\n\n// Clear every component-storage slot that the entity currently owns.\n// Walks the entity's mask; for each set bit, zeroes the SoA columns or\n// undefines the AoS slot at the entity index. Tag storages are bit-only.\n// Caller (e.g. destroyEntity) is expected to clear the mask separately.\nexport function clearAllEntityStorages(state: WorldState, eid: EntityId): void {\n const wordCount = state.options.maskWordCount\n const idx = (eid as number) & state.options.indexMask\n const base = idx * wordCount\n forEachSetBit(state.entityMask, base, wordCount, (bit) => {\n const storage = state.componentStorageByBit[bit]\n const info = state.componentInfoByBit[bit]\n if (storage?.kind === 'soa' && storage.soa && info) {\n clearSoAEntity(storage.soa, info.fields, idx)\n } else if (storage?.kind === 'aos' && storage.aos) {\n storage.aos[idx] = undefined\n }\n })\n}\n\nfunction migrateEntity(state: WorldState, packedEid: number, newMask: Uint32Array): void {\n // Unpack to raw index for sparse-array lookups\n const idx = packedEid & state.options.indexMask\n const srcArchId = state.entityArchetype[idx] ?? 0\n const srcArch = state.archetypes[srcArchId]\n if (!srcArch) return\n\n const found = findOrCreateArchetype(state, newMask)\n const destArchId = found.archId\n const destArch = state.archetypes[destArchId]\n if (!destArch) return\n\n if (destArchId !== srcArchId) {\n // Swap-pop from src (arch.entities / entityRow use packed eid as key)\n const row = srcArch.entityRow.get(packedEid)\n if (row !== undefined) {\n const lastRow = srcArch.size - 1\n if (row !== lastRow) {\n const moved = srcArch.entities[lastRow] ?? 0\n srcArch.entities[row] = moved\n srcArch.entityRow.set(moved, row)\n }\n srcArch.entities[lastRow] = 0\n srcArch.entityRow.delete(packedEid)\n srcArch.size--\n }\n\n // Append to dest (store packed eid)\n ensureArchetypeCapacity(destArch, destArch.size + 1)\n const newRow = destArch.size\n destArch.entities[newRow] = packedEid\n destArch.entityRow.set(packedEid, newRow)\n destArch.size++\n\n state.entityArchetype[idx] = destArchId\n }\n\n writeEntityMask(state, packedEid, newMask)\n}\n\n// --- Observer dispatch (lazy-bound) ---\n\ninterface ObserversDispatchAPI {\n fireAdd(state: WorldState, eid: EntityId, bit: number): void\n fireRemove(state: WorldState, eid: EntityId, bit: number): void\n fireSet(state: WorldState, eid: EntityId, bit: number, value: unknown): void\n}\nlet _dispatch: ObserversDispatchAPI = {\n fireAdd: () => {},\n fireRemove: () => {},\n fireSet: () => {},\n}\n\ntype MaskChangeFn = (\n state: WorldState,\n eid: EntityId,\n bit: number,\n prev: Uint32Array,\n next: Uint32Array,\n) => void\nlet _maskChange: MaskChangeFn = () => {}\nexport function registerMaskChangeDispatch(fn: MaskChangeFn): void {\n _maskChange = fn\n}\nfunction notifyMaskChange(\n state: WorldState,\n eid: number,\n bit: number,\n prev: Uint32Array,\n next: Uint32Array,\n): void {\n _maskChange(state, eid as EntityId, bit, prev, next)\n}\n\n// Fire the reactive enter/exit mask-change notification for an entity being\n// destroyed. destroyEntity clears the entity's mask wholesale rather than\n// removing components one-by-one, so it never reaches removeComponent's\n// `notifyMaskChange` call — leaving exitQuery buffers empty on destroy while a\n// component-by-component teardown would have populated them (asymmetric with\n// observe(q,'remove')). We replay the removals here.\n//\n// CORRECTNESS: transition ONE bit at a time through evolving masks, exactly as a\n// sequence of removeComponent() calls would. Passing a single (prevMask, empty)\n// pair once per set bit double-counts — a query matching on several of the\n// entity's components would see wasMatch=true,isMatch=false on every bit and push\n// the same exit N times. Clearing bits incrementally flips wasMatch=false after\n// the first component that breaks each query's match, so every query records\n// exactly one exit.\n//\n// SNAPSHOT DISCIPLINE: `prevMask` is captured at destroy entry (a private copy,\n// same discipline as dispatchDestroyObservers' preMask) so reentrant handlers\n// run earlier in destroy cannot mutate live state and suppress the exit. We\n// iterate that snapshot and mutate only our own clones.\nexport function dispatchDestroyMaskChange(\n state: WorldState,\n eid: EntityId,\n prevMask: Uint32Array,\n): void {\n const w = state.options.maskWordCount\n const before = cloneMask(prevMask) // current bit still set\n const after = cloneMask(prevMask) // current bit cleared\n forEachSetBit(prevMask, 0, w, (bit) => {\n clearBit(after, bit)\n notifyMaskChange(state, eid as number, bit, before, after)\n clearBit(before, bit)\n })\n}\nexport function registerObserverDispatch(api: ObserversDispatchAPI): void {\n _dispatch = api\n}\nfunction fireAddObservers(state: WorldState, eid: number, bit: number): void {\n _dispatch.fireAdd(state, eid as EntityId, bit)\n}\nfunction fireRemoveObservers(state: WorldState, eid: number, bit: number): void {\n _dispatch.fireRemove(state, eid as EntityId, bit)\n}\nfunction fireSetObservers(state: WorldState, eid: number, bit: number, value: unknown): void {\n _dispatch.fireSet(state, eid as EntityId, bit, value)\n}\n\n// --- Helper for serialize/worker ---\n\nexport function getComponentByInternalId(id: number): ComponentInfo | undefined {\n return componentInfoById.get(id)\n}\n\nexport function listAllComponents(): ComponentInfo[] {\n return Array.from(componentInfoById.values())\n}\n\nexport function _resetComponentRegistry_FOR_TESTS_ONLY(): void {\n componentInfoById.clear()\n nextComponentId = 1\n}\n","import { clearAllEntityStorages, dispatchDestroyMaskChange } from './component.js'\nimport type { EntityId, ResolvedWorldOptions, World, WorldState } from './types.js'\nimport { ensureArchetypeCapacity, ensureCapacity, getWorldState, readEntityMask } from './world.js'\n\n// --- Default bit layout constants (used by public getEntityIndex / getEntityGeneration / packEntity) ---\n// These use the default 24/8 split. See §4.4 limitation: callers using non-default\n// createWorld({ indexBits, generationBits }) should not rely on these functions for unpacking.\nexport const DEFAULT_INDEX_BITS = 24\nexport const DEFAULT_GENERATION_BITS = 8\nexport const DEFAULT_INDEX_MASK = (1 << DEFAULT_INDEX_BITS) - 1\nexport const DEFAULT_GENERATION_MASK = (1 << DEFAULT_GENERATION_BITS) - 1\n\n// --- Internal pack/unpack helpers (world-options-aware) ---\n\nexport function packEid(idx: number, gen: number, opts: ResolvedWorldOptions): EntityId {\n // `>>> 0` normalises to unsigned: for generation ≥ 128 (default 8-bit gen) the\n // signed `<<`/`|` would yield a negative number that diverges from the unsigned\n // value stored in `arch.entities` (Uint32Array), breaking entityRow lookups for\n // query-iterated high-generation entities. Keep EntityId a non-negative int32.\n return ((((gen & opts.generationMask) << opts.indexBits) | (idx & opts.indexMask)) >>>\n 0) as EntityId\n}\n\nexport function unpackIdx(eid: number, opts: ResolvedWorldOptions): number {\n return eid & opts.indexMask\n}\n\nexport function unpackGen(eid: number, opts: ResolvedWorldOptions): number {\n return (eid >>> opts.indexBits) & opts.generationMask\n}\n\nexport function createEntity(world: World): EntityId {\n const state = getWorldState(world)\n if (state.readOnly) {\n throw new Error('aiecsjs: cannot createEntity on a read-only world (worker-attached)')\n }\n\n let idx: number\n if (state.freeList.length > 0) {\n idx = state.freeList.pop()!\n } else {\n if (state.nextFreshIndex >= state.options.maxEntities) {\n throw new Error(`aiecsjs: reached maxEntities ${state.options.maxEntities}`)\n }\n if (state.nextFreshIndex >= state.capacity) {\n ensureCapacity(state, state.nextFreshIndex + 1)\n }\n idx = state.nextFreshIndex++\n }\n\n const gen = state.generations[idx] ?? 0\n const eid = packEid(idx, gen, state.options)\n\n // Move into the empty archetype (0)\n const arch = state.archetypes[0]\n if (!arch) throw new Error('aiecsjs: missing empty archetype')\n ensureArchetypeCapacity(arch, arch.size + 1)\n const row = arch.size\n arch.entities[row] = eid\n arch.entityRow.set(eid, row)\n arch.size++\n\n state.entityArchetype[idx] = 0\n // Reset entityMask row for this idx\n const w = state.options.maskWordCount\n const base = idx * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = 0\n\n state.size++\n return eid\n}\n\n// Ensure a LIVE entity occupies slot `idx`, returning its packed EntityId.\n// Used by delta apply() to materialise a replica entity at the SAME slot the\n// source used (the wire stores raw slot indices), so a source eid keeps\n// addressing the replica by slot. Mirrors createEntity's placement but targets\n// a specific slot:\n// - slot already live -> reuse it (return its current packed id)\n// - slot in the freeList -> reclaim it\n// - slot beyond the frontier -> advance nextFreshIndex, pushing the skipped\n// slots onto the freeList so they remain\n// allocatable (mirrors holes in the source)\n// The slot's CURRENT generation is used (never gen=0), so a replica whose\n// generation has advanced is handled without a dead-entity throw.\nexport function ensureEntityAtSlot(state: WorldState, idx: number): EntityId {\n if (state.readOnly) {\n /* v8 ignore next — defensive: apply() only writes to writable worlds */\n throw new Error('aiecsjs: cannot create entities on a read-only world (worker-attached)')\n }\n if (idx <= 0 || idx >= state.options.maxEntities) {\n /* v8 ignore next — defensive: apply() pre-guards the eid range */\n throw new Error(`aiecsjs: slot index ${idx} out of range`)\n }\n if (idx >= state.capacity) ensureCapacity(state, idx + 1)\n\n const gen = state.generations[idx] ?? 0\n const eid = packEid(idx, gen, state.options)\n if (isAliveInternal(state, eid)) return eid // already live — reuse\n\n // Reclaim the free slot.\n if (idx >= state.nextFreshIndex) {\n // Free the slots we skip over so they can still be allocated later.\n for (let s = state.nextFreshIndex; s < idx; s++) state.freeList.push(s)\n state.nextFreshIndex = idx + 1\n } else {\n // Below the frontier, so the slot must be in the freeList — remove it.\n const pos = state.freeList.lastIndexOf(idx)\n if (pos !== -1) {\n const last = state.freeList.length - 1\n state.freeList[pos] = state.freeList[last]!\n state.freeList.pop()\n }\n }\n\n // Place into the empty archetype (0) — identical to createEntity's tail.\n const arch = state.archetypes[0]\n if (!arch) throw new Error('aiecsjs: missing empty archetype')\n ensureArchetypeCapacity(arch, arch.size + 1)\n const row = arch.size\n arch.entities[row] = eid\n arch.entityRow.set(eid, row)\n arch.size++\n\n state.entityArchetype[idx] = 0\n const w = state.options.maskWordCount\n const base = idx * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = 0\n\n state.size++\n return eid\n}\n\nexport function destroyEntity(world: World, eid: EntityId): void {\n const state = getWorldState(world)\n if (state.readOnly) {\n throw new Error('aiecsjs: cannot destroyEntity on a read-only world')\n }\n if (!isAliveInternal(state, eid)) return\n\n const idx = eid & state.options.indexMask\n\n // Snapshot the pre-destroy mask BEFORE any teardown runs. dispatchDestroyObservers\n // (and relation cleanup) may reentrantly mutate live state.entityMask; capturing\n // here lets the reactive exit notification below fire against the state at destroy\n // entry — same snapshot discipline dispatchDestroyObservers uses for its preMask.\n const prevMask = readEntityMask(state, eid)\n\n // Fire onRemove for every component the entity has, plus reactive exit\n // (Late-bound to avoid circular imports — done via observers module.)\n const { dispatchDestroyObservers } = lazyObservers()\n dispatchDestroyObservers(state, eid)\n\n // Clean up relations referring to this entity\n cleanupRelationsOnDestroy(state, eid)\n\n // Zero the SoA columns / undefine the AoS slots the entity owned, before\n // the mask is cleared. Without this, destroyed entities leave stale data\n // visible to snapshots and serialisation.\n clearAllEntityStorages(state, eid)\n\n // Swap-pop from its archetype\n const archId = state.entityArchetype[idx] ?? 0\n const arch = state.archetypes[archId]\n if (arch) {\n const row = arch.entityRow.get(eid)\n if (row !== undefined) {\n const lastRow = arch.size - 1\n if (row !== lastRow) {\n const moved = arch.entities[lastRow] ?? 0\n arch.entities[row] = moved\n arch.entityRow.set(moved, row)\n }\n arch.entities[lastRow] = 0\n arch.entityRow.delete(eid)\n arch.size--\n }\n }\n\n // Notify the REACTIVE enter/exit surface that the entity is leaving every\n // query it was matching. destroyEntity clears the mask wholesale rather than\n // routing through removeComponent, so without this exitQuery buffers stay\n // empty on destroy (asymmetric with observe(q,'remove')). We pass the entry\n // snapshot so reentrant teardown handlers above cannot suppress the exit; the\n // helper computes post-state = empty mask (component absent).\n dispatchDestroyMaskChange(state, eid, prevMask)\n\n // Wipe state\n state.entityArchetype[idx] = 0\n const w = state.options.maskWordCount\n const base = idx * w\n for (let i = 0; i < w; i++) state.entityMask[base + i] = 0\n // Bump generation — use generationMask so non-default generationBits wraps correctly\n state.generations[idx] = ((state.generations[idx] ?? 0) + 1) & state.options.generationMask\n\n // freeList stores raw idx (not packed); createEntity packs on re-use\n state.freeList.push(idx)\n state.size--\n}\n\nexport function entityExists(world: World, eid: EntityId): boolean {\n const state = getWorldState(world)\n return isAliveInternal(state, eid)\n}\n\nexport function isAliveInternal(state: WorldState, eid: number): boolean {\n const idx = eid & state.options.indexMask\n if (idx <= 0) return false\n if (idx >= state.capacity) return false\n const archId = state.entityArchetype[idx] ?? 0\n const arch = state.archetypes[archId]\n if (!arch) return false\n if (!arch.entityRow.has(eid)) return false\n // Generation comparison: packed eid must match stored generation\n const storedGen = state.generations[idx] ?? 0\n const refGen = (eid >>> state.options.indexBits) & state.options.generationMask\n return storedGen === refGen\n}\n\n/**\n * Extract the index portion of a packed entity ID.\n *\n * Uses the default 24-bit index layout. If you created the world with a\n * non-default `indexBits`, use `EntityRef` + `deref` instead.\n */\nexport function getEntityIndex(eid: EntityId): number {\n return (eid as number) & DEFAULT_INDEX_MASK\n}\n\n/**\n * Extract the generation portion of a packed entity ID.\n *\n * Uses the default 8-bit generation layout. If you created the world with a\n * non-default `generationBits`, use `EntityRef` + `deref` instead.\n */\nexport function getEntityGeneration(eid: EntityId): number {\n return ((eid as number) >>> DEFAULT_INDEX_BITS) & DEFAULT_GENERATION_MASK\n}\n\n/**\n * Pack an index and generation into an EntityId using the default 24/8 bit layout.\n *\n * Uses the default `indexBits=24, generationBits=8`. If you created the world\n * with non-default bit sizes, this will produce values with incorrect layout.\n * Use `EntityRef` and `deref` for portable cross-world identity matching.\n */\nexport function packEntity(index: number, generation: number): EntityId {\n // `>>> 0` normalises to unsigned — see packEid. Keeps EntityId a non-negative int32.\n return ((((generation & DEFAULT_GENERATION_MASK) << DEFAULT_INDEX_BITS) |\n (index & DEFAULT_INDEX_MASK)) >>>\n 0) as EntityId\n}\n\nexport function isEntity(world: World, x: unknown): x is EntityId {\n if (typeof x !== 'number') return false\n return entityExists(world, x as EntityId)\n}\n\n// --- Lazy loaders to break import cycles ---\n\ninterface ObserversAPI {\n dispatchDestroyObservers(state: WorldState, eid: EntityId): void\n}\nlet _observersAPI: ObserversAPI | null = null\nexport function registerObserversAPI(api: ObserversAPI): void {\n _observersAPI = api\n}\nfunction lazyObservers(): ObserversAPI {\n if (!_observersAPI) {\n return { dispatchDestroyObservers: () => {} }\n }\n return _observersAPI\n}\n\nlet _relationsCleanup: ((state: WorldState, eid: EntityId) => void) | null = null\nexport function registerRelationsCleanup(fn: (state: WorldState, eid: EntityId) => void): void {\n _relationsCleanup = fn\n}\nfunction cleanupRelationsOnDestroy(state: WorldState, eid: EntityId): void {\n if (_relationsCleanup) _relationsCleanup(state, eid)\n}\n"]}
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkQ2XLL6YG_cjs=require('./chunk-Q2XLL6YG.cjs');var x=1,f=new Map;function A(n){let e=(n.all??[]).map(o=>o.__id).sort((o,i)=>o-i).join("-"),t=(n.any??[]).map(o=>o.__id).sort((o,i)=>o-i).join("-"),r=(n.none??[]).map(o=>o.__id).sort((o,i)=>o-i).join("-");return `A${e}|Y${t}|N${r}`}function T(n){let e=Array.isArray(n)?{all:n}:n;for(let i of [...e.all??[],...e.any??[],...e.none??[]])if(!i||typeof i!="object"||typeof i.__id!="number")throw new TypeError("aiecsjs: defineQuery received a non-component value");let t=A(e),r=f.get(t);if(r)return r;let o={id:x++,mask:[],all:(e.all??[]).map(i=>i.__id),any:(e.any??[]).map(i=>i.__id),none:(e.none??[]).map(i=>i.__id),columnViewCache:[...e.all??[],...e.any??[]],reactiveKind:"normal",sourceQueryId:-1,sourceQuery:null};return f.set(t,o),o}function $(n){let e=n,t=`enter:${e.id}`,r=f.get(t);if(r)return r;let o={id:x++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"enter",sourceQueryId:e.id,sourceQuery:e};return f.set(t,o),o}function D(n){let e=n,t=`exit:${e.id}`,r=f.get(t);if(r)return r;let o={id:x++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"exit",sourceQueryId:e.id,sourceQuery:e};return f.set(t,o),o}function p(n,e){if(n.queries[e.id]===e&&n.queryMasks.has(e.id))return;let t=n.options.maskWordCount,r=chunkQ2XLL6YG_cjs.b(t),o=chunkQ2XLL6YG_cjs.b(t),i=chunkQ2XLL6YG_cjs.b(t);for(let a of e.all){let u=g(a),d=chunkQ2XLL6YG_cjs.q(n,u);chunkQ2XLL6YG_cjs.c(r,d);}for(let a of e.any){let u=g(a),d=chunkQ2XLL6YG_cjs.q(n,u);chunkQ2XLL6YG_cjs.c(o,d);}for(let a of e.none){let u=g(a),d=chunkQ2XLL6YG_cjs.q(n,u);chunkQ2XLL6YG_cjs.c(i,d);}let c={withMask:r,anyMask:o,noneMask:i,anyHasBits:!chunkQ2XLL6YG_cjs.d(o)};n.queryMasks.set(e.id,c),n.queries[e.id]=e,n.queryArchetypeCache[e.id]=null,n.queryArchetypeStamp[e.id]=-1;let s=[...chunkQ2XLL6YG_cjs.f(r),...chunkQ2XLL6YG_cjs.f(o),...chunkQ2XLL6YG_cjs.f(i)];for(let a of s){let u=n.bitToQueries.get(a);u||(u=new Set,n.bitToQueries.set(a,u)),u.add(e.id);}e.reactiveKind!=="normal"&&(n.reactiveBuffers.has(e.id)||n.reactiveBuffers.set(e.id,{entered:[],exited:[]}),e.sourceQuery&&p(n,e.sourceQuery));}function h(n,e){if(p(n,e),n.queryArchetypeCache[e.id]&&n.queryArchetypeStamp[e.id]===n.queryVersion)return n.queryArchetypeCache[e.id];let t=n.queryMasks.get(e.id),r=n.options.maskWordCount,o=[];for(let i=0;i<n.archetypes.length;i++){let c=n.archetypes[i];chunkQ2XLL6YG_cjs.e(c.mask,t.withMask,t.anyMask,t.noneMask,t.anyHasBits,r)&&o.push(i);}return n.queryArchetypeCache[e.id]=o,n.queryArchetypeStamp[e.id]=n.queryVersion,o}function H(n,e){let t=chunkQ2XLL6YG_cjs.j(n),o=h(t,e),i=[];for(let c of o){let s=t.archetypes[c];i.push({id:s.id,mask:Array.from(s.mask),size:s.size});}return i}function L(n,e){let t=chunkQ2XLL6YG_cjs.j(n),r=e,o=[];if(r.reactiveKind==="enter"){let c=t.reactiveBuffers.get(r.id);if(c){for(let s of c.entered)o.push(s);c.entered.length=0;}return o}if(r.reactiveKind==="exit"){let c=t.reactiveBuffers.get(r.id);if(c){for(let s of c.exited)o.push(s);c.exited.length=0;}return o}let i=h(t,r);for(let c of i){let s=t.archetypes[c];for(let a=0;a<s.size;a++)o.push(s.entities[a]);}return o}function*F(n,e){let t=chunkQ2XLL6YG_cjs.j(n),r=e;if(r.reactiveKind!=="normal"){let i=t.reactiveBuffers.get(r.id);if(!i)return;let c=r.reactiveKind==="enter"?i.entered:i.exited;for(let s of c)yield s;c.length=0;return}let o=h(t,r);for(let i of o){let c=t.archetypes[i];for(let s=0;s<c.size;s++)yield c.entities[s];}}function O(n,e,t){let r=chunkQ2XLL6YG_cjs.j(n),o=e;if(o.reactiveKind!=="normal"){let s=r.reactiveBuffers.get(o.id);if(!s)return;let a=o.reactiveKind==="enter"?s.entered:s.exited;if(a.length===0)return;let u=b(r,o);for(let d=0;d<a.length;d++){let y=a[d];w(t,y,u);}a.length=0;return}p(r,o);let i=h(r,o),c=b(r,o);for(let s of i){let a=r.archetypes[s];for(let u=0;u<a.size;u++)w(t,a.entities[u],c);}}function w(n,e,t){switch(t.length){case 0:n(e);break;case 1:n(e,t[0]);break;case 2:n(e,t[0],t[1]);break;case 3:n(e,t[0],t[1],t[2]);break;case 4:n(e,t[0],t[1],t[2],t[3]);break;case 5:n(e,t[0],t[1],t[2],t[3],t[4]);break;default:n(e,...t);}}function G(n,e,t){let r=chunkQ2XLL6YG_cjs.j(n),o=e,i=r.options.indexMask;if(o.reactiveKind!=="normal"){let a=r.reactiveBuffers.get(o.id);if(!a)return;let u=o.reactiveKind==="enter"?a.entered:a.exited;if(u.length===0)return;let d=b(r,o);for(let y=0;y<u.length;y++){let E=u[y];W(t,E,E&i,d);}u.length=0;return}p(r,o);let c=h(r,o),s=b(r,o);for(let a of c){let u=r.archetypes[a];for(let d=0;d<u.size;d++){let y=u.entities[d];W(t,y,y&i,s);}}}function W(n,e,t,r){switch(r.length){case 0:n(e,t);break;case 1:n(e,t,r[0]);break;case 2:n(e,t,r[0],r[1]);break;case 3:n(e,t,r[0],r[1],r[2]);break;case 4:n(e,t,r[0],r[1],r[2],r[3]);break;case 5:n(e,t,r[0],r[1],r[2],r[3],r[4]);break;default:n(e,t,...r);}}function b(n,e){let t=[];for(let r of e.columnViewCache){let o=chunkQ2XLL6YG_cjs.J(r),i=n.componentBitFor.get(o.id);if(i===void 0){t.push(void 0);continue}let c=n.componentStorageByBit[i];if(!c){t.push(void 0);continue}c.kind==="soa"?t.push(c.soa):c.kind==="aos"?t.push(c.aos):t.push(true);}return t}function N(n,e,t,r,o){for(let s of f.values())s.reactiveKind!=="normal"&&s.sourceQuery&&n.queries[s.sourceQuery.id]!==s.sourceQuery&&p(n,s.sourceQuery);let i=n.bitToQueries.get(t);if(!i)return;let c=n.options.maskWordCount;for(let s of i){let a=n.queries[s];if(!a||a.reactiveKind!=="normal")continue;let u=n.queryMasks.get(s);if(!u)continue;let d=chunkQ2XLL6YG_cjs.e(r,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c),y=chunkQ2XLL6YG_cjs.e(o,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c);!d&&y?_(n,s,"enter",e):d&&!y&&_(n,s,"exit",e);}}function _(n,e,t,r){for(let o of f.values()){if(o.sourceQueryId!==e||o.reactiveKind!==t)continue;p(n,o);let i=K(n,o.id);t==="enter"?i.entered.push(r):i.exited.push(r);}}function K(n,e){let t=n.reactiveBuffers.get(e);return t||(t={entered:[],exited:[]},n.reactiveBuffers.set(e,t)),t}function g(n){let e=S(n);if(!e)throw new Error(`aiecsjs: component id ${n} not registered`);return e}var C=null;function U(n){C=n;}function S(n){return C?C(n):void 0}exports.a=T;exports.b=$;exports.c=D;exports.d=H;exports.e=L;exports.f=F;exports.g=O;exports.h=G;exports.i=N;exports.j=U;//# sourceMappingURL=chunk-USHKPJQG.cjs.map
2
+ //# sourceMappingURL=chunk-USHKPJQG.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/query.ts"],"names":["nextQueryId","moduleQueryCache","descKey","d","all","c","a","b","any","none","defineQuery","arg","desc","key","cached","q","enterQuery","query","reactive","exitQuery","ensureQueryRegistered","state","ww","withMask","createMask","anyMask","noneMask","compId","info","getComponentInfoById","bit","getOrRegisterComponentBit","setBit","bundle","isMaskZero","involvedBits","listBits","s","getQueryArchetypes","words","list","arch","matches","queryArchetypes","world","getWorldState","ids","out","id","runQuery","buf","e","archIds","r","iterQuery","src","forEachEntity","fn","cols","buildColumnViews","i","callWithCols","eid","forEachEntityIndexed","indexMask","callWithColsIndexed","comp","getComponentInfo","storage","recordEntityMaskChange","changedBit","prevMask","nextMask","involved","qid","wasMatch","isMatch","pushReactive","queryId","kind","ensureReactiveBuffer","componentId","lazyGetComponentInfo","_getComponentInfoFn","registerComponentLookup"],"mappings":"mEAsBA,IAAIA,CAAAA,CAAc,EACZC,CAAAA,CAAmB,IAAI,IAE7B,SAASC,CAAAA,CAAQC,EAA4B,CAC3C,IAAMC,GAAOD,CAAAA,CAAE,GAAA,EAAO,EAAC,EACpB,GAAA,CAAKE,GAAMA,CAAAA,CAAE,IAAI,CAAA,CACjB,IAAA,CAAK,CAACC,CAAAA,CAAGC,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nE,OAAOmC,CAAAA,CAAsBA,CAAAA,CAAoBnC,CAAE,CAAA,CAAI,MACzD","file":"chunk-USHKPJQG.cjs","sourcesContent":["import { createMask, isMaskZero, listBits, matches, setBit } from './bitmask.js'\nimport { getComponentInfo } from './component.js'\nimport type {\n Archetype,\n ComponentInfo,\n ComponentLike,\n EntityId,\n Query,\n QueryDescriptor,\n QueryInternal,\n QueryMaskBundle,\n ReactiveBuffer,\n World,\n WorldState,\n} from './types.js'\nimport {\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n} from './world.js'\n\nlet nextQueryId = 1\nconst moduleQueryCache = new Map<string, QueryInternal>()\n\nfunction descKey(d: QueryDescriptor): string {\n const all = (d.all ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const any = (d.any ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const none = (d.none ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n return `A${all}|Y${any}|N${none}`\n}\n\nexport function defineQuery(arg: ComponentLike[] | QueryDescriptor): Query {\n const desc: QueryDescriptor = Array.isArray(arg) ? { all: arg } : arg\n\n // Validate all members are components\n for (const c of [...(desc.all ?? []), ...(desc.any ?? []), ...(desc.none ?? [])]) {\n if (!c || typeof c !== 'object' || typeof (c as any).__id !== 'number') {\n throw new TypeError('aiecsjs: defineQuery received a non-component value')\n }\n }\n\n const key = descKey(desc)\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n\n const q: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: (desc.all ?? []).map((c) => c.__id),\n any: (desc.any ?? []).map((c) => c.__id),\n none: (desc.none ?? []).map((c) => c.__id),\n columnViewCache: [...(desc.all ?? []), ...(desc.any ?? [])],\n reactiveKind: 'normal',\n sourceQueryId: -1,\n sourceQuery: null,\n }\n moduleQueryCache.set(key, q)\n return q\n}\n\n/**\n * Reactive \"entered\" view of `query`: each read drains the entities that began\n * matching since the last read (via `runQuery` / `iterQuery` / `forEachEntity`).\n *\n * **MUST-DRAIN CONTRACT (unbounded buffer).** The enter buffer has **no cap**.\n * Every structural change that makes an entity newly match pushes one id; the\n * buffer only shrinks when you read the reactive view. A view that is created\n * but never read — e.g. a disabled system, or reading only the {@link exitQuery}\n * twin — accumulates one number per event **forever**, an unbounded memory leak\n * at churn rates (e.g. ~1k spawns/frame). Read every enter view you create, once\n * per frame. Dropping ids silently would corrupt enter/exit symmetry, so capping\n * is intentionally not done — draining is the caller's responsibility.\n */\nexport function enterQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `enter:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'enter',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\n/**\n * Reactive \"exited\" view of `query`: each read drains the entities that stopped\n * matching since the last read (via `runQuery` / `iterQuery` / `forEachEntity`).\n *\n * **MUST-DRAIN CONTRACT (unbounded buffer).** The exit buffer has **no cap** —\n * same discipline as {@link enterQuery}. An unread exit view accumulates one id\n * per matching structural change (including every `destroyEntity` of a matching\n * entity) without bound. Read every exit view you create, once per frame. Capping\n * is intentionally not done because dropping ids would break enter/exit symmetry.\n */\nexport function exitQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `exit:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'exit',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\n// --- Per-world query setup ---\n\nfunction ensureQueryRegistered(state: WorldState, q: QueryInternal): void {\n if (state.queries[q.id] === q && state.queryMasks.has(q.id)) return\n\n // Build per-world bitmasks (this may register new bits)\n const ww = state.options.maskWordCount\n const withMask = createMask(ww)\n const anyMask = createMask(ww)\n const noneMask = createMask(ww)\n for (const compId of q.all) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(withMask, bit)\n }\n for (const compId of q.any) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(anyMask, bit)\n }\n for (const compId of q.none) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(noneMask, bit)\n }\n\n const bundle: QueryMaskBundle = {\n withMask,\n anyMask,\n noneMask,\n anyHasBits: !isMaskZero(anyMask),\n }\n state.queryMasks.set(q.id, bundle)\n\n state.queries[q.id] = q\n state.queryArchetypeCache[q.id] = null\n state.queryArchetypeStamp[q.id] = -1\n\n // Build bit → queries index for fast reactive lookup\n const involvedBits: number[] = [\n ...listBits(withMask),\n ...listBits(anyMask),\n ...listBits(noneMask),\n ]\n for (const b of involvedBits) {\n let s = state.bitToQueries.get(b)\n if (!s) {\n s = new Set<number>()\n state.bitToQueries.set(b, s)\n }\n s.add(q.id)\n }\n\n // Initialize reactive buffer for enter/exit queries\n if (q.reactiveKind !== 'normal') {\n if (!state.reactiveBuffers.has(q.id)) {\n state.reactiveBuffers.set(q.id, { entered: [], exited: [] })\n }\n // Also register the source query so recordEntityMaskChange will see it\n if (q.sourceQuery) ensureQueryRegistered(state, q.sourceQuery)\n }\n}\n\nfunction getQueryArchetypes(state: WorldState, q: QueryInternal): number[] {\n ensureQueryRegistered(state, q)\n if (state.queryArchetypeCache[q.id] && state.queryArchetypeStamp[q.id] === state.queryVersion) {\n return state.queryArchetypeCache[q.id]!\n }\n const bundle = state.queryMasks.get(q.id)!\n const words = state.options.maskWordCount\n const list: number[] = []\n for (let i = 0; i < state.archetypes.length; i++) {\n const arch = state.archetypes[i]!\n if (\n matches(arch.mask, bundle.withMask, bundle.anyMask, bundle.noneMask, bundle.anyHasBits, words)\n ) {\n list.push(i)\n }\n }\n state.queryArchetypeCache[q.id] = list\n state.queryArchetypeStamp[q.id] = state.queryVersion\n return list\n}\n\nexport function queryArchetypes(world: World, query: Query): readonly Archetype[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const ids = getQueryArchetypes(state, q)\n const out: Archetype[] = []\n for (const id of ids) {\n const arch = state.archetypes[id]!\n out.push({ id: arch.id, mask: Array.from(arch.mask), size: arch.size })\n }\n return out\n}\n\nexport function runQuery(world: World, query: Query): readonly EntityId[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const out: EntityId[] = []\n if (q.reactiveKind === 'enter') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.entered) out.push(e as EntityId)\n buf.entered.length = 0\n }\n return out\n }\n if (q.reactiveKind === 'exit') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.exited) out.push(e as EntityId)\n buf.exited.length = 0\n }\n return out\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n out.push(arch.entities[r] as EntityId)\n }\n }\n return out\n}\n\nexport function* iterQuery(world: World, query: Query): IterableIterator<EntityId> {\n const state = getWorldState(world)\n const q = query as QueryInternal\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n for (const e of src) yield e as EntityId\n src.length = 0\n return\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n yield arch.entities[r] as EntityId\n }\n }\n}\n\n/**\n * Iterate every entity matching `query`, invoking `fn(e, ...cols)` once per row\n * with the packed {@link EntityId} and the query's SoA column views.\n *\n * **Caution — `e` is a packed EntityId, not a column subscript.** It carries the\n * generation in its high bits, so indexing a column view with it directly\n * (`pos.x[e]`) reads out of bounds once a slot has been recycled. Use `e` only\n * for identity operations (`destroyEntity` / `hasComponent` / `refOf`). To index\n * columns safely, prefer {@link forEachEntityIndexed} — which yields the masked\n * slot index `i` alongside `e` — or mask it yourself with {@link getEntityIndex}.\n *\n * @see {@link forEachEntityIndexed} — same iteration plus the safe column index `i`.\n * @see {@link getEntityIndex} — mask a packed EntityId to its raw slot index.\n */\nexport function forEachEntity(\n world: World,\n query: Query,\n fn: (eid: EntityId, ...cols: any[]) => void,\n): void {\n const state = getWorldState(world)\n const q = query as QueryInternal\n\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n if (src.length === 0) return\n const cols = buildColumnViews(state, q)\n for (let i = 0; i < src.length; i++) {\n const e = src[i] as EntityId\n callWithCols(fn, e, cols)\n }\n src.length = 0\n return\n }\n\n ensureQueryRegistered(state, q)\n const archIds = getQueryArchetypes(state, q)\n const cols = buildColumnViews(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n // Re-read `arch.size` AND `arch.entities` each iteration (do NOT cache either):\n // - `arch.size`: an in-loop `destroyEntity` swap-pops the visited row, shrinks\n // `arch.size`, and zeroes the freed tail slot. A cached bound would keep\n // walking into those zeroed tail rows and hand back the sentinel eid 0\n // (ECS-B-01). The swapped-in survivor is intentionally skipped this pass.\n // - `arch.entities`: an in-loop create (createEntity / addComponent landing in\n // this archetype) can grow it past capacity, so ensureArchetypeCapacity\n // swaps in a NEW, larger Uint32Array. A cached reference would still point at\n // the OLD shorter array, so its tail rows read `undefined` (C4) — the\n // sentinel leaking across the public callback boundary again.\n // Both are scalar property reads — no per-iteration allocation, so the\n // zero-allocation hot-path contract holds. Mirrors runQuery (:230) / iterQuery.\n for (let r = 0; r < arch.size; r++) {\n callWithCols(fn, arch.entities[r] as EntityId, cols)\n }\n }\n}\n\nfunction callWithCols(\n fn: (eid: EntityId, ...cols: any[]) => void,\n eid: EntityId,\n cols: any[],\n): void {\n // Specialise for low arities to avoid spread allocation.\n switch (cols.length) {\n case 0:\n fn(eid)\n break\n case 1:\n fn(eid, cols[0])\n break\n case 2:\n fn(eid, cols[0], cols[1])\n break\n case 3:\n fn(eid, cols[0], cols[1], cols[2])\n break\n case 4:\n fn(eid, cols[0], cols[1], cols[2], cols[3])\n break\n case 5:\n fn(eid, cols[0], cols[1], cols[2], cols[3], cols[4])\n break\n default:\n fn(eid, ...cols)\n }\n}\n\n/**\n * Like {@link forEachEntity}, but yields the masked column index `i` alongside\n * the packed `EntityId`. The callback signature is `(e, i, ...cols)`:\n *\n * - `e` — the packed EntityId (carries the generation in its high bits). Use\n * it for in-loop `destroyEntity` / `hasComponent` / `refOf`, exactly as with\n * `forEachEntity`.\n * - `i` — `e & indexMask`, the raw slot index. This is the **correct subscript**\n * for SoA column views (`pos.x[i]`), and stays correct after a slot is\n * recycled — where indexing with the packed `e` would read out of bounds.\n * - `...cols` — the same column views `forEachEntity` passes.\n *\n * This closes the packed-EntityId footgun (A1): callers no longer need to call\n * `getEntityIndex(e)` (or hand-mask) themselves to index columns safely.\n */\nexport function forEachEntityIndexed(\n world: World,\n query: Query,\n fn: (e: EntityId, i: number, ...cols: any[]) => void,\n): void {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const indexMask = state.options.indexMask\n\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n if (src.length === 0) return\n const cols = buildColumnViews(state, q)\n for (let i = 0; i < src.length; i++) {\n const e = src[i] as EntityId\n callWithColsIndexed(fn, e, e & indexMask, cols)\n }\n src.length = 0\n return\n }\n\n ensureQueryRegistered(state, q)\n const archIds = getQueryArchetypes(state, q)\n const cols = buildColumnViews(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n // Re-read `arch.size` AND `arch.entities` each iteration — see forEachEntity\n // for the rationale. An in-loop `destroyEntity` swap-pops the row and zeroes\n // the freed tail; an in-loop create can reallocate `arch.entities`. A cached\n // bound replays the sentinel eid 0, and a cached array reads `undefined` off\n // its stale tail — there `undefined & indexMask === 0`, so a bogus i=0 payload\n // leaks too (C4 / ECS-B-01). Scalar reads only; zero-allocation contract holds.\n for (let r = 0; r < arch.size; r++) {\n const e = arch.entities[r] as EntityId\n callWithColsIndexed(fn, e, e & indexMask, cols)\n }\n }\n}\n\nfunction callWithColsIndexed(\n fn: (e: EntityId, i: number, ...cols: any[]) => void,\n e: EntityId,\n i: number,\n cols: any[],\n): void {\n // Specialise for low arities to avoid spread allocation.\n switch (cols.length) {\n case 0:\n fn(e, i)\n break\n case 1:\n fn(e, i, cols[0])\n break\n case 2:\n fn(e, i, cols[0], cols[1])\n break\n case 3:\n fn(e, i, cols[0], cols[1], cols[2])\n break\n case 4:\n fn(e, i, cols[0], cols[1], cols[2], cols[3])\n break\n case 5:\n fn(e, i, cols[0], cols[1], cols[2], cols[3], cols[4])\n break\n default:\n fn(e, i, ...cols)\n }\n}\n\nfunction buildColumnViews(state: WorldState, q: QueryInternal): any[] {\n const out: any[] = []\n for (const comp of q.columnViewCache) {\n const info = getComponentInfo(comp)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n out.push(undefined)\n continue\n }\n const storage = state.componentStorageByBit[bit]\n if (!storage) {\n out.push(undefined)\n continue\n }\n if (storage.kind === 'soa') out.push(storage.soa)\n else if (storage.kind === 'aos') out.push(storage.aos)\n else out.push(true) // tag\n }\n return out\n}\n\n// --- Reactive query updates (called from migration code) ---\n\nexport function recordEntityMaskChange(\n state: WorldState,\n eid: EntityId,\n changedBit: number,\n prevMask: Uint32Array,\n nextMask: Uint32Array,\n): void {\n // Lazy-register any reactive queries (and their sources) so we can correctly\n // determine match transitions even if the user only ever called enterQuery/exitQuery.\n for (const q of moduleQueryCache.values()) {\n if (q.reactiveKind === 'normal') continue\n if (q.sourceQuery && state.queries[q.sourceQuery.id] !== q.sourceQuery) {\n ensureQueryRegistered(state, q.sourceQuery)\n }\n }\n\n const involved = state.bitToQueries.get(changedBit)\n if (!involved) return\n const words = state.options.maskWordCount\n for (const qid of involved) {\n const q = state.queries[qid]\n if (!q) continue\n if (q.reactiveKind !== 'normal') continue\n const bundle = state.queryMasks.get(qid)\n if (!bundle) continue\n const wasMatch = matches(\n prevMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n const isMatch = matches(\n nextMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n if (!wasMatch && isMatch) {\n pushReactive(state, qid, 'enter', eid)\n } else if (wasMatch && !isMatch) {\n pushReactive(state, qid, 'exit', eid)\n }\n }\n}\n\nfunction pushReactive(\n state: WorldState,\n queryId: number,\n kind: 'enter' | 'exit',\n eid: EntityId,\n): void {\n // Walk the module cache (not just state.queries) so reactive variants that\n // haven't been registered with this world yet still receive events.\n for (const r of moduleQueryCache.values()) {\n if (r.sourceQueryId !== queryId) continue\n if (r.reactiveKind !== kind) continue\n // Lazily register the reactive query in this world so subsequent reads can find it\n ensureQueryRegistered(state, r)\n const buf = ensureReactiveBuffer(state, r.id)\n if (kind === 'enter') buf.entered.push(eid as number)\n else buf.exited.push(eid as number)\n }\n}\n\nfunction ensureReactiveBuffer(state: WorldState, qid: number): ReactiveBuffer {\n let buf = state.reactiveBuffers.get(qid)\n if (!buf) {\n buf = { entered: [], exited: [] }\n state.reactiveBuffers.set(qid, buf)\n }\n return buf\n}\n\n// --- Helpers ---\n\nfunction getComponentInfoById(componentId: number): ComponentInfo {\n // We need access to the component registry's lookup by id. Re-import dynamically to avoid cycles.\n const info = lazyGetComponentInfo(componentId)\n if (!info) throw new Error(`aiecsjs: component id ${componentId} not registered`)\n return info\n}\n\nlet _getComponentInfoFn: ((id: number) => ComponentInfo | undefined) | null = null\nexport function registerComponentLookup(fn: (id: number) => ComponentInfo | undefined): void {\n _getComponentInfoFn = fn\n}\nfunction lazyGetComponentInfo(id: number): ComponentInfo | undefined {\n return _getComponentInfoFn ? _getComponentInfoFn(id) : undefined\n}\n\nexport function _resetQueryRegistry_FOR_TESTS_ONLY(): void {\n moduleQueryCache.clear()\n nextQueryId = 1\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {j,J,e,b as b$1,q,c,d,f as f$1}from'./chunk-OBMQME2P.js';var x=1,f=new Map;function A(n){let e=(n.all??[]).map(o=>o.__id).sort((o,i)=>o-i).join("-"),t=(n.any??[]).map(o=>o.__id).sort((o,i)=>o-i).join("-"),r=(n.none??[]).map(o=>o.__id).sort((o,i)=>o-i).join("-");return `A${e}|Y${t}|N${r}`}function T(n){let e=Array.isArray(n)?{all:n}:n;for(let i of [...e.all??[],...e.any??[],...e.none??[]])if(!i||typeof i!="object"||typeof i.__id!="number")throw new TypeError("aiecsjs: defineQuery received a non-component value");let t=A(e),r=f.get(t);if(r)return r;let o={id:x++,mask:[],all:(e.all??[]).map(i=>i.__id),any:(e.any??[]).map(i=>i.__id),none:(e.none??[]).map(i=>i.__id),columnViewCache:[...e.all??[],...e.any??[]],reactiveKind:"normal",sourceQueryId:-1,sourceQuery:null};return f.set(t,o),o}function $(n){let e=n,t=`enter:${e.id}`,r=f.get(t);if(r)return r;let o={id:x++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"enter",sourceQueryId:e.id,sourceQuery:e};return f.set(t,o),o}function D(n){let e=n,t=`exit:${e.id}`,r=f.get(t);if(r)return r;let o={id:x++,mask:[],all:e.all,any:e.any,none:e.none,columnViewCache:e.columnViewCache,reactiveKind:"exit",sourceQueryId:e.id,sourceQuery:e};return f.set(t,o),o}function p(n,e){if(n.queries[e.id]===e&&n.queryMasks.has(e.id))return;let t=n.options.maskWordCount,r=b$1(t),o=b$1(t),i=b$1(t);for(let a of e.all){let u=g(a),d=q(n,u);c(r,d);}for(let a of e.any){let u=g(a),d=q(n,u);c(o,d);}for(let a of e.none){let u=g(a),d=q(n,u);c(i,d);}let c$1={withMask:r,anyMask:o,noneMask:i,anyHasBits:!d(o)};n.queryMasks.set(e.id,c$1),n.queries[e.id]=e,n.queryArchetypeCache[e.id]=null,n.queryArchetypeStamp[e.id]=-1;let s=[...f$1(r),...f$1(o),...f$1(i)];for(let a of s){let u=n.bitToQueries.get(a);u||(u=new Set,n.bitToQueries.set(a,u)),u.add(e.id);}e.reactiveKind!=="normal"&&(n.reactiveBuffers.has(e.id)||n.reactiveBuffers.set(e.id,{entered:[],exited:[]}),e.sourceQuery&&p(n,e.sourceQuery));}function h(n,e$1){if(p(n,e$1),n.queryArchetypeCache[e$1.id]&&n.queryArchetypeStamp[e$1.id]===n.queryVersion)return n.queryArchetypeCache[e$1.id];let t=n.queryMasks.get(e$1.id),r=n.options.maskWordCount,o=[];for(let i=0;i<n.archetypes.length;i++){let c=n.archetypes[i];e(c.mask,t.withMask,t.anyMask,t.noneMask,t.anyHasBits,r)&&o.push(i);}return n.queryArchetypeCache[e$1.id]=o,n.queryArchetypeStamp[e$1.id]=n.queryVersion,o}function H(n,e){let t=j(n),o=h(t,e),i=[];for(let c of o){let s=t.archetypes[c];i.push({id:s.id,mask:Array.from(s.mask),size:s.size});}return i}function L(n,e){let t=j(n),r=e,o=[];if(r.reactiveKind==="enter"){let c=t.reactiveBuffers.get(r.id);if(c){for(let s of c.entered)o.push(s);c.entered.length=0;}return o}if(r.reactiveKind==="exit"){let c=t.reactiveBuffers.get(r.id);if(c){for(let s of c.exited)o.push(s);c.exited.length=0;}return o}let i=h(t,r);for(let c of i){let s=t.archetypes[c];for(let a=0;a<s.size;a++)o.push(s.entities[a]);}return o}function*F(n,e){let t=j(n),r=e;if(r.reactiveKind!=="normal"){let i=t.reactiveBuffers.get(r.id);if(!i)return;let c=r.reactiveKind==="enter"?i.entered:i.exited;for(let s of c)yield s;c.length=0;return}let o=h(t,r);for(let i of o){let c=t.archetypes[i];for(let s=0;s<c.size;s++)yield c.entities[s];}}function O(n,e,t){let r=j(n),o=e;if(o.reactiveKind!=="normal"){let s=r.reactiveBuffers.get(o.id);if(!s)return;let a=o.reactiveKind==="enter"?s.entered:s.exited;if(a.length===0)return;let u=b(r,o);for(let d=0;d<a.length;d++){let y=a[d];w(t,y,u);}a.length=0;return}p(r,o);let i=h(r,o),c=b(r,o);for(let s of i){let a=r.archetypes[s];for(let u=0;u<a.size;u++)w(t,a.entities[u],c);}}function w(n,e,t){switch(t.length){case 0:n(e);break;case 1:n(e,t[0]);break;case 2:n(e,t[0],t[1]);break;case 3:n(e,t[0],t[1],t[2]);break;case 4:n(e,t[0],t[1],t[2],t[3]);break;case 5:n(e,t[0],t[1],t[2],t[3],t[4]);break;default:n(e,...t);}}function G(n,e,t){let r=j(n),o=e,i=r.options.indexMask;if(o.reactiveKind!=="normal"){let a=r.reactiveBuffers.get(o.id);if(!a)return;let u=o.reactiveKind==="enter"?a.entered:a.exited;if(u.length===0)return;let d=b(r,o);for(let y=0;y<u.length;y++){let E=u[y];W(t,E,E&i,d);}u.length=0;return}p(r,o);let c=h(r,o),s=b(r,o);for(let a of c){let u=r.archetypes[a];for(let d=0;d<u.size;d++){let y=u.entities[d];W(t,y,y&i,s);}}}function W(n,e,t,r){switch(r.length){case 0:n(e,t);break;case 1:n(e,t,r[0]);break;case 2:n(e,t,r[0],r[1]);break;case 3:n(e,t,r[0],r[1],r[2]);break;case 4:n(e,t,r[0],r[1],r[2],r[3]);break;case 5:n(e,t,r[0],r[1],r[2],r[3],r[4]);break;default:n(e,t,...r);}}function b(n,e){let t=[];for(let r of e.columnViewCache){let o=J(r),i=n.componentBitFor.get(o.id);if(i===void 0){t.push(void 0);continue}let c=n.componentStorageByBit[i];if(!c){t.push(void 0);continue}c.kind==="soa"?t.push(c.soa):c.kind==="aos"?t.push(c.aos):t.push(true);}return t}function N(n,e$1,t,r,o){for(let s of f.values())s.reactiveKind!=="normal"&&s.sourceQuery&&n.queries[s.sourceQuery.id]!==s.sourceQuery&&p(n,s.sourceQuery);let i=n.bitToQueries.get(t);if(!i)return;let c=n.options.maskWordCount;for(let s of i){let a=n.queries[s];if(!a||a.reactiveKind!=="normal")continue;let u=n.queryMasks.get(s);if(!u)continue;let d=e(r,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c),y=e(o,u.withMask,u.anyMask,u.noneMask,u.anyHasBits,c);!d&&y?_(n,s,"enter",e$1):d&&!y&&_(n,s,"exit",e$1);}}function _(n,e,t,r){for(let o of f.values()){if(o.sourceQueryId!==e||o.reactiveKind!==t)continue;p(n,o);let i=K(n,o.id);t==="enter"?i.entered.push(r):i.exited.push(r);}}function K(n,e){let t=n.reactiveBuffers.get(e);return t||(t={entered:[],exited:[]},n.reactiveBuffers.set(e,t)),t}function g(n){let e=S(n);if(!e)throw new Error(`aiecsjs: component id ${n} not registered`);return e}var C=null;function U(n){C=n;}function S(n){return C?C(n):void 0}export{T as a,$ as b,D as c,H as d,L as e,F as f,O as g,G as h,N as i,U as j};//# sourceMappingURL=chunk-XKN3ULCC.js.map
2
+ //# sourceMappingURL=chunk-XKN3ULCC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/query.ts"],"names":["nextQueryId","moduleQueryCache","descKey","d","all","c","a","b","any","none","defineQuery","arg","desc","key","cached","q","enterQuery","query","reactive","exitQuery","ensureQueryRegistered","state","ww","withMask","createMask","anyMask","noneMask","compId","info","getComponentInfoById","bit","getOrRegisterComponentBit","setBit","bundle","isMaskZero","involvedBits","listBits","s","getQueryArchetypes","words","list","arch","matches","queryArchetypes","world","getWorldState","ids","out","id","runQuery","buf","e","archIds","r","iterQuery","src","forEachEntity","fn","cols","buildColumnViews","i","callWithCols","eid","forEachEntityIndexed","indexMask","callWithColsIndexed","comp","getComponentInfo","storage","recordEntityMaskChange","changedBit","prevMask","nextMask","involved","qid","wasMatch","isMatch","pushReactive","queryId","kind","ensureReactiveBuffer","componentId","lazyGetComponentInfo","_getComponentInfoFn","registerComponentLookup"],"mappings":"gEAsBA,IAAIA,CAAAA,C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,CAAW,iBAAiB,CAAA,CAChF,OAAOrD,CACT,CAEA,IAAIuD,EAA0E,IAAA,CACvE,SAASC,CAAAA,CAAwB3B,CAAAA,CAAqD,CAC3F0B,CAAAA,CAAsB1B,EACxB,CACA,SAASyB,EAAqBlC,CAAAA,CAAuC,CACnE,OAAOmC,CAAAA,CAAsBA,CAAAA,CAAoBnC,CAAE,CAAA,CAAI,MACzD","file":"chunk-XKN3ULCC.js","sourcesContent":["import { createMask, isMaskZero, listBits, matches, setBit } from './bitmask.js'\nimport { getComponentInfo } from './component.js'\nimport type {\n Archetype,\n ComponentInfo,\n ComponentLike,\n EntityId,\n Query,\n QueryDescriptor,\n QueryInternal,\n QueryMaskBundle,\n ReactiveBuffer,\n World,\n WorldState,\n} from './types.js'\nimport {\n getOrRegisterComponentBit,\n getWorldState,\n readEntityMask,\n tryGetComponentBit,\n} from './world.js'\n\nlet nextQueryId = 1\nconst moduleQueryCache = new Map<string, QueryInternal>()\n\nfunction descKey(d: QueryDescriptor): string {\n const all = (d.all ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const any = (d.any ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n const none = (d.none ?? [])\n .map((c) => c.__id)\n .sort((a, b) => a - b)\n .join('-')\n return `A${all}|Y${any}|N${none}`\n}\n\nexport function defineQuery(arg: ComponentLike[] | QueryDescriptor): Query {\n const desc: QueryDescriptor = Array.isArray(arg) ? { all: arg } : arg\n\n // Validate all members are components\n for (const c of [...(desc.all ?? []), ...(desc.any ?? []), ...(desc.none ?? [])]) {\n if (!c || typeof c !== 'object' || typeof (c as any).__id !== 'number') {\n throw new TypeError('aiecsjs: defineQuery received a non-component value')\n }\n }\n\n const key = descKey(desc)\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n\n const q: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: (desc.all ?? []).map((c) => c.__id),\n any: (desc.any ?? []).map((c) => c.__id),\n none: (desc.none ?? []).map((c) => c.__id),\n columnViewCache: [...(desc.all ?? []), ...(desc.any ?? [])],\n reactiveKind: 'normal',\n sourceQueryId: -1,\n sourceQuery: null,\n }\n moduleQueryCache.set(key, q)\n return q\n}\n\n/**\n * Reactive \"entered\" view of `query`: each read drains the entities that began\n * matching since the last read (via `runQuery` / `iterQuery` / `forEachEntity`).\n *\n * **MUST-DRAIN CONTRACT (unbounded buffer).** The enter buffer has **no cap**.\n * Every structural change that makes an entity newly match pushes one id; the\n * buffer only shrinks when you read the reactive view. A view that is created\n * but never read — e.g. a disabled system, or reading only the {@link exitQuery}\n * twin — accumulates one number per event **forever**, an unbounded memory leak\n * at churn rates (e.g. ~1k spawns/frame). Read every enter view you create, once\n * per frame. Dropping ids silently would corrupt enter/exit symmetry, so capping\n * is intentionally not done — draining is the caller's responsibility.\n */\nexport function enterQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `enter:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'enter',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\n/**\n * Reactive \"exited\" view of `query`: each read drains the entities that stopped\n * matching since the last read (via `runQuery` / `iterQuery` / `forEachEntity`).\n *\n * **MUST-DRAIN CONTRACT (unbounded buffer).** The exit buffer has **no cap** —\n * same discipline as {@link enterQuery}. An unread exit view accumulates one id\n * per matching structural change (including every `destroyEntity` of a matching\n * entity) without bound. Read every exit view you create, once per frame. Capping\n * is intentionally not done because dropping ids would break enter/exit symmetry.\n */\nexport function exitQuery(query: Query): Query {\n const q = query as QueryInternal\n const key = `exit:${q.id}`\n const cached = moduleQueryCache.get(key)\n if (cached) return cached\n const reactive: QueryInternal = {\n id: nextQueryId++,\n mask: [],\n all: q.all,\n any: q.any,\n none: q.none,\n columnViewCache: q.columnViewCache,\n reactiveKind: 'exit',\n sourceQueryId: q.id,\n sourceQuery: q,\n }\n moduleQueryCache.set(key, reactive)\n return reactive\n}\n\n// --- Per-world query setup ---\n\nfunction ensureQueryRegistered(state: WorldState, q: QueryInternal): void {\n if (state.queries[q.id] === q && state.queryMasks.has(q.id)) return\n\n // Build per-world bitmasks (this may register new bits)\n const ww = state.options.maskWordCount\n const withMask = createMask(ww)\n const anyMask = createMask(ww)\n const noneMask = createMask(ww)\n for (const compId of q.all) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(withMask, bit)\n }\n for (const compId of q.any) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(anyMask, bit)\n }\n for (const compId of q.none) {\n const info = getComponentInfoById(compId)\n const bit = getOrRegisterComponentBit(state, info)\n setBit(noneMask, bit)\n }\n\n const bundle: QueryMaskBundle = {\n withMask,\n anyMask,\n noneMask,\n anyHasBits: !isMaskZero(anyMask),\n }\n state.queryMasks.set(q.id, bundle)\n\n state.queries[q.id] = q\n state.queryArchetypeCache[q.id] = null\n state.queryArchetypeStamp[q.id] = -1\n\n // Build bit → queries index for fast reactive lookup\n const involvedBits: number[] = [\n ...listBits(withMask),\n ...listBits(anyMask),\n ...listBits(noneMask),\n ]\n for (const b of involvedBits) {\n let s = state.bitToQueries.get(b)\n if (!s) {\n s = new Set<number>()\n state.bitToQueries.set(b, s)\n }\n s.add(q.id)\n }\n\n // Initialize reactive buffer for enter/exit queries\n if (q.reactiveKind !== 'normal') {\n if (!state.reactiveBuffers.has(q.id)) {\n state.reactiveBuffers.set(q.id, { entered: [], exited: [] })\n }\n // Also register the source query so recordEntityMaskChange will see it\n if (q.sourceQuery) ensureQueryRegistered(state, q.sourceQuery)\n }\n}\n\nfunction getQueryArchetypes(state: WorldState, q: QueryInternal): number[] {\n ensureQueryRegistered(state, q)\n if (state.queryArchetypeCache[q.id] && state.queryArchetypeStamp[q.id] === state.queryVersion) {\n return state.queryArchetypeCache[q.id]!\n }\n const bundle = state.queryMasks.get(q.id)!\n const words = state.options.maskWordCount\n const list: number[] = []\n for (let i = 0; i < state.archetypes.length; i++) {\n const arch = state.archetypes[i]!\n if (\n matches(arch.mask, bundle.withMask, bundle.anyMask, bundle.noneMask, bundle.anyHasBits, words)\n ) {\n list.push(i)\n }\n }\n state.queryArchetypeCache[q.id] = list\n state.queryArchetypeStamp[q.id] = state.queryVersion\n return list\n}\n\nexport function queryArchetypes(world: World, query: Query): readonly Archetype[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const ids = getQueryArchetypes(state, q)\n const out: Archetype[] = []\n for (const id of ids) {\n const arch = state.archetypes[id]!\n out.push({ id: arch.id, mask: Array.from(arch.mask), size: arch.size })\n }\n return out\n}\n\nexport function runQuery(world: World, query: Query): readonly EntityId[] {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const out: EntityId[] = []\n if (q.reactiveKind === 'enter') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.entered) out.push(e as EntityId)\n buf.entered.length = 0\n }\n return out\n }\n if (q.reactiveKind === 'exit') {\n const buf = state.reactiveBuffers.get(q.id)\n if (buf) {\n for (const e of buf.exited) out.push(e as EntityId)\n buf.exited.length = 0\n }\n return out\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n out.push(arch.entities[r] as EntityId)\n }\n }\n return out\n}\n\nexport function* iterQuery(world: World, query: Query): IterableIterator<EntityId> {\n const state = getWorldState(world)\n const q = query as QueryInternal\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n for (const e of src) yield e as EntityId\n src.length = 0\n return\n }\n const archIds = getQueryArchetypes(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n for (let r = 0; r < arch.size; r++) {\n yield arch.entities[r] as EntityId\n }\n }\n}\n\n/**\n * Iterate every entity matching `query`, invoking `fn(e, ...cols)` once per row\n * with the packed {@link EntityId} and the query's SoA column views.\n *\n * **Caution — `e` is a packed EntityId, not a column subscript.** It carries the\n * generation in its high bits, so indexing a column view with it directly\n * (`pos.x[e]`) reads out of bounds once a slot has been recycled. Use `e` only\n * for identity operations (`destroyEntity` / `hasComponent` / `refOf`). To index\n * columns safely, prefer {@link forEachEntityIndexed} — which yields the masked\n * slot index `i` alongside `e` — or mask it yourself with {@link getEntityIndex}.\n *\n * @see {@link forEachEntityIndexed} — same iteration plus the safe column index `i`.\n * @see {@link getEntityIndex} — mask a packed EntityId to its raw slot index.\n */\nexport function forEachEntity(\n world: World,\n query: Query,\n fn: (eid: EntityId, ...cols: any[]) => void,\n): void {\n const state = getWorldState(world)\n const q = query as QueryInternal\n\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n if (src.length === 0) return\n const cols = buildColumnViews(state, q)\n for (let i = 0; i < src.length; i++) {\n const e = src[i] as EntityId\n callWithCols(fn, e, cols)\n }\n src.length = 0\n return\n }\n\n ensureQueryRegistered(state, q)\n const archIds = getQueryArchetypes(state, q)\n const cols = buildColumnViews(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n // Re-read `arch.size` AND `arch.entities` each iteration (do NOT cache either):\n // - `arch.size`: an in-loop `destroyEntity` swap-pops the visited row, shrinks\n // `arch.size`, and zeroes the freed tail slot. A cached bound would keep\n // walking into those zeroed tail rows and hand back the sentinel eid 0\n // (ECS-B-01). The swapped-in survivor is intentionally skipped this pass.\n // - `arch.entities`: an in-loop create (createEntity / addComponent landing in\n // this archetype) can grow it past capacity, so ensureArchetypeCapacity\n // swaps in a NEW, larger Uint32Array. A cached reference would still point at\n // the OLD shorter array, so its tail rows read `undefined` (C4) — the\n // sentinel leaking across the public callback boundary again.\n // Both are scalar property reads — no per-iteration allocation, so the\n // zero-allocation hot-path contract holds. Mirrors runQuery (:230) / iterQuery.\n for (let r = 0; r < arch.size; r++) {\n callWithCols(fn, arch.entities[r] as EntityId, cols)\n }\n }\n}\n\nfunction callWithCols(\n fn: (eid: EntityId, ...cols: any[]) => void,\n eid: EntityId,\n cols: any[],\n): void {\n // Specialise for low arities to avoid spread allocation.\n switch (cols.length) {\n case 0:\n fn(eid)\n break\n case 1:\n fn(eid, cols[0])\n break\n case 2:\n fn(eid, cols[0], cols[1])\n break\n case 3:\n fn(eid, cols[0], cols[1], cols[2])\n break\n case 4:\n fn(eid, cols[0], cols[1], cols[2], cols[3])\n break\n case 5:\n fn(eid, cols[0], cols[1], cols[2], cols[3], cols[4])\n break\n default:\n fn(eid, ...cols)\n }\n}\n\n/**\n * Like {@link forEachEntity}, but yields the masked column index `i` alongside\n * the packed `EntityId`. The callback signature is `(e, i, ...cols)`:\n *\n * - `e` — the packed EntityId (carries the generation in its high bits). Use\n * it for in-loop `destroyEntity` / `hasComponent` / `refOf`, exactly as with\n * `forEachEntity`.\n * - `i` — `e & indexMask`, the raw slot index. This is the **correct subscript**\n * for SoA column views (`pos.x[i]`), and stays correct after a slot is\n * recycled — where indexing with the packed `e` would read out of bounds.\n * - `...cols` — the same column views `forEachEntity` passes.\n *\n * This closes the packed-EntityId footgun (A1): callers no longer need to call\n * `getEntityIndex(e)` (or hand-mask) themselves to index columns safely.\n */\nexport function forEachEntityIndexed(\n world: World,\n query: Query,\n fn: (e: EntityId, i: number, ...cols: any[]) => void,\n): void {\n const state = getWorldState(world)\n const q = query as QueryInternal\n const indexMask = state.options.indexMask\n\n if (q.reactiveKind !== 'normal') {\n const buf = state.reactiveBuffers.get(q.id)\n if (!buf) return\n const src = q.reactiveKind === 'enter' ? buf.entered : buf.exited\n if (src.length === 0) return\n const cols = buildColumnViews(state, q)\n for (let i = 0; i < src.length; i++) {\n const e = src[i] as EntityId\n callWithColsIndexed(fn, e, e & indexMask, cols)\n }\n src.length = 0\n return\n }\n\n ensureQueryRegistered(state, q)\n const archIds = getQueryArchetypes(state, q)\n const cols = buildColumnViews(state, q)\n for (const id of archIds) {\n const arch = state.archetypes[id]!\n // Re-read `arch.size` AND `arch.entities` each iteration — see forEachEntity\n // for the rationale. An in-loop `destroyEntity` swap-pops the row and zeroes\n // the freed tail; an in-loop create can reallocate `arch.entities`. A cached\n // bound replays the sentinel eid 0, and a cached array reads `undefined` off\n // its stale tail — there `undefined & indexMask === 0`, so a bogus i=0 payload\n // leaks too (C4 / ECS-B-01). Scalar reads only; zero-allocation contract holds.\n for (let r = 0; r < arch.size; r++) {\n const e = arch.entities[r] as EntityId\n callWithColsIndexed(fn, e, e & indexMask, cols)\n }\n }\n}\n\nfunction callWithColsIndexed(\n fn: (e: EntityId, i: number, ...cols: any[]) => void,\n e: EntityId,\n i: number,\n cols: any[],\n): void {\n // Specialise for low arities to avoid spread allocation.\n switch (cols.length) {\n case 0:\n fn(e, i)\n break\n case 1:\n fn(e, i, cols[0])\n break\n case 2:\n fn(e, i, cols[0], cols[1])\n break\n case 3:\n fn(e, i, cols[0], cols[1], cols[2])\n break\n case 4:\n fn(e, i, cols[0], cols[1], cols[2], cols[3])\n break\n case 5:\n fn(e, i, cols[0], cols[1], cols[2], cols[3], cols[4])\n break\n default:\n fn(e, i, ...cols)\n }\n}\n\nfunction buildColumnViews(state: WorldState, q: QueryInternal): any[] {\n const out: any[] = []\n for (const comp of q.columnViewCache) {\n const info = getComponentInfo(comp)\n const bit = state.componentBitFor.get(info.id)\n if (bit === undefined) {\n out.push(undefined)\n continue\n }\n const storage = state.componentStorageByBit[bit]\n if (!storage) {\n out.push(undefined)\n continue\n }\n if (storage.kind === 'soa') out.push(storage.soa)\n else if (storage.kind === 'aos') out.push(storage.aos)\n else out.push(true) // tag\n }\n return out\n}\n\n// --- Reactive query updates (called from migration code) ---\n\nexport function recordEntityMaskChange(\n state: WorldState,\n eid: EntityId,\n changedBit: number,\n prevMask: Uint32Array,\n nextMask: Uint32Array,\n): void {\n // Lazy-register any reactive queries (and their sources) so we can correctly\n // determine match transitions even if the user only ever called enterQuery/exitQuery.\n for (const q of moduleQueryCache.values()) {\n if (q.reactiveKind === 'normal') continue\n if (q.sourceQuery && state.queries[q.sourceQuery.id] !== q.sourceQuery) {\n ensureQueryRegistered(state, q.sourceQuery)\n }\n }\n\n const involved = state.bitToQueries.get(changedBit)\n if (!involved) return\n const words = state.options.maskWordCount\n for (const qid of involved) {\n const q = state.queries[qid]\n if (!q) continue\n if (q.reactiveKind !== 'normal') continue\n const bundle = state.queryMasks.get(qid)\n if (!bundle) continue\n const wasMatch = matches(\n prevMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n const isMatch = matches(\n nextMask,\n bundle.withMask,\n bundle.anyMask,\n bundle.noneMask,\n bundle.anyHasBits,\n words,\n )\n if (!wasMatch && isMatch) {\n pushReactive(state, qid, 'enter', eid)\n } else if (wasMatch && !isMatch) {\n pushReactive(state, qid, 'exit', eid)\n }\n }\n}\n\nfunction pushReactive(\n state: WorldState,\n queryId: number,\n kind: 'enter' | 'exit',\n eid: EntityId,\n): void {\n // Walk the module cache (not just state.queries) so reactive variants that\n // haven't been registered with this world yet still receive events.\n for (const r of moduleQueryCache.values()) {\n if (r.sourceQueryId !== queryId) continue\n if (r.reactiveKind !== kind) continue\n // Lazily register the reactive query in this world so subsequent reads can find it\n ensureQueryRegistered(state, r)\n const buf = ensureReactiveBuffer(state, r.id)\n if (kind === 'enter') buf.entered.push(eid as number)\n else buf.exited.push(eid as number)\n }\n}\n\nfunction ensureReactiveBuffer(state: WorldState, qid: number): ReactiveBuffer {\n let buf = state.reactiveBuffers.get(qid)\n if (!buf) {\n buf = { entered: [], exited: [] }\n state.reactiveBuffers.set(qid, buf)\n }\n return buf\n}\n\n// --- Helpers ---\n\nfunction getComponentInfoById(componentId: number): ComponentInfo {\n // We need access to the component registry's lookup by id. Re-import dynamically to avoid cycles.\n const info = lazyGetComponentInfo(componentId)\n if (!info) throw new Error(`aiecsjs: component id ${componentId} not registered`)\n return info\n}\n\nlet _getComponentInfoFn: ((id: number) => ComponentInfo | undefined) | null = null\nexport function registerComponentLookup(fn: (id: number) => ComponentInfo | undefined): void {\n _getComponentInfoFn = fn\n}\nfunction lazyGetComponentInfo(id: number): ComponentInfo | undefined {\n return _getComponentInfoFn ? _getComponentInfoFn(id) : undefined\n}\n\nexport function _resetQueryRegistry_FOR_TESTS_ONLY(): void {\n moduleQueryCache.clear()\n nextQueryId = 1\n}\n"]}
@@ -1,2 +1,2 @@
1
- import {j,s,l,v,R as R$1,K,a,S,w}from'./chunk-YFTCD2UG.js';var p="AIEC",b=1;function Q(n,o){let e=B(n);return o?.components&&(e.entities=e.entities.map(t=>({eid:t.eid,components:t.components.filter(i=>o.components.some(c=>c.__id===i.id))}))),D(e)}function Z(n,o){let e=x(n,o);return T(e)}function B(n){let o=j(n),e=[];for(let t=1;t<o.capacity;t++){let i=o.entityArchetype[t]??0;if(i===0)continue;let c=o.archetypes[i];if(!c)continue;let r=o.generations[t]??0,a=s(t,r,o.options);if(!c.entityRow.has(a))continue;let s$1=o.options.maskWordCount,f=t*s$1,l=[];for(let d=0;d<s$1;d++){let m=o.entityMask[f+d]??0;for(;m!==0;){let M=m&-m,_=(d<<5)+(31-Math.clz32(M)),h=o.componentInfoByBit[_];if(h){let S=o.componentStorageByBit[_],w=null;if(h.kind==="soa"&&S?.soa){let y={};for(let u of h.fields){let g=S.soa[u.name];if(g)if(u.vectorLen===1)y[u.name]=g[t];else {let v=[],N=t*u.vectorLen;for(let C=0;C<u.vectorLen;C++)v.push(g[N+C]??0);y[u.name]=v;}}w=y;}else h.kind==="aos"&&S?.aos?w=S.aos[t]??null:w=true;l.push({kind:h.kind,id:h.id,data:w});}m&=m-1;}}e.push({eid:t,components:l});}return {version:o.version,capacity:o.capacity,entities:e}}var R=1024;function J(n,o){let e=Math.max(R,o+1);return typeof n!="number"||!Number.isFinite(n)||n<=0?e:Math.min(Math.floor(n),e)}function T(n){let o=J(n.capacity,n.entities.length),e=l({initialCapacity:o}),t=new Map;for(let i of n.entities){let c=v(e);t.set(i.eid,c);}for(let i of n.entities){let c=t.get(i.eid);for(let r of i.components){let a=R$1(r.id);if(!a)continue;let s=A(a);s&&K(e,c,s,r.data);}}return e}function A(n){if(n.kind==="soa")return {__kind:"soa",__id:n.id,__schema:n.schema??{}};if(n.kind==="aos"){let o=n.factory??(()=>({}));return {__kind:"aos",__id:n.id,__factory:o}}return {__kind:"tag",__id:n.id}}function D(n){let o=JSON.stringify(n),e=new TextEncoder().encode(o),t=new TextEncoder().encode(a),c=12+t.length+4+e.length,r=new Uint8Array(c),a$1=new DataView(r.buffer),s=0;return r[s++]=p.charCodeAt(0),r[s++]=p.charCodeAt(1),r[s++]=p.charCodeAt(2),r[s++]=p.charCodeAt(3),a$1.setUint32(s,b,true),s+=4,a$1.setUint32(s,t.length,true),s+=4,r.set(t,s),s+=t.length,a$1.setUint32(s,e.length,true),s+=4,r.set(e,s),r}function x(n,o){if(n.length<12)throw new Error("aiecsjs: bytes too short to be a valid snapshot");let e=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n[0]!==p.charCodeAt(0)||n[1]!==p.charCodeAt(1)||n[2]!==p.charCodeAt(2)||n[3]!==p.charCodeAt(3))throw new Error("aiecsjs: invalid magic bytes");let t=4,i=e.getUint32(t,true);t+=4;let c=o?.onUnknownVersion??"throw";if(i!==b&&c==="throw")throw new Error(`aiecsjs: format version ${i} not supported`);let r=64*1024*1024;if(t+4>n.length)throw new Error("aiecsjs: snapshot truncated before verLen");let a=e.getUint32(t,true);if(t+=4,a>r||t+a>n.length)throw new Error(`aiecsjs: snapshot verLen=${a} out of bounds`);if(t+=a,t+4>n.length)throw new Error("aiecsjs: snapshot truncated before jsonLen");let s=e.getUint32(t,true);if(t+=4,s>r||t+s>n.length)throw new Error(`aiecsjs: snapshot jsonLen=${s} out of bounds`);let f=n.subarray(t,t+s),l=new TextDecoder().decode(f);try{return JSON.parse(l)}catch(d){throw new Error("aiecsjs: snapshot body is not valid JSON",{cause:d})}}function tt(n,o){let e={world:n,components:o?.components??S().map(t=>A(t)).filter(Boolean),lastSnapshot:null};return {capture(){let t=B(e.world),i;return e.lastSnapshot?i=V(e.lastSnapshot,t):i=t,e.lastSnapshot=t,D(i)},apply(t,i){let c=x(i),r=j(t);for(let a of c.entities){if(a.eid<=0||a.eid>=r.options.maxEntities)continue;let s=w(r,a.eid);for(let f of a.components){let l=R$1(f.id);if(!l)continue;let d=A(l);d&&K(t,s,d,f.data);}}},reset(){e.lastSnapshot=null;}}}function V(n,o){let e=new Map(n.entities.map(i=>[i.eid,i])),t=[];for(let i of o.entities){let c=e.get(i.eid);if(!c){t.push(i);continue}let r=JSON.stringify(c.components),a=JSON.stringify(i.components);r!==a&&t.push(i);}return {version:o.version,capacity:o.capacity,entities:t}}export{Q as a,Z as b,B as c,T as d,tt as e};//# sourceMappingURL=chunk-TNZMD7E5.js.map
2
- //# sourceMappingURL=chunk-TNZMD7E5.js.map
1
+ import {j,s,l,v,R as R$1,K,a,S,w}from'./chunk-OBMQME2P.js';var p="AIEC",b=1;function Q(n,o){let e=B(n);return o?.components&&(e.entities=e.entities.map(t=>({eid:t.eid,components:t.components.filter(i=>o.components.some(c=>c.__id===i.id))}))),D(e)}function Z(n,o){let e=x(n,o);return T(e)}function B(n){let o=j(n),e=[];for(let t=1;t<o.capacity;t++){let i=o.entityArchetype[t]??0;if(i===0)continue;let c=o.archetypes[i];if(!c)continue;let r=o.generations[t]??0,a=s(t,r,o.options);if(!c.entityRow.has(a))continue;let s$1=o.options.maskWordCount,f=t*s$1,l=[];for(let d=0;d<s$1;d++){let m=o.entityMask[f+d]??0;for(;m!==0;){let M=m&-m,_=(d<<5)+(31-Math.clz32(M)),h=o.componentInfoByBit[_];if(h){let S=o.componentStorageByBit[_],w=null;if(h.kind==="soa"&&S?.soa){let y={};for(let u of h.fields){let g=S.soa[u.name];if(g)if(u.vectorLen===1)y[u.name]=g[t];else {let v=[],N=t*u.vectorLen;for(let C=0;C<u.vectorLen;C++)v.push(g[N+C]??0);y[u.name]=v;}}w=y;}else h.kind==="aos"&&S?.aos?w=S.aos[t]??null:w=true;l.push({kind:h.kind,id:h.id,data:w});}m&=m-1;}}e.push({eid:t,components:l});}return {version:o.version,capacity:o.capacity,entities:e}}var R=1024;function J(n,o){let e=Math.max(R,o+1);return typeof n!="number"||!Number.isFinite(n)||n<=0?e:Math.min(Math.floor(n),e)}function T(n){let o=J(n.capacity,n.entities.length),e=l({initialCapacity:o}),t=new Map;for(let i of n.entities){let c=v(e);t.set(i.eid,c);}for(let i of n.entities){let c=t.get(i.eid);for(let r of i.components){let a=R$1(r.id);if(!a)continue;let s=A(a);s&&K(e,c,s,r.data);}}return e}function A(n){if(n.kind==="soa")return {__kind:"soa",__id:n.id,__schema:n.schema??{}};if(n.kind==="aos"){let o=n.factory??(()=>({}));return {__kind:"aos",__id:n.id,__factory:o}}return {__kind:"tag",__id:n.id}}function D(n){let o=JSON.stringify(n),e=new TextEncoder().encode(o),t=new TextEncoder().encode(a),c=12+t.length+4+e.length,r=new Uint8Array(c),a$1=new DataView(r.buffer),s=0;return r[s++]=p.charCodeAt(0),r[s++]=p.charCodeAt(1),r[s++]=p.charCodeAt(2),r[s++]=p.charCodeAt(3),a$1.setUint32(s,b,true),s+=4,a$1.setUint32(s,t.length,true),s+=4,r.set(t,s),s+=t.length,a$1.setUint32(s,e.length,true),s+=4,r.set(e,s),r}function x(n,o){if(n.length<12)throw new Error("aiecsjs: bytes too short to be a valid snapshot");let e=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n[0]!==p.charCodeAt(0)||n[1]!==p.charCodeAt(1)||n[2]!==p.charCodeAt(2)||n[3]!==p.charCodeAt(3))throw new Error("aiecsjs: invalid magic bytes");let t=4,i=e.getUint32(t,true);t+=4;let c=o?.onUnknownVersion??"throw";if(i!==b&&c==="throw")throw new Error(`aiecsjs: format version ${i} not supported`);let r=64*1024*1024;if(t+4>n.length)throw new Error("aiecsjs: snapshot truncated before verLen");let a=e.getUint32(t,true);if(t+=4,a>r||t+a>n.length)throw new Error(`aiecsjs: snapshot verLen=${a} out of bounds`);if(t+=a,t+4>n.length)throw new Error("aiecsjs: snapshot truncated before jsonLen");let s=e.getUint32(t,true);if(t+=4,s>r||t+s>n.length)throw new Error(`aiecsjs: snapshot jsonLen=${s} out of bounds`);let f=n.subarray(t,t+s),l=new TextDecoder().decode(f);try{return JSON.parse(l)}catch(d){throw new Error("aiecsjs: snapshot body is not valid JSON",{cause:d})}}function tt(n,o){let e={world:n,components:o?.components??S().map(t=>A(t)).filter(Boolean),lastSnapshot:null};return {capture(){let t=B(e.world),i;return e.lastSnapshot?i=V(e.lastSnapshot,t):i=t,e.lastSnapshot=t,D(i)},apply(t,i){let c=x(i),r=j(t);for(let a of c.entities){if(a.eid<=0||a.eid>=r.options.maxEntities)continue;let s=w(r,a.eid);for(let f of a.components){let l=R$1(f.id);if(!l)continue;let d=A(l);d&&K(t,s,d,f.data);}}},reset(){e.lastSnapshot=null;}}}function V(n,o){let e=new Map(n.entities.map(i=>[i.eid,i])),t=[];for(let i of o.entities){let c=e.get(i.eid);if(!c){t.push(i);continue}let r=JSON.stringify(c.components),a=JSON.stringify(i.components);r!==a&&t.push(i);}return {version:o.version,capacity:o.capacity,entities:t}}export{Q as a,Z as b,B as c,T as d,tt as e};//# sourceMappingURL=chunk-ZZBNE7C5.js.map
2
+ //# sourceMappingURL=chunk-ZZBNE7C5.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/serialize.ts"],"names":["MAGIC","FORMAT_VERSION","serializeWorld","world","options","snapshot","toJSON","e","c","comp","packBinary","deserializeWorld","bytes","unpackBinary","fromJSON","state","getWorldState","entities","idx","archId","arch","gen","packedEid","packEid","w","base","components","wi","word","lsb","bit","info","storage","data","obj","f","col","arr","baseI","i","RESTORE_CAPACITY_FLOOR","clampRestoreCapacity","rawCapacity","entityCount","needed","initialCapacity","createWorld","eidMap","eid","createEntity","getComponentByInternalId","handle","getComponentHandle","addComponent","factory","json","jsonBytes","versionBytes","VERSION","total","out","view","off","formatVersion","onUnknown","MAX_FIELD_LEN","verLen","jsonLen","cause","createDeltaSerializer","listAllComponents","current","delta","computeDelta","targetWorld","deltaBytes","targetState","ensureEntityAtSlot","prev","curr","prevByEid","changed","prevE","prevSig","currSig"],"mappings":"2DA2BA,IAAMA,CAAAA,CAAQ,MAAA,CACRC,CAAAA,CAAiB,CAAA,CAEhB,SAASC,CAAAA,CAAeC,CAAAA,CAAcC,CAAAA,CAAwC,CACnF,IAAMC,CAAAA,CAAWC,CAAAA,CAAOH,CAAK,CAAA,CAC7B,OAAIC,CAAAA,EAAS,UAAA,GACXC,CAAAA,CAAS,QAAA,CAAWA,CAAAA,CAAS,QAAA,CAAS,GAAA,CAAKE,CAAAA,GAAO,CAChD,GAAA,CAAKA,CAAAA,CAAE,GAAA,CACP,UAAA,CAAYA,CAAAA,CAAE,WAAW,MAAA,CAAQC,CAAAA,EAC/BJ,CAAAA,CAAQ,UAAA,CAAY,IAAA,CAAMK,CAAAA,EAASA,CAAAA,CAAK,IAAA,GAASD,CAAAA,CAAE,EAAE,CACvD,CACF,CAAA,CAAE,CAAA,CAAA,CAEGE,CAAAA,CAAWL,CAAQ,CAC5B,CAEO,SAASM,CAAAA,CAAiBC,CAAAA,CAAmBR,CAAAA,CAAqC,CACvF,IAAMC,CAAAA,CAAWQ,CAAAA,CAAaD,CAAAA,CAAOR,CAAO,CAAA,CAC5C,OAAOU,EAAST,CAAQ,CAC1B,CASO,SAASC,CAAAA,CAAOH,CAAAA,CAA6B,CAClD,IAAMY,CAAAA,CAAQC,CAAAA,CAAcb,CAAK,CAAA,CAC3Bc,CAAAA,CAAsC,EAAC,CAG7C,IAAA,IAASC,CAAAA,CAAM,CAAA,CAAGA,CAAAA,CAAMH,CAAAA,CAAM,QAAA,CAAUG,CAAAA,EAAAA,CAAO,CAC7C,IAAMC,CAAAA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,IAAA,CAAK,SAAA,CAAUD,CAAAA,CAAM,UAAU,CAAA,CACzCE,CAAAA,CAAU,IAAA,CAAK,SAAA,CAAU7E,CAAAA,CAAE,UAAU,CAAA,CACvC4E,CAAAA,GAAYC,CAAAA,EAASH,CAAAA,CAAQ,IAAA,CAAK1E,CAAC,EACzC,CACA,OAAO,CAAE,OAAA,CAASwE,CAAAA,CAAK,OAAA,CAAS,QAAA,CAAUA,CAAAA,CAAK,QAAA,CAAU,QAAA,CAAUE,CAAQ,CAC7E","file":"chunk-TNZMD7E5.js","sourcesContent":["// aiecsjs/serialize — binary, JSON, and delta serializers.\n\nimport { testBit } from './internal/bitmask.js'\nimport {\n addComponent,\n defineComponent,\n defineObjectComponent,\n defineTag,\n getComponentByInternalId,\n getComponentInfo,\n listAllComponents,\n} from './internal/component.js'\nimport { createEntity, destroyEntity, ensureEntityAtSlot, packEid } from './internal/entity.js'\nimport type {\n ComponentInfo,\n ComponentInit,\n ComponentLike,\n DeltaSerializer,\n DeserializeOptions,\n EntityId,\n SerializeOptions,\n World,\n WorldSnapshot,\n} from './internal/types.js'\nimport { createWorld, getWorldState } from './internal/world.js'\nimport { VERSION } from './version.js'\n\nconst MAGIC = 'AIEC'\nconst FORMAT_VERSION = 1\n\nexport function serializeWorld(world: World, options?: SerializeOptions): Uint8Array {\n const snapshot = toJSON(world)\n if (options?.components) {\n snapshot.entities = snapshot.entities.map((e) => ({\n eid: e.eid,\n components: e.components.filter((c) =>\n options.components!.some((comp) => comp.__id === c.id),\n ),\n }))\n }\n return packBinary(snapshot)\n}\n\nexport function deserializeWorld(bytes: Uint8Array, options?: DeserializeOptions): World {\n const snapshot = unpackBinary(bytes, options)\n return fromJSON(snapshot)\n}\n\n/**\n * Serialize a world snapshot to a plain JSON-compatible object.\n *\n * Note: `EntityRef` is in-memory only — not preserved across serialize/deserialize.\n * Generation counters reset on world load. Stale refs from before serialization\n * will deref to null after loading the snapshot into a new world.\n */\nexport function toJSON(world: World): WorldSnapshot {\n const state = getWorldState(world)\n const entities: WorldSnapshot['entities'] = []\n // Iterate by raw slot index; snapshot stores raw idx in the `eid` field\n // (wire format unchanged — idx is used for load-side entity re-creation).\n for (let idx = 1; idx < state.capacity; idx++) {\n const archId = state.entityArchetype[idx] ?? 0\n if (archId === 0) continue // slot unused\n\n const arch = state.archetypes[archId]\n if (!arch) continue\n\n // Build the packed eid from idx + current generation to do alive check\n const gen = state.generations[idx] ?? 0\n const packedEid = packEid(idx, gen, state.options)\n if (!arch.entityRow.has(packedEid)) continue\n\n const w = state.options.maskWordCount\n const base = idx * w\n const components: WorldSnapshot['entities'][0]['components'] = []\n for (let wi = 0; wi < w; wi++) {\n let word = state.entityMask[base + wi] ?? 0\n while (word !== 0) {\n const lsb = word & -word\n const bit = (wi << 5) + (31 - Math.clz32(lsb))\n const info = state.componentInfoByBit[bit]\n if (info) {\n const storage = state.componentStorageByBit[bit]\n let data: unknown = null\n if (info.kind === 'soa' && storage?.soa) {\n const obj: Record<string, unknown> = {}\n for (const f of info.fields) {\n const col = storage.soa[f.name]\n if (!col) continue\n if (f.vectorLen === 1) {\n obj[f.name] = col[idx]\n } else {\n const arr: number[] = []\n const baseI = idx * f.vectorLen\n for (let i = 0; i < f.vectorLen; i++) arr.push(col[baseI + i] ?? 0)\n obj[f.name] = arr\n }\n }\n data = obj\n } else if (info.kind === 'aos' && storage?.aos) {\n data = storage.aos[idx] ?? null\n } else {\n data = true\n }\n components.push({ kind: info.kind, id: info.id, data })\n }\n word &= word - 1\n }\n }\n // Wire format stores raw idx (not packed) for cross-session portability\n entities.push({ eid: idx, components })\n }\n return {\n version: state.version,\n capacity: state.capacity,\n entities,\n }\n}\n\n// Default initial-capacity floor for a restored world (matches createWorld's\n// own default). Keeps the common round-trip from needlessly shrinking while\n// staying a trivial allocation (~36 KB of index arrays at 1024 slots).\nconst RESTORE_CAPACITY_FLOOR = 1024\n\n// SECURITY (ECS-S-01): the snapshot `capacity` field is attacker-controlled on\n// any untrusted-load path (localStorage, network — both documented flows for the\n// stable deserializeWorld). createWorld only clamps to 1<<indexBits (16,777,216),\n// so an inflated value forces a near-600 MB TypedArray allocation from a tiny\n// payload — a browser-tab OOM DoS. Clamp the *starting* capacity to the real\n// entity count (fromJSON re-creates entities via createEntity, which grows the\n// world on demand, so a tight initial hint never loses data). A garbage/missing\n// value falls back to the count too.\nfunction clampRestoreCapacity(rawCapacity: unknown, entityCount: number): number {\n const needed = Math.max(RESTORE_CAPACITY_FLOOR, entityCount + 1)\n if (typeof rawCapacity !== 'number' || !Number.isFinite(rawCapacity) || rawCapacity <= 0) {\n return needed\n }\n return Math.min(Math.floor(rawCapacity), needed)\n}\n\nexport function fromJSON(snapshot: WorldSnapshot): World {\n const initialCapacity = clampRestoreCapacity(snapshot.capacity, snapshot.entities.length)\n const world = createWorld({ initialCapacity })\n const eidMap = new Map<number, EntityId>()\n for (const e of snapshot.entities) {\n const eid = createEntity(world)\n eidMap.set(e.eid, eid)\n }\n for (const e of snapshot.entities) {\n const eid = eidMap.get(e.eid)!\n for (const comp of e.components) {\n const info = getComponentByInternalId(comp.id)\n if (!info) {\n // Component missing — silently skip; future version may throw based on options\n continue\n }\n const handle = getComponentHandle(info)\n if (handle) {\n addComponent(world, eid, handle, comp.data as ComponentInit<ComponentLike>)\n }\n }\n }\n return world\n}\n\n// Reconstruct a component handle from its ComponentInfo. Since defineComponent\n// returns plain handles { __kind, __id, __schema }, we can synthesize them.\nfunction getComponentHandle(info: ComponentInfo): ComponentLike | null {\n if (info.kind === 'soa') {\n return { __kind: 'soa', __id: info.id, __schema: info.schema ?? {} } as ComponentLike\n }\n if (info.kind === 'aos') {\n const factory = info.factory ?? (() => ({}))\n return { __kind: 'aos', __id: info.id, __factory: factory } as ComponentLike\n }\n return { __kind: 'tag', __id: info.id } as ComponentLike\n}\n\n// --- Binary packing (wrapped JSON for 0.1) ---\n\nfunction packBinary(snapshot: WorldSnapshot): Uint8Array {\n const json = JSON.stringify(snapshot)\n const jsonBytes = new TextEncoder().encode(json)\n const versionBytes = new TextEncoder().encode(VERSION)\n const headerSize = 4 + 4 + 4 + versionBytes.length + 4\n const total = headerSize + jsonBytes.length\n const out = new Uint8Array(total)\n const view = new DataView(out.buffer)\n let off = 0\n out[off++] = MAGIC.charCodeAt(0)\n out[off++] = MAGIC.charCodeAt(1)\n out[off++] = MAGIC.charCodeAt(2)\n out[off++] = MAGIC.charCodeAt(3)\n view.setUint32(off, FORMAT_VERSION, true)\n off += 4\n view.setUint32(off, versionBytes.length, true)\n off += 4\n out.set(versionBytes, off)\n off += versionBytes.length\n view.setUint32(off, jsonBytes.length, true)\n off += 4\n out.set(jsonBytes, off)\n return out\n}\n\nfunction unpackBinary(bytes: Uint8Array, options?: DeserializeOptions): WorldSnapshot {\n if (bytes.length < 12) throw new Error('aiecsjs: bytes too short to be a valid snapshot')\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n if (\n bytes[0] !== MAGIC.charCodeAt(0) ||\n bytes[1] !== MAGIC.charCodeAt(1) ||\n bytes[2] !== MAGIC.charCodeAt(2) ||\n bytes[3] !== MAGIC.charCodeAt(3)\n ) {\n throw new Error('aiecsjs: invalid magic bytes')\n }\n let off = 4\n const formatVersion = view.getUint32(off, true)\n off += 4\n const onUnknown = options?.onUnknownVersion ?? 'throw'\n if (formatVersion !== FORMAT_VERSION && onUnknown === 'throw') {\n throw new Error(`aiecsjs: format version ${formatVersion} not supported`)\n }\n\n // SECURITY: explicit bounds checks on every length field. DataView itself\n // throws on out-of-range reads, but an attacker who controls the bytes can\n // still craft a `verLen` that skips past data of their choosing — we make\n // each step's invariant explicit and impose a sane cap to short-circuit\n // pathological payloads early.\n const MAX_FIELD_LEN = 64 * 1024 * 1024 // 64 MiB\n if (off + 4 > bytes.length) {\n throw new Error('aiecsjs: snapshot truncated before verLen')\n }\n const verLen = view.getUint32(off, true)\n off += 4\n if (verLen > MAX_FIELD_LEN || off + verLen > bytes.length) {\n throw new Error(`aiecsjs: snapshot verLen=${verLen} out of bounds`)\n }\n off += verLen // skip the aiecsjs version string\n\n if (off + 4 > bytes.length) {\n throw new Error('aiecsjs: snapshot truncated before jsonLen')\n }\n const jsonLen = view.getUint32(off, true)\n off += 4\n if (jsonLen > MAX_FIELD_LEN || off + jsonLen > bytes.length) {\n throw new Error(`aiecsjs: snapshot jsonLen=${jsonLen} out of bounds`)\n }\n const jsonBytes = bytes.subarray(off, off + jsonLen)\n const json = new TextDecoder().decode(jsonBytes)\n // Wrap the parse so a malformed body (e.g. a truncated/garbled payload reached\n // under onUnknownVersion:'best-effort') surfaces a namespaced `aiecsjs:` error\n // instead of leaking a raw SyntaxError — consistent with the rest of the module.\n // Bounds checks above already guarantee `json` covers exactly the declared body.\n try {\n return JSON.parse(json) as WorldSnapshot\n } catch (cause) {\n throw new Error('aiecsjs: snapshot body is not valid JSON', { cause })\n }\n}\n\n// --- Delta serializer ---\n\ninterface DeltaState {\n world: World\n components: ComponentLike[]\n lastSnapshot: WorldSnapshot | null\n}\n\nexport function createDeltaSerializer(world: World, options?: SerializeOptions): DeltaSerializer {\n const state: DeltaState = {\n world,\n components:\n options?.components ??\n listAllComponents()\n .map((i) => getComponentHandle(i)!)\n .filter(Boolean),\n lastSnapshot: null,\n }\n return {\n capture(): Uint8Array {\n const current = toJSON(state.world)\n let delta: WorldSnapshot\n if (!state.lastSnapshot) {\n delta = current\n } else {\n // Compute simple delta: entities with changed components\n delta = computeDelta(state.lastSnapshot, current)\n }\n state.lastSnapshot = current\n return packBinary(delta)\n },\n apply(targetWorld: World, deltaBytes: Uint8Array): void {\n const snapshot = unpackBinary(deltaBytes)\n // Materialise each snapshot entity at the SAME slot index the source used\n // (the wire stores raw slot indices in `eid`). ensureEntityAtSlot reuses a\n // live slot, reclaims a freed one, or advances the frontier — so apply() is\n // sound on a non-pristine / independently-churned replica (it uses the\n // slot's CURRENT generation, never gen=0) and never spawns phantom padding\n // entities for holes in the source's slot range.\n //\n // CAVEAT: deltas carry added/changed entities only (see computeDelta) —\n // entity REMOVALS are not represented, so a replica is not pruned when the\n // source destroys an entity, and a component removed on the source is not\n // removed on the replica. apply() is additive/updating.\n const targetState = getWorldState(targetWorld)\n for (const e of snapshot.entities) {\n if (e.eid <= 0 || e.eid >= targetState.options.maxEntities) continue\n const eid = ensureEntityAtSlot(targetState, e.eid)\n for (const comp of e.components) {\n const info = getComponentByInternalId(comp.id)\n if (!info) continue\n const handle = getComponentHandle(info)\n if (handle)\n addComponent(targetWorld, eid, handle, comp.data as ComponentInit<ComponentLike>)\n }\n }\n },\n reset(): void {\n state.lastSnapshot = null\n },\n }\n}\n\nfunction computeDelta(prev: WorldSnapshot, curr: WorldSnapshot): WorldSnapshot {\n const prevByEid = new Map(prev.entities.map((e) => [e.eid, e]))\n const changed: WorldSnapshot['entities'] = []\n for (const e of curr.entities) {\n const prevE = prevByEid.get(e.eid)\n if (!prevE) {\n changed.push(e)\n continue\n }\n const prevSig = JSON.stringify(prevE.components)\n const currSig = JSON.stringify(e.components)\n if (prevSig !== currSig) changed.push(e)\n }\n return { version: curr.version, capacity: curr.capacity, entities: changed }\n}\n"]}
1
+ {"version":3,"sources":["../src/serialize.ts"],"names":["MAGIC","FORMAT_VERSION","serializeWorld","world","options","snapshot","toJSON","e","c","comp","packBinary","deserializeWorld","bytes","unpackBinary","fromJSON","state","getWorldState","entities","idx","archId","arch","gen","packedEid","packEid","w","base","components","wi","word","lsb","bit","info","storage","data","obj","f","col","arr","baseI","i","RESTORE_CAPACITY_FLOOR","clampRestoreCapacity","rawCapacity","entityCount","needed","initialCapacity","createWorld","eidMap","eid","createEntity","getComponentByInternalId","handle","getComponentHandle","addComponent","factory","json","jsonBytes","versionBytes","VERSION","total","out","view","off","formatVersion","onUnknown","MAX_FIELD_LEN","verLen","jsonLen","cause","createDeltaSerializer","listAllComponents","current","delta","computeDelta","targetWorld","deltaBytes","targetState","ensureEntityAtSlot","prev","curr","prevByEid","changed","prevE","prevSig","currSig"],"mappings":"2DA2BA,IAAMA,CAAAA,CAAQ,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QAAA,CAAU,QAAA,CAAUE,CAAQ,CAC7E","file":"chunk-ZZBNE7C5.js","sourcesContent":["// aiecsjs/serialize — binary, JSON, and delta serializers.\n\nimport { testBit } from './internal/bitmask.js'\nimport {\n addComponent,\n defineComponent,\n defineObjectComponent,\n defineTag,\n getComponentByInternalId,\n getComponentInfo,\n listAllComponents,\n} from './internal/component.js'\nimport { createEntity, destroyEntity, ensureEntityAtSlot, packEid } from './internal/entity.js'\nimport type {\n ComponentInfo,\n ComponentInit,\n ComponentLike,\n DeltaSerializer,\n DeserializeOptions,\n EntityId,\n SerializeOptions,\n World,\n WorldSnapshot,\n} from './internal/types.js'\nimport { createWorld, getWorldState } from './internal/world.js'\nimport { VERSION } from './version.js'\n\nconst MAGIC = 'AIEC'\nconst FORMAT_VERSION = 1\n\nexport function serializeWorld(world: World, options?: SerializeOptions): Uint8Array {\n const snapshot = toJSON(world)\n if (options?.components) {\n snapshot.entities = snapshot.entities.map((e) => ({\n eid: e.eid,\n components: e.components.filter((c) =>\n options.components!.some((comp) => comp.__id === c.id),\n ),\n }))\n }\n return packBinary(snapshot)\n}\n\nexport function deserializeWorld(bytes: Uint8Array, options?: DeserializeOptions): World {\n const snapshot = unpackBinary(bytes, options)\n return fromJSON(snapshot)\n}\n\n/**\n * Serialize a world snapshot to a plain JSON-compatible object.\n *\n * Note: `EntityRef` is in-memory only — not preserved across serialize/deserialize.\n * Generation counters reset on world load. Stale refs from before serialization\n * will deref to null after loading the snapshot into a new world.\n */\nexport function toJSON(world: World): WorldSnapshot {\n const state = getWorldState(world)\n const entities: WorldSnapshot['entities'] = []\n // Iterate by raw slot index; snapshot stores raw idx in the `eid` field\n // (wire format unchanged — idx is used for load-side entity re-creation).\n for (let idx = 1; idx < state.capacity; idx++) {\n const archId = state.entityArchetype[idx] ?? 0\n if (archId === 0) continue // slot unused\n\n const arch = state.archetypes[archId]\n if (!arch) continue\n\n // Build the packed eid from idx + current generation to do alive check\n const gen = state.generations[idx] ?? 0\n const packedEid = packEid(idx, gen, state.options)\n if (!arch.entityRow.has(packedEid)) continue\n\n const w = state.options.maskWordCount\n const base = idx * w\n const components: WorldSnapshot['entities'][0]['components'] = []\n for (let wi = 0; wi < w; wi++) {\n let word = state.entityMask[base + wi] ?? 0\n while (word !== 0) {\n const lsb = word & -word\n const bit = (wi << 5) + (31 - Math.clz32(lsb))\n const info = state.componentInfoByBit[bit]\n if (info) {\n const storage = state.componentStorageByBit[bit]\n let data: unknown = null\n if (info.kind === 'soa' && storage?.soa) {\n const obj: Record<string, unknown> = {}\n for (const f of info.fields) {\n const col = storage.soa[f.name]\n if (!col) continue\n if (f.vectorLen === 1) {\n obj[f.name] = col[idx]\n } else {\n const arr: number[] = []\n const baseI = idx * f.vectorLen\n for (let i = 0; i < f.vectorLen; i++) arr.push(col[baseI + i] ?? 0)\n obj[f.name] = arr\n }\n }\n data = obj\n } else if (info.kind === 'aos' && storage?.aos) {\n data = storage.aos[idx] ?? null\n } else {\n data = true\n }\n components.push({ kind: info.kind, id: info.id, data })\n }\n word &= word - 1\n }\n }\n // Wire format stores raw idx (not packed) for cross-session portability\n entities.push({ eid: idx, components })\n }\n return {\n version: state.version,\n capacity: state.capacity,\n entities,\n }\n}\n\n// Default initial-capacity floor for a restored world (matches createWorld's\n// own default). Keeps the common round-trip from needlessly shrinking while\n// staying a trivial allocation (~36 KB of index arrays at 1024 slots).\nconst RESTORE_CAPACITY_FLOOR = 1024\n\n// SECURITY (ECS-S-01): the snapshot `capacity` field is attacker-controlled on\n// any untrusted-load path (localStorage, network — both documented flows for the\n// stable deserializeWorld). createWorld only clamps to 1<<indexBits (16,777,216),\n// so an inflated value forces a near-600 MB TypedArray allocation from a tiny\n// payload — a browser-tab OOM DoS. Clamp the *starting* capacity to the real\n// entity count (fromJSON re-creates entities via createEntity, which grows the\n// world on demand, so a tight initial hint never loses data). A garbage/missing\n// value falls back to the count too.\nfunction clampRestoreCapacity(rawCapacity: unknown, entityCount: number): number {\n const needed = Math.max(RESTORE_CAPACITY_FLOOR, entityCount + 1)\n if (typeof rawCapacity !== 'number' || !Number.isFinite(rawCapacity) || rawCapacity <= 0) {\n return needed\n }\n return Math.min(Math.floor(rawCapacity), needed)\n}\n\nexport function fromJSON(snapshot: WorldSnapshot): World {\n const initialCapacity = clampRestoreCapacity(snapshot.capacity, snapshot.entities.length)\n const world = createWorld({ initialCapacity })\n const eidMap = new Map<number, EntityId>()\n for (const e of snapshot.entities) {\n const eid = createEntity(world)\n eidMap.set(e.eid, eid)\n }\n for (const e of snapshot.entities) {\n const eid = eidMap.get(e.eid)!\n for (const comp of e.components) {\n const info = getComponentByInternalId(comp.id)\n if (!info) {\n // Component missing — silently skip; future version may throw based on options\n continue\n }\n const handle = getComponentHandle(info)\n if (handle) {\n addComponent(world, eid, handle, comp.data as ComponentInit<ComponentLike>)\n }\n }\n }\n return world\n}\n\n// Reconstruct a component handle from its ComponentInfo. Since defineComponent\n// returns plain handles { __kind, __id, __schema }, we can synthesize them.\nfunction getComponentHandle(info: ComponentInfo): ComponentLike | null {\n if (info.kind === 'soa') {\n return { __kind: 'soa', __id: info.id, __schema: info.schema ?? {} } as ComponentLike\n }\n if (info.kind === 'aos') {\n const factory = info.factory ?? (() => ({}))\n return { __kind: 'aos', __id: info.id, __factory: factory } as ComponentLike\n }\n return { __kind: 'tag', __id: info.id } as ComponentLike\n}\n\n// --- Binary packing (wrapped JSON for 0.1) ---\n\nfunction packBinary(snapshot: WorldSnapshot): Uint8Array {\n const json = JSON.stringify(snapshot)\n const jsonBytes = new TextEncoder().encode(json)\n const versionBytes = new TextEncoder().encode(VERSION)\n const headerSize = 4 + 4 + 4 + versionBytes.length + 4\n const total = headerSize + jsonBytes.length\n const out = new Uint8Array(total)\n const view = new DataView(out.buffer)\n let off = 0\n out[off++] = MAGIC.charCodeAt(0)\n out[off++] = MAGIC.charCodeAt(1)\n out[off++] = MAGIC.charCodeAt(2)\n out[off++] = MAGIC.charCodeAt(3)\n view.setUint32(off, FORMAT_VERSION, true)\n off += 4\n view.setUint32(off, versionBytes.length, true)\n off += 4\n out.set(versionBytes, off)\n off += versionBytes.length\n view.setUint32(off, jsonBytes.length, true)\n off += 4\n out.set(jsonBytes, off)\n return out\n}\n\nfunction unpackBinary(bytes: Uint8Array, options?: DeserializeOptions): WorldSnapshot {\n if (bytes.length < 12) throw new Error('aiecsjs: bytes too short to be a valid snapshot')\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n if (\n bytes[0] !== MAGIC.charCodeAt(0) ||\n bytes[1] !== MAGIC.charCodeAt(1) ||\n bytes[2] !== MAGIC.charCodeAt(2) ||\n bytes[3] !== MAGIC.charCodeAt(3)\n ) {\n throw new Error('aiecsjs: invalid magic bytes')\n }\n let off = 4\n const formatVersion = view.getUint32(off, true)\n off += 4\n const onUnknown = options?.onUnknownVersion ?? 'throw'\n if (formatVersion !== FORMAT_VERSION && onUnknown === 'throw') {\n throw new Error(`aiecsjs: format version ${formatVersion} not supported`)\n }\n\n // SECURITY: explicit bounds checks on every length field. DataView itself\n // throws on out-of-range reads, but an attacker who controls the bytes can\n // still craft a `verLen` that skips past data of their choosing — we make\n // each step's invariant explicit and impose a sane cap to short-circuit\n // pathological payloads early.\n const MAX_FIELD_LEN = 64 * 1024 * 1024 // 64 MiB\n if (off + 4 > bytes.length) {\n throw new Error('aiecsjs: snapshot truncated before verLen')\n }\n const verLen = view.getUint32(off, true)\n off += 4\n if (verLen > MAX_FIELD_LEN || off + verLen > bytes.length) {\n throw new Error(`aiecsjs: snapshot verLen=${verLen} out of bounds`)\n }\n off += verLen // skip the aiecsjs version string\n\n if (off + 4 > bytes.length) {\n throw new Error('aiecsjs: snapshot truncated before jsonLen')\n }\n const jsonLen = view.getUint32(off, true)\n off += 4\n if (jsonLen > MAX_FIELD_LEN || off + jsonLen > bytes.length) {\n throw new Error(`aiecsjs: snapshot jsonLen=${jsonLen} out of bounds`)\n }\n const jsonBytes = bytes.subarray(off, off + jsonLen)\n const json = new TextDecoder().decode(jsonBytes)\n // Wrap the parse so a malformed body (e.g. a truncated/garbled payload reached\n // under onUnknownVersion:'best-effort') surfaces a namespaced `aiecsjs:` error\n // instead of leaking a raw SyntaxError — consistent with the rest of the module.\n // Bounds checks above already guarantee `json` covers exactly the declared body.\n try {\n return JSON.parse(json) as WorldSnapshot\n } catch (cause) {\n throw new Error('aiecsjs: snapshot body is not valid JSON', { cause })\n }\n}\n\n// --- Delta serializer ---\n\ninterface DeltaState {\n world: World\n components: ComponentLike[]\n lastSnapshot: WorldSnapshot | null\n}\n\nexport function createDeltaSerializer(world: World, options?: SerializeOptions): DeltaSerializer {\n const state: DeltaState = {\n world,\n components:\n options?.components ??\n listAllComponents()\n .map((i) => getComponentHandle(i)!)\n .filter(Boolean),\n lastSnapshot: null,\n }\n return {\n capture(): Uint8Array {\n const current = toJSON(state.world)\n let delta: WorldSnapshot\n if (!state.lastSnapshot) {\n delta = current\n } else {\n // Compute simple delta: entities with changed components\n delta = computeDelta(state.lastSnapshot, current)\n }\n state.lastSnapshot = current\n return packBinary(delta)\n },\n apply(targetWorld: World, deltaBytes: Uint8Array): void {\n const snapshot = unpackBinary(deltaBytes)\n // Materialise each snapshot entity at the SAME slot index the source used\n // (the wire stores raw slot indices in `eid`). ensureEntityAtSlot reuses a\n // live slot, reclaims a freed one, or advances the frontier — so apply() is\n // sound on a non-pristine / independently-churned replica (it uses the\n // slot's CURRENT generation, never gen=0) and never spawns phantom padding\n // entities for holes in the source's slot range.\n //\n // CAVEAT: deltas carry added/changed entities only (see computeDelta) —\n // entity REMOVALS are not represented, so a replica is not pruned when the\n // source destroys an entity, and a component removed on the source is not\n // removed on the replica. apply() is additive/updating.\n const targetState = getWorldState(targetWorld)\n for (const e of snapshot.entities) {\n if (e.eid <= 0 || e.eid >= targetState.options.maxEntities) continue\n const eid = ensureEntityAtSlot(targetState, e.eid)\n for (const comp of e.components) {\n const info = getComponentByInternalId(comp.id)\n if (!info) continue\n const handle = getComponentHandle(info)\n if (handle)\n addComponent(targetWorld, eid, handle, comp.data as ComponentInit<ComponentLike>)\n }\n }\n },\n reset(): void {\n state.lastSnapshot = null\n },\n }\n}\n\nfunction computeDelta(prev: WorldSnapshot, curr: WorldSnapshot): WorldSnapshot {\n const prevByEid = new Map(prev.entities.map((e) => [e.eid, e]))\n const changed: WorldSnapshot['entities'] = []\n for (const e of curr.entities) {\n const prevE = prevByEid.get(e.eid)\n if (!prevE) {\n changed.push(e)\n continue\n }\n const prevSig = JSON.stringify(prevE.components)\n const currSig = JSON.stringify(e.components)\n if (prevSig !== currSig) changed.push(e)\n }\n return { version: curr.version, capacity: curr.capacity, entities: changed }\n}\n"]}
package/dist/commands.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkZIZSWIHW_cjs=require('./chunk-ZIZSWIHW.cjs');function l(e){let n={worldId:chunkZIZSWIHW_cjs.j(e).id,ops:[],nextPlaceholder:-1,flushing:false};return h(n)}function C(e){let o=y(e);if(!o.flushing){o.flushing=true;try{let n=k(o.worldId),r=new Map;for(let t of o.ops)t.kind==="create"&&r.set(t.placeholder,chunkZIZSWIHW_cjs.v(n));let d=t=>{let i=t;if(i<0){let f=r.get(i);if(f===void 0)throw new Error(`aiecsjs: unresolved placeholder ${i}`);return f}return t};for(let t of o.ops)t.kind==="add"?chunkZIZSWIHW_cjs.K(n,d(t.eid),t.component,t.initial):t.kind==="remove"&&chunkZIZSWIHW_cjs.L(n,d(t.eid),t.component);for(let t of o.ops)t.kind==="destroy"&&chunkZIZSWIHW_cjs.x(n,d(t.eid));o.ops.length=0,o.nextPlaceholder=-1;}finally{o.flushing=false;}}}function b(e,o){let n=l(e),r=o(n);return C(n),r}var p=new WeakMap;function h(e){let o={add(n,r,d){e.ops.push({kind:"add",eid:n,component:r,initial:d});},remove(n,r){e.ops.push({kind:"remove",eid:n,component:r});},destroy(n){e.ops.push({kind:"destroy",eid:n});},create(){let n=e.nextPlaceholder--;return e.ops.push({kind:"create",placeholder:n}),n}};return p.set(o,e),o}function y(e){let o=p.get(e);if(!o)throw new Error("aiecsjs: unknown CommandBuffer");return o}function k(e){let o=B(e);return {id:o.id,capacity:o.capacity,version:o.version}}function B(e){return chunkZIZSWIHW_cjs.j({id:e,capacity:0,version:"0.0.0"})}exports.createCommandBuffer=l;exports.flush=C;exports.withCommandBuffer=b;//# sourceMappingURL=commands.cjs.map
1
+ 'use strict';var chunkQ2XLL6YG_cjs=require('./chunk-Q2XLL6YG.cjs');function l(e){let n={worldId:chunkQ2XLL6YG_cjs.j(e).id,ops:[],nextPlaceholder:-1,flushing:false};return h(n)}function C(e){let o=y(e);if(!o.flushing){o.flushing=true;try{let n=k(o.worldId),r=new Map;for(let t of o.ops)t.kind==="create"&&r.set(t.placeholder,chunkQ2XLL6YG_cjs.v(n));let d=t=>{let i=t;if(i<0){let f=r.get(i);if(f===void 0)throw new Error(`aiecsjs: unresolved placeholder ${i}`);return f}return t};for(let t of o.ops)t.kind==="add"?chunkQ2XLL6YG_cjs.K(n,d(t.eid),t.component,t.initial):t.kind==="remove"&&chunkQ2XLL6YG_cjs.L(n,d(t.eid),t.component);for(let t of o.ops)t.kind==="destroy"&&chunkQ2XLL6YG_cjs.x(n,d(t.eid));o.ops.length=0,o.nextPlaceholder=-1;}finally{o.flushing=false;}}}function b(e,o){let n=l(e),r=o(n);return C(n),r}var p=new WeakMap;function h(e){let o={add(n,r,d){e.ops.push({kind:"add",eid:n,component:r,initial:d});},remove(n,r){e.ops.push({kind:"remove",eid:n,component:r});},destroy(n){e.ops.push({kind:"destroy",eid:n});},create(){let n=e.nextPlaceholder--;return e.ops.push({kind:"create",placeholder:n}),n}};return p.set(o,e),o}function y(e){let o=p.get(e);if(!o)throw new Error("aiecsjs: unknown CommandBuffer");return o}function k(e){let o=B(e);return {id:o.id,capacity:o.capacity,version:o.version}}function B(e){return chunkQ2XLL6YG_cjs.j({id:e,capacity:0,version:"0.0.0"})}exports.createCommandBuffer=l;exports.flush=C;exports.withCommandBuffer=b;//# sourceMappingURL=commands.cjs.map
2
2
  //# sourceMappingURL=commands.cjs.map
package/dist/commands.js CHANGED
@@ -1,2 +1,2 @@
1
- import {j,v,K,L,x}from'./chunk-YFTCD2UG.js';function l(e){let n={worldId:j(e).id,ops:[],nextPlaceholder:-1,flushing:false};return h(n)}function C(e){let o=y(e);if(!o.flushing){o.flushing=true;try{let n=k(o.worldId),r=new Map;for(let t of o.ops)t.kind==="create"&&r.set(t.placeholder,v(n));let d=t=>{let i=t;if(i<0){let f=r.get(i);if(f===void 0)throw new Error(`aiecsjs: unresolved placeholder ${i}`);return f}return t};for(let t of o.ops)t.kind==="add"?K(n,d(t.eid),t.component,t.initial):t.kind==="remove"&&L(n,d(t.eid),t.component);for(let t of o.ops)t.kind==="destroy"&&x(n,d(t.eid));o.ops.length=0,o.nextPlaceholder=-1;}finally{o.flushing=false;}}}function b(e,o){let n=l(e),r=o(n);return C(n),r}var p=new WeakMap;function h(e){let o={add(n,r,d){e.ops.push({kind:"add",eid:n,component:r,initial:d});},remove(n,r){e.ops.push({kind:"remove",eid:n,component:r});},destroy(n){e.ops.push({kind:"destroy",eid:n});},create(){let n=e.nextPlaceholder--;return e.ops.push({kind:"create",placeholder:n}),n}};return p.set(o,e),o}function y(e){let o=p.get(e);if(!o)throw new Error("aiecsjs: unknown CommandBuffer");return o}function k(e){let o=B(e);return {id:o.id,capacity:o.capacity,version:o.version}}function B(e){return j({id:e,capacity:0,version:"0.0.0"})}export{l as createCommandBuffer,C as flush,b as withCommandBuffer};//# sourceMappingURL=commands.js.map
1
+ import {j,v,K,L,x}from'./chunk-OBMQME2P.js';function l(e){let n={worldId:j(e).id,ops:[],nextPlaceholder:-1,flushing:false};return h(n)}function C(e){let o=y(e);if(!o.flushing){o.flushing=true;try{let n=k(o.worldId),r=new Map;for(let t of o.ops)t.kind==="create"&&r.set(t.placeholder,v(n));let d=t=>{let i=t;if(i<0){let f=r.get(i);if(f===void 0)throw new Error(`aiecsjs: unresolved placeholder ${i}`);return f}return t};for(let t of o.ops)t.kind==="add"?K(n,d(t.eid),t.component,t.initial):t.kind==="remove"&&L(n,d(t.eid),t.component);for(let t of o.ops)t.kind==="destroy"&&x(n,d(t.eid));o.ops.length=0,o.nextPlaceholder=-1;}finally{o.flushing=false;}}}function b(e,o){let n=l(e),r=o(n);return C(n),r}var p=new WeakMap;function h(e){let o={add(n,r,d){e.ops.push({kind:"add",eid:n,component:r,initial:d});},remove(n,r){e.ops.push({kind:"remove",eid:n,component:r});},destroy(n){e.ops.push({kind:"destroy",eid:n});},create(){let n=e.nextPlaceholder--;return e.ops.push({kind:"create",placeholder:n}),n}};return p.set(o,e),o}function y(e){let o=p.get(e);if(!o)throw new Error("aiecsjs: unknown CommandBuffer");return o}function k(e){let o=B(e);return {id:o.id,capacity:o.capacity,version:o.version}}function B(e){return j({id:e,capacity:0,version:"0.0.0"})}export{l as createCommandBuffer,C as flush,b as withCommandBuffer};//# sourceMappingURL=commands.js.map
2
2
  //# sourceMappingURL=commands.js.map