A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(sdk): resource defaults stop aliasing across worlds
esenginea4737ad0a873
diff --git a/sdk/src/component.ts b/sdk/src/component.tsindex cffd0528e..22eaa3366 100644--- a/sdk/src/component.ts+++ b/sdk/src/component.ts@@ -6,6 +6,7 @@*/import { Entity, Vec2, Vec3, Color, Quat } from './types';+import { deepClone } from './deepClone';import { COMPONENT_META, type AssetFieldMeta, type SpineFieldMeta } from './component.generated';// C++-backed component data shapes, generated from the ES_COMPONENT structs (single// source — a TS field can no longer drift from C++). Re-exported below so the public@@ -169,20 +170,6 @@ export interface ComponentDef<T> {create(data?: Partial<T>): T;}-function deepClone<T>(value: T): T {- if (value === null || typeof value !== 'object') {- return value;- }- if (Array.isArray(value)) {- return value.map(deepClone) as T;- }- const result: Record<string, unknown> = {};- for (const key in value) {- result[key] = deepClone((value as Record<string, unknown>)[key]);- }- return result as T;-}-function classifyKeys(obj: object): { flatKeys: string[]; objectKeys: string[]; arrayKeys: string[] } | null {const flatKeys: string[] = [];const objectKeys: string[] = [];diff --git a/sdk/src/deepClone.ts b/sdk/src/deepClone.tsnew file mode 100644index 000000000..d12a96f51--- /dev/null+++ b/sdk/src/deepClone.ts@@ -0,0 +1,37 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file deepClone.ts+ * @brief Structural deep clone for plain data (objects, arrays, primitives)+ */++/**+ * Recursively clone plain objects and arrays; primitives AND class instances+ * (Map, Date, a custom class with methods, …) pass through by reference.+ *+ * Used to materialise per-instance copies of shared default templates (component+ * defaults, resource defaults) so mutating one instance never leaks into the+ * shared definition or a sibling world. Class instances pass through because+ * cloning them into a bare object would strip their prototype (and methods) — a+ * resource whose default is a stateful singleton keeps its identity. Avoids+ * `structuredClone`, which is absent in some minigame runtimes.+ */+export function deepClone<T>(value: T): T {+ if (value === null || typeof value !== 'object') {+ return value;+ }+ if (Array.isArray(value)) {+ return value.map(deepClone) as T;+ }+ // Only plain objects are cloned; a class instance (non-Object prototype) is+ // shared by reference so its methods survive.+ const proto = Object.getPrototypeOf(value);+ if (proto !== Object.prototype && proto !== null) {+ return value;+ }+ const result: Record<string, unknown> = {};+ for (const key in value) {+ result[key] = deepClone((value as Record<string, unknown>)[key]);+ }+ return result as T;+}diff --git a/sdk/src/resource.ts b/sdk/src/resource.tsindex 2c47d6899..38df61b0f 100644--- a/sdk/src/resource.ts+++ b/sdk/src/resource.ts@@ -5,6 +5,8 @@* @brief Resource system for global singleton data*/+import { deepClone } from './deepClone';+// =============================================================================// Resource Definition// =============================================================================@@ -102,7 +104,9 @@ export class ResourceStorage {get<T>(resource: ResourceDef<T>): T {if (!this.resources_.has(resource._id)) {- this.resources_.set(resource._id, resource._default);+ // Clone so each storage owns its default; mutating it never leaks+ // into the shared ResourceDef or a sibling world.+ this.resources_.set(resource._id, deepClone(resource._default));}return this.resources_.get(resource._id) as T;}diff --git a/sdk/tests/resource.test.ts b/sdk/tests/resource.test.tsindex 067a8fe76..d53f6be0a 100644--- a/sdk/tests/resource.test.ts+++ b/sdk/tests/resource.test.ts@@ -261,4 +261,34 @@ describe('ResourceStorage', () => {expect(storage.get(Config)).toEqual({ debug: true });});});++ describe('default isolation', () => {+ it('does not alias the shared default across two storages', () => {+ const Shared = defineResource({ score: 0, tags: [] as string[] }, 'IsoConfig');+ const a = new ResourceStorage();+ const b = new ResourceStorage();++ const va = a.get(Shared);+ va.score = 42;+ va.tags.push('x');++ const vb = b.get(Shared);+ expect(vb.score).toBe(0);+ expect(vb.tags).toEqual([]);+ });++ it('materialising a default never mutates the ResourceDef itself', () => {+ const Shared = defineResource({ n: 0 }, 'IsoConfig2');+ new ResourceStorage().get(Shared).n = 7;+ expect(Shared._default.n).toBe(0);+ });++ it('a class-instance default keeps its prototype and methods (not cloned to a bare object)', () => {+ class Svc { hits = 0; ping(): number { return ++this.hits; } }+ const Service = defineResource(new Svc(), 'IsoService');+ const got = new ResourceStorage().get(Service);+ expect(got).toBeInstanceOf(Svc);+ expect(got.ping()).toBe(1); // method survived; a plain-object clone would throw+ });+ });});