aiecsjs 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +1 -1
  2. package/README_ZHTW.md +1 -1
  3. package/api.json +1 -1
  4. package/dist/chunk-7O3CM4D2.cjs +2 -0
  5. package/dist/chunk-7O3CM4D2.cjs.map +1 -0
  6. package/dist/chunk-BUFJWGRQ.js +2 -0
  7. package/dist/chunk-BUFJWGRQ.js.map +1 -0
  8. package/dist/chunk-I2SPFVXH.cjs +2 -0
  9. package/dist/chunk-I2SPFVXH.cjs.map +1 -0
  10. package/dist/{chunk-2CF2MNMH.cjs → chunk-I726BP65.cjs} +2 -2
  11. package/dist/{chunk-2CF2MNMH.cjs.map → chunk-I726BP65.cjs.map} +1 -1
  12. package/dist/chunk-LU55S4LK.js +2 -0
  13. package/dist/{chunk-ZNLOJVCV.js.map → chunk-LU55S4LK.js.map} +1 -1
  14. package/dist/chunk-QC25WDOZ.js +2 -0
  15. package/dist/chunk-QC25WDOZ.js.map +1 -0
  16. package/dist/commands.cjs +1 -1
  17. package/dist/commands.js +1 -1
  18. package/dist/index.cjs +1 -1
  19. package/dist/index.d.cts +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/observers.cjs +1 -1
  23. package/dist/observers.js +1 -1
  24. package/dist/observers.js.map +1 -1
  25. package/dist/relations.cjs +1 -1
  26. package/dist/relations.js +1 -1
  27. package/dist/serialize.cjs +1 -1
  28. package/dist/serialize.js +1 -1
  29. package/dist/worker.cjs +1 -1
  30. package/dist/worker.js +1 -1
  31. package/llms-full.txt +36 -17
  32. package/package.json +1 -1
  33. package/dist/chunk-7NNM4PGP.cjs +0 -2
  34. package/dist/chunk-7NNM4PGP.cjs.map +0 -1
  35. package/dist/chunk-AW254W5F.js +0 -2
  36. package/dist/chunk-AW254W5F.js.map +0 -1
  37. package/dist/chunk-XU3BVVCJ.cjs +0 -2
  38. package/dist/chunk-XU3BVVCJ.cjs.map +0 -1
  39. package/dist/chunk-YAHZHZNR.js +0 -2
  40. package/dist/chunk-YAHZHZNR.js.map +0 -1
  41. package/dist/chunk-ZNLOJVCV.js +0 -2
@@ -1,2 +1,2 @@
1
- 'use strict';var chunk7NNM4PGP_cjs=require('./chunk-7NNM4PGP.cjs');var x=1;function p(r){return {__kind:"relation",__id:x++,__exclusive:r?.exclusive??false,__hasData:false}}var _=p({exclusive:true});function v(r,l){let s=r.relationStorage.get(l.__id);return s||(s={rel:l,exclusive:l.__exclusive?new Int32Array(r.capacity).fill(-1):null,outgoing:new Map,data:new Map},r.relationStorage.set(l.__id,s),s)}function R(r,l,s,i,n){let t=chunk7NNM4PGP_cjs.i(r);if(t.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");let e=v(t,s),o=l&t.options.indexMask,d=i&t.options.indexMask;if(e.exclusive){if(o>=e.exclusive.length){let c=new Int32Array(Math.max(o+1,e.exclusive.length*2)).fill(-1);c.set(e.exclusive),e.exclusive=c;}let a=e.exclusive[o]??-1;if(a>=0&&a!==d){let c=e.data.get(o);c?.delete(a),c&&c.size===0&&e.data.delete(o);}e.exclusive[o]=d;}else {let a=e.outgoing.get(o);a||(a=[],e.outgoing.set(o,a)),a.includes(d)||a.push(d);}if(n!==void 0){let a=e.data.get(o);a||(a=new Map,e.data.set(o,a)),a.set(d,n);}}function b(r,l,s,i){let n=chunk7NNM4PGP_cjs.i(r);if(n.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");let t=n.relationStorage.get(s.__id);if(!t)return;let e=l&n.options.indexMask,o=i&n.options.indexMask;if(t.exclusive)e<t.exclusive.length&&t.exclusive[e]===o&&(t.exclusive[e]=-1);else {let a=t.outgoing.get(e);if(a){let c=a.indexOf(o);c>=0&&a.splice(c,1),a.length===0&&t.outgoing.delete(e);}}let d=t.data.get(e);d&&(d.delete(o),d.size===0&&t.data.delete(e));}function h(r,l,s){let i=chunk7NNM4PGP_cjs.i(r),n=i.relationStorage.get(s.__id);if(!n)return [];let t=l&i.options.indexMask;if(n.exclusive){if(t<n.exclusive.length){let o=n.exclusive[t]??-1;if(o>=0){let d=i.generations[o]??0;return [chunk7NNM4PGP_cjs.r(o,d,i.options)]}}return []}let e=n.outgoing.get(t);return e?e.map(o=>{let d=i.generations[o]??0;return chunk7NNM4PGP_cjs.r(o,d,i.options)}):[]}function w(r,l,s,i){let n=chunk7NNM4PGP_cjs.i(r),t=n.relationStorage.get(s.__id);if(!t)return;let e=l&n.options.indexMask,o=i&n.options.indexMask;return t.data.get(e)?.get(o)}chunk7NNM4PGP_cjs.D((r,l)=>{let s=l&r.options.indexMask;for(let i of r.relationStorage.values()){if(i.exclusive){s<i.exclusive.length&&(i.exclusive[s]=-1);for(let n=0;n<i.exclusive.length;n++)i.exclusive[n]===s&&(i.exclusive[n]=-1);}i.outgoing.delete(s);for(let[n,t]of i.outgoing){let e=t.indexOf(s);e>=0&&(t.splice(e,1),t.length===0&&i.outgoing.delete(n));}i.data.delete(s);for(let[n,t]of i.data)t.delete(s),t.size===0&&i.data.delete(n);}});exports.ChildOf=_;exports.addRelation=R;exports.defineRelation=p;exports.getRelationData=w;exports.getRelationTargets=h;exports.removeRelation=b;//# sourceMappingURL=relations.cjs.map
1
+ 'use strict';var chunk7O3CM4D2_cjs=require('./chunk-7O3CM4D2.cjs');var x=1;function p(r){return {__kind:"relation",__id:x++,__exclusive:r?.exclusive??false,__hasData:false}}var _=p({exclusive:true});function v(r,l){let s=r.relationStorage.get(l.__id);return s||(s={rel:l,exclusive:l.__exclusive?new Int32Array(r.capacity).fill(-1):null,outgoing:new Map,data:new Map},r.relationStorage.set(l.__id,s),s)}function R(r,l,s,i,n){let t=chunk7O3CM4D2_cjs.i(r);if(t.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");let e=v(t,s),o=l&t.options.indexMask,d=i&t.options.indexMask;if(e.exclusive){if(o>=e.exclusive.length){let c=new Int32Array(Math.max(o+1,e.exclusive.length*2)).fill(-1);c.set(e.exclusive),e.exclusive=c;}let a=e.exclusive[o]??-1;if(a>=0&&a!==d){let c=e.data.get(o);c?.delete(a),c&&c.size===0&&e.data.delete(o);}e.exclusive[o]=d;}else {let a=e.outgoing.get(o);a||(a=[],e.outgoing.set(o,a)),a.includes(d)||a.push(d);}if(n!==void 0){let a=e.data.get(o);a||(a=new Map,e.data.set(o,a)),a.set(d,n);}}function b(r,l,s,i){let n=chunk7O3CM4D2_cjs.i(r);if(n.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");let t=n.relationStorage.get(s.__id);if(!t)return;let e=l&n.options.indexMask,o=i&n.options.indexMask;if(t.exclusive)e<t.exclusive.length&&t.exclusive[e]===o&&(t.exclusive[e]=-1);else {let a=t.outgoing.get(e);if(a){let c=a.indexOf(o);c>=0&&a.splice(c,1),a.length===0&&t.outgoing.delete(e);}}let d=t.data.get(e);d&&(d.delete(o),d.size===0&&t.data.delete(e));}function h(r,l,s){let i=chunk7O3CM4D2_cjs.i(r),n=i.relationStorage.get(s.__id);if(!n)return [];let t=l&i.options.indexMask;if(n.exclusive){if(t<n.exclusive.length){let o=n.exclusive[t]??-1;if(o>=0){let d=i.generations[o]??0;return [chunk7O3CM4D2_cjs.r(o,d,i.options)]}}return []}let e=n.outgoing.get(t);return e?e.map(o=>{let d=i.generations[o]??0;return chunk7O3CM4D2_cjs.r(o,d,i.options)}):[]}function w(r,l,s,i){let n=chunk7O3CM4D2_cjs.i(r),t=n.relationStorage.get(s.__id);if(!t)return;let e=l&n.options.indexMask,o=i&n.options.indexMask;return t.data.get(e)?.get(o)}chunk7O3CM4D2_cjs.E((r,l)=>{let s=l&r.options.indexMask;for(let i of r.relationStorage.values()){if(i.exclusive){s<i.exclusive.length&&(i.exclusive[s]=-1);for(let n=0;n<i.exclusive.length;n++)i.exclusive[n]===s&&(i.exclusive[n]=-1);}i.outgoing.delete(s);for(let[n,t]of i.outgoing){let e=t.indexOf(s);e>=0&&(t.splice(e,1),t.length===0&&i.outgoing.delete(n));}i.data.delete(s);for(let[n,t]of i.data)t.delete(s),t.size===0&&i.data.delete(n);}});exports.ChildOf=_;exports.addRelation=R;exports.defineRelation=p;exports.getRelationData=w;exports.getRelationTargets=h;exports.removeRelation=b;//# sourceMappingURL=relations.cjs.map
2
2
  //# sourceMappingURL=relations.cjs.map
package/dist/relations.js CHANGED
@@ -1,2 +1,2 @@
1
- import {D,i,r}from'./chunk-YAHZHZNR.js';var x=1;function p(r){return {__kind:"relation",__id:x++,__exclusive:r?.exclusive??false,__hasData:false}}var _=p({exclusive:true});function v(r,l){let s=r.relationStorage.get(l.__id);return s||(s={rel:l,exclusive:l.__exclusive?new Int32Array(r.capacity).fill(-1):null,outgoing:new Map,data:new Map},r.relationStorage.set(l.__id,s),s)}function R(r,l,s,i$1,n){let t=i(r);if(t.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");let e=v(t,s),o=l&t.options.indexMask,d=i$1&t.options.indexMask;if(e.exclusive){if(o>=e.exclusive.length){let c=new Int32Array(Math.max(o+1,e.exclusive.length*2)).fill(-1);c.set(e.exclusive),e.exclusive=c;}let a=e.exclusive[o]??-1;if(a>=0&&a!==d){let c=e.data.get(o);c?.delete(a),c&&c.size===0&&e.data.delete(o);}e.exclusive[o]=d;}else {let a=e.outgoing.get(o);a||(a=[],e.outgoing.set(o,a)),a.includes(d)||a.push(d);}if(n!==void 0){let a=e.data.get(o);a||(a=new Map,e.data.set(o,a)),a.set(d,n);}}function b(r,l,s,i$1){let n=i(r);if(n.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");let t=n.relationStorage.get(s.__id);if(!t)return;let e=l&n.options.indexMask,o=i$1&n.options.indexMask;if(t.exclusive)e<t.exclusive.length&&t.exclusive[e]===o&&(t.exclusive[e]=-1);else {let a=t.outgoing.get(e);if(a){let c=a.indexOf(o);c>=0&&a.splice(c,1),a.length===0&&t.outgoing.delete(e);}}let d=t.data.get(e);d&&(d.delete(o),d.size===0&&t.data.delete(e));}function h(r$1,l,s){let i$1=i(r$1),n=i$1.relationStorage.get(s.__id);if(!n)return [];let t=l&i$1.options.indexMask;if(n.exclusive){if(t<n.exclusive.length){let o=n.exclusive[t]??-1;if(o>=0){let d=i$1.generations[o]??0;return [r(o,d,i$1.options)]}}return []}let e=n.outgoing.get(t);return e?e.map(o=>{let d=i$1.generations[o]??0;return r(o,d,i$1.options)}):[]}function w(r,l,s,i$1){let n=i(r),t=n.relationStorage.get(s.__id);if(!t)return;let e=l&n.options.indexMask,o=i$1&n.options.indexMask;return t.data.get(e)?.get(o)}D((r,l)=>{let s=l&r.options.indexMask;for(let i of r.relationStorage.values()){if(i.exclusive){s<i.exclusive.length&&(i.exclusive[s]=-1);for(let n=0;n<i.exclusive.length;n++)i.exclusive[n]===s&&(i.exclusive[n]=-1);}i.outgoing.delete(s);for(let[n,t]of i.outgoing){let e=t.indexOf(s);e>=0&&(t.splice(e,1),t.length===0&&i.outgoing.delete(n));}i.data.delete(s);for(let[n,t]of i.data)t.delete(s),t.size===0&&i.data.delete(n);}});export{_ as ChildOf,R as addRelation,p as defineRelation,w as getRelationData,h as getRelationTargets,b as removeRelation};//# sourceMappingURL=relations.js.map
1
+ import {E,i,r}from'./chunk-BUFJWGRQ.js';var x=1;function p(r){return {__kind:"relation",__id:x++,__exclusive:r?.exclusive??false,__hasData:false}}var _=p({exclusive:true});function v(r,l){let s=r.relationStorage.get(l.__id);return s||(s={rel:l,exclusive:l.__exclusive?new Int32Array(r.capacity).fill(-1):null,outgoing:new Map,data:new Map},r.relationStorage.set(l.__id,s),s)}function R(r,l,s,i$1,n){let t=i(r);if(t.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");let e=v(t,s),o=l&t.options.indexMask,d=i$1&t.options.indexMask;if(e.exclusive){if(o>=e.exclusive.length){let c=new Int32Array(Math.max(o+1,e.exclusive.length*2)).fill(-1);c.set(e.exclusive),e.exclusive=c;}let a=e.exclusive[o]??-1;if(a>=0&&a!==d){let c=e.data.get(o);c?.delete(a),c&&c.size===0&&e.data.delete(o);}e.exclusive[o]=d;}else {let a=e.outgoing.get(o);a||(a=[],e.outgoing.set(o,a)),a.includes(d)||a.push(d);}if(n!==void 0){let a=e.data.get(o);a||(a=new Map,e.data.set(o,a)),a.set(d,n);}}function b(r,l,s,i$1){let n=i(r);if(n.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");let t=n.relationStorage.get(s.__id);if(!t)return;let e=l&n.options.indexMask,o=i$1&n.options.indexMask;if(t.exclusive)e<t.exclusive.length&&t.exclusive[e]===o&&(t.exclusive[e]=-1);else {let a=t.outgoing.get(e);if(a){let c=a.indexOf(o);c>=0&&a.splice(c,1),a.length===0&&t.outgoing.delete(e);}}let d=t.data.get(e);d&&(d.delete(o),d.size===0&&t.data.delete(e));}function h(r$1,l,s){let i$1=i(r$1),n=i$1.relationStorage.get(s.__id);if(!n)return [];let t=l&i$1.options.indexMask;if(n.exclusive){if(t<n.exclusive.length){let o=n.exclusive[t]??-1;if(o>=0){let d=i$1.generations[o]??0;return [r(o,d,i$1.options)]}}return []}let e=n.outgoing.get(t);return e?e.map(o=>{let d=i$1.generations[o]??0;return r(o,d,i$1.options)}):[]}function w(r,l,s,i$1){let n=i(r),t=n.relationStorage.get(s.__id);if(!t)return;let e=l&n.options.indexMask,o=i$1&n.options.indexMask;return t.data.get(e)?.get(o)}E((r,l)=>{let s=l&r.options.indexMask;for(let i of r.relationStorage.values()){if(i.exclusive){s<i.exclusive.length&&(i.exclusive[s]=-1);for(let n=0;n<i.exclusive.length;n++)i.exclusive[n]===s&&(i.exclusive[n]=-1);}i.outgoing.delete(s);for(let[n,t]of i.outgoing){let e=t.indexOf(s);e>=0&&(t.splice(e,1),t.length===0&&i.outgoing.delete(n));}i.data.delete(s);for(let[n,t]of i.data)t.delete(s),t.size===0&&i.data.delete(n);}});export{_ as ChildOf,R as addRelation,p as defineRelation,w as getRelationData,h as getRelationTargets,b as removeRelation};//# sourceMappingURL=relations.js.map
2
2
  //# sourceMappingURL=relations.js.map
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkXU3BVVCJ_cjs=require('./chunk-XU3BVVCJ.cjs');require('./chunk-7NNM4PGP.cjs');Object.defineProperty(exports,"createDeltaSerializer",{enumerable:true,get:function(){return chunkXU3BVVCJ_cjs.e}});Object.defineProperty(exports,"deserializeWorld",{enumerable:true,get:function(){return chunkXU3BVVCJ_cjs.b}});Object.defineProperty(exports,"fromJSON",{enumerable:true,get:function(){return chunkXU3BVVCJ_cjs.d}});Object.defineProperty(exports,"serializeWorld",{enumerable:true,get:function(){return chunkXU3BVVCJ_cjs.a}});Object.defineProperty(exports,"toJSON",{enumerable:true,get:function(){return chunkXU3BVVCJ_cjs.c}});//# sourceMappingURL=serialize.cjs.map
1
+ 'use strict';var chunkI2SPFVXH_cjs=require('./chunk-I2SPFVXH.cjs');require('./chunk-7O3CM4D2.cjs');Object.defineProperty(exports,"createDeltaSerializer",{enumerable:true,get:function(){return chunkI2SPFVXH_cjs.e}});Object.defineProperty(exports,"deserializeWorld",{enumerable:true,get:function(){return chunkI2SPFVXH_cjs.b}});Object.defineProperty(exports,"fromJSON",{enumerable:true,get:function(){return chunkI2SPFVXH_cjs.d}});Object.defineProperty(exports,"serializeWorld",{enumerable:true,get:function(){return chunkI2SPFVXH_cjs.a}});Object.defineProperty(exports,"toJSON",{enumerable:true,get:function(){return chunkI2SPFVXH_cjs.c}});//# sourceMappingURL=serialize.cjs.map
2
2
  //# sourceMappingURL=serialize.cjs.map
package/dist/serialize.js CHANGED
@@ -1,2 +1,2 @@
1
- export{e as createDeltaSerializer,b as deserializeWorld,d as fromJSON,a as serializeWorld,c as toJSON}from'./chunk-AW254W5F.js';import'./chunk-YAHZHZNR.js';//# sourceMappingURL=serialize.js.map
1
+ export{e as createDeltaSerializer,b as deserializeWorld,d as fromJSON,a as serializeWorld,c as toJSON}from'./chunk-QC25WDOZ.js';import'./chunk-BUFJWGRQ.js';//# sourceMappingURL=serialize.js.map
2
2
  //# sourceMappingURL=serialize.js.map
package/dist/worker.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkXU3BVVCJ_cjs=require('./chunk-XU3BVVCJ.cjs'),chunk7NNM4PGP_cjs=require('./chunk-7NNM4PGP.cjs');var l=1095320899;function W(r){let e=chunk7NNM4PGP_cjs.i(r),o=chunkXU3BVVCJ_cjs.a(r);if(typeof SharedArrayBuffer>"u"){let n=new ArrayBuffer(o.byteLength);return new Uint8Array(n).set(o),{buffer:n,meta:p(e)}}let t=new SharedArrayBuffer(o.byteLength);return new Uint8Array(t).set(o),{buffer:t,meta:p(e)}}function b(r){m(r.meta);let e=new Uint8Array(r.buffer);return chunkXU3BVVCJ_cjs.b(e)}function S(r,e){let o=new Uint8Array(r),t=chunkXU3BVVCJ_cjs.b(o);if(e?.readOnly){let n=chunk7NNM4PGP_cjs.i(t);n.readOnly=true;}return t}function w(r){chunk7NNM4PGP_cjs.j(r.id)&&chunk7NNM4PGP_cjs.l(r);}function p(r){let e=[];for(let o of r.componentInfoByBit)o&&e.push({id:o.id,kind:o.kind,schema:o.schema});return {magic:l,formatVersion:1,aiecsjsVersion:chunk7NNM4PGP_cjs.a,indexBits:r.options.indexBits,generationBits:r.options.generationBits,maxComponents:r.options.maxComponents,maskWordCount:r.options.maskWordCount,capacity:r.capacity,componentSchemas:e}}function m(r){if(r.magic!==l)throw new Error("aiecsjs: invalid snapshot meta (wrong magic)");if(r.formatVersion!==1)throw new Error(`aiecsjs: unsupported snapshot format version ${r.formatVersion}`)}exports.adoptSnapshot=b;exports.attachWorld=S;exports.detachWorld=w;exports.transferableSnapshot=W;//# sourceMappingURL=worker.cjs.map
1
+ 'use strict';var chunkI2SPFVXH_cjs=require('./chunk-I2SPFVXH.cjs'),chunk7O3CM4D2_cjs=require('./chunk-7O3CM4D2.cjs');var l=1095320899;function W(r){let e=chunk7O3CM4D2_cjs.i(r),o=chunkI2SPFVXH_cjs.a(r);if(typeof SharedArrayBuffer>"u"){let n=new ArrayBuffer(o.byteLength);return new Uint8Array(n).set(o),{buffer:n,meta:p(e)}}let t=new SharedArrayBuffer(o.byteLength);return new Uint8Array(t).set(o),{buffer:t,meta:p(e)}}function b(r){m(r.meta);let e=new Uint8Array(r.buffer);return chunkI2SPFVXH_cjs.b(e)}function S(r,e){let o=new Uint8Array(r),t=chunkI2SPFVXH_cjs.b(o);if(e?.readOnly){let n=chunk7O3CM4D2_cjs.i(t);n.readOnly=true;}return t}function w(r){chunk7O3CM4D2_cjs.j(r.id)&&chunk7O3CM4D2_cjs.l(r);}function p(r){let e=[];for(let o of r.componentInfoByBit)o&&e.push({id:o.id,kind:o.kind,schema:o.schema});return {magic:l,formatVersion:1,aiecsjsVersion:chunk7O3CM4D2_cjs.a,indexBits:r.options.indexBits,generationBits:r.options.generationBits,maxComponents:r.options.maxComponents,maskWordCount:r.options.maskWordCount,capacity:r.capacity,componentSchemas:e}}function m(r){if(r.magic!==l)throw new Error("aiecsjs: invalid snapshot meta (wrong magic)");if(r.formatVersion!==1)throw new Error(`aiecsjs: unsupported snapshot format version ${r.formatVersion}`)}exports.adoptSnapshot=b;exports.attachWorld=S;exports.detachWorld=w;exports.transferableSnapshot=W;//# sourceMappingURL=worker.cjs.map
2
2
  //# sourceMappingURL=worker.cjs.map
package/dist/worker.js CHANGED
@@ -1,2 +1,2 @@
1
- import {a,b as b$1}from'./chunk-AW254W5F.js';import {i,j,l as l$1,a as a$1}from'./chunk-YAHZHZNR.js';var l=1095320899;function W(r){let e=i(r),o=a(r);if(typeof SharedArrayBuffer>"u"){let n=new ArrayBuffer(o.byteLength);return new Uint8Array(n).set(o),{buffer:n,meta:p(e)}}let t=new SharedArrayBuffer(o.byteLength);return new Uint8Array(t).set(o),{buffer:t,meta:p(e)}}function b(r){m(r.meta);let e=new Uint8Array(r.buffer);return b$1(e)}function S(r,e){let o=new Uint8Array(r),t=b$1(o);if(e?.readOnly){let n=i(t);n.readOnly=true;}return t}function w(r){j(r.id)&&l$1(r);}function p(r){let e=[];for(let o of r.componentInfoByBit)o&&e.push({id:o.id,kind:o.kind,schema:o.schema});return {magic:l,formatVersion:1,aiecsjsVersion:a$1,indexBits:r.options.indexBits,generationBits:r.options.generationBits,maxComponents:r.options.maxComponents,maskWordCount:r.options.maskWordCount,capacity:r.capacity,componentSchemas:e}}function m(r){if(r.magic!==l)throw new Error("aiecsjs: invalid snapshot meta (wrong magic)");if(r.formatVersion!==1)throw new Error(`aiecsjs: unsupported snapshot format version ${r.formatVersion}`)}export{b as adoptSnapshot,S as attachWorld,w as detachWorld,W as transferableSnapshot};//# sourceMappingURL=worker.js.map
1
+ import {a,b as b$1}from'./chunk-QC25WDOZ.js';import {i,j,l as l$1,a as a$1}from'./chunk-BUFJWGRQ.js';var l=1095320899;function W(r){let e=i(r),o=a(r);if(typeof SharedArrayBuffer>"u"){let n=new ArrayBuffer(o.byteLength);return new Uint8Array(n).set(o),{buffer:n,meta:p(e)}}let t=new SharedArrayBuffer(o.byteLength);return new Uint8Array(t).set(o),{buffer:t,meta:p(e)}}function b(r){m(r.meta);let e=new Uint8Array(r.buffer);return b$1(e)}function S(r,e){let o=new Uint8Array(r),t=b$1(o);if(e?.readOnly){let n=i(t);n.readOnly=true;}return t}function w(r){j(r.id)&&l$1(r);}function p(r){let e=[];for(let o of r.componentInfoByBit)o&&e.push({id:o.id,kind:o.kind,schema:o.schema});return {magic:l,formatVersion:1,aiecsjsVersion:a$1,indexBits:r.options.indexBits,generationBits:r.options.generationBits,maxComponents:r.options.maxComponents,maskWordCount:r.options.maskWordCount,capacity:r.capacity,componentSchemas:e}}function m(r){if(r.magic!==l)throw new Error("aiecsjs: invalid snapshot meta (wrong magic)");if(r.formatVersion!==1)throw new Error(`aiecsjs: unsupported snapshot format version ${r.formatVersion}`)}export{b as adoptSnapshot,S as attachWorld,w as detachWorld,W as transferableSnapshot};//# sourceMappingURL=worker.js.map
2
2
  //# sourceMappingURL=worker.js.map
package/llms-full.txt CHANGED
@@ -690,7 +690,7 @@ ws.onmessage = (e) => remoteDelta.apply(remoteWorld, new Uint8Array(e.data))
690
690
 
691
691
  ## Migration Guides
692
692
 
693
- Full tables in [`docs/MIGRATION.md`](./docs/MIGRATION.md).
693
+ Full tables in [`docs/MIGRATION.md`](https://github.com/yshengliao/aiecsjs/blob/main/docs/MIGRATION.md).
694
694
 
695
695
  ### From bitECS 0.4
696
696
 
@@ -939,6 +939,39 @@ All notable changes to `aiecsjs` are recorded in this file.
939
939
 
940
940
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
941
941
 
942
+ ## [Unreleased]
943
+
944
+ ### Planned for 0.4+
945
+
946
+ - Add `pipeAsync` for async system composition.
947
+ - Doc-test harness so README code blocks are mechanically verified.
948
+ - Promote `aiecsjs/worker` to `stable` once true SAB shared-memory column aliasing is implemented.
949
+ - Document the 8-bit generation wrap caveat in [STABILITY.md](./STABILITY.md): with the
950
+ default `generationBits=8`, a single slot recycled 256 times wraps back to its
951
+ starting generation, briefly re-opening the ABA window. Safe for v0.5 shmup
952
+ workloads (~5000 frame to wrap a single slot at 60 fps × ~1k destroys); high-churn
953
+ pools should set `createWorld({ indexBits: 16, generationBits: 16 })` (16 + 16 = 32 bits;
954
+ 65 536 entities × 65 536 generations). See test
955
+ [tests/ref.test.ts](./tests/ref.test.ts) `generation wrap` describe block.
956
+
957
+ ## [0.5.1] - 2026-06-02
958
+
959
+ ### Fixed
960
+
961
+ - **`destroyEntity` now fires the reactive `enterQuery`/`exitQuery` surface.** Previously `destroyEntity` cleared the entity mask wholesale without notifying `recordEntityMaskChange`, so `exitQuery(...)` buffers stayed empty on destroy — asymmetric with both `removeComponent` (which notifies) and the query-targeted `observe(q, 'remove')` observer (which already fired on destroy). A destroyed entity now records an exit for every query it was matching. The pre-destroy mask is snapshotted at destroy entry so reentrant teardown handlers cannot suppress the exit. No public API change.
962
+ - **`disposeWorld` / `destroyWorld` now release the large per-entity arrays.** The dispose path cleared archetypes/storages/queries but left `entityMask`, `entityArchetype`, `generations`, `freeList`, `componentBitFor`, `bitToQueries`, `queryArchetypeStamp`, and `sab` allocated. Because the public world handle's `capacity` getter closes over the internal state object, those arrays survived for the lifetime of the (typically retained) handle, defeating the "clear large buffers to help GC" intent. They are now released (typed arrays swapped to length-0 instances, Maps/arrays cleared, `sab` nulled). Post-dispose operations still throw as before — this is internal state, not public API.
963
+ - **`unpackBinary` best-effort mode no longer leaks a raw `SyntaxError`.** Under `onUnknownVersion: 'best-effort'`, a malformed/garbled snapshot body reaching `JSON.parse` now surfaces a namespaced `aiecsjs:` error (with the original parse error attached as `cause`), consistent with the rest of the serializer. All existing length/bounds checks are unchanged.
964
+ - **`DeltaSerializer.apply()` is now sound on a non-pristine / churned replica.** It previously treated the wire `eid` (a raw slot index, generation 0) as a packed id — throwing `addComponent on dead entity` once a replica slot's generation had advanced — and padded with `while (targetState.size < e.eid) createEntity()`, conflating the live count with a slot index and spawning phantom entities for holes in the source id space. `apply()` now materialises each entity at the source's slot via a new internal `ensureEntityAtSlot` primitive (reuse a live slot, reclaim a freed one, or advance the frontier), using the slot's current generation. No public API or wire-format change. Caveat: deltas carry only added/changed entities — entity/component removals are not propagated, so `apply()` remains additive.
965
+
966
+ ## [0.5.0] - 2026-05-30
967
+
968
+ ai\*js family version-unify milestone — the seven packages align on a common `0.5.0`. **No runtime API change; `dist/` is byte-identical to 0.4.1 apart from the bumped `VERSION` string.**
969
+
970
+ ### Changed
971
+
972
+ - **Migration-guide links repointed to GitHub blob URLs.** `docs/` became repository-only in 0.4.1 (dropped from the npm `files[]`), so the relative `./docs/MIGRATION*.md` links in `README.md` / `README_ZHTW.md` no longer resolved from the npm package page or the installed tarball. They now point at `https://github.com/yshengliao/aiecsjs/blob/main/docs/…` so consumers can follow them.
973
+ - **Version aligned to the ai\*js family `0.5.0` unify milestone.** A coordinated family-wide minor bump; aiecsjs carries no source / public-API / relations change in this release.
974
+
942
975
  ## [0.4.1] - 2026-05-29
943
976
 
944
977
  Consistency patch — packaging and documentation surface aligned to the ai*js family. **No runtime API change; `dist/` is byte-identical to 0.4.0 apart from the bumped `VERSION` string.**
@@ -994,21 +1027,6 @@ Consistency patch — packaging and documentation surface aligned to the ai*js f
994
1027
  - Dispose three-cycle tests, error-path tests, and observer handler-throw behaviour documented in `tests/world.test.ts` / `tests/observers.test.ts`.
995
1028
  - `scripts/check-dist-subpaths.mjs` (`npm run verify:dist`): post-build smoke test that imports `createWorld`+`createEntity` from the core subpath and calls `serializeWorld`, `addRelation`/`getRelationTargets`, and `transferableSnapshot` from their respective subpaths for both ESM (`dist/*.js`) and CJS (`dist/*.cjs`). Wired into `prepublishOnly` (after `build`) and CI.
996
1029
 
997
- ## [Unreleased]
998
-
999
- ### Planned for 0.4+
1000
-
1001
- - Add `pipeAsync` for async system composition.
1002
- - Doc-test harness so README code blocks are mechanically verified.
1003
- - Promote `aiecsjs/worker` to `stable` once true SAB shared-memory column aliasing is implemented.
1004
- - Document the 8-bit generation wrap caveat in [STABILITY.md](./STABILITY.md): with the
1005
- default `generationBits=8`, a single slot recycled 256 times wraps back to its
1006
- starting generation, briefly re-opening the ABA window. Safe for v0.5 shmup
1007
- workloads (~5000 frame to wrap a single slot at 60 fps × ~1k destroys); high-churn
1008
- pools should set `createWorld({ indexBits: 16, generationBits: 16 })` (16 + 16 = 32 bits;
1009
- 65 536 entities × 65 536 generations). See test
1010
- [tests/ref.test.ts](./tests/ref.test.ts) `generation wrap` describe block.
1011
-
1012
1030
  ## [0.3.0] - 2026-05-29
1013
1031
 
1014
1032
  ### Added (API)
@@ -1234,7 +1252,8 @@ The "documentation honesty + test backstop" release. No new public APIs; this is
1234
1252
  - Worker/SAB uses snapshot-copy in 0.1 rather than true shared-memory aliasing.
1235
1253
  - EntityId is unversioned; ABA-safe references arrive with `EntityRef` in 0.2.
1236
1254
 
1237
- [Unreleased]: https://github.com/yshengliao/aiecsjs/compare/v0.1.0...HEAD
1255
+ [Unreleased]: https://github.com/yshengliao/aiecsjs/compare/v0.5.1...HEAD
1256
+ [0.5.1]: https://github.com/yshengliao/aiecsjs/compare/v0.5.0...v0.5.1
1238
1257
  [0.1.0]: https://github.com/yshengliao/aiecsjs/releases/tag/v0.1.0
1239
1258
 
1240
1259
  ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiecsjs",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "TypeScript-first archetype ECS with TypedArray SoA, SAB-ready snapshot transport, and AI-readable docs.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -1,2 +0,0 @@
1
- 'use strict';var O="0.4.1";function R(n){return new Uint32Array(n)}function _(n,t){let e=t>>>5;n[e]=(n[e]??0)|1<<(t&31);}function j(n,t){let e=t>>>5;n[e]=(n[e]??0)&~(1<<(t&31));}function m(n,t){let e=t>>>5;return ((n[e]??0)&1<<(t&31))!==0}function w(n){let t=new Uint32Array(n.length);for(let e=0;e<n.length;e++)t[e]=n[e]??0;return t}function v(n){let t=[];for(let e=0;e<n.length;e++)t.push((n[e]??0).toString(16));return t.join(",")}function xt(n){for(let t=0;t<n.length;t++)if((n[t]??0)!==0)return false;return true}function ht(n,t,e,o,i,s){let r=!i;for(let a=0;a<s;a++){let d=n[a]??0,c=t[a]??0,u=e[a]??0,f=o[a]??0;if((d&c)!==c||(d&f)!==0)return false;!r&&(d&u)!==0&&(r=true);}return r}function At(n){let t=[];for(let e=0;e<n.length;e++){let o=n[e]??0;for(;o!==0;){let i=(e<<5)+T(o);t.push(i),o&=o-1;}}return t}function L(n,t,e,o){for(let i=0;i<e;i++){let s=n[t+i]??0;for(;s!==0;){let r=(i<<5)+T(s);o(r),s&=s-1;}}}function wt(n,t,e,o,i,s,r){let a=!r;for(let d=0;d<e;d++){let c=n[t+d]??0,u=o[d]??0,f=i[d]??0,l=s[d]??0;if((c&u)!==u||(c&l)!==0)return false;!a&&(c&f)!==0&&(a=true);}return a}function T(n){return 31-Math.clz32(n&-n)}var C={initialCapacity:1024,maxEntities:1e6,indexBits:24,generationBits:8},Q=256,Z=1,b=new Map;function y(n){let t=b.get(n.id);if(!t)throw new Error(`aiecsjs: world ${n.id} is destroyed or unknown`);if(t.destroyed)throw new Error(`aiecsjs: world ${n.id} is destroyed`);return t}function J(n){b.set(n.id,n);}function tt(n){b.delete(n);}function Et(n){return b.has(n)}function nt(n){let t=n??{},e=t.indexBits??C.indexBits,o=t.generationBits??C.generationBits,i=Q;if(e<1||e>24)throw new Error("aiecsjs: indexBits must be in [1, 24]");if(o<0||o>16)throw new Error("aiecsjs: generationBits must be in [0, 16]");if(e+o>32)throw new Error(`aiecsjs: indexBits (${e}) + generationBits (${o}) must be <= 32`);let s=1<<e,r=Math.max(1,Math.min(t.initialCapacity??C.initialCapacity,s)),a=Math.max(r,Math.min(t.maxEntities??C.maxEntities,s));return {initialCapacity:r,maxEntities:a,indexBits:e,generationBits:o,indexMask:(1<<e)-1,generationMask:o===0?0:(1<<o)-1,maxComponents:i,maskWordCount:Math.ceil(i/32),buffer:t.buffer??null,bufferByteOffset:t.bufferByteOffset??0}}function et(n,t){return {id:0,mask:R(n),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:[],edgeAdd:new Int32Array(t).fill(-1),edgeRemove:new Int32Array(t).fill(-1)}}function vt(n){let t=nt(n),e=Z++,o=t.generationBits>8?Uint16Array:Uint8Array,i=new o(t.initialCapacity),s={id:e,capacity:t.initialCapacity,version:O,options:t,size:0,nextFreshIndex:1,freeList:[],generations:i,destroyed:false,componentBitFor:new Map,componentInfoByBit:new Array(t.maxComponents).fill(null),componentStorageByBit:new Array(t.maxComponents).fill(null),nextComponentBit:0,entityArchetype:new Uint32Array(t.initialCapacity),entityMask:new Uint32Array(t.initialCapacity*t.maskWordCount),archetypes:[],archetypeByMaskHash:new Map,queryVersion:0,queries:[],queryMasks:new Map,queryArchetypeCache:[],queryArchetypeStamp:[],bitToQueries:new Map,reactiveBuffers:new Map,observers:[],relationStorage:new Map,sab:t.buffer,readOnly:false},r=et(t.maskWordCount,t.maxComponents);return r.id=0,s.archetypes.push(r),s.archetypeByMaskHash.set(v(r.mask),0),J(s),ot(s)}function ot(n){return {id:n.id,get capacity(){return n.capacity},version:n.version}}function St(n){let t=b.get(n.id);!t||t.destroyed||(t.destroyed=true,t.archetypes=[],t.archetypeByMaskHash.clear(),t.componentInfoByBit=[],t.componentStorageByBit=[],t.queries=[],t.queryMasks.clear(),t.queryArchetypeCache=[],t.observers=[],t.relationStorage.clear(),t.reactiveBuffers.clear(),tt(n.id));}function Wt(n){let t=y(n);t.size=0,t.nextFreshIndex=1,t.freeList=[],t.generations.fill(0),t.entityArchetype.fill(0),t.entityMask.fill(0);for(let e of t.archetypes)e.size=0,e.entityRow.clear();for(let e of t.componentStorageByBit)if(e)if(e.kind==="soa"&&e.soa)for(let o of Object.keys(e.soa))e.soa[o]?.fill(0);else e.kind==="aos"&&e.aos&&e.aos.fill(void 0);t.queryVersion++;for(let e of t.reactiveBuffers.values())e.entered.length=0,e.exited.length=0;}function Bt(n){return y(n).size}function Mt(n){return y(n).capacity}function F(n,t){if(t<=n.capacity)return;if(t>n.options.maxEntities)throw new Error(`aiecsjs: requested capacity ${t} exceeds maxEntities ${n.options.maxEntities}`);let e=n.capacity;for(;e<t;)e=Math.min(e*2,n.options.maxEntities);rt(n,e);}function rt(n,t){let e=n.generations.constructor,o=new e(t);o.set(n.generations),n.generations=o;let i=new Uint32Array(t);i.set(n.entityArchetype),n.entityArchetype=i;let s=n.options.maskWordCount,r=new Uint32Array(t*s);r.set(n.entityMask),n.entityMask=r;for(let a of n.componentStorageByBit)if(a)if(a.kind==="soa"&&a.soa){let d=n.componentInfoByBit[a.bit];d&&it(a.soa,d.fields,t);}else a.kind==="aos"&&a.aos&&(a.aos.length=t);n.capacity=t;}function it(n,t,e){for(let o of t){let i=n[o.name];if(!i)continue;let s=e*o.vectorLen;if(i.length>=s)continue;let r=new o.ctor(s);r.set(i),n[o.name]=r;}}function z(n,t){let e=v(t),o=n.archetypeByMaskHash.get(e);if(o!==void 0)return {archId:o,created:false};let i=n.archetypes.length,s={id:i,mask:w(t),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:st(t),edgeAdd:new Int32Array(n.options.maxComponents).fill(-1),edgeRemove:new Int32Array(n.options.maxComponents).fill(-1)};return n.archetypes.push(s),n.archetypeByMaskHash.set(e,i),n.queryVersion++,{archId:i,created:true}}function I(n,t){if(t<=n.capacity)return;let e=n.capacity;for(;e<t;)e*=2;let o=new Uint32Array(e);o.set(n.entities),n.entities=o,n.capacity=e;}function st(n){let t=[];for(let e=0;e<n.length;e++){let o=n[e]??0;for(;o!==0;){let i=o&-o,s=(e<<5)+(31-Math.clz32(i));t.push(s),o&=o-1;}}return t}function D(n,t){let e=n.componentBitFor.get(t.id);if(e!==void 0)return e;if(n.nextComponentBit>=n.options.maxComponents)throw new Error(`aiecsjs: world reached maxComponents=${n.options.maxComponents}`);let o=n.nextComponentBit++;n.componentBitFor.set(t.id,o),n.componentInfoByBit[o]=t;let i;if(t.kind==="soa"){let s={};for(let r of t.fields)s[r.name]=new r.ctor(n.capacity*r.vectorLen);i={kind:"soa",componentId:t.id,bit:o,soa:s};}else t.kind==="aos"?i={kind:"aos",componentId:t.id,bit:o,aos:new Array(n.capacity)}:i={kind:"tag",componentId:t.id,bit:o};return n.componentStorageByBit[o]=i,o}function x(n,t){let e=n.options.maskWordCount,o=new Uint32Array(e),s=(t&n.options.indexMask)*e;for(let r=0;r<e;r++)o[r]=n.entityMask[s+r]??0;return o}function N(n,t,e){let o=n.options.maskWordCount,s=(t&n.options.indexMask)*o;for(let r=0;r<o;r++)n.entityMask[s+r]=e[r]??0;}function g(n,t){return n.componentBitFor.get(t.id)}function Ut(n){if(!n||typeof n!="object")return false;let t=n;return typeof t.id!="number"||typeof t.version!="string"?false:b.has(t.id)}var W=1,at={i8:Int8Array,u8:Uint8Array,i16:Int16Array,u16:Uint16Array,i32:Int32Array,u32:Uint32Array,f32:Float32Array,f64:Float64Array,eid:Uint32Array,bool:Uint8Array},h=new Map;function Lt(n){let t=[];for(let[s,r]of Object.entries(n)){let a,d=1;if(typeof r=="string")a=r;else if(Array.isArray(r)){let[u,f]=r;a=u,d=f;}else throw new TypeError(`aiecsjs: invalid field declaration for "${s}"`);let c=at[a];if(!c)throw new TypeError(`aiecsjs: unknown field type "${a}" for field "${s}"`);t.push({name:s,type:a,vectorLen:d,ctor:c,bytesPerElement:c.BYTES_PER_ELEMENT});}let e=W++,o={id:e,kind:"soa",schema:n,fields:t,factory:null};return h.set(e,o),{__kind:"soa",__id:e,__schema:n}}function Tt(){let n=W++,t={id:n,kind:"tag",schema:null,fields:[],factory:null};return h.set(n,t),{__kind:"tag",__id:n}}function Ft(n){let t=W++,e=n??(()=>({})),o={id:t,kind:"aos",schema:null,fields:[],factory:e};return h.set(t,o),{__kind:"aos",__id:t,__factory:e}}function A(n){let t=h.get(n.__id);if(!t)throw new Error("aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)");return t}function P(n,t,e,o){let i=y(n);if(i.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!p(i,t))throw new Error(`aiecsjs: addComponent on dead entity ${t}`);let s=A(e),r=D(i,s),a=x(i,t);if(m(a,r)){o!==void 0&&S(i,t,e,o);return}let d=w(a);_(d,r),G(i,t,d),S(i,t,e,o),ct(i,t,r),V(i,t,r,a,d);}function zt(n,t,e){let o=y(n);if(o.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!p(o,t))return;let i=A(e),s=g(o,i);if(s===void 0)return;let r=x(o,t);if(!m(r,s))return;let a=w(r);j(a,s),G(o,t,a),dt(o,t,s);let d=t&o.options.indexMask,c=o.componentStorageByBit[s];c?.kind==="soa"&&c.soa?q(c.soa,i.fields,d):c?.kind==="aos"&&c.aos&&(c.aos[d]=void 0),V(o,t,s,r,a);}function Dt(n,t,e){let o=y(n);if(!p(o,t))return false;let i=A(e),s=g(o,i);if(s===void 0)return false;let r=x(o,t);return m(r,s)}function Nt(n,t,e){let o=y(n);if(!p(o,t))return;let i=A(e),s=g(o,i);if(s===void 0)return;let r=x(o,t);if(!m(r,s))return;let a=o.componentStorageByBit[s];if(a){if(a.kind==="soa")return a.soa;if(a.kind==="aos"){let d=t&o.options.indexMask;return a.aos?.[d]}return true}}function Pt(n,t,e,o){let i=y(n);if(i.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!p(i,t))throw new Error(`aiecsjs: setComponent on dead entity ${t}`);let s=A(e),r=g(i,s);if(r===void 0){P(n,t,e,o);return}let a=x(i,t);if(!m(a,r)){P(n,t,e,o);return}S(i,t,e,o),ft(i,t,r,o);}function S(n,t,e,o){let i=A(e),s=n.componentBitFor.get(i.id);if(s===void 0)return;let r=n.componentStorageByBit[s];if(!r)return;let a=t&n.options.indexMask;if(i.kind==="soa"&&r.soa){if(o==null)return;let d=o;for(let c of i.fields){if(!(c.name in d))continue;let u=r.soa[c.name];if(!u)continue;let f=d[c.name];if(c.vectorLen===1)u[a]=typeof f=="boolean"?f?1:0:Number(f);else if(Array.isArray(f)||ArrayBuffer.isView(f)){let l=a*c.vectorLen,K=f;for(let k=0;k<c.vectorLen;k++)u[l+k]=Number(K[k]??0);}}}else if(i.kind==="aos"&&r.aos){let d=i.factory??(()=>({})),c=r.aos[a];if(c===void 0&&(c=d(),r.aos[a]=c),o&&typeof o=="object"){let u=o,f=c;for(let l of Object.keys(u))l==="__proto__"||l==="constructor"||l==="prototype"||(f[l]=u[l]);}}}function q(n,t,e){for(let o of t){let i=n[o.name];if(i)if(o.vectorLen===1)i[e]=0;else {let s=e*o.vectorLen;for(let r=0;r<o.vectorLen;r++)i[s+r]=0;}}}function $(n,t){let e=n.options.maskWordCount,o=t&n.options.indexMask,i=o*e;L(n.entityMask,i,e,s=>{let r=n.componentStorageByBit[s],a=n.componentInfoByBit[s];r?.kind==="soa"&&r.soa&&a?q(r.soa,a.fields,o):r?.kind==="aos"&&r.aos&&(r.aos[o]=void 0);});}function G(n,t,e){let o=t&n.options.indexMask,i=n.entityArchetype[o]??0,s=n.archetypes[i];if(!s)return;let a=z(n,e).archId,d=n.archetypes[a];if(d){if(a!==i){let c=s.entityRow.get(t);if(c!==void 0){let f=s.size-1;if(c!==f){let l=s.entities[f]??0;s.entities[c]=l,s.entityRow.set(l,c);}s.entities[f]=0,s.entityRow.delete(t),s.size--;}I(d,d.size+1);let u=d.size;d.entities[u]=t,d.entityRow.set(t,u),d.size++,n.entityArchetype[o]=a;}N(n,t,e);}}var E={fireAdd:()=>{},fireRemove:()=>{},fireSet:()=>{}},H=()=>{};function qt(n){H=n;}function V(n,t,e,o,i){H(n,t,e,o,i);}function $t(n){E=n;}function ct(n,t,e){E.fireAdd(n,t,e);}function dt(n,t,e){E.fireRemove(n,t,e);}function ft(n,t,e,o){E.fireSet(n,t,e,o);}function Gt(n){return h.get(n)}function Ht(){return Array.from(h.values())}var U=24,ut=8,Y=(1<<U)-1,X=(1<<ut)-1;function yt(n,t,e){return ((t&e.generationMask)<<e.indexBits|n&e.indexMask)>>>0}function Kt(n,t){return n&t.indexMask}function Qt(n,t){return n>>>t.indexBits&t.generationMask}function Zt(n){let t=y(n);if(t.readOnly)throw new Error("aiecsjs: cannot createEntity on a read-only world (worker-attached)");let e;if(t.freeList.length>0)e=t.freeList.pop();else {if(t.nextFreshIndex>=t.options.maxEntities)throw new Error(`aiecsjs: reached maxEntities ${t.options.maxEntities}`);t.nextFreshIndex>=t.capacity&&F(t,t.nextFreshIndex+1),e=t.nextFreshIndex++;}let o=t.generations[e]??0,i=yt(e,o,t.options),s=t.archetypes[0];if(!s)throw new Error("aiecsjs: missing empty archetype");I(s,s.size+1);let r=s.size;s.entities[r]=i,s.entityRow.set(i,r),s.size++,t.entityArchetype[e]=0;let a=t.options.maskWordCount,d=e*a;for(let c=0;c<a;c++)t.entityMask[d+c]=0;return t.size++,i}function Jt(n,t){let e=y(n);if(e.readOnly)throw new Error("aiecsjs: cannot destroyEntity on a read-only world");if(!p(e,t))return;let o=t&e.options.indexMask,{dispatchDestroyObservers:i}=pt();i(e,t),mt(e,t),$(e,t);let s=e.entityArchetype[o]??0,r=e.archetypes[s];if(r){let c=r.entityRow.get(t);if(c!==void 0){let u=r.size-1;if(c!==u){let f=r.entities[u]??0;r.entities[c]=f,r.entityRow.set(f,c);}r.entities[u]=0,r.entityRow.delete(t),r.size--;}}e.entityArchetype[o]=0;let a=e.options.maskWordCount,d=o*a;for(let c=0;c<a;c++)e.entityMask[d+c]=0;e.generations[o]=(e.generations[o]??0)+1&e.options.generationMask,e.freeList.push(o),e.size--;}function lt(n,t){let e=y(n);return p(e,t)}function p(n,t){let e=t&n.options.indexMask;if(e<=0||e>=n.capacity)return false;let o=n.entityArchetype[e]??0,i=n.archetypes[o];if(!i||!i.entityRow.has(t))return false;let s=n.generations[e]??0,r=t>>>n.options.indexBits&n.options.generationMask;return s===r}function tn(n){return n&Y}function nn(n){return n>>>U&X}function en(n,t){return ((t&X)<<U|n&Y)>>>0}function on(n,t){return typeof t!="number"?false:lt(n,t)}var B=null;function rn(n){B=n;}function pt(){return B||{dispatchDestroyObservers:()=>{}}}var M=null;function sn(n){M=n;}function mt(n,t){M&&M(n,t);}exports.A=en;exports.B=on;exports.C=rn;exports.D=sn;exports.E=Lt;exports.F=Tt;exports.G=Ft;exports.H=A;exports.I=P;exports.J=zt;exports.K=Dt;exports.L=Nt;exports.M=Pt;exports.N=qt;exports.O=$t;exports.P=Gt;exports.Q=Ht;exports.a=O;exports.b=R;exports.c=_;exports.d=xt;exports.e=ht;exports.f=At;exports.g=L;exports.h=wt;exports.i=y;exports.j=Et;exports.k=vt;exports.l=St;exports.m=Wt;exports.n=Bt;exports.o=Mt;exports.p=D;exports.q=Ut;exports.r=yt;exports.s=Kt;exports.t=Qt;exports.u=Zt;exports.v=Jt;exports.w=lt;exports.x=p;exports.y=tn;exports.z=nn;//# sourceMappingURL=chunk-7NNM4PGP.cjs.map
2
- //# sourceMappingURL=chunk-7NNM4PGP.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/version.ts","../src/internal/bitmask.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","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","registerObserverDispatch","api","getComponentByInternalId","listAllComponents","DEFAULT_INDEX_BITS","DEFAULT_GENERATION_BITS","DEFAULT_INDEX_MASK","DEFAULT_GENERATION_MASK","packEid","gen","unpackIdx","unpackGen","createEntity","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,EAAgC,CACzD,OAAO,IAAI,WAAA,CAAYA,CAAS,CAClC,CAEO,SAASC,CAAAA,CAAOC,EAAmBC,CAAAA,CAAmB,CAC3D,IAAMC,CAAAA,CAAID,CAAAA,GAAQ,CAAA,CAClBD,CAAAA,CAAKE,CAAC,CAAA,CAAA,CAAKF,EAAKE,CAAC,CAAA,EAAK,GAAM,CAAA,GAAMD,CAAAA,CAAM,IAC1C,CAEO,SAASE,CAAAA,CAASH,CAAAA,CAAmBC,CAAAA,CAAmB,CAC7D,IAAMC,CAAAA,CAAID,CAAAA,GAAQ,EAClBD,CAAAA,CAAKE,CAAC,GAAKF,CAAAA,CAAKE,CAAC,CAAA,EAAK,CAAA,EAAK,EAAE,CAAA,GAAMD,EAAM,EAAA,CAAA,EAC3C,CAEO,SAASG,CAAAA,CAAQJ,CAAAA,CAAmBC,EAAsB,CAC/D,IAAMC,CAAAA,CAAID,CAAAA,GAAQ,CAAA,CAClB,OAAA,CAAA,CAASD,EAAKE,CAAC,CAAA,EAAK,GAAM,CAAA,GAAMD,CAAAA,CAAM,OAAU,CAClD,CAOO,SAASI,CAAAA,CAAUC,CAAAA,CAA+B,CACvD,IAAMC,CAAAA,CAAM,IAAI,YAAYD,CAAAA,CAAI,MAAM,EACtC,IAAA,IAASE,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIF,CAAAA,CAAI,MAAA,CAAQE,IAAKD,CAAAA,CAAIC,CAAC,EAAIF,CAAAA,CAAIE,CAAC,GAAK,CAAA,CACxD,OAAOD,CACT,CASO,SAASE,CAAAA,CAASC,EAAwB,CAE/C,IAAMC,EAAkB,EAAC,CACzB,QAASH,CAAAA,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AAgB1B,EAClB,CACA,SAASc,EAAAA,EAA8B,CACrC,OAAKY,CAAAA,EACI,CAAE,yBAA0B,IAAM,CAAC,CAAE,CAGhD,CAEA,IAAIE,CAAAA,CAAyE,IAAA,CACtE,SAASC,EAAAA,CAAyB7J,CAAAA,CAAsD,CAC7F4J,EAAoB5J,EACtB,CACA,SAAS+I,EAAAA,CAA0BpI,CAAAA,CAAmBwD,CAAAA,CAAqB,CACrEyF,CAAAA,EAAmBA,CAAAA,CAAkBjJ,CAAAA,CAAOwD,CAAG,EACrD","file":"chunk-7NNM4PGP.cjs","sourcesContent":["export const VERSION = '0.4.1'\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","import { VERSION } from '../version.js'\nimport { cloneMask, copyMask, createMask, maskHash } from './bitmask.js'\nimport type {\n ArchetypeState,\n ComponentInfo,\n FieldInfo,\n ResolvedWorldOptions,\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 Error(`aiecsjs: world ${world.id} is destroyed or unknown`)\n if (state.destroyed) throw new Error(`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 Error('aiecsjs: indexBits must be in [1, 24]')\n }\n if (generationBits < 0 || generationBits > 16) {\n throw new Error('aiecsjs: generationBits must be in [0, 16]')\n }\n if (indexBits + generationBits > 32) {\n throw new Error(\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\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 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 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 Error(\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: any = state.generations.constructor\n const newGen = new genCtor(newCap) as Uint8Array | Uint16Array\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: Record<string, any>, 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 Error(`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: Record<string, any> = {}\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 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)) {\n let type: keyof typeof TYPE_CTOR\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: type as any,\n vectorLen,\n ctor,\n bytesPerElement: (ctor as any).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 = { id, kind: 'aos', schema: null, fields: [], factory: fac as any }\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 any)\n return\n }\n const mask = readEntityMask(state, eid)\n if (!testBit(mask, bit)) {\n addComponent(world, eid, component, value as any)\n return\n }\n writeInitial(state, eid as number, component, value as any)\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}\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 } from './component.js'\nimport type { EntityId, ResolvedWorldOptions, World, WorldState } from './types.js'\nimport { ensureArchetypeCapacity, ensureCapacity, getWorldState } 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\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 // 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 // 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"]}
@@ -1,2 +0,0 @@
1
- import {i,r,k,u,P as P$1,I,a,Q as Q$1,w}from'./chunk-YAHZHZNR.js';var d="AIEC",B=1;function P(n,o){let e=D(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))}))),x(e)}function Q(n,o){let e=N(n,o);return J(e)}function D(n){let o=i(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$1=o.generations[t]??0,a=r(t,r$1,o.options);if(!c.entityRow.has(a))continue;let s=o.options.maskWordCount,l=t*s,p=[];for(let m=0;m<s;m++){let u=o.entityMask[l+m]??0;for(;u!==0;){let b=u&-u,_=(m<<5)+(31-Math.clz32(b)),f=o.componentInfoByBit[_];if(f){let S=o.componentStorageByBit[_],w=null;if(f.kind==="soa"&&S?.soa){let y={};for(let h of f.fields){let g=S.soa[h.name];if(g)if(h.vectorLen===1)y[h.name]=g[t];else {let L=[],M=t*h.vectorLen;for(let C=0;C<h.vectorLen;C++)L.push(g[M+C]??0);y[h.name]=L;}}w=y;}else f.kind==="aos"&&S?.aos?w=S.aos[t]??null:w=true;p.push({kind:f.kind,id:f.id,data:w});}u&=u-1;}}e.push({eid:t,components:p});}return {version:o.version,capacity:o.capacity,entities:e}}function J(n){let o=k({initialCapacity:n.capacity}),e=new Map;for(let t of n.entities){let i=u(o);e.set(t.eid,i);}for(let t of n.entities){let i=e.get(t.eid);for(let c of t.components){let r=P$1(c.id);if(!r)continue;let a=A(r);a&&I(o,i,a,c.data);}}return o}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 x(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++]=d.charCodeAt(0),r[s++]=d.charCodeAt(1),r[s++]=d.charCodeAt(2),r[s++]=d.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 N(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]!==d.charCodeAt(0)||n[1]!==d.charCodeAt(1)||n[2]!==d.charCodeAt(2)||n[3]!==d.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 l=n.subarray(t,t+s),p=new TextDecoder().decode(l);return JSON.parse(p)}function Y(n,o){let e={world:n,components:o?.components??Q$1().map(t=>A(t)).filter(Boolean),lastSnapshot:null};return {capture(){let t=D(e.world),i;return e.lastSnapshot?i=V(e.lastSnapshot,t):i=t,e.lastSnapshot=t,x(i)},apply(t,i$1){let c=N(i$1),r=i(t);for(let a of c.entities)if(!(a.eid>=r.capacity)){if(!w(t,a.eid))for(;r.size<a.eid;)u(t);for(let s of a.components){let l=P$1(s.id);if(!l)continue;let p=A(l);p&&I(t,a.eid,p,s.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{P as a,Q as b,D as c,J as d,Y as e};//# sourceMappingURL=chunk-AW254W5F.js.map
2
- //# sourceMappingURL=chunk-AW254W5F.js.map
@@ -1 +0,0 @@
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","createWorld","eidMap","eid","createEntity","getComponentByInternalId","handle","getComponentHandle","addComponent","factory","json","jsonBytes","versionBytes","VERSION","total","out","view","off","formatVersion","onUnknown","MAX_FIELD_LEN","verLen","jsonLen","createDeltaSerializer","listAllComponents","current","delta","computeDelta","targetWorld","deltaBytes","targetState","entityExists","prev","curr","prevByEid","changed","prevE","prevSig","currSig"],"mappings":"kEA0BA,IAAMA,CAAAA,CAAQ,MAAA,CACRC,CAAAA,CAAiB,CAAA,CAEhB,SAASC,EAAeC,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,WAAYA,CAAAA,CAAE,UAAA,CAAW,MAAA,CAAQC,CAAAA,EAC/BJ,CAAAA,CAAQ,UAAA,CAAY,IAAA,CAAMK,CAAAA,EAASA,CAAAA,CAAK,IAAA,GAASD,CAAAA,CAAE,EAAE,CACvD,CACF,EAAE,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,CAAAA,CAAST,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,CAASJ,EAAM,eAAA,CAAgBG,CAAG,CAAA,EAAK,CAAA,CAC7C,GAAIC,CAAAA,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AAAA,EAAM,CAACA,CAAAA,CAAE,GAAA,CAAKA,CAAC,CAAC,CAAC,CAAA,CACxDmE,CAAAA,CAAqC,EAAC,CAC5C,IAAA,IAAWnE,CAAAA,IAAKiE,CAAAA,CAAK,QAAA,CAAU,CAC7B,IAAMG,CAAAA,CAAQF,CAAAA,CAAU,GAAA,CAAIlE,EAAE,GAAG,CAAA,CACjC,GAAI,CAACoE,CAAAA,CAAO,CACVD,CAAAA,CAAQ,IAAA,CAAKnE,CAAC,CAAA,CACd,QACF,CACA,IAAMqE,CAAAA,CAAU,KAAK,SAAA,CAAUD,CAAAA,CAAM,UAAU,CAAA,CACzCE,CAAAA,CAAU,IAAA,CAAK,SAAA,CAAUtE,CAAAA,CAAE,UAAU,CAAA,CACvCqE,CAAAA,GAAYC,CAAAA,EAASH,CAAAA,CAAQ,IAAA,CAAKnE,CAAC,EACzC,CACA,OAAO,CAAE,OAAA,CAASiE,CAAAA,CAAK,OAAA,CAAS,QAAA,CAAUA,CAAAA,CAAK,QAAA,CAAU,QAAA,CAAUE,CAAQ,CAC7E","file":"chunk-AW254W5F.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, entityExists, packEid } from './internal/entity.js'\nimport type {\n ComponentInfo,\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\nexport function fromJSON(snapshot: WorldSnapshot): World {\n const world = createWorld({ initialCapacity: snapshot.capacity })\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 any)\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 return JSON.parse(json) as WorldSnapshot\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 // Apply: ensure entities exist, then add/update their components\n const targetState = getWorldState(targetWorld)\n for (const e of snapshot.entities) {\n if (e.eid >= targetState.capacity) continue\n if (!entityExists(targetWorld, e.eid as EntityId)) {\n // Create the entity. For simplicity, we just spawn until we have enough.\n while (targetState.size < e.eid) {\n createEntity(targetWorld)\n }\n }\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) addComponent(targetWorld, e.eid as EntityId, handle, comp.data as any)\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,2 +0,0 @@
1
- 'use strict';var chunk7NNM4PGP_cjs=require('./chunk-7NNM4PGP.cjs');var d="AIEC",B=1;function P(n,o){let e=D(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))}))),x(e)}function Q(n,o){let e=N(n,o);return J(e)}function D(n){let o=chunk7NNM4PGP_cjs.i(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=chunk7NNM4PGP_cjs.r(t,r,o.options);if(!c.entityRow.has(a))continue;let s=o.options.maskWordCount,l=t*s,p=[];for(let m=0;m<s;m++){let u=o.entityMask[l+m]??0;for(;u!==0;){let b=u&-u,_=(m<<5)+(31-Math.clz32(b)),f=o.componentInfoByBit[_];if(f){let S=o.componentStorageByBit[_],w=null;if(f.kind==="soa"&&S?.soa){let y={};for(let h of f.fields){let g=S.soa[h.name];if(g)if(h.vectorLen===1)y[h.name]=g[t];else {let L=[],M=t*h.vectorLen;for(let C=0;C<h.vectorLen;C++)L.push(g[M+C]??0);y[h.name]=L;}}w=y;}else f.kind==="aos"&&S?.aos?w=S.aos[t]??null:w=true;p.push({kind:f.kind,id:f.id,data:w});}u&=u-1;}}e.push({eid:t,components:p});}return {version:o.version,capacity:o.capacity,entities:e}}function J(n){let o=chunk7NNM4PGP_cjs.k({initialCapacity:n.capacity}),e=new Map;for(let t of n.entities){let i=chunk7NNM4PGP_cjs.u(o);e.set(t.eid,i);}for(let t of n.entities){let i=e.get(t.eid);for(let c of t.components){let r=chunk7NNM4PGP_cjs.P(c.id);if(!r)continue;let a=A(r);a&&chunk7NNM4PGP_cjs.I(o,i,a,c.data);}}return o}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 x(n){let o=JSON.stringify(n),e=new TextEncoder().encode(o),t=new TextEncoder().encode(chunk7NNM4PGP_cjs.a),c=12+t.length+4+e.length,r=new Uint8Array(c),a=new DataView(r.buffer),s=0;return r[s++]=d.charCodeAt(0),r[s++]=d.charCodeAt(1),r[s++]=d.charCodeAt(2),r[s++]=d.charCodeAt(3),a.setUint32(s,B,true),s+=4,a.setUint32(s,t.length,true),s+=4,r.set(t,s),s+=t.length,a.setUint32(s,e.length,true),s+=4,r.set(e,s),r}function N(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]!==d.charCodeAt(0)||n[1]!==d.charCodeAt(1)||n[2]!==d.charCodeAt(2)||n[3]!==d.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 l=n.subarray(t,t+s),p=new TextDecoder().decode(l);return JSON.parse(p)}function Y(n,o){let e={world:n,components:o?.components??chunk7NNM4PGP_cjs.Q().map(t=>A(t)).filter(Boolean),lastSnapshot:null};return {capture(){let t=D(e.world),i;return e.lastSnapshot?i=V(e.lastSnapshot,t):i=t,e.lastSnapshot=t,x(i)},apply(t,i){let c=N(i),r=chunk7NNM4PGP_cjs.i(t);for(let a of c.entities)if(!(a.eid>=r.capacity)){if(!chunk7NNM4PGP_cjs.w(t,a.eid))for(;r.size<a.eid;)chunk7NNM4PGP_cjs.u(t);for(let s of a.components){let l=chunk7NNM4PGP_cjs.P(s.id);if(!l)continue;let p=A(l);p&&chunk7NNM4PGP_cjs.I(t,a.eid,p,s.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}}exports.a=P;exports.b=Q;exports.c=D;exports.d=J;exports.e=Y;//# sourceMappingURL=chunk-XU3BVVCJ.cjs.map
2
- //# sourceMappingURL=chunk-XU3BVVCJ.cjs.map
@@ -1 +0,0 @@
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","createWorld","eidMap","eid","createEntity","getComponentByInternalId","handle","getComponentHandle","addComponent","factory","json","jsonBytes","versionBytes","VERSION","total","out","view","off","formatVersion","onUnknown","MAX_FIELD_LEN","verLen","jsonLen","createDeltaSerializer","listAllComponents","current","delta","computeDelta","targetWorld","deltaBytes","targetState","entityExists","prev","curr","prevByEid","changed","prevE","prevSig","currSig"],"mappings":"mEA0BA,IAAMA,CAAAA,CAAQ,MAAA,CACRC,CAAAA,CAAiB,CAAA,CAEhB,SAASC,EAAeC,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,WAAYA,CAAAA,CAAE,UAAA,CAAW,MAAA,CAAQC,CAAAA,EAC/BJ,CAAAA,CAAQ,UAAA,CAAY,IAAA,CAAMK,CAAAA,EAASA,CAAAA,CAAK,IAAA,GAAS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AU,QAAA,CAAUE,CAAQ,CAC7E","file":"chunk-XU3BVVCJ.cjs","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, entityExists, packEid } from './internal/entity.js'\nimport type {\n ComponentInfo,\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\nexport function fromJSON(snapshot: WorldSnapshot): World {\n const world = createWorld({ initialCapacity: snapshot.capacity })\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 any)\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 return JSON.parse(json) as WorldSnapshot\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 // Apply: ensure entities exist, then add/update their components\n const targetState = getWorldState(targetWorld)\n for (const e of snapshot.entities) {\n if (e.eid >= targetState.capacity) continue\n if (!entityExists(targetWorld, e.eid as EntityId)) {\n // Create the entity. For simplicity, we just spawn until we have enough.\n while (targetState.size < e.eid) {\n createEntity(targetWorld)\n }\n }\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) addComponent(targetWorld, e.eid as EntityId, handle, comp.data as any)\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,2 +0,0 @@
1
- var O="0.4.1";function R(n){return new Uint32Array(n)}function _(n,t){let e=t>>>5;n[e]=(n[e]??0)|1<<(t&31);}function j(n,t){let e=t>>>5;n[e]=(n[e]??0)&~(1<<(t&31));}function m(n,t){let e=t>>>5;return ((n[e]??0)&1<<(t&31))!==0}function w(n){let t=new Uint32Array(n.length);for(let e=0;e<n.length;e++)t[e]=n[e]??0;return t}function v(n){let t=[];for(let e=0;e<n.length;e++)t.push((n[e]??0).toString(16));return t.join(",")}function xt(n){for(let t=0;t<n.length;t++)if((n[t]??0)!==0)return false;return true}function ht(n,t,e,o,i,s){let r=!i;for(let a=0;a<s;a++){let d=n[a]??0,c=t[a]??0,u=e[a]??0,f=o[a]??0;if((d&c)!==c||(d&f)!==0)return false;!r&&(d&u)!==0&&(r=true);}return r}function At(n){let t=[];for(let e=0;e<n.length;e++){let o=n[e]??0;for(;o!==0;){let i=(e<<5)+T(o);t.push(i),o&=o-1;}}return t}function L(n,t,e,o){for(let i=0;i<e;i++){let s=n[t+i]??0;for(;s!==0;){let r=(i<<5)+T(s);o(r),s&=s-1;}}}function wt(n,t,e,o,i,s,r){let a=!r;for(let d=0;d<e;d++){let c=n[t+d]??0,u=o[d]??0,f=i[d]??0,l=s[d]??0;if((c&u)!==u||(c&l)!==0)return false;!a&&(c&f)!==0&&(a=true);}return a}function T(n){return 31-Math.clz32(n&-n)}var C={initialCapacity:1024,maxEntities:1e6,indexBits:24,generationBits:8},Q=256,Z=1,b=new Map;function y(n){let t=b.get(n.id);if(!t)throw new Error(`aiecsjs: world ${n.id} is destroyed or unknown`);if(t.destroyed)throw new Error(`aiecsjs: world ${n.id} is destroyed`);return t}function J(n){b.set(n.id,n);}function tt(n){b.delete(n);}function Et(n){return b.has(n)}function nt(n){let t=n??{},e=t.indexBits??C.indexBits,o=t.generationBits??C.generationBits,i=Q;if(e<1||e>24)throw new Error("aiecsjs: indexBits must be in [1, 24]");if(o<0||o>16)throw new Error("aiecsjs: generationBits must be in [0, 16]");if(e+o>32)throw new Error(`aiecsjs: indexBits (${e}) + generationBits (${o}) must be <= 32`);let s=1<<e,r=Math.max(1,Math.min(t.initialCapacity??C.initialCapacity,s)),a=Math.max(r,Math.min(t.maxEntities??C.maxEntities,s));return {initialCapacity:r,maxEntities:a,indexBits:e,generationBits:o,indexMask:(1<<e)-1,generationMask:o===0?0:(1<<o)-1,maxComponents:i,maskWordCount:Math.ceil(i/32),buffer:t.buffer??null,bufferByteOffset:t.bufferByteOffset??0}}function et(n,t){return {id:0,mask:R(n),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:[],edgeAdd:new Int32Array(t).fill(-1),edgeRemove:new Int32Array(t).fill(-1)}}function vt(n){let t=nt(n),e=Z++,o=t.generationBits>8?Uint16Array:Uint8Array,i=new o(t.initialCapacity),s={id:e,capacity:t.initialCapacity,version:O,options:t,size:0,nextFreshIndex:1,freeList:[],generations:i,destroyed:false,componentBitFor:new Map,componentInfoByBit:new Array(t.maxComponents).fill(null),componentStorageByBit:new Array(t.maxComponents).fill(null),nextComponentBit:0,entityArchetype:new Uint32Array(t.initialCapacity),entityMask:new Uint32Array(t.initialCapacity*t.maskWordCount),archetypes:[],archetypeByMaskHash:new Map,queryVersion:0,queries:[],queryMasks:new Map,queryArchetypeCache:[],queryArchetypeStamp:[],bitToQueries:new Map,reactiveBuffers:new Map,observers:[],relationStorage:new Map,sab:t.buffer,readOnly:false},r=et(t.maskWordCount,t.maxComponents);return r.id=0,s.archetypes.push(r),s.archetypeByMaskHash.set(v(r.mask),0),J(s),ot(s)}function ot(n){return {id:n.id,get capacity(){return n.capacity},version:n.version}}function St(n){let t=b.get(n.id);!t||t.destroyed||(t.destroyed=true,t.archetypes=[],t.archetypeByMaskHash.clear(),t.componentInfoByBit=[],t.componentStorageByBit=[],t.queries=[],t.queryMasks.clear(),t.queryArchetypeCache=[],t.observers=[],t.relationStorage.clear(),t.reactiveBuffers.clear(),tt(n.id));}function Wt(n){let t=y(n);t.size=0,t.nextFreshIndex=1,t.freeList=[],t.generations.fill(0),t.entityArchetype.fill(0),t.entityMask.fill(0);for(let e of t.archetypes)e.size=0,e.entityRow.clear();for(let e of t.componentStorageByBit)if(e)if(e.kind==="soa"&&e.soa)for(let o of Object.keys(e.soa))e.soa[o]?.fill(0);else e.kind==="aos"&&e.aos&&e.aos.fill(void 0);t.queryVersion++;for(let e of t.reactiveBuffers.values())e.entered.length=0,e.exited.length=0;}function Bt(n){return y(n).size}function Mt(n){return y(n).capacity}function F(n,t){if(t<=n.capacity)return;if(t>n.options.maxEntities)throw new Error(`aiecsjs: requested capacity ${t} exceeds maxEntities ${n.options.maxEntities}`);let e=n.capacity;for(;e<t;)e=Math.min(e*2,n.options.maxEntities);rt(n,e);}function rt(n,t){let e=n.generations.constructor,o=new e(t);o.set(n.generations),n.generations=o;let i=new Uint32Array(t);i.set(n.entityArchetype),n.entityArchetype=i;let s=n.options.maskWordCount,r=new Uint32Array(t*s);r.set(n.entityMask),n.entityMask=r;for(let a of n.componentStorageByBit)if(a)if(a.kind==="soa"&&a.soa){let d=n.componentInfoByBit[a.bit];d&&it(a.soa,d.fields,t);}else a.kind==="aos"&&a.aos&&(a.aos.length=t);n.capacity=t;}function it(n,t,e){for(let o of t){let i=n[o.name];if(!i)continue;let s=e*o.vectorLen;if(i.length>=s)continue;let r=new o.ctor(s);r.set(i),n[o.name]=r;}}function z(n,t){let e=v(t),o=n.archetypeByMaskHash.get(e);if(o!==void 0)return {archId:o,created:false};let i=n.archetypes.length,s={id:i,mask:w(t),size:0,capacity:16,entities:new Uint32Array(16),entityRow:new Map,componentBits:st(t),edgeAdd:new Int32Array(n.options.maxComponents).fill(-1),edgeRemove:new Int32Array(n.options.maxComponents).fill(-1)};return n.archetypes.push(s),n.archetypeByMaskHash.set(e,i),n.queryVersion++,{archId:i,created:true}}function I(n,t){if(t<=n.capacity)return;let e=n.capacity;for(;e<t;)e*=2;let o=new Uint32Array(e);o.set(n.entities),n.entities=o,n.capacity=e;}function st(n){let t=[];for(let e=0;e<n.length;e++){let o=n[e]??0;for(;o!==0;){let i=o&-o,s=(e<<5)+(31-Math.clz32(i));t.push(s),o&=o-1;}}return t}function D(n,t){let e=n.componentBitFor.get(t.id);if(e!==void 0)return e;if(n.nextComponentBit>=n.options.maxComponents)throw new Error(`aiecsjs: world reached maxComponents=${n.options.maxComponents}`);let o=n.nextComponentBit++;n.componentBitFor.set(t.id,o),n.componentInfoByBit[o]=t;let i;if(t.kind==="soa"){let s={};for(let r of t.fields)s[r.name]=new r.ctor(n.capacity*r.vectorLen);i={kind:"soa",componentId:t.id,bit:o,soa:s};}else t.kind==="aos"?i={kind:"aos",componentId:t.id,bit:o,aos:new Array(n.capacity)}:i={kind:"tag",componentId:t.id,bit:o};return n.componentStorageByBit[o]=i,o}function x(n,t){let e=n.options.maskWordCount,o=new Uint32Array(e),s=(t&n.options.indexMask)*e;for(let r=0;r<e;r++)o[r]=n.entityMask[s+r]??0;return o}function N(n,t,e){let o=n.options.maskWordCount,s=(t&n.options.indexMask)*o;for(let r=0;r<o;r++)n.entityMask[s+r]=e[r]??0;}function g(n,t){return n.componentBitFor.get(t.id)}function Ut(n){if(!n||typeof n!="object")return false;let t=n;return typeof t.id!="number"||typeof t.version!="string"?false:b.has(t.id)}var W=1,at={i8:Int8Array,u8:Uint8Array,i16:Int16Array,u16:Uint16Array,i32:Int32Array,u32:Uint32Array,f32:Float32Array,f64:Float64Array,eid:Uint32Array,bool:Uint8Array},h=new Map;function Lt(n){let t=[];for(let[s,r]of Object.entries(n)){let a,d=1;if(typeof r=="string")a=r;else if(Array.isArray(r)){let[u,f]=r;a=u,d=f;}else throw new TypeError(`aiecsjs: invalid field declaration for "${s}"`);let c=at[a];if(!c)throw new TypeError(`aiecsjs: unknown field type "${a}" for field "${s}"`);t.push({name:s,type:a,vectorLen:d,ctor:c,bytesPerElement:c.BYTES_PER_ELEMENT});}let e=W++,o={id:e,kind:"soa",schema:n,fields:t,factory:null};return h.set(e,o),{__kind:"soa",__id:e,__schema:n}}function Tt(){let n=W++,t={id:n,kind:"tag",schema:null,fields:[],factory:null};return h.set(n,t),{__kind:"tag",__id:n}}function Ft(n){let t=W++,e=n??(()=>({})),o={id:t,kind:"aos",schema:null,fields:[],factory:e};return h.set(t,o),{__kind:"aos",__id:t,__factory:e}}function A(n){let t=h.get(n.__id);if(!t)throw new Error("aiecsjs: component is not registered (call defineComponent/defineTag/defineObjectComponent)");return t}function P(n,t,e,o){let i=y(n);if(i.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!p(i,t))throw new Error(`aiecsjs: addComponent on dead entity ${t}`);let s=A(e),r=D(i,s),a=x(i,t);if(m(a,r)){o!==void 0&&S(i,t,e,o);return}let d=w(a);_(d,r),G(i,t,d),S(i,t,e,o),ct(i,t,r),V(i,t,r,a,d);}function zt(n,t,e){let o=y(n);if(o.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!p(o,t))return;let i=A(e),s=g(o,i);if(s===void 0)return;let r=x(o,t);if(!m(r,s))return;let a=w(r);j(a,s),G(o,t,a),dt(o,t,s);let d=t&o.options.indexMask,c=o.componentStorageByBit[s];c?.kind==="soa"&&c.soa?q(c.soa,i.fields,d):c?.kind==="aos"&&c.aos&&(c.aos[d]=void 0),V(o,t,s,r,a);}function Dt(n,t,e){let o=y(n);if(!p(o,t))return false;let i=A(e),s=g(o,i);if(s===void 0)return false;let r=x(o,t);return m(r,s)}function Nt(n,t,e){let o=y(n);if(!p(o,t))return;let i=A(e),s=g(o,i);if(s===void 0)return;let r=x(o,t);if(!m(r,s))return;let a=o.componentStorageByBit[s];if(a){if(a.kind==="soa")return a.soa;if(a.kind==="aos"){let d=t&o.options.indexMask;return a.aos?.[d]}return true}}function Pt(n,t,e,o){let i=y(n);if(i.readOnly)throw new Error("aiecsjs: cannot mutate a read-only world");if(!p(i,t))throw new Error(`aiecsjs: setComponent on dead entity ${t}`);let s=A(e),r=g(i,s);if(r===void 0){P(n,t,e,o);return}let a=x(i,t);if(!m(a,r)){P(n,t,e,o);return}S(i,t,e,o),ft(i,t,r,o);}function S(n,t,e,o){let i=A(e),s=n.componentBitFor.get(i.id);if(s===void 0)return;let r=n.componentStorageByBit[s];if(!r)return;let a=t&n.options.indexMask;if(i.kind==="soa"&&r.soa){if(o==null)return;let d=o;for(let c of i.fields){if(!(c.name in d))continue;let u=r.soa[c.name];if(!u)continue;let f=d[c.name];if(c.vectorLen===1)u[a]=typeof f=="boolean"?f?1:0:Number(f);else if(Array.isArray(f)||ArrayBuffer.isView(f)){let l=a*c.vectorLen,K=f;for(let k=0;k<c.vectorLen;k++)u[l+k]=Number(K[k]??0);}}}else if(i.kind==="aos"&&r.aos){let d=i.factory??(()=>({})),c=r.aos[a];if(c===void 0&&(c=d(),r.aos[a]=c),o&&typeof o=="object"){let u=o,f=c;for(let l of Object.keys(u))l==="__proto__"||l==="constructor"||l==="prototype"||(f[l]=u[l]);}}}function q(n,t,e){for(let o of t){let i=n[o.name];if(i)if(o.vectorLen===1)i[e]=0;else {let s=e*o.vectorLen;for(let r=0;r<o.vectorLen;r++)i[s+r]=0;}}}function $(n,t){let e=n.options.maskWordCount,o=t&n.options.indexMask,i=o*e;L(n.entityMask,i,e,s=>{let r=n.componentStorageByBit[s],a=n.componentInfoByBit[s];r?.kind==="soa"&&r.soa&&a?q(r.soa,a.fields,o):r?.kind==="aos"&&r.aos&&(r.aos[o]=void 0);});}function G(n,t,e){let o=t&n.options.indexMask,i=n.entityArchetype[o]??0,s=n.archetypes[i];if(!s)return;let a=z(n,e).archId,d=n.archetypes[a];if(d){if(a!==i){let c=s.entityRow.get(t);if(c!==void 0){let f=s.size-1;if(c!==f){let l=s.entities[f]??0;s.entities[c]=l,s.entityRow.set(l,c);}s.entities[f]=0,s.entityRow.delete(t),s.size--;}I(d,d.size+1);let u=d.size;d.entities[u]=t,d.entityRow.set(t,u),d.size++,n.entityArchetype[o]=a;}N(n,t,e);}}var E={fireAdd:()=>{},fireRemove:()=>{},fireSet:()=>{}},H=()=>{};function qt(n){H=n;}function V(n,t,e,o,i){H(n,t,e,o,i);}function $t(n){E=n;}function ct(n,t,e){E.fireAdd(n,t,e);}function dt(n,t,e){E.fireRemove(n,t,e);}function ft(n,t,e,o){E.fireSet(n,t,e,o);}function Gt(n){return h.get(n)}function Ht(){return Array.from(h.values())}var U=24,ut=8,Y=(1<<U)-1,X=(1<<ut)-1;function yt(n,t,e){return ((t&e.generationMask)<<e.indexBits|n&e.indexMask)>>>0}function Kt(n,t){return n&t.indexMask}function Qt(n,t){return n>>>t.indexBits&t.generationMask}function Zt(n){let t=y(n);if(t.readOnly)throw new Error("aiecsjs: cannot createEntity on a read-only world (worker-attached)");let e;if(t.freeList.length>0)e=t.freeList.pop();else {if(t.nextFreshIndex>=t.options.maxEntities)throw new Error(`aiecsjs: reached maxEntities ${t.options.maxEntities}`);t.nextFreshIndex>=t.capacity&&F(t,t.nextFreshIndex+1),e=t.nextFreshIndex++;}let o=t.generations[e]??0,i=yt(e,o,t.options),s=t.archetypes[0];if(!s)throw new Error("aiecsjs: missing empty archetype");I(s,s.size+1);let r=s.size;s.entities[r]=i,s.entityRow.set(i,r),s.size++,t.entityArchetype[e]=0;let a=t.options.maskWordCount,d=e*a;for(let c=0;c<a;c++)t.entityMask[d+c]=0;return t.size++,i}function Jt(n,t){let e=y(n);if(e.readOnly)throw new Error("aiecsjs: cannot destroyEntity on a read-only world");if(!p(e,t))return;let o=t&e.options.indexMask,{dispatchDestroyObservers:i}=pt();i(e,t),mt(e,t),$(e,t);let s=e.entityArchetype[o]??0,r=e.archetypes[s];if(r){let c=r.entityRow.get(t);if(c!==void 0){let u=r.size-1;if(c!==u){let f=r.entities[u]??0;r.entities[c]=f,r.entityRow.set(f,c);}r.entities[u]=0,r.entityRow.delete(t),r.size--;}}e.entityArchetype[o]=0;let a=e.options.maskWordCount,d=o*a;for(let c=0;c<a;c++)e.entityMask[d+c]=0;e.generations[o]=(e.generations[o]??0)+1&e.options.generationMask,e.freeList.push(o),e.size--;}function lt(n,t){let e=y(n);return p(e,t)}function p(n,t){let e=t&n.options.indexMask;if(e<=0||e>=n.capacity)return false;let o=n.entityArchetype[e]??0,i=n.archetypes[o];if(!i||!i.entityRow.has(t))return false;let s=n.generations[e]??0,r=t>>>n.options.indexBits&n.options.generationMask;return s===r}function tn(n){return n&Y}function nn(n){return n>>>U&X}function en(n,t){return ((t&X)<<U|n&Y)>>>0}function on(n,t){return typeof t!="number"?false:lt(n,t)}var B=null;function rn(n){B=n;}function pt(){return B||{dispatchDestroyObservers:()=>{}}}var M=null;function sn(n){M=n;}function mt(n,t){M&&M(n,t);}export{en as A,on as B,rn as C,sn as D,Lt as E,Tt as F,Ft as G,A as H,P as I,zt as J,Dt as K,Nt as L,Pt as M,qt as N,$t as O,Gt as P,Ht as Q,O as a,R as b,_ as c,xt as d,ht as e,At as f,L as g,wt as h,y as i,Et as j,vt as k,St as l,Wt as m,Bt as n,Mt as o,D as p,Ut as q,yt as r,Kt as s,Qt as t,Zt as u,Jt as v,lt as w,p as x,tn as y,nn as z};//# sourceMappingURL=chunk-YAHZHZNR.js.map
2
- //# sourceMappingURL=chunk-YAHZHZNR.js.map