diff --git a/README.md b/README.md index 50831ee..ef6f3f0 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ New version of JsonDatabase is based on dynamic properties. This database supports all possible [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) class operations from ECMAScript. - [Starting Using Con-Databases](./docs/HOW_TO_SETUP.md) - [Basic API documentation](./docs/API-Documentation.md) +- [Using DynamicTables](./docs/Using-DynamicTable.md) ### Inherited from Map - size: number of properties @@ -66,9 +67,9 @@ Each key is unique to its player because key include players id, so database key Code ```js import {world} from "@minecraft/server"; -import {WorldDatabase} from "databases.js"; +import { JsonDatabase } from "databases.js"; -const stats = new WorldDatabase("playerStats"); +const stats = new JsonDatabase("playerStats"); world.afterEvents.entityDie.subscribe(({deadEntity})=> setDeaths(deadEntity,getDeaths(deadEntity) + 1); diff --git a/con-database.d.ts b/con-database.d.ts new file mode 100644 index 0000000..1d0302c --- /dev/null +++ b/con-database.d.ts @@ -0,0 +1,105 @@ +import { World, Entity } from "@minecraft/server"; + +class DynamicSource { + readonly source: World | Entity; + constructor(source: World | Entity) + getIds(): string[] + get(key: string): any + set(key: string, value: any): void + delete(key): boolean | undefined + isValid():boolean +} +class DynamicDatabase extends Map{ + constructor(source: DynamicSource, id: string, kind: string, parser: {stringify(object: any): string, parse(raw: string): any}) + isValid(): boolean + dispose(): void + readonly isDisposed: boolean +} +class JsonDatabase extends DynamicDatabase{ constructor(id: string, source?: World | Entity ); } +interface DynamicProxyConstructor{ + new (id: string, source?: World | Entity): {[k: string]: any | undefined} +} +const DynamicProxy: DynamicProxyConstructor; +enum SerializableKinds { + Boolean="c0211201-0001-4002-8001-4f90af596647", + Number="c0211201-0001-4002-8002-4f90af596647", + String="c0211201-0001-4002-8003-4f90af596647", + Object="c0211201-0001-4002-8004-4f90af596647", + DynamicTable="c0211201-0001-4002-8101-4f90af596647" +} +interface Deserializer extends Generator{ + continue(): T, + readonly source: DynamicSource; + readonly length: number; + readonly rootKey: string; + readonly kind: string; +} + +namespace Serializer { + function isSerializable(object: any): boolean + function getSerializerKind(object: any): string | undefined + function isRegistredKind(kind: string): boolean + function setSerializableKind(object: object, kind: string): boolean + function registrySerializer(kind: K, serializer: (object: any)=>Generator, deserializer: (source: Deserializer)=>void): K; + function getSerializer(kind: string): null | ((object: any)=>Generator) + function getDeserializer(kind: string): ((source: Deserializer)=>void) | null + function setSerializableClass(construct: new (...any: any[])=>any, kind: string, serializer: (object: any)=>Generator, deserializer: (source: Deserializer)=>void): void + function getKindFromClass(construct: new (...any: any[])=>any): string | null; + function getSerializerKinds(): IterableIterator + function getSerializers(kind: string): {serializer: (object: any)=>Generator, deserializer: (source: Deserializer)=>void} + function overrideSerializers(kind: K, serializer: (object: any)=>Generator, deserializer: (source: Deserializer)=>void): K; +} + +class DynamicTable extends Map{ + static readonly KIND: string; + static OpenCreate(id: string): DynamicTable; + static ClearAll(): void; + static getTableIds(): IterableIterator; + static DeleteTable(id: string): boolean; + + readonly tableId: string; + private constructor(); + isValid(): boolean; +} +class DataCoruptionError extends ReferenceError{ + constructor(source: DynamicSource, rootKey: string, message: string); + remove(): void +} + +export {JsonDatabase, DynamicProxy, DynamicTable, Serializer, DataCoruptionError, SerializableKinds}; +/** + * resitry basic serializations for API classes, based on compatibility but doesn't breaks in older or newer versions, each feature is available based on your module version used + * - BlockType class + * - EntityType class + * - ItemType class + * - BlockPermutation class --> requires BlockType class feature + * - ItemStack class + * - typeId + * - amount + * - nameTag + * - keepOnDeath + * - lockMode + * - lore + * - canDestroy + * - canPlaceOn + * - dynamic Properties + * - enchantable component + * - durability component + * - Vector class + * + * Example of API serializers + * ```js + * const dt = DynamicTable.OpenCreate("test"); + * dt.set("item", new ItemStack("iron_sword")); + * const canPlaceOn = dt.get("item").getCanPlaceOn(); + * ``` + */ +export const registryAPISerializers: ()=>void +export enum APISerializableKinds { + BlockType = "c0211201-0001-4002-8201-4f90af596647", + EntityType = "c0211201-0001-4002-8202-4f90af596647", + ItemType = "c0211201-0001-4002-8203-4f90af596647", + BlockPermutation = "c0211201-0001-4002-8204-4f90af596647", + ItemStack = "c0211201-0001-4002-8205-4f90af596647", + Vector = "c0211201-0001-4002-8206-4f90af596647", +} \ No newline at end of file diff --git a/con-database.js b/con-database.js new file mode 100644 index 0000000..bfebd37 --- /dev/null +++ b/con-database.js @@ -0,0 +1,808 @@ +import { world, World, Entity, system } from "@minecraft/server"; +import * as mc from "@minecraft/server"; +const mc_world = world; +const {setDynamicProperty: wSDP, getDynamicProperty: wGDP, getDynamicPropertyIds: wGDPI} = World.prototype; +let {isValid: isValidEntity, setDynamicProperty: eSDP, getDynamicProperty: eGDP, getDynamicPropertyIds: eGDPI} = Entity.prototype; +const DYNAMIC_DB_PREFIX = "\u1221\u2112"; +const ROOT_CONTENT_TABLE_UUID = "c0211201-0001-4001-8001-4f90af596647"; +const STRING_LIMIT = 32e3; +const TABLE_STRING_LENGTH = 31e3; +const eP = { + gDP: eGDP, + sDP: eSDP, + gDPI: eGDPI +}; +const wP = { + gDP: wGDP, + sDP: wSDP, + gDPI: wGDPI +}; +class DynamicSource { + /**@readonly @type {World | Entity} */ + source; + /**@param {World | Entity} source */ + constructor(source){ + this.source = source; + if(SOURCE_INSTANCES.has(source)) return SOURCE_INSTANCES.get(source); + if(source === mc_world) Object.assign(this, wP); else if (isValidEntity.call(source)) Object.assign(this, eP); + else throw new ReferenceError("Invald source type: " + source); + SOURCE_INSTANCES.set(source, this); + } + /**@returns {string[]} */ + getIds(){return this.gDPI.call(this.source);} + /**@param {string} key @returns {number | boolean | string | import("@minecraft/server").Vector3}*/ + get(key){return this.gDP.call(this.source,key);} + /**@param {string} key */ + set(key,value){ this.sDP.call(this.source, key, value);} + /**@param {string} key @returns {boolean} */ + delete(key){this.sDP.call(this.source, key, undefined); return true;} + /**@returns {boolean} */ + isValid(){ return this.source === world || isValidEntity.call(this.source); } +} +/////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////// DYNAMIC DATABASE +/////////////////////////////////////////////////////////////////////////////////////////////////////// +const SOURCE_INSTANCES = new WeakMap(); +const DDB_SUBINSTANCES = new WeakMap(); +class DynamicDatabase extends Map{ + /**@readonly @private @type {DynamicSource} */ + _source; + /**@readonly @private @type {string} */ + _prefix; + /**@readonly @private @type {string} */ + _prefixLength; + /**@readonly @private */ + _STRINGIFY; + /**@readonly @private*/ + _PARSE; + /** @private*/ + _notDisposed; + /**@param {World | Entity} source @param {string} id @param {string} kind */ + constructor(source, id, kind, parser){ + super(); + this._source = new DynamicSource(source); + const PRE = `${kind}${DYNAMIC_DB_PREFIX}${id}${DYNAMIC_DB_PREFIX}`, LENGTH = PRE.length, SOURCE = this._source, PARSE = parser.parse; + const MAP_INSTANCES = DDB_SUBINSTANCES.get(SOURCE)??new Map; + if(MAP_INSTANCES.has(PRE)) return MAP_INSTANCES.get(PRE); + MAP_INSTANCES.set(PRE, this); DDB_SUBINSTANCES.set(SOURCE, MAP_INSTANCES); + if(!SOURCE.isValid()) throw new ReferenceError("Source is no longer valid: " + SOURCE.source); + this._prefix = PRE; + this._prefixLength = LENGTH; + this._STRINGIFY = parser.stringify; + //this._PARSE = PARSE; + this._notDisposed = true; + for (const K of SOURCE.getIds()) if(K.startsWith(PRE)) { + const key = K.substring(LENGTH); + const value = SOURCE.get(K); + if(typeof value === "string") super.set(key, PARSE(value)); + } + } + /**@param {string} key @param {any} value */ + set(key, value){ + if(!this.isValid()) throw new ReferenceError("This database instance is no longer valid"); + if(key.length + this._prefixLength > STRING_LIMIT) throw new TypeError("Key is too long: " + key.length); + if(value === undefined) { + this.delete(key); + return this; + } + const data = this._STRINGIFY(value); + if(data.length > STRING_LIMIT) throw new TypeError("Size of data in string is too long: " + data.length); + this._source.set(this._prefix + key, data); + return super.set(key,value); + } + /**@param {string} key */ + delete(key){ + if(!this.isValid()) throw new ReferenceError("This database instance is no longer valid"); + if(!this.has(key)) return false; + this._source.delete(this._prefix + key); + return super.delete(key); + } + clear(){ + if(!this.isValid()) throw new ReferenceError("This database instance is no longer valid"); + const P = this._prefix; + const s = this._source; + for(const key of this.keys()) s.delete(P + key); + return super.clear(); + } + /**@returns {boolean} */ + isValid(){return this._source.isValid() && this._notDisposed;} + dispose(){ + this._notDisposed = false; + DDB_SUBINSTANCES.get(this._source)?.delete?.(this._prefix); + super.clear(); + } + /**@readonly @type {boolean} */ + get isDisposed(){return !this._notDisposed;} +} +class DynamicWrapper { + + /**@readonly @private @type {Entity | World | ItemStack} */ + _source; + /**@readonly @private @type {string} */ + _prefix; + /**@readonly @private @type {string} */ + _prefixLength; + /**@readonly @private */ + _STRINGIFY; + /**@readonly @private*/ + _PARSE; + /**@param {World | Entity} source @param {string} id @param {string} kind */ + constructor(source, id, kind, parser){ + this._source = source; + const PRE = `${kind}${DYNAMIC_DB_PREFIX}${id}${DYNAMIC_DB_PREFIX}`, LENGTH = PRE.length; + this._prefix = PRE; + this._prefixLength = LENGTH; + this._STRINGIFY = parser.stringify; + this._PARSE = parser.parse; + } + clear(){ for( const k of this.__getKeys()) this._source.set(k, undefined); }; + /** + * @returns true if an element in the Map existed and has been removed, or false if the element does not exist. + */ + delete(key) { + const has = this.has(key); + this._source.set(this._prefix + key, undefined); + return has; + }; + /** + * Executes a provided function once per each key/value pair in the Map, in insertion order. + * @param {(value: any, key: string, map: DynamicWrapper) => void} callbackfn + * @param {any} thisArg + */ + forEach(callbackfn, thisArg = null){ + for (const k of this.keys()) { + try { + callbackfn.call(thisArg??null, k, this.get(k), this); + } catch (error) { + + } + } + } + /** + * Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map. + * @returns Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned. + */ + get(key){ const a = this._source.get(this._prefix + key); typeof a === "string"?this._PARSE(a):a; }; + /** + * @returns boolean indicating whether an element with the specified key exists or not. + */ + has(key){ return this._source.get(this._prefix + key)!==undefined; } + /** + * Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated. + */ + set(key, value){ + this._source.set(this._prefix + key, this._STRINGIFY(value)); + return this; + }; + /** + * @returns the number of elements in the Map. + */ + get size(){return [...this.__getKeys()].length;}; + /** Returns an iterable of entries in the map. */ + [Symbol.iterator](){return this.entries();} + /** + * Returns an iterable of key, value pairs for every entry in the map. + */ + *entries(){for( const k of this.__getKeys()) yield [k.substring(this._prefixLength),this._PARSE(this._source.get(k))]}; + /** + * Returns an iterable of keys in the map + */ + *keys(){for( const k of this.__getKeys()) yield k.substring(this._prefixLength);}; + /** + * Returns an iterable of values in the map + */ + *values(){for( const k of this.__getKeys()) yield this._PARSE(this._source.get(k));} + *__getKeys(){ for (const K of this._source.getIds()) if(K.startsWith(this._prefix)) yield K; } +} +class JsonDatabase extends DynamicDatabase{ constructor(id, source = world){ super(source, id, "JSON", JSON); } } +class JSONDynamicWrapper extends DynamicWrapper{ constructor(id, source = world){ super(source, id, "JSON", JSON); } } + +class DynamicProxy extends JsonDatabase{ + constructor(id, source = world){ + super(id, source); + return new Proxy(this,{ + defineProperty(t,p,att){ + if(att.value && typeof p === "string"){ + t.set(p,att.value); + return true; + } + return false; + }, + deleteProperty(t,p){ + console.warn("DELETE: ",p); + if(typeof p === "string") return t.delete(p); + return false; + }, + set(t, p, newValue){ + if(typeof p === "string") { + t.set(p, newValue); + return true; + } + return false; + }, + get(t, p){ + if(typeof p === "string") { + return t.get(p)??Object.prototype[p]; + } + return false; + }, + getPrototypeOf(t){return Object.prototype;}, + isExtensible(t){return true;}, + setPrototypeOf(t){return false;}, + has(t,k){return t.has(k);}, + preventExtensions(t){return false;}, + ownKeys(t){ return [...t.keys()]; }, + getOwnPropertyDescriptor(t,k){ + if(t.has(k)){ + return {value:t.get(k), enumerable: true, configurable: true, writable: true}; + } + } + }); + } +} +/////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////// COMPLEX DATABASE +/////////////////////////////////////////////////////////////////////////////////////////////////////// +const PARSER_SYMBOL = Symbol("SERIALIZEABLE"); +const SERIALIZERS = new Map(); +const DESERIALIZER_INFO = new WeakMap(); +const ROOT_KEY = "root::" + ROOT_CONTENT_TABLE_UUID; +const TABLE_SOURCES = new WeakMap(); +const TABLE_ID = new WeakMap(); +const ID_TABLE = new WeakMap(); +const TABLE_VALIDS = new WeakSet(); +let isNativeCall = false; +let RootTable; +function getRootTable(){ + if(RootTable) return RootTable; + return RootTable = world.getDynamicProperty(ROOT_KEY)?DATABASE_MANAGER.deserialize(ROOT_KEY, new DynamicSource(world)):(()=>{ + const source = new DynamicSource(world); + isNativeCall = true; + const value = new DynamicTable(); + isNativeCall = false; + TABLE_SOURCES.set(value, source); + TABLE_ID.set(value, ROOT_KEY); + SetTable(source, ROOT_KEY, value); + TABLE_VALIDS.add(value); + DATABASE_MANAGER.serialize(ROOT_KEY, source, value); + return value; + })(); +} + +const SerializableKinds = { + Boolean:"c0211201-0001-4002-8001-4f90af596647", + Number:"c0211201-0001-4002-8002-4f90af596647", + String:"c0211201-0001-4002-8003-4f90af596647", + Object:"c0211201-0001-4002-8004-4f90af596647", + DynamicTable: "c0211201-0001-4002-8101-4f90af596647" +}; +SerializableKinds[SerializableKinds.Boolean] = "Boolean"; +SerializableKinds[SerializableKinds.Number] = "Number"; +SerializableKinds[SerializableKinds.String] = "String"; +SerializableKinds[SerializableKinds.Object] = "Object"; +SerializableKinds[SerializableKinds.DynamicTable] = "DynamicTable"; +const Serializer = { + isSerializable(object){ return object[PARSER_SYMBOL] != undefined; }, + getSerializerKind(object){ return object[PARSER_SYMBOL];}, + isRegistredKind(kind){return SERIALIZERS.has(kind);}, + setSerializableKind(object, kind){ + if(SERIALIZERS.has(kind)){ object[PARSER_SYMBOL] = kind; return true; } + return false; + }, + registrySerializer(kind, serializer, deserializer){ + if(SERIALIZERS.has(kind)) throw new ReferenceError("Duplicate serialization kind: " + kind); + if(typeof kind != "string") throw new TypeError("Kind must be type of string."); + if(typeof serializer != "function" || typeof deserializer != "function") throw new TypeError("serializer or deserializer is not a function"); + SERIALIZERS.set(kind,{serializer,deserializer}); + return kind; + }, + getSerializer(kind){ + return SERIALIZERS.get(kind)?.serializer??null; + }, + getDeserializer(kind){ + return SERIALIZERS.get(kind)?.deserializer??null; + }, + getSerializers(kind){ + const data = SERIALIZERS.get(kind); + if(!data) return null; + return {...data}; + }, + setSerializableClass(construct, kind, serializer, deserializer){ + Serializer.registrySerializer(kind, serializer, deserializer); + Serializer.setSerializableKind(construct.prototype,kind); + }, + getKindFromClass(construct){ + return construct?.prototype?.[PARSER_SYMBOL]??null; + }, + getSerializerKinds(){return SERIALIZERS.keys();}, + overrideSerializers(kind, serializer, deserializer){ + if(typeof kind != "string") throw new TypeError("Kind must be type of string."); + if(typeof serializer != "function" || typeof deserializer != "function") throw new TypeError("serializer or deserializer is not a function"); + SERIALIZERS.set(kind,{serializer,deserializer}); + return kind; + } +} +const DATABASE_MANAGER = { + getHeader(rootRef, source){ + const data = source.get(rootRef); + if(typeof data != "string") return null; + return JSONReadable(data); + }, + serialize(rootRef, source, object){ + if(!Serializer.isRegistredKind(Serializer.getSerializerKind(object))) throw new TypeError("object is not serializeable."); + const kind = Serializer.getSerializerKind(object) + const serializer = Serializer.getSerializer(kind); + if(!serializer) throw new ReferenceError("No serializer for " + kind); + return this.serializationResolver( + serializer(object, {kind,source,rootRef}) + ,rootRef,source, kind + ); + }, + /**@param {Generator} gen */ + serializationResolver(gen, rootRef, source, kind){ + const oldHeader = this.getHeader(rootRef, source); + const prefix = rootRef + "::"; + let oldLength = 0, newLength = 0; + if(oldHeader){ + const [data] = oldHeader; + oldLength = parseInt(data["length"],36); + } + try { + let genNext = gen.next(); + if(!genNext.done) { + const headerData = genNext.value + ""; + if(headerData.length > TABLE_STRING_LENGTH) gen.throw(new RangeError("Yielded stirng is too big: " + headerData.length)); + genNext = gen.next(); + while (!genNext.done) { + const key = prefix + newLength; + try { + source.set(key, genNext.value + ""); + newLength++; + } catch (error) { + gen.throw(error); + } + genNext = gen.next(); + } + source.set(rootRef, JSONWritable({length:newLength.toString(36),kind},headerData)); + } + } finally { + for (let i = newLength; i < oldLength; i++) source.delete(prefix + i); + return newLength; + } + }, + deserialize(rootRef, source, header = undefined){ + try { + const oldHeader = header??this.getHeader(rootRef, source); + if(!oldHeader) return null; + const prefix = rootRef + "::"; + const [{length:le,kind}, data] = oldHeader; + let length = parseInt(le,36); + if(!Serializer.isRegistredKind(kind)) throw new ReferenceError("Unknown parser kind: " + kind); + const deserializeResolver = Serializer.getDeserializer(kind); + if(!deserializeResolver) throw new ReferenceError("No deserializer for: " + kind); + const deserializer = this.deserializer(source, rootRef, prefix, length, data); + DESERIALIZER_INFO.set(deserializer, { + source, + rootRef, + kind, + deserializeResolver, + oldHeader, + length, + }); + return deserializeResolver(deserializer); + } catch (error) { + error.rootKey = rootRef; + error.source = source; + throw Object.setPrototypeOf(error, DataCoruptionError); + } + }, + *deserializer(source, root, prefix, length, initial){ + yield initial; + let i = 0; + while(i < length){ + const data = source.get(prefix + i); + if(!data) throw new DataCoruptionError(source, root, "No continual data at index of " + i); + yield data; + i++; + } + }, + removeTree(rootRef, source){ + const oldHeader = this.getHeader(rootRef, source); + if(!oldHeader) return false; + const prefix = rootRef + "::"; + const [{length:le}] = oldHeader; + let length = parseInt(le,36); + if(!isFinite(length)) return false; + for (let i = 0; i < length; i++) source.delete(prefix + i); + source.delete(rootRef); + return true; + } +} +Object.defineProperties(DATABASE_MANAGER.deserializer.prototype,Object.getOwnPropertyDescriptors({ + return(){ + return {done:true}; + }, + continue(){ + return this.next(...arguments).value; + }, + get source(){ + if(!DESERIALIZER_INFO.has(this)) throw new ReferenceError("Object bound to prototype does not exist."); + return DESERIALIZER_INFO.get(this).source; + }, + get rootKey(){ + if(!DESERIALIZER_INFO.has(this)) throw new ReferenceError("Object bound to prototype does not exist."); + return DESERIALIZER_INFO.get(this).rootRef; + }, + get length(){ + if(!DESERIALIZER_INFO.has(this)) throw new ReferenceError("Object bound to prototype does not exist."); + return DESERIALIZER_INFO.get(this).length; + }, + get kind(){ + if(!DESERIALIZER_INFO.has(this)) throw new ReferenceError("Object bound to prototype does not exist."); + return DESERIALIZER_INFO.get(this).kind; + } +})); + + +class DynamicTable extends Map{ + /**@readonly */ + static get KIND(){return "c0211201-0001-4002-8101-4f90af596647";} + /**@readonly @type {string} */ + get tableId(){return TABLE_ID.get(this);} + constructor(){ + if(!isNativeCall) throw new ReferenceError("No constructor for " + DynamicTable.name); + super(); + } + get(key){ + if(!this.isValid()) throw new ReferenceError("Object bound to prototype doesn't not exist at [DynamicTable::get()]."); + if(!this.has(key)) return; + const source = TABLE_SOURCES.get(this); + const dataId = super.get(key); + return DATABASE_MANAGER.deserialize(dataId, source); + } + set(key, value){ + if(!this.isValid()) throw new ReferenceError("Object bound to prototype doesn't not exist at [DynamicTable::get()]."); + if(value == null) throw new ReferenceError("You can not assign property to null or undefined"); + if(!Serializer.isRegistredKind(Serializer.getSerializerKind(value))) throw new TypeError("value is not serializeable."); + if(value instanceof DynamicTable) throw new TypeError("You can't set value as DynamicTable please use AddTable"); + const has = this.has(key); + + const source = TABLE_SOURCES.get(this); + + let newKey; + if(has){ + newKey = super.get(key); + const header = DATABASE_MANAGER.getHeader(newKey, source); + if(header?.[0]?.kind === DynamicTable.KIND) { + const a = DATABASE_MANAGER.deserialize(newKey, source, header); + a.clear(); + TABLE_VALIDS.delete(a); + } + }else{ + newKey = "k:" + v4uuid() + super.set(key, newKey); + SaveState(this); + } + DATABASE_MANAGER.serialize(newKey, source, value); + return this; + } + clear(){ + if(!this.isValid()) throw new ReferenceError("Object bound to prototype doesn't not exist at [DynamicTable::clear()]."); + const source = TABLE_SOURCES.get(this); + const KIND = DynamicTable.KIND; + for (const k of super.keys()) { + const dataId = super.get(k); + const header = DATABASE_MANAGER.getHeader(dataId,source); + if(header?.[0]?.kind === KIND) { + const a = DATABASE_MANAGER.deserialize(dataId, source, header); + a.clear(); + TABLE_VALIDS.delete(a); + } + DATABASE_MANAGER.removeTree(dataId, source); + } + SaveState(this); + super.clear(); + } + delete(key){ + if(!this.isValid()) throw new ReferenceError("Object bound to prototype doesn't not exist at [DynamicTable::delete()]."); + const source = TABLE_SOURCES.get(this); + if(!this.has(key)) return false; + const dataId = super.get(key); + const header = DATABASE_MANAGER.getHeader(dataId,source); + if(header?.[0]?.kind === DynamicTable.KIND) { + const a = DATABASE_MANAGER.deserialize(dataId, source, header); + a.clear(); + TABLE_VALIDS.delete(a); + } + DATABASE_MANAGER.removeTree(dataId, source); + SaveState(this); + return super.delete(); + } + *entries(){ + if(!this.isValid()) throw new ReferenceError("Object bound to prototype doesn't not exist at [DynamicTable::entries()]."); + for (const [k,v] of super.entries()) yield [k, this.get(k)]; + } + [Symbol.iterator](){return this.entries();} + *values(){ + if(!this.isValid()) throw new ReferenceError("Object bound to prototype doesn't not exist at [DynamicTable::values()]."); + for (const k of super.keys()) yield this.get(k); + } + isValid(){ + return !!(TABLE_VALIDS.has(this) && TABLE_SOURCES.get(this)?.isValid?.()); + } + /**@returns {DynamicTable} */ + static OpenCreate(id){ + let fromTable = getRootTable(); + let a = fromTable.get(id); + if(a === undefined) { + if(!fromTable.isValid()) throw new ReferenceError("Object bound to prototype doesn't not exist at [DynamicTable::get()]."); + if(Map.prototype.has.call(fromTable,id)) throw new ReferenceError("Value of this key already exists"); + const source = TABLE_SOURCES.get(fromTable); + let newKey = "t" + v4uuid(); + isNativeCall = true; + const value = new DynamicTable(); + isNativeCall = false; + Map.prototype.set.call(fromTable, id, newKey); + SaveState(fromTable); + DATABASE_MANAGER.serialize(newKey, source, value); + TABLE_SOURCES.set(value, source); + TABLE_ID.set(value, newKey); + SetTable(source, newKey, value); + TABLE_VALIDS.add(value); + a = value; + } + else if(!(a instanceof DynamicTable)) throw new TypeError(`Value saved in ${id} is not a dynamic table.`); + return a; + } + static ClearAll(){ getRootTable().clear(); } + static getTableIds(){ return getRootTable().keys(); } + static DeleteTable(key){ return getRootTable().delete(key);} +} +function SaveState(table){ + if(table._task === undefined) { + table._task = system.run(()=>{ + table._task = undefined; + if(table.isValid()){ + DATABASE_MANAGER.serialize(table.tableId, TABLE_SOURCES.get(table), table); + } + }); + } +} +function GetTable(source, rootRef){ return ID_TABLE.get(source)?.get(rootRef); } +function SetTable(source, rootRef, table){ + if(!ID_TABLE.has(source)) ID_TABLE.set(source,new Map()); + ID_TABLE.get(source).set(rootRef, table); +} +class DataCoruptionError extends ReferenceError{ + constructor(source, rootKey, message){ + super(message); + this.rootKey = rootKey; + this.source = source; + } + remove(){ + if(!this.source.isValid()) throw new ReferenceError("Source is no longer valid"); + DATABASE_MANAGER.removeTree(this.rootKey, this.source); + } +} + +Serializer.setSerializableClass(DynamicTable, DynamicTable.KIND, + function*(table){ + let obj = {}, i = 0; + const get = Map.prototype.get, maxSize = 300; + yield Math.ceil(table.size / maxSize); + for(const key of table.keys()) { + if(++i >= maxSize){ + yield JSON.stringify(obj); + i = 0, obj = {}; + } + obj[key] = get.call(table,key); + } + if(i) yield JSON.stringify(obj); + }, + function(n){ + if(GetTable(n.source,n.rootKey)) return GetTable(n.source,n.rootKey); + isNativeCall = true; + const table = new DynamicTable(); + isNativeCall = false; + TABLE_SOURCES.set(table, n.source); + TABLE_ID.set(table, n.rootKey); + SetTable(n.source, n.rootKey, table); + TABLE_VALIDS.add(table); + const set = Map.prototype.set; + const length = Number(n.continue()); + for (let i = 0; i < length; i++) { + const data = n.continue(); + if(!data) throw new DataCoruptionError(n.source,n.rootKey,"Data for this dynamic table are corupted."); + const obj = JSON.parse(data); + for(const k of Object.getOwnPropertyNames(obj)) set.call(table, k, obj[k]); + } + return table; + } +); +Serializer.setSerializableClass(Boolean, SerializableKinds.Boolean, function*(n){yield n;}, function(n){for(const a of n) return a==="true";}); +Serializer.setSerializableClass(Number, SerializableKinds.Number, function*(n){yield n;}, function(n){for(const a of n) return Number(a);}); +Serializer.setSerializableClass(String, SerializableKinds.String, + function*(n){ + let length = n.length; + let cursor = 0; + let i = 0; + yield Math.ceil(length / TABLE_STRING_LENGTH); + while(length > 0){ + const s = n.substring(cursor,cursor + TABLE_STRING_LENGTH); + const l = s.length; + if(l <= 0) return; + length -= l, cursor += l; + yield s; + i++; + } + }, + function(n){ + const count = Number(n.continue()); + const l = new Array(count); + for (let i = 0; i < count; i++) { + l[i] = n.continue(); + } + return l.join(""); + } +); +Serializer.setSerializableClass(Object, SerializableKinds.Object, + function(n){ return Serializer.getSerializer(SerializableKinds.String)(JSON.stringify(n)); }, + function(n){ return JSON.parse(Serializer.getDeserializer(SerializableKinds.String)(n)); } +); +function v4uuid(timestamp = Date.now()){ + const {random,floor} = Math; + const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) =>{ + let r = (timestamp + random() * 16) % 16 | 0; + timestamp = floor(timestamp / 16); + return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); + }); + return uuid; +} +function Readable(text){ + const size = text.charCodeAt(0); + const info = text.substring(1,1+size); + const data = text.substring(1+size); + return [info, data, size]; +} +function JSONReadable(text){ + const [info, data, size] = Readable(text); + return [JSON.parse(info), data, size]; +} +function Writable(json, text){ + return `${String.fromCharCode(json.length)}${json}${text}`; +} +function JSONWritable(json, text){ return Writable(JSON.stringify(json),text); }; + +export {JsonDatabase, DynamicProxy, DynamicTable, Serializer, DataCoruptionError, SerializableKinds}; + +export const APISerializableKinds = { + BlockType: "c0211201-0001-4002-8201-4f90af596647", + EntityType: "c0211201-0001-4002-8202-4f90af596647", + ItemType: "c0211201-0001-4002-8203-4f90af596647", + BlockPermutation: "c0211201-0001-4002-8204-4f90af596647", + ItemStack: "c0211201-0001-4002-8205-4f90af596647", + Vector: "c0211201-0001-4002-8206-4f90af596647", + "c0211201-0001-4002-8201-4f90af596647": "BlockType", + "c0211201-0001-4002-8202-4f90af596647": "EntityType", + "c0211201-0001-4002-8203-4f90af596647": "ItemType", + "c0211201-0001-4002-8204-4f90af596647": "BlockPermutation", + "c0211201-0001-4002-8205-4f90af596647": "ItemStack", + "c0211201-0001-4002-8206-4f90af596647": "Vector", +} +export const registryAPISerializers = ()=>{ + const { + BlockType, BlockTypes, BlockPermutation, + EntityType, EntityTypes, + ItemType, ItemTypes, ItemStack, Vector + } = mc; + const ItemStackSupportLevel = { + dynamicProperties: ItemStack.prototype.getDynamicProperty, + canPlaceOn: ItemStack.prototype.getCanPlaceOn, + canDestory: ItemStack.prototype.getCanDestroy, + lore: ItemStack.prototype.getLore, + lockMode: mc.ItemLockMode, + keepOnDeath: "keepOnDeath" in ItemStack.prototype, + components: ItemStack.prototype.getComponents, + enchantable: mc.ItemEnchantableComponent, + durability: mc.ItemDurabilityComponent, + } + for (const key in ItemStackSupportLevel) { + if (Object.hasOwnProperty.call(ItemStackSupportLevel, key)) { + const element = ItemStackSupportLevel[key]; + console.warn(key, !!element); + } + } + const ItemStackComponentManager = { + serializers:{ }, + deserializers:{ } + } + const { + serializers: ItemComponentSerializers, + deserializers: ItemComponentDeserializers + } = ItemStackComponentManager; + if(ItemStackSupportLevel.durability) { + ItemComponentSerializers[ItemStackSupportLevel.durability.componentId] = function(component){ return component.damage;}; + ItemComponentDeserializers[ItemStackSupportLevel.durability.componentId] = function(component,v){ component.damage = v;}; + } + if(ItemStackSupportLevel.enchantable){ + ItemComponentSerializers[ItemStackSupportLevel.enchantable.componentId] = function(component){ return component.getEnchantments().map(e=>({t:e.type.id,l:e.level}));}; + ItemComponentDeserializers[ItemStackSupportLevel.enchantable.componentId] = function(component,v){ component.addEnchantments(v.map(e=>({type:e.t,level:e.l})));}; + } + + if(BlockTypes) Serializer.setSerializableClass(BlockType, APISerializableKinds.BlockType, function*(n){yield n.id;}, function(n){for(const a of n) return BlockTypes.get(a);}); + if(EntityTypes) Serializer.setSerializableClass(EntityType, APISerializableKinds.EntityType, function*(n){yield n.id;}, function(n){for(const a of n) return EntityTypes.get(a);}); + if(ItemTypes) Serializer.setSerializableClass(ItemType, APISerializableKinds.ItemType, function*(n){yield n.id;}, function(n){for(const a of n) return ItemTypes.get(a);}); + + if("type" in BlockPermutation.prototype) Serializer.setSerializableClass(BlockPermutation, APISerializableKinds.BlockPermutation, + function*(n){ + yield n.type.id; + yield JSON.stringify(n.getAllStates()); + }, + function(n){ + const [typeId, states] = n; + return BlockPermutation.resolve(typeId, JSON.parse(states)); + } + ); + Serializer.setSerializableClass(ItemStack, APISerializableKinds.ItemStack, + function*(n){ + const components = ItemStackSupportLevel.components?[...n.getComponents()].filter(e=>e && (e.typeId in ItemComponentSerializers)):[]; + const canPlaceOn = ItemStackSupportLevel.canPlaceOn?n.getCanPlaceOn():[]; + const canDestroy = ItemStackSupportLevel.canDestory?n.getCanDestroy():[]; + const dynamicProperties = ItemStackSupportLevel.dynamicProperties?n.getDynamicPropertyIds():[]; + yield JSON.stringify([ + n.typeId, + n.amount, + ItemStackSupportLevel.keepOnDeath?n.keepOnDeath:false, + ItemStackSupportLevel.lockMode?n.lockMode:"", + typeof n.nameTag === "string", + components.length, + canPlaceOn.length, + canDestroy.length, + dynamicProperties.length + ]); + n.nameTag?yield n.nameTag:null; + yield JSON.stringify(ItemStackSupportLevel.lore?n.getLore():[]); + for (const com of components) yield JSON.stringify([com.typeId, ItemComponentSerializers[com.typeId](com)]); + yield * canPlaceOn; + yield * canDestroy; + for(const k of dynamicProperties) { + const data = JSON.stringify(n.getDynamicProperty(k)); + if((data.length + k.length) > TABLE_STRING_LENGTH) throw new TypeError(`Dynamic property '${k}' of this item is too large'${data.length}'`); + yield Writable(k,data); + } + }, + function(n){ + const [ + typeId, amount, keepOnDeath, lockMode, hasNameTag, + componentsCount, canPlaceOnCount, canDestroyCount, dynamicPropertiesCount + ] = JSON.parse(n.continue()); + const item = new ItemStack(typeId, amount); + if(ItemStackSupportLevel.keepOnDeath) item.keepOnDeath = keepOnDeath; + if(ItemStackSupportLevel.lockMode) item.lockMode = lockMode; + if(hasNameTag) item.nameTag = n.continue(); + const lore = JSON.parse(n.continue()); + if(ItemStackSupportLevel.lore) item.setLore(lore); + let i = componentsCount; + while(i--) { + const [id,data] = JSON.parse(n.continue()); + ItemComponentDeserializers[id](item.getComponent(id), data); + } + i = canPlaceOnCount; + const canPlaceOn = []; + while(i--) canPlaceOn.push(n.continue()); + i = canDestroyCount; + const canDestroy = []; + while(i--) canDestroy.push(n.continue()); + item.setCanPlaceOn(canPlaceOn); + item.setCanDestroy(canDestroy); + i = dynamicPropertiesCount; + while(i--) { + const [k,sata] = Readable(n.continue()); + item.setDynamicProperty(k,JSON.parse(sata)); + } + return item; + } + ); + + if(Vector) Serializer.setSerializableClass(Vector, APISerializableKinds.Vector, function(s){const {x,y,z} = s; return Object.Serialize({x,y,z});}, function(n){const {x,y,z} = Object.Deserialize(n);return new Vector(x,y,z);}) +}; \ No newline at end of file diff --git a/database.d.ts b/database.d.ts deleted file mode 100644 index de97e57..0000000 --- a/database.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {World, Entity} from "@minecraft/server"; -declare class DynamicDatabase extends Map{ - protected constructor(); - set(key: string, value: any) - delete(key: string): boolean - clear(): void - isValid(): boolean - dispose(): void - readonly isDisposed: boolean -} -//@ts-ignore -export class JsonDatabase extends DynamicDatabase{ constructor(source: World | Entity, id: string); } -//@ts-ignore -export class WorldDatabase extends JsonDatabase { constructor(id: string) } \ No newline at end of file diff --git a/database.js b/database.js deleted file mode 100644 index 633a272..0000000 --- a/database.js +++ /dev/null @@ -1,200 +0,0 @@ -import { world, World, Entity } from "@minecraft/server"; -const mc_world = world; -const {setDynamicProperty: wSDP, getDynamicProperty: wGDP, getDynamicPropertyIds: wGDPI} = World.prototype; -const {isValid: isValidEntity, setDynamicProperty: eSDP, getDynamicProperty: eGDP, getDynamicPropertyIds: eGDPI} = Entity.prototype; -const DYNAMIC_DB_PREFIX = "\u1221\u2112"; -const SOURCE_INSTANCES = new WeakMap(); -const DDB_SUBINSTANCES = new WeakMap(); -const STRING_LIMIT = 32e3; -const eP = { - gDP: eGDP, - sDP: eSDP, - gDPI: eGDPI -}; -const wP = { - gDP: wGDP, - sDP: wSDP, - gDPI: wGDPI -}; -class DynamicSource { - /**@readonly @type {World | Entity} */ - source; - /**@param {World | Entity} source */ - constructor(source){ - this.source = source; - if(SOURCE_INSTANCES.has(source)) return SOURCE_INSTANCES.get(source); - if(source === mc_world) Object.assign(this, wP); else if (isValidEntity.call(source)) Object.assign(this, eP); - else throw new ReferenceError("Invald source type: " + source); - SOURCE_INSTANCES.set(source, this); - } - /**@returns {string[]} */ - getDynamicPropertyIds(){return this.gDPI.call(this.source);} - /**@param {string} key @returns {number | boolean | string | import("@minecraft/server").Vector3}*/ - getDynamicProperty(key){return this.gDP.call(this.source,key);} - /**@param {string} key */ - setDynamicProperty(key,value){ this.sDP.call(this.source, key, value);} - /**@param {string} key @returns {boolean} */ - deleteDynamicProperty(key){this.sDP.call(this.source, key, undefined); return true;} - /**@returns {boolean} */ - isValid(){ return this.source === world || isValidEntity.call(this.source); } -} -class DynamicDatabase extends Map{ - /**@readonly @private @type {DynamicSource} */ - _source; - /**@readonly @private @type {string} */ - _prefix; - /**@readonly @private @type {string} */ - _prefixLength; - /**@readonly @private */ - _STRINGIFY; - /**@readonly @private*/ - _PARSE; - /** @private*/ - _notDisposed; - /**@param {World | Entity} source @param {string} id @param {string} kind */ - constructor(source, id, kind, parser){ - super(); - this._source = new DynamicSource(source); - const PRE = `${kind}${DYNAMIC_DB_PREFIX}${id}${DYNAMIC_DB_PREFIX}`, LENGTH = PRE.length, SOURCE = this._source, PARSE = parser.parse; - const MAP_INSTANCES = DDB_SUBINSTANCES.get(SOURCE)??new Map; - if(MAP_INSTANCES.has(PRE)) return MAP_INSTANCES.get(PRE); - MAP_INSTANCES.set(PRE, this); DDB_SUBINSTANCES.set(SOURCE, MAP_INSTANCES); - if(!SOURCE.isValid()) throw new ReferenceError("Source is no longer valid: " + SOURCE.source); - this._prefix = PRE; - this._prefixLength = LENGTH; - this._STRINGIFY = parser.stringify; - //this._PARSE = PARSE; - this._notDisposed = true; - for (const K of SOURCE.getDynamicPropertyIds()) if(K.startsWith(PRE)) { - const key = K.substring(LENGTH); - const value = SOURCE.getDynamicProperty(K); - if(typeof value === "string") super.set(key, PARSE(value)); - } - } - /**@param {string} key @param {any} value */ - set(key, value){ - if(!this.isValid()) throw new ReferenceError("This database instance is no longer valid"); - if(key.length + this._prefixLength > STRING_LIMIT) throw new TypeError("Key is too long: " + key.length); - if(value === undefined) { - this.delete(key); - return this; - } - const data = this._STRINGIFY(value); - if(data.length > STRING_LIMIT) throw new TypeError("Size of data in string is too long: " + data.length); - this._source.setDynamicProperty(this._prefix + key, data); - return super.set(key,value); - } - /**@param {string} key */ - delete(key){ - if(!this.isValid()) throw new ReferenceError("This database instance is no longer valid"); - if(!this.has(key)) return false; - this._source.deleteDynamicProperty(this._prefix + key); - return super.delete(key); - } - clear(){ - if(!this.isValid()) throw new ReferenceError("This database instance is no longer valid"); - const P = this._prefix; - const s = this._source; - for(const key of this.keys()) s.deleteDynamicProperty(P + key); - return super.clear(); - } - /**@returns {boolean} */ - isValid(){return this._source.isValid() && this._notDisposed;} - dispose(){ - this._notDisposed = false; - DDB_SUBINSTANCES.get(this._source)?.delete?.(this._prefix); - super.clear(); - } - /**@readonly @type {boolean} */ - get isDisposed(){return !this._notDisposed;} -} -class DynamicWrapper { - - /**@readonly @private @type {Entity | World | ItemStack} */ - _source; - /**@readonly @private @type {string} */ - _prefix; - /**@readonly @private @type {string} */ - _prefixLength; - /**@readonly @private */ - _STRINGIFY; - /**@readonly @private*/ - _PARSE; - /**@param {World | Entity} source @param {string} id @param {string} kind */ - constructor(source, id, kind, parser){ - super(); - this._source = source; - const PRE = `${kind}${DYNAMIC_DB_PREFIX}${id}${DYNAMIC_DB_PREFIX}`, LENGTH = PRE.length; - this._prefix = PRE; - this._prefixLength = LENGTH; - this._STRINGIFY = parser.stringify; - this._PARSE = parser.parse; - } - clear(){ for( const k of this.__getKeys()) yield this._source.setDynamicProperty(k, undefined); }; - /** - * @returns true if an element in the Map existed and has been removed, or false if the element does not exist. - */ - delete(key) { - const has = this.has(key); - this._source.setDynamicProperty(this._prefix + key, undefined); - return has; - }; - /** - * Executes a provided function once per each key/value pair in the Map, in insertion order. - * @param {(value: any, key: string, map: DynamicWrapper) => void} callbackfn - * @param {any} thisArg - */ - forEach(callbackfn, thisArg = null){ - for (const k of this.keys()) { - try { - callbackfn.call(thisArg??null, k, this.get(k), this); - } catch (error) { - - } - } - } - /** - * Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map. - * @returns Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned. - */ - get(key){ const a = this._source.getDynamicProperty(this._prefix + key); typeof a === "string"?this._PARSE(a):a; }; - /** - * @returns boolean indicating whether an element with the specified key exists or not. - */ - has(key){ return this._source.getDynamicProperty(this._prefix + key)!==undefined; } - /** - * Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated. - */ - set(key, value){ - this._source.setDynamicProperty(this._prefix + key, this._STRINGIFY(value)); - return this; - }; - /** - * @returns the number of elements in the Map. - */ - get size(){return [...this.__getKeys()].length;}; - /** Returns an iterable of entries in the map. */ - [Symbol.iterator](){return this.entries();} - /** - * Returns an iterable of key, value pairs for every entry in the map. - */ - *entries(){for( const k of this.__getKeys()) yield [k.substring(this._prefixLength),this._PARSE(this._source.getDynamicProperty(k))]}; - /** - * Returns an iterable of keys in the map - */ - *keys(){for( const k of this.__getKeys()) yield k.substring(this._prefixLength);}; - /** - * Returns an iterable of values in the map - */ - *values(){for( const k of this.__getKeys()) yield this._PARSE(this._source.getDynamicProperty(k));} - *__getKeys(){ for (const K of this._source.getDynamicPropertyIds()) if(K.startsWith(this._prefix)) yield K; } -} -export class JsonDatabase extends DynamicDatabase{ - /**@param {World | Entity} source @param {string} id */ - constructor(source, id){ super(source, id, "JSON", JSON); } -} -export class WorldDatabase extends JsonDatabase { - /**@param {string} id */ - constructor(id){ super(mc_world, id); } -} -export class JSONDynamicWrapper extends DynamicWrapper{ constructor(source, id){ super(source, id, "JSON", JSON); } } \ No newline at end of file diff --git a/docs/HOW_TO_SETUP.md b/docs/HOW_TO_SETUP.md index 87d8bf0..2189dd6 100644 --- a/docs/HOW_TO_SETUP.md +++ b/docs/HOW_TO_SETUP.md @@ -22,7 +22,7 @@ Then download your required files Now you can just use, save and load your data ```js -const database = new WorldDatabase("my_database_id"); +const database = new JsonDatabase("my_database_id"); database.set("some key", "string data"); database.set("some key2", 645654); diff --git a/docs/Using-DynamicTable.md b/docs/Using-DynamicTable.md new file mode 100644 index 0000000..031b1cf --- /dev/null +++ b/docs/Using-DynamicTable.md @@ -0,0 +1,68 @@ +# Using DynamicTable +Why should I use DynamicTable? DynamicTable provides far more options and its disadvantages are also advantages. Here are some problems that DynamicTable can solve unlike JsonDatabase. + - **Value Size** limitation of the size of the value for each of the keys, Dynamictable does not have this limitation, more data can be stored for an individual key than is allowed for the script api to run. -> 100MB + - **Loading** JsonDatabase is loaded whole on initialization for fast data access, but this can lead to slowness on initialization. Dynamictable loads only the keys and deserializes only when the value is queried. Initialization is very fast, but it does not load all values, it also saves memory. + - **Serialization APIs** JsonDatabase only uses the specified parse (JSON parse) to process the data. Dynamictable uses different data processing, and you can also create your own parsers that call to serialize classes as well, it makes sense that the data after loading already has a prototype of the class, according to deserialization. + +## DynamicTable +Here is a simple example of how to instantiate a DynamicTable and use it. Some native classes can also be serialized, but this function needs to be enabled by calling the function `registryAPISerializers()`. +```js +import { DynamicTable, registryAPISerializers } from "./con-database"; +import {ItemStack} from "@minecraft/server"; + +registryAPISerializers(); //required for serialization of ItemStack +const table = DynamicTable.OpenCreate("id-of-the-table"); + +table.set("key-the-test", "very long string idk size but realy long, this text x 500000".repeat(500_000)); +table.set("key-the-item", new ItemStack("dirt", 32)); + +const savedValue = table.get("key-the-test"); +const savedItem = table.get("key-the-item"); +const typeId = savedItem.typeId; + +table.delete("key-the-test"); //deletes kkey value +table.clear(); //clears all values and keys form DynamicTable + + +DynamicTable.ClearAll(); //removes all created DynamicTables +``` + +## Custom Serializers +Custom serializers could help you keep you data types avaliable even after load, here is example of creating new serialization kind for my class. + +```js +import { SerializableKinds } from "./con-database"; +import { DynamicTable, Serializer } from "./con-database"; + + +class MyClassWithMethods { + constructor(id, message){ + this.id = id; + this.message = message; + } + warn(){ + console.warn(this.id,this.message); + } +} +Serializer.setSerializableClass( + MyClassWithMethods, + "custom-kind-id", + function({id,message}){ // serialization function, called when DynamicTable.set() + const objectSerializer = Serializer.getSerializer(SerializableKinds.Object); + return objectSerializer({id,message}); //basic serialization as poor object + }, + function(n){ //deserialization function, called when DynamicTable.get(); + const object = Serializer.getDeserializer(SerializableKinds.Object)(n); //loaded poor object + return Object.setPrototypeOf(object, MyClassWithMethods.prototype); //add a MyClassWithMethods prototype + } +) + + + + +const table = DynamicTable.OpenCreate("id-of-the-table"); +table.set("key-the-test", new MyClassWithMethods("warn-id", "My custom message")); + + +table.get("key-the-test").warn(); //warn method from MyClasswithMethods +``` \ No newline at end of file diff --git a/package.json b/package.json index 8946322..0bca5b0 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "database.d.ts" ], "dependencies": { - "@minecraft/server": "^1.5.0-beta.1.20.20-preview.20", - "@minecraft/server-ui": "^1.2.0-beta.1.20.20-preview.20" + "@minecraft/server": "^1.9.0-beta.1.20.60-preview.23", + "@minecraft/server-ui": "^1.2.0-beta.1.20.60-preview.23" } } diff --git a/packs/BP/manifest.json b/packs/BP/manifest.json index 5585373..4869d08 100644 --- a/packs/BP/manifest.json +++ b/packs/BP/manifest.json @@ -1,7 +1,7 @@ { "format_version": 2, "header": { - "name": "Database testing Pack", + "name": "Database Release testing Pack", "description": "TDatabase testing Pack", "uuid": "92019559-6abd-4d17-aeda-f7d5a65f7fe0", "version": "1.2.0-beta", @@ -16,8 +16,7 @@ } ], "dependencies": [ - {"module_name": "@minecraft/server","version": "1.6.0-beta"}, - {"module_name": "@minecraft/server-ui","version": "1.2.0-beta"} + {"module_name": "@minecraft/server","version": "1.7.0"} ], "capabilities": ["script_eval"] } \ No newline at end of file diff --git a/packs/BP/scripts/index.js b/packs/BP/scripts/index.js index 53ed18a..ac34b28 100644 --- a/packs/BP/scripts/index.js +++ b/packs/BP/scripts/index.js @@ -1,9 +1,44 @@ -/*import { DatabaseSavingModes, NBTDatabase, JsonDatabase } from "database"; +import { system, world } from "@minecraft/server"; +import { SerializableKinds, JsonDatabase } from "./con-database"; +import { DynamicTable, Serializer } from "./con-database"; -const a = new NBTDatabase("sus2",DatabaseSavingModes.OneTimeSave,50).load(); -const b = new JsonDatabase("sus2"); -console.warn(a === b); -a.set("sussy",{jerremy:(a.get("sussy")?.jerremy??0) + 1}); +class MyClassWithMethods { + constructor(id, message){ + this.id = id; + this.message = message; + } + warn(){ + console.warn(this.id,this.message); + } +} +Serializer.setSerializableClass( + MyClassWithMethods, + "custom-kind-id", + function({id,message}){ // serialization function, called when DynamicTable.set() + const objectSerializer = Serializer.getSerializer(SerializableKinds.Object); + return objectSerializer({id,message}); //basic serialization as poor object + }, + function(n){ //deserialization function, called when DynamicTable.get(); + const object = Serializer.getDeserializer(SerializableKinds.Object)(n); //loaded poor object + return Object.setPrototypeOf(object, MyClassWithMethods.prototype); //add a MyClassWithMethods prototype + } +) -console.warn("Current sussy count is " + a.get("sussy").jerremy);*/ \ No newline at end of file + + + +const table = DynamicTable.OpenCreate("id-of-the-table"); +table.set("key-the-test", new MyClassWithMethods("warn-id", "My custom message")); + + +table.get("key-the-test").warn(); //warn method from MyClasswithMethods +const jsDB = new JsonDatabase("the id"); +jsDB.set("Lmao","adfasdfsa".repeat(600)); +jsDB.set("Some test", {asd:"asdfasdf",asds:{asdfasdfa:"asdfasdf"}}); +for (const [k,v] of jsDB) { + console.warn(k,v); +} +jsDB.clear(); +DynamicTable.ClearAll(); +system.runTimeout(()=>console.warn(world.getDynamicPropertyTotalByteCount()), 3); \ No newline at end of file