Skip to content

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.

feat(bundle): the project script bundle is built again only when a file it read changed, and Cocos scripts that write the same class name each get a component of their own

yhhd3581b796fb2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c5ce883dc..04fe83002 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,8 @@ published separately; it ships inside the editor.
- **Scroll areas can be pulled past an end and spring back.** A scroll area whose movement is Elastic now does what the setting always said: a drag past an end is stiffer the further out it goes, letting go returns the content, and a flick that reaches an end bounces off it. It is opt-in per area (`ScrollMovement.Elastic`; Clamped, the default, behaves as before), and the gesture model (`ScrollMotion`, with `ScrollContainer.dragTo` and `getOverscroll`) is exported for scrolling anything else the same way.
- **More easing curves.** Sine, quart, quint, expo and circ (each in, out and in-out), bounce in and in-out, and smoothstep and smootherstep join the quad, cubic, back, elastic and out-bounce curves. They are new `EasingType` members after the existing ones, so a saved tween keeps its curve, and they ease the same in a C++ tween and a script value tween.
- **World content has a rectangle: `ContentRect`.** A size and the pivot the entity's transform sits on, which the `Sprite` and `Text` on the entity follow and which a `UIMask` on it clips to — no `UINode` needed, so a clipping region or a scroll viewport can stand in the world. `contentRectContains` tests a world point against it.
+- **The script bundle is not rebuilt for nothing.** The project-script bundle is stamped with every file it read (size and modification time) and the build tool that made it, and Play builds it again only when one of those changed: a project of thousands of scripts goes from a multi-second build at every Play to a check of a few hundred milliseconds.
+- **Two Cocos classes with one name.** Cocos tells classes apart by their script, so two scripts may write the same `@ccclass` name. The converted project gives the second its own component name (`Name_2`, in path order), writes which script that was beside the entry, and the bundler writes the new name into that script decorator.
- **Large projects open faster.** The asset dependency scan no longer asks the path index about every string in every document (names, types and labels cannot be paths), which took the open of a 5000-document project from 17 s to under 5 s, and the Cocos script rewrite makes two passes over a file instead of one per declaration.
- **A model texture the project does not have is left off.** A model whose material names a texture file that is not there is imported without it, with a warning, instead of keeping a reference that fails to load on every use.
- **An unlit mesh variant with tangents links.** The fragment stage declared the tangent varying wherever a mesh had tangents, though the vertex stage wrote it only when lit, so an unlit variant failed to link.
diff --git a/pipeline/src/bundle/buildScripts.ts b/pipeline/src/bundle/buildScripts.ts
index 9e288b5b8..1c71b1602 100644
--- a/pipeline/src/bundle/buildScripts.ts
+++ b/pipeline/src/bundle/buildScripts.ts
@@ -14,11 +14,12 @@
*/
import type { BuildResult } from 'esbuild';
import { existsSync } from 'node:fs';
+import { readFile, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { loadEsbuild } from './esbuildRuntime';
import { explainBundleErrors, type BundleMessage } from './bundleDiagnostics';
import { officialPackagesPlugin } from './officialPackages';
-import { cocosCompatPlugin } from './cocosCompat';
+import { COCOS_COMPAT_VERSION, cocosCompatPlugin } from './cocosCompat';
/** esengine and any subpath import are left for the realm's import map to resolve. */
const EXTERNAL = ['esengine', 'esengine/*'];
@@ -36,10 +37,68 @@ export interface BuildScriptsResult {
warnings: string[];
}
+/** Bumped when what a build does changes in a way the stamp cannot see, so an older bundle is rebuilt. */
+const STAMP_VERSION = 1;
+const STAMP = 'scripts.stamp.json';
+
+/** What a bundle was built from: enough to know, without building, whether building again would give the same bytes. */
+interface BuildStamp {
+ version: number;
+ compat: number;
+ esbuild: string;
+ entry: string;
+ packagesDir: string;
+ /** Every file the bundle read, with its size and modification time. */
+ inputs: Record<string, [number, number]>;
+ warnings: string[];
+}
+
+/** The file an esbuild metafile input names, or null for one a plugin made up (a namespace, not a path). */
+function inputFile(key: string): string | null {
+ if (/^[A-Za-z]:[\\/]/.test(key)) return key;
+ if (key.includes(':')) return null;
+ return path.resolve(key);
+}
+
+async function signature(file: string): Promise<[number, number] | null> {
+ try {
+ const s = await stat(file);
+ return [s.size, Math.round(s.mtimeMs)];
+ } catch {
+ return null;
+ }
+}
+
+/** The stamp when the bundle on disk is still what building now would write; null when it must be built. */
+async function currentStamp(stampPath: string, outputPath: string, want: Omit<BuildStamp, 'inputs' | 'warnings'>): Promise<BuildStamp | null> {
+ if (!existsSync(outputPath)) return null;
+ let stamp: BuildStamp;
+ try {
+ stamp = JSON.parse(await readFile(stampPath, 'utf8')) as BuildStamp;
+ } catch {
+ return null;
+ }
+ if (stamp.version !== want.version || stamp.compat !== want.compat || stamp.esbuild !== want.esbuild
+ || stamp.entry !== want.entry || stamp.packagesDir !== want.packagesDir) return null;
+ const files = Object.entries(stamp.inputs);
+ // in slices, so a project of thousands of scripts does not open thousands of files at once
+ for (let i = 0; i < files.length; i += 256) {
+ const now = await Promise.all(files.slice(i, i + 256).map(([file]) => signature(file)));
+ for (const [j, sig] of now.entries()) {
+ const was = files[i + j]![1];
+ if (!sig || sig[0] !== was[0] || sig[1] !== was[1]) return null;
+ }
+ }
+ return stamp;
+}
+
/**
* Bundle `<root>/<entry>` (project-relative, default `src/main.ts`) →
* `<root>/.esengine/cache/scripts.mjs`, esengine external. Never throws —
* failures come back as `{ ok:false, errors }`.
+ *
+ * A bundle of a project of thousands of scripts takes seconds, and the editor asks for one at every Play. It is built again only when a file
+ * it read has changed (or how it is built has): the files are stamped beside it, and checking them costs a stat each.
*/
export async function buildProjectScripts(
root: string,
@@ -50,9 +109,14 @@ export async function buildProjectScripts(
return { ok: false, outputPath: null, errors: [`script entry not found: ${entryPath}`], warnings: [] };
}
const outputPath = path.join(root, CACHE_DIR, OUTPUT);
+ const stampPath = path.join(root, CACHE_DIR, STAMP);
try {
- const { build } = await loadEsbuild();
- const result: BuildResult = await build({
+ const esbuild = await loadEsbuild();
+ const want = { version: STAMP_VERSION, compat: COCOS_COMPAT_VERSION, esbuild: esbuild.version, entry: entryPath, packagesDir: opts.packagesDir };
+ const fresh = await currentStamp(stampPath, outputPath, want);
+ if (fresh) return { ok: true, outputPath, errors: [], warnings: fresh.warnings };
+
+ const result: BuildResult = await esbuild.build({
entryPoints: [entryPath],
bundle: true,
format: 'esm',
@@ -63,13 +127,27 @@ export async function buildProjectScripts(
outfile: outputPath,
sourcemap: true,
write: true,
+ metafile: true,
logLevel: 'silent',
});
+ const warnings = result.warnings.map((w) => w.text);
+ // What it read, plus what esbuild reads without reporting: the project's tsconfig and package.json decide how a file is compiled.
+ const files = new Set<string>([path.join(root, 'tsconfig.json'), path.join(root, 'package.json')]);
+ for (const key of Object.keys(result.metafile?.inputs ?? {})) {
+ const file = inputFile(key);
+ if (file) files.add(file);
+ }
+ const inputs: Record<string, [number, number]> = {};
+ for (const file of files) {
+ const sig = await signature(file);
+ if (sig) inputs[file] = sig;
+ }
+ await writeFile(stampPath, JSON.stringify({ ...want, inputs, warnings } satisfies BuildStamp));
return {
ok: true,
outputPath,
errors: explainBundleErrors(result.errors),
- warnings: result.warnings.map((w) => w.text),
+ warnings,
};
} catch (err) {
const e = err as { errors?: BundleMessage[]; warnings?: { text: string }[]; message?: string };
diff --git a/pipeline/src/bundle/cocosCompat.ts b/pipeline/src/bundle/cocosCompat.ts
index 723b641fe..76bc16ee8 100644
--- a/pipeline/src/bundle/cocosCompat.ts
+++ b/pipeline/src/bundle/cocosCompat.ts
@@ -24,12 +24,15 @@
* Only files that import `cc` are touched: a script that does not is not a Cocos script, and keeps whatever its own tsconfig says.
* The project's files are read, never written.
*/
-import { existsSync, statSync } from 'node:fs';
+import { existsSync, readFileSync, statSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
-import type { Plugin } from 'esbuild';
+import type { Plugin, PluginBuild } from 'esbuild';
import { loadEsbuild } from './esbuildRuntime';
+/** Changes whenever what this plugin does to a script changes, so a bundle built by an older one is not taken for current. */
+export const COCOS_COMPAT_VERSION = 4;
+
/** What `cc` and `cc/env` resolve to. */
export const COCOS_LAYER = 'esengine/cocos';
@@ -92,10 +95,35 @@ export function letTheReassignedConsts(source: string): string {
return source.replace(CONST_DECL, (all: string, name: string) => (assigned.has(name) ? all.replace('const', 'let') : all));
}
+/** The script classes a converted project renamed, from the file the import wrote beside the project's entry; empty when there is none. */
+function readClassNames(build: PluginBuild): Map<string, { from: string; to: string }> {
+ const options = build.initialOptions;
+ const first = options.entryPoints;
+ const entry = Array.isArray(first) ? first[0] : first && typeof first === 'object' ? Object.values(first)[0] : undefined;
+ const entryFile = typeof entry === 'string' ? entry : entry?.in;
+ const dir = entryFile ? path.dirname(path.resolve(options.absWorkingDir ?? '.', entryFile)) : options.stdin?.resolveDir ? path.join(options.stdin.resolveDir, 'src') : null;
+ const out = new Map<string, { from: string; to: string }>();
+ if (!dir) return out;
+ try {
+ const names = JSON.parse(readFileSync(path.join(dir, 'cocos-class-names.json'), 'utf8')) as Record<string, { from: string; to: string }>;
+ for (const [key, v] of Object.entries(names)) out.set(path.resolve(dir, key).toLowerCase(), v);
+ } catch { /* none renamed */ }
+ return out;
+}
+
+/** The decorator of a renamed class, written with its new name: `@ccclass('Old')` and a bare `@ccclass` both become `@ccclass('New')`. */
+export function renameClass(source: string, from: string, to: string): string {
+ const escaped = from.replace(/[$]/g, (c) => `\\${c}`);
+ const named = new RegExp(String.raw`@ccclass\(\s*(['"])${escaped}\1\s*\)`);
+ if (named.test(source)) return source.replace(named, `@ccclass('${to}')`);
+ return source.replace(/@ccclass(?![\w(])/, `@ccclass('${to}')`);
+}
+
export function cocosCompatPlugin(): Plugin {
return {
name: 'estella-cocos-compat',
setup(build) {
+ const renames = readClassNames(build);
build.onResolve({ filter: CC }, async (args) => {
if (args.pluginData === RESOLVING) return undefined;
const layer = await build.resolve(COCOS_LAYER, {
@@ -129,6 +157,8 @@ export function cocosCompatPlugin(): Plugin {
} catch {
return undefined;
}
+ const renamed = renames.get(args.path.replace(/\.(tsx?|jsx?)$/, '').toLowerCase());
+ if (renamed) source = renameClass(source, renamed.from, renamed.to);
if (!IMPORTS_CC.test(source)) {
const fixed = letTheReassignedConsts(source);
return fixed === source ? undefined : { contents: fixed, loader: args.path.endsWith('x') ? 'tsx' : 'ts', resolveDir: path.dirname(args.path) };
diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.ts
index 089d4108f..6135c104e 100644
--- a/pipeline/src/import/cocos/importProject.ts
+++ b/pipeline/src/import/cocos/importProject.ts
@@ -129,6 +129,23 @@ function placeFile(from: string, to: string): void {
utimesSync(to, source.atime, source.mtime);
}
+/**
+ * The scripts whose class was given another name than it wrote (two scripts wrote the same `@ccclass` name) — all of them, not only the ones a scene
+ * uses, since a script is loaded by whatever imports it — by the path the entry requires them
+ * at. The bundler reads this beside the entry and writes the new name into the decorator, so the component a scene names is the class it means.
+ */
+function writeClassNames(out: string, entry: string, assetsDir: string, scripts: Map<string, { name: string; rel: string; wrote?: string }>): void {
+ const names: Record<string, { from: string; to: string }> = {};
+ for (const cls of scripts.values()) {
+ if (!cls.wrote) continue;
+ const target = path.join(assetsDir, cls.rel.replace(/\.(ts|js)$/, ''));
+ names[path.relative(path.dirname(entry), target).split(path.sep).join('/')] = { from: cls.wrote, to: cls.name };
+ }
+ const file = path.join(out, 'src', 'cocos-class-names.json');
+ if (Object.keys(names).length > 0) writeOut(file, JSON.stringify(names, null, 2) + '\n');
+ else rmSync(file, { force: true });
+}
+
const GENERATED = 'Generated by import-cocos';
/** A default for a field, of the kind its sample is: what the editor shows before anything is typed. */
@@ -637,6 +654,7 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impo
...loads, '',
].join('\n');
if (!opts.dryRun) writeOut(entry, text);
+ if (!opts.dryRun) writeClassNames(out, entry, assetsDir, scripts);
report.note('cocos-scripts-entry', `${path.relative(out, entry).split(path.sep).join('/')}: ${usedScripts.size} script(s)`);
if (!opts.dryRun) wireProjectEntries(out, scriptFields);
}
diff --git a/pipeline/src/import/cocos/scripts.ts b/pipeline/src/import/cocos/scripts.ts
index 90629a7a7..a6353be82 100644
--- a/pipeline/src/import/cocos/scripts.ts
+++ b/pipeline/src/import/cocos/scripts.ts
@@ -32,6 +32,8 @@ export interface ScriptClass {
name: string;
/** Path of the script, relative to the project's `assets`. */
rel: string;
+ /** The `@ccclass` name the script wrote, when another script had it first and this class was given a name of its own. */
+ wrote?: string;
}
const NAMED = /@ccclass\(\s*['"]([^'"]+)['"]\s*\)/;
@@ -43,7 +45,10 @@ const UNNAMED = new RegExp(String.raw`@ccclass(?:\(\s*\))?(?![\w(])${BETWEEN}(?:
/** The compressed uuid of every script that declares a component class, mapped to that class. */
export function buildScriptIndex(assets: CocosAssetIndex): Map<string, ScriptClass> {
const out = new Map<string, ScriptClass>();
- for (const entry of assets.byUuid.values()) {
+ // Cocos tells classes apart by their script, so two may share a name; here a name is a component, so the second of a name (in path order,
+ // which is the same on every import) is numbered.
+ const taken = new Set<string>();
+ for (const entry of [...assets.byUuid.values()].sort((x, y) => (x.rel < y.rel ? -1 : x.rel > y.rel ? 1 : 0))) {
if (!/\.(ts|js)$/.test(entry.rel) || entry.rel.endsWith('.d.ts')) continue;
if (entry.importer !== 'typescript' && entry.importer !== 'javascript') continue;
let text: string;
@@ -54,7 +59,10 @@ export function buildScriptIndex(assets: CocosAssetIndex): Map<string, ScriptCla
}
const name = NAMED.exec(text)?.[1] ?? UNNAMED.exec(text)?.[1];
if (!name) continue;
- out.set(compressUuid(entry.uuid), { name, rel: entry.rel });
+ let unique = name;
+ for (let n = 2; taken.has(unique); n++) unique = `${name}_${n}`;
+ taken.add(unique);
+ out.set(compressUuid(entry.uuid), { name: unique, rel: entry.rel, ...(unique !== name ? { wrote: name } : {}) });
}
return out;
}
diff --git a/pipeline/tests/build-scripts-cache.test.ts b/pipeline/tests/build-scripts-cache.test.ts
new file mode 100644
index 000000000..1286537db
--- /dev/null
+++ b/pipeline/tests/build-scripts-cache.test.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The project-script bundle is built again only when a file it read has changed.
+ */
+import { mkdtempSync, mkdirSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { buildProjectScripts } from '../src/bundle/buildScripts';
+
+describe('building a project\'s scripts', () => {
+ let root: string;
+ let packages: string;
+ const bundle = () => path.join(root, '.esengine', 'cache', 'scripts.mjs');
+ const built = () => statSync(bundle()).mtimeMs;
+
+ beforeAll(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'scripts-cache-'));
+ packages = path.join(root, 'packages');
+ mkdirSync(packages);
+ mkdirSync(path.join(root, 'src'));
+ writeFileSync(path.join(root, 'src', 'main.ts'), "import { answer } from './answer';\nconsole.log(answer);\n");
+ writeFileSync(path.join(root, 'src', 'answer.ts'), 'export const answer = 42;\n');
+ });
+ afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));
+
+ it('builds the first time and leaves the bundle alone the second', async () => {
+ const first = await buildProjectScripts(root, { packagesDir: packages });
+ expect(first.ok).toBe(true);
+ const at = built();
+ // the clock must be able to tell a rewrite from a skip
+ utimesSync(bundle(), new Date(at - 60_000), new Date(at - 60_000));
+ const before = built();
+ const second = await buildProjectScripts(root, { packagesDir: packages });
+ expect(second.ok).toBe(true);
+ expect(second.outputPath).toBe(first.outputPath);
+ expect(built()).toBe(before);
+ });
+
+ it('builds again when a file it read changed, even a file the entry only reaches through another', async () => {
+ const before = built();
+ writeFileSync(path.join(root, 'src', 'answer.ts'), 'export const answer = 43;\n');
+ const result = await buildProjectScripts(root, { packagesDir: packages });
+ expect(result.ok).toBe(true);
+ expect(built()).toBeGreaterThan(before);
+ const text = (await import('node:fs')).readFileSync(bundle(), 'utf8');
+ expect(text).toContain('43');
+ });
+
+ it('builds again when the bundle is gone', async () => {
+ rmSync(bundle());
+ const result = await buildProjectScripts(root, { packagesDir: packages });
+ expect(result.ok).toBe(true);
+ expect(built()).toBeGreaterThan(0);
+ });
+});
diff --git a/pipeline/tests/cocos-class-names.test.ts b/pipeline/tests/cocos-class-names.test.ts
new file mode 100644
index 000000000..f959778f0
--- /dev/null
+++ b/pipeline/tests/cocos-class-names.test.ts
@@ -0,0 +1,90 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Two Cocos scripts may write the same `@ccclass` name (Cocos tells classes apart by their script). Here a name is a component, so
+ * the second is given a name of its own, and the decorator in the bundle says so.
+ */
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { build } from 'esbuild';
+import { importCocosProject } from '../src/import/cocos';
+import { buildCocosAssetIndex } from '../src/import/cocos/assets';
+import { buildScriptIndex, compressUuid } from '../src/import/cocos/scripts';
+import { cocosCompatPlugin, renameClass } from '../src/bundle/cocosCompat';
+
+const A = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const B = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const meta = (uuid: string, importer: string): object => ({ ver: '1', importer, uuid, subMetas: {}, userData: {} });
+
+describe('two scripts that write the same class name', () => {
+ let root: string;
+ beforeAll(async () => {
+ root = mkdtempSync(path.join(tmpdir(), 'cocos-names-'));
+ const put = (rel: string, v: string | object): void => {
+ const f = path.join(root, 'creator', 'assets', rel);
+ mkdirSync(path.dirname(f), { recursive: true });
+ writeFileSync(f, typeof v === 'string' ? v : JSON.stringify(v));
+ };
+ put('a/Skin.ts', "import { _decorator, Component } from 'cc';\nconst { ccclass } = _decorator;\n@ccclass('Skin')\nexport class Skin extends Component {}\n");
+ put('a/Skin.ts.meta', meta(A, 'typescript'));
+ put('b/Skin.ts', "import { _decorator, Component } from 'cc';\nconst { ccclass } = _decorator;\n@ccclass('Skin')\nexport class Skin extends Component {}\n");
+ put('b/Skin.ts.meta', meta(B, 'typescript'));
+ const unit = { __type__: 'cc.Vec3', x: 1, y: 1, z: 1 };
+ const zero = { __type__: 'cc.Vec3', x: 0, y: 0, z: 0 };
+ const node = (name: string, comp: number): object => ({ __type__: 'cc.Node', _name: name, _parent: { __id__: 1 }, _children: [], _active: true, _components: [{ __id__: comp }], _prefab: null, _lpos: zero, _lrot: { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 }, _lscale: unit, _layer: 1 });
+ put('main.scene', [
+ { __type__: 'cc.SceneAsset', _name: 'main', scene: { __id__: 1 } },
+ { __type__: 'cc.Scene', _name: 'main', _children: [{ __id__: 2 }, { __id__: 3 }] },
+ node('one', 4), node('two', 5),
+ { __type__: compressUuid(A), node: { __id__: 2 }, _enabled: true, hp: 1 },
+ { __type__: compressUuid(B), node: { __id__: 3 }, _enabled: true, mp: 2 },
+ ]);
+ put('main.scene.meta', meta('dddddddd-dddd-4ddd-8ddd-dddddddddddd', 'scene'));
+ mkdirSync(path.join(root, 'out', 'src'), { recursive: true });
+ writeFileSync(path.join(root, 'out', 'src', 'main.ts'), "// entry\nimport './components';\n");
+ await importCocosProject({ source: path.join(root, 'creator'), out: path.join(root, 'out') });
+ });
+ afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));
+
+ it('numbers the second, in path order', () => {
+ const index = buildScriptIndex(buildCocosAssetIndex(path.join(root, 'creator', 'assets')));
+ expect(index.get(compressUuid(A))).toEqual({ name: 'Skin', rel: 'a/Skin.ts' });
+ expect(index.get(compressUuid(B))).toEqual({ name: 'Skin_2', rel: 'b/Skin.ts', wrote: 'Skin' });
+ });
+
+ it('names each instance by its own class in the scene', () => {
+ const scene = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'main.esscene'), 'utf8')) as { entities: Array<{ name: string; components: Array<{ type: string }> }> };
+ const types = (name: string) => scene.entities.find((e) => e.name === name)!.components.map((c) => c.type);
+ expect(types('one')).toContain('Cocos.Skin');
+ expect(types('two')).toContain('Cocos.Skin_2');
+ });
+
+ it('writes which script was renamed, beside the entry, and the editor declarations carry both', () => {
+ const names = JSON.parse(readFileSync(path.join(root, 'out', 'src', 'cocos-class-names.json'), 'utf8')) as Record<string, { from: string; to: string }>;
+ expect(Object.values(names)).toEqual([{ from: 'Skin', to: 'Skin_2' }]);
+ const components = readFileSync(path.join(root, 'out', 'src', 'components.ts'), 'utf8');
+ expect(components).toContain('"Cocos.Skin"');
+ expect(components).toContain('"Cocos.Skin_2"');
+ });
+
+ it('bundles the renamed class under its new name', async () => {
+ const result = await build({
+ entryPoints: [path.join(root, 'out', 'src', 'cocos-scripts.ts')],
+ bundle: true, write: false, format: 'esm', platform: 'browser', logLevel: 'silent',
+ external: ['esengine/cocos'], plugins: [cocosCompatPlugin()],
+ }).catch((e) => e);
+ const text = result.outputFiles?.[0]?.text ?? '';
+ expect((text.match(/ccclass\d*\("Skin_2"\)/g) ?? []).length).toBe(1);
+ expect((text.match(/ccclass\d*\("Skin"\)/g) ?? []).length).toBe(1);
+ });
+});
+
+describe('renaming a decorator', () => {
+ it('rewrites the named form and the bare one', () => {
+ expect(renameClass("@ccclass('Skin')\nclass Skin {}", 'Skin', 'Skin_2')).toContain("@ccclass('Skin_2')");
+ expect(renameClass('@ccclass("Skin")\nclass Skin {}', 'Skin', 'Skin_2')).toContain("@ccclass('Skin_2')");
+ expect(renameClass('@ccclass\nclass Skin {}', 'Skin', 'Skin_2')).toContain("@ccclass('Skin_2')");
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 66557614c..171431788 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'feat(bundle): the project script bundle is built again only when a file it read changed, and Cocos scripts that write the same class name each get a component of their own':
+ {"note":"The script bundle is not rebuilt for nothing."},
'fix(editor): opening a large project no longer spends seconds on strings that cannot be paths, a model texture the project lacks is left off instead of dangling, and an unlit mesh variant with tangents links':
{"note":"Large projects open faster, and a model texture the project lacks is left off."},
'feat(cocos): one script that fails to load no longer takes the others with it, a part of cc the layer lacks is a stand-in that survives use, and Director, AssetManager.Cache and the input dispatcher hook exist':