import test from "node:test"; import assert from "node:assert/strict"; import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; import * as ts from "typescript"; import * as tstl from "typescript-to-lua"; import { createRequire } from "node:module"; import { spawnSync } from "node:child_process"; const require = createRequire(import.meta.url); const luaBin = ["lua5.4", "lua"].find((cmd) => { const probe = spawnSync(cmd, ["-v"], { encoding: "utf8" }); return probe.status === 0 && /Lua 5\.4/.test((probe.stdout || "") + (probe.stderr || "")); }); const projectRoot = path.resolve(import.meta.dirname, ".."); const unluaTypesContent = fs.readFileSync(path.join(projectRoot, "types", "unlua.d.ts"), "utf8"); const moduleTypesContent = fs.readFileSync(path.join(projectRoot, "types", "module.d.ts"), "utf8"); const pluginPath = path.join(projectRoot, "dist", "plugin", "index.js"); const { UnLuaDiagnosticCode } = require(pluginPath); const VIRTUAL_LUA_GLOBALS_DTS = ` declare const _G: Record; declare function tostring(this: void, v: unknown): string; declare function require(this: void, mod: string): any; `; function transpile(files, pluginOpts = {}) { const virtualFiles = { "unlua.d.ts": unluaTypesContent, "module.d.ts": moduleTypesContent, "lua.globals.d.ts": VIRTUAL_LUA_GLOBALS_DTS, ...files, }; return tstl.transpileVirtualProject(virtualFiles, { target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler, lib: ["lib.esnext.d.ts"], strict: true, skipLibCheck: true, experimentalDecorators: true, rootDir: ".", luaTarget: tstl.LuaTarget.Lua54, luaLibImport: tstl.LuaLibImportKind.RequireMinimal, noImplicitSelf: false, noHeader: true, luaPlugins: [{ name: pluginPath, ...pluginOpts }], }); } function getErrors(result) { return result.diagnostics.filter((d) => d.category === ts.DiagnosticCategory.Error); } function formatDiagnostics(diags) { return diags .map((d) => `${d.file?.fileName ?? ""} [${d.source ?? "ts"}:${d.code}] ${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`) .join("\n"); } function getLuaFile(result, relPath) { const normalized = relPath.replace(/\\/g, "/"); return result.transpiledFiles.find((f) => { const out = (f.outPath || "").replace(/\\/g, "/"); return out === normalized || out.endsWith("/" + normalized); }); } function writeTranspiledToDir(result, outDir) { for (const file of result.transpiledFiles) { const rel = file.outPath.replace(/^\/+/, ""); const fullPath = path.join(outDir, rel); fs.mkdirSync(path.dirname(fullPath), { recursive: true }); fs.writeFileSync(fullPath, file.lua, "utf8"); } } function runLuaInDir(dir, script) { assert.ok(luaBin, "Lua 5.4 binary is required to run runtime tests"); const wrapped = ` package.path = ${JSON.stringify(path.join(dir, "?.lua"))} .. ";" .. ${JSON.stringify( path.join(dir, "?/init.lua") )} .. ";" .. package.path require("Lib.Module") require("Lib.Class") ${script} `; const proc = spawnSync(luaBin, ["-e", wrapped], { encoding: "utf8", cwd: dir }); assert.equal(proc.status, 0, `Lua execution failed:\nSTDOUT:\n${proc.stdout}\nSTDERR:\n${proc.stderr}`); return proc.stdout; } function withTempDir(fn) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ts2lua-hotreload-")); try { return fn(dir); } finally { fs.rmSync(dir, { recursive: true, force: true }); } } // ============================================================ // 1. 编译期产物与开关校验 // ============================================================ test("hot-reload mode (default) auto-emits Lib/Module.lua and Lib/Class.lua and transforms imports/exports/classes", () => { const result = transpile({ "Framework/Log.ts": ` /** @noSelfInFile */ export function Info(msg: string): string { return "[INFO] " + msg; } export default function DefaultTag(): string { return "LOG"; } `, "Logic/Worker.ts": ` import DefaultTag, { Info as LogInfo } from "../Framework/Log"; import * as LogNS from "../Framework/Log"; declare function require(this: void, mod: string): any; const cjson = require("cjson"); /** @module_data */ let count = 0; /** @module_data */ export let activeName = "init"; export class Worker { tag: string; constructor(tag: string) { this.tag = tag; } Run(): string { count = count + 1; activeName = this.tag; return LogInfo(DefaultTag() + ":" + LogNS.Info(this.tag)) + tostring(cjson); } } `, }); assert.equal(getErrors(result).length, 0, formatDiagnostics(getErrors(result))); // 自动产出 Lib/Module.lua 与 Lib/Class.lua assert.ok(getLuaFile(result, "Lib/Module.lua"), "Expected Lib/Module.lua to be emitted"); assert.ok(getLuaFile(result, "Lib/Class.lua"), "Expected Lib/Class.lua to be emitted"); const workerLua = getLuaFile(result, "Logic/Worker.lua").lua; assert.match(workerLua, /local ____exports = __module\.env/); assert.doesNotMatch(workerLua, /return ____exports/); assert.match(workerLua, /__MODULE__\.Import\("Framework\.Log", __module\)/); // 保留原生 require("cjson") assert.match(workerLua, /local cjson = require\("cjson"\)/); // 顶层纯 TS 类采用扁平全局函数 __TS__DefineClass,且不再从 lualib_bundle 引入 __TS__Class assert.match(workerLua, /____exports\.Worker = __TS__DefineClass\("Worker", __module\)/); assert.doesNotMatch(workerLua, /__TS__\.__?Class|____lualib\.__TS__Class/); // 生成 StashData / RestoreData / UpdateImports assert.match(workerLua, /function __module\.StashData\(env, to\)/); assert.match(workerLua, /function __module\.RestoreData\(env, from\)/); assert.match(workerLua, /function __module\.UpdateImports\(\)/); assert.match(workerLua, /LogInfo = M__Framework_Log\.Info/); assert.match(workerLua, /DefaultTag = M__Framework_Log\.default/); }); test("plugin options support emitRuntime: false and moduleSystem: 'standard'", () => { const noRuntime = transpile( { "A.ts": `export const x = 1;` }, { emitRuntime: false } ); assert.equal(getErrors(noRuntime).length, 0); assert.equal(getLuaFile(noRuntime, "Lib/Module.lua"), undefined); assert.equal(getLuaFile(noRuntime, "Lib/Class.lua"), undefined); const standard = transpile( { "A.ts": `export function Foo() { return 1; }`, "B.ts": `import { Foo } from "./A"; export class C { v() { return Foo(); } }`, }, { moduleSystem: "standard" } ); assert.equal(getErrors(standard).length, 0); assert.equal(getLuaFile(standard, "Lib/Module.lua"), undefined); const bLua = getLuaFile(standard, "B.lua").lua; assert.match(bLua, /local ____exports = \{\}/); assert.match(bLua, /require\("A"\)/); assert.match(bLua, /return ____exports/); assert.doesNotMatch(bLua, /__MODULE__\.Import/); assert.doesNotMatch(bLua, /__TS__DefineClass/); }); test("diagnostics reject invalid @module_data usage and CommonJS export = in hot-reload mode", () => { const bad = transpile({ "Bad.ts": ` /** @module_data */ const { a } = { a: 1 }; void a; export function fn() { /** @module_data */ let inner = 1; return inner; } `, "BadCjs.ts": ` const obj = { x: 1 }; export = obj; `, }); const unluaErrors = bad.diagnostics.filter((d) => d.source === "ts2lua-unlua"); const codes = unluaErrors.map((d) => d.code); assert.equal( codes.filter((c) => c === UnLuaDiagnosticCode.InvalidModuleDataUsage).length, 2, formatDiagnostics(unluaErrors) ); assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenExportEqualsInHotReload)); }); // ============================================================ // 2. 真实 Lua 5.4 运行时热更端到端验证 // ============================================================ test("Lua 5.4 runtime: single-file Reimport updates downstream named/default/namespace imports and triggers OnDepModuleReimported", () => { withTempDir((dir) => { const v1 = transpile({ "Logic/MathUtil.ts": ` /** @noSelfInFile */ export function Add(a: number, b: number): number { return a + b; } export default function Scale(v: number): number { return v * 2; } `, "Logic/Consumer.ts": ` /** @noSelfInFile */ import Scale, { Add } from "./MathUtil"; import * as MathNS from "./MathUtil"; /** @module_data */ export let notified: string[] = []; export function Eval(x: number, y: number): string { return tostring(Add(x, y)) + ":" + tostring(Scale(x)) + ":" + tostring(MathNS.Add(x, y)); } __module.OnDepModuleReimported = (mname: string) => { notified[notified.length] = mname + "=" + Eval(3, 4); }; `, }); assert.equal(getErrors(v1).length, 0, formatDiagnostics(getErrors(v1))); writeTranspiledToDir(v1, dir); const v2Math = transpile({ "Logic/MathUtil.ts": ` /** @noSelfInFile */ export function Add(a: number, b: number): number { return (a + b) * 10; } export default function Scale(v: number): number { return v * 100; } `, }); assert.equal(getErrors(v2Math).length, 0); const mathV2Path = path.join(dir, "Logic", "MathUtil_v2.lua"); fs.writeFileSync(mathV2Path, getLuaFile(v2Math, "Logic/MathUtil.lua").lua, "utf8"); runLuaInDir( dir, ` local consumer = __MODULE__.Import("Logic/Consumer") assert(__MODULE__.GetModuleByName("Logic.Consumer") == consumer) assert(consumer.Eval(3, 4) == "7:6:7", "v1 failed: " .. consumer.Eval(3, 4)) -- 将 MathUtil.lua 替换为 v2(单文件热更,不重载 Consumer) local f = assert(io.open("Logic/MathUtil_v2.lua", "rb")) local v2Code = f:read("a") f:close() local fw = assert(io.open("Logic/MathUtil.lua", "wb")) fw:write(v2Code) fw:close() local ok, err = __MODULE__.ReimportSafely("Logic.MathUtil") assert(ok, "ReimportSafely failed: " .. tostring(err)) -- 命名导入、默认导入、命名空间导入均即时生效 assert(consumer.Eval(3, 4) == "70:300:70", "v2 failed: " .. consumer.Eval(3, 4)) -- OnDepModuleReimported 在 UpdateImports 之后触发 assert(#consumer.notified == 1 and consumer.notified[1] == "Logic.MathUtil=70:300:70", "notify failed: " .. tostring(consumer.notified[1])) ` ); }); }); test("Lua 5.4 runtime: @module_data preserves local/exported/nil values and keeps initializer for newly added @module_data", () => { withTempDir((dir) => { const v1 = transpile({ "State/Store.ts": ` /** @noSelfInFile */ /** @module_data */ let counter = 1; /** @module_data */ const cache: Record = {}; /** @module_data */ export let activeTag = "v1"; /** @module_data */ let nullable: string | undefined = "present"; let ephemeral = "reset-v1"; export function Mutate(): void { counter = 42; cache["k"] = 99; activeTag = "mutated"; nullable = undefined; ephemeral = "changed"; } export function Read() { return { counter, cache, activeTag, nullable, ephemeral }; } `, }); assert.equal(getErrors(v1).length, 0, formatDiagnostics(getErrors(v1))); writeTranspiledToDir(v1, dir); const v2 = transpile({ "State/Store.ts": ` /** @noSelfInFile */ /** @module_data */ let counter = 1; /** @module_data */ const cache: Record = {}; /** @module_data */ export let activeTag = "v2-default"; /** @module_data */ let nullable: string | undefined = "should-stay-nil"; /** @module_data */ let addedInV2 = 777; let ephemeral = "reset-v2"; export function ReadV2() { return { counter, cache, activeTag, nullable, addedInV2, ephemeral }; } `, }); assert.equal(getErrors(v2).length, 0, formatDiagnostics(getErrors(v2))); fs.writeFileSync(path.join(dir, "State", "Store_v2.lua"), getLuaFile(v2, "State/Store.lua").lua, "utf8"); runLuaInDir( dir, ` local store = __MODULE__.Import("State.Store") store.Mutate() local s1 = store.Read() assert(s1.counter == 42 and s1.cache.k == 99 and s1.activeTag == "mutated" and store.activeTag == "mutated" and s1.nullable == nil and s1.ephemeral == "changed") local f = assert(io.open("State/Store_v2.lua", "rb")) local code = f:read("a"); f:close() local fw = assert(io.open("State/Store.lua", "wb")) fw:write(code); fw:close() local ok, err = __MODULE__.ReimportSafely("State.Store") assert(ok, tostring(err)) local s2 = store.ReadV2() assert(s2.counter == 42, "counter not preserved: " .. tostring(s2.counter)) assert(s2.cache == s1.cache and s2.cache.k == 99, "cache table identity not preserved") assert(s2.activeTag == "mutated" and store.activeTag == "mutated", "exported @module_data not preserved") assert(s2.nullable == nil, "nil @module_data was overwritten: " .. tostring(s2.nullable)) assert(s2.addedInV2 == 777, "newly added @module_data was clobbered: " .. tostring(s2.addedInV2)) assert(s2.ephemeral == "reset-v2", "non-@module_data should reset") ` ); }); }); test("Lua 5.4 runtime: Lib/Class.lua hot-reloads pure TS base & child classes preserving instances, inheritance, instanceof, and cleaning removed methods", () => { withTempDir((dir) => { const v1 = transpile({ "Logic/Animal.ts": ` export class Animal { name: string; constructor(name: string) { this.name = name; } Speak(): string { return "v1:" + this.name; } LegacyMethod(): string { return "legacy"; } } `, "Logic/Dog.ts": ` import { Animal } from "./Animal"; export class Dog extends Animal { Speak(): string { return "dog(" + super.Speak() + ")"; } } export function MakePair(this: void) { const a = new Animal("Cat"); const d = new Dog("Rex"); return { a, d }; } export function CheckInstanceOf(this: void, a: unknown, d: unknown): boolean { return a instanceof Animal && d instanceof Dog && d instanceof Animal; } `, }); assert.equal(getErrors(v1).length, 0, formatDiagnostics(getErrors(v1))); writeTranspiledToDir(v1, dir); const v2Animal = transpile({ "Logic/Animal.ts": ` export class Animal { name: string; constructor(name: string) { this.name = name; } Speak(): string { return "v2:" + this.name; } Shout(): string { return "SHOUT:" + this.name; } } `, }); assert.equal(getErrors(v2Animal).length, 0); fs.writeFileSync( path.join(dir, "Logic", "Animal_v2.lua"), getLuaFile(v2Animal, "Logic/Animal.lua").lua, "utf8" ); runLuaInDir( dir, ` local dogMod = __MODULE__.Import("Logic.Dog") local animalMod = __MODULE__.GetModuleByName("Logic.Animal") local oldClass = animalMod.Animal local oldProto = oldClass.prototype local pair = dogMod.MakePair() assert(pair.a:Speak() == "v1:Cat") assert(pair.d:Speak() == "dog(v1:Rex)") assert(pair.a:LegacyMethod() == "legacy") assert(dogMod.CheckInstanceOf(pair.a, pair.d) == true) -- 仅热更父类 Animal.lua local f = assert(io.open("Logic/Animal_v2.lua", "rb")) local code = f:read("a"); f:close() local fw = assert(io.open("Logic/Animal.lua", "wb")) fw:write(code); fw:close() local ok, err = __MODULE__.ReimportSafely("Logic.Animal") assert(ok, tostring(err)) -- 类表与原型表引用完全复用 assert(animalMod.Animal == oldClass) assert(animalMod.Animal.prototype == oldProto) -- 已有父类与子类实例立即生效 assert(pair.a:Speak() == "v2:Cat", "base instance not updated: " .. pair.a:Speak()) assert(pair.d:Speak() == "dog(v2:Rex)", "child super call not updated: " .. pair.d:Speak()) assert(pair.a:Shout() == "SHOUT:Cat") assert(pair.d:Shout() == "SHOUT:Rex") -- 已删除方法已清理 assert(pair.a.LegacyMethod == nil, "removed method should be nil") assert(pair.d.LegacyMethod == nil, "removed inherited method should be nil") -- instanceof 依然为 true assert(dogMod.CheckInstanceOf(pair.a, pair.d) == true) ` ); }); }); test("Lua 5.4 runtime: barrel re-exports (export { ... } from & export * from) cascade hot-reload without corrupting __module", () => { withTempDir((dir) => { const v1 = transpile({ "Core/Calc.ts": ` /** @noSelfInFile */ export function Compute(n: number): number { return n + 1; } `, "Core/Extra.ts": ` /** @noSelfInFile */ export const TAG = "v1-tag"; export function Format(s: string): string { return "[" + s + "]"; } `, "Core/index.ts": ` export { Compute } from "./Calc"; export * from "./Extra"; `, "App/Main.ts": ` /** @noSelfInFile */ import { Compute, TAG, Format } from "../Core/index"; export function Run(n: number): string { return Format(TAG + ":" + tostring(Compute(n))); } `, }); assert.equal(getErrors(v1).length, 0, formatDiagnostics(getErrors(v1))); writeTranspiledToDir(v1, dir); const v2Calc = transpile({ "Core/Calc.ts": ` /** @noSelfInFile */ export function Compute(n: number): number { return n * 100; } `, }); const v2Extra = transpile({ "Core/Extra.ts": ` /** @noSelfInFile */ export const TAG = "v2-tag"; export function Format(s: string): string { return "<" + s + ">"; } `, }); fs.writeFileSync(path.join(dir, "Core", "Calc_v2.lua"), getLuaFile(v2Calc, "Core/Calc.lua").lua, "utf8"); fs.writeFileSync(path.join(dir, "Core", "Extra_v2.lua"), getLuaFile(v2Extra, "Core/Extra.lua").lua, "utf8"); runLuaInDir( dir, ` local app = __MODULE__.Import("App.Main") local barrel = __MODULE__.GetModuleByName("Core.index") assert(barrel.__module.name == "Core.index", "export * corrupted __module!") assert(app.Run(5) == "[v1-tag:6]", "v1 failed: " .. app.Run(5)) local function overwrite(src, dst) local f = assert(io.open(src, "rb")) local c = f:read("a"); f:close() local fw = assert(io.open(dst, "wb")) fw:write(c); fw:close() end overwrite("Core/Calc_v2.lua", "Core/Calc.lua") assert(__MODULE__.ReimportSafely("Core.Calc")) assert(app.Run(5) == "[v1-tag:500]", "calc cascade failed: " .. app.Run(5)) overwrite("Core/Extra_v2.lua", "Core/Extra.lua") assert(__MODULE__.ReimportSafely("Core.Extra")) assert(app.Run(5) == "", "extra star cascade failed: " .. app.Run(5)) assert(barrel.__module.name == "Core.index", "export * reload corrupted __module!") ` ); }); }); test("Lua 5.4 runtime: circular imports, lifecycle order, failure safety, and all 5 gamelogic defect fixes", () => { withTempDir((dir) => { const res = transpile({ "Cycle/A.ts": ` /** @noSelfInFile */ import { GetB } from "./B"; export const VAL_A = 42; export function ReadViaB(): number { return GetB(); } `, "Cycle/B.ts": ` /** @noSelfInFile */ import { VAL_A } from "./A"; export function GetB(): number { return VAL_A; } `, }); assert.equal(getErrors(res).length, 0); writeTranspiledToDir(res, dir); runLuaInDir( dir, ` -- 1. 循环依赖回填验证 local a = __MODULE__.Import("Cycle.A") assert(a.ReadViaB() == 42, "circular import failed: " .. tostring(a.ReadViaB())) -- Defect #2: 成功后清理 loadingModuleTbl assert(__MODULE__.loadingModuleTbl["Cycle.A"] == nil) assert(__MODULE__.loadingModuleTbl["Cycle.B"] == nil) -- 2. Defect #1: waiting refresh 传入 module.env local function makeLoader(src, p, h) return function(name, env) local chunk, err = load(src, p or ("@" .. name .. ".lua"), nil, env) assert(chunk, err) return chunk, p or ("@" .. name .. ".lua"), h end end __MODULE__.RegistryModuleLoader("wait.a", makeLoader([[ b = __MODULE__.Import("wait.b", __module) value = 10 ]], "@wait/a.lua")) __MODULE__.RegistryModuleLoader("wait.b", makeLoader([[ local wa = __MODULE__.Import("wait.a", __module) __module.UpdateImports = function(M) receivedEnv = (M == _ENV) seen = wa.value end ]], "@wait/b.lua")) local wa = __MODULE__.Import("wait.a") assert(wa.b.seen == 10, "waiting seen failed") assert(wa.b.receivedEnv == true, "Defect #1 regression: UpdateImports did not receive module.env") -- 3. Defect #3 & #2: nil-path loader 报错且不残留半初始化模块,重试可成功 local okNil, errNil = pcall(__MODULE__.Import, "defect.retry", nil, function() return function() end end) assert(not okNil and string.find(tostring(errNil), "cannot found module file at", 1, true)) assert(__MODULE__.loadingModuleTbl["defect.retry"] == nil) local recovered = __MODULE__.Import("defect.retry", nil, makeLoader("value = 5", "@defect/retry.lua")) assert(recovered.value == 5 and __MODULE__.GetModuleByName("defect.retry") == recovered) -- 4. Defect #4: 最长 Pattern Loader 优先 __MODULE__.RegistryModuleLoader("^pkg%.", makeLoader('origin = "short"', "@pattern/short.lua")) __MODULE__.RegistryModuleLoader("^pkg%.sub%.", makeLoader('origin = "long"', "@pattern/long.lua")) assert(__MODULE__.Import("pkg.sub.item").origin == "long", "Defect #4 regression: longest pattern did not win") -- 5. 失败热更不破坏旧模块 + IsReimporting 生命周期验证 _G.__TEST_TRACE = {} local lm = __MODULE__.Import("life.order", nil, makeLoader([[ __TEST_TRACE[#__TEST_TRACE + 1] = "chunk" val = 10 __module.UpdateImports = function() __TEST_TRACE[#__TEST_TRACE + 1] = "imports" end __module.UpdateExports = function() __TEST_TRACE[#__TEST_TRACE + 1] = "exports" end __module.StashData = function(M, d) __TEST_TRACE[#__TEST_TRACE + 1] = "stash"; d.val = M.val end __module.OnImport = function() __TEST_TRACE[#__TEST_TRACE + 1] = "import:" .. tostring(__MODULE__.IsReimporting(__module)) end ]], "@life/order.lua")) assert(table.concat(__TEST_TRACE, ",") == "chunk,imports,exports,stash,import:false,exports", "unexpected initial order: " .. table.concat(__TEST_TRACE, ",")) -- 语法/加载失败的 ReimportSafely 不破坏旧模块 local okFail, failErr = __MODULE__.ReimportSafely("@life/order.lua", function() return nil, "broken replacement" end) assert(okFail == false and failErr == "broken replacement") assert(lm.val == 10) -- 正常按 @path Reimport _G.__TEST_TRACE = {} local okReload, reloadErr = __MODULE__.ReimportSafely("@life/order.lua", makeLoader([[ __TEST_TRACE[#__TEST_TRACE + 1] = "chunk:" .. tostring(__MODULE__.IsReimporting(__module)) val = 0 __module.RestoreData = function(M, d) __TEST_TRACE[#__TEST_TRACE + 1] = "restore"; M.val = d.val + 1 end __module.UpdateImports = function() __TEST_TRACE[#__TEST_TRACE + 1] = "imports" end __module.UpdateExports = function() __TEST_TRACE[#__TEST_TRACE + 1] = "exports" end __module.OnReimport = function() __TEST_TRACE[#__TEST_TRACE + 1] = "reimport:" .. tostring(__MODULE__.IsReimporting()) end ]], "@life/order.lua")) assert(okReload, tostring(reloadErr)) assert(lm.val == 11) assert(__MODULE__.IsReimporting() == false) assert(table.concat(__TEST_TRACE, ",") == "stash,chunk:true,restore,imports,exports,reimport:true", "unexpected reload order: " .. table.concat(__TEST_TRACE, ",")) -- 6. Defect #5: 移除依赖后不再收到旧依赖的热更通知 local depA = __MODULE__.Import("dep.a", nil, makeLoader("v = 1", "@dep/a.lua")) local depCalls = 0 local user = __MODULE__.Import("dep.user", nil, makeLoader([[ local a = __MODULE__.Import("dep.a", __module) __module.OnDepModuleReimported = function() depCalls = depCalls + 1 end ]], "@dep/user.lua")) -- 热更 user 移除对 dep.a 的导入 assert(__MODULE__.ReimportSafely("dep.user", makeLoader([[ __module.OnDepModuleReimported = function() _G.__STALE_CALLED = true end ]], "@dep/user.lua"))) assert(__MODULE__.ReimportSafely("dep.a", makeLoader("v = 2", "@dep/a.lua"))) assert(_G.__STALE_CALLED == nil, "Defect #5 regression: removed dependency still triggered notification") ` ); }); }); test("Lua 5.4 runtime: default-exported class hot-reload, side-effect import, two-step re-export, and native require()", () => { withTempDir((dir) => { const v1 = transpile({ "Init/SideEffect.ts": ` /** @noSelfInFile */ export const loaded = true; (_G as any).__SIDE_EFFECT_RAN = ((_G as any).__SIDE_EFFECT_RAN ?? 0) + 1; `, "Logic/DefaultCls.ts": ` export default class Greeter { who: string; constructor(who: string) { this.who = who; } Hello(): string { return "hi:" + this.who; } } `, "Logic/ReexportStep.ts": ` import Greeter from "./DefaultCls"; export { Greeter }; `, "Logic/Entry.ts": ` /** @noSelfInFile */ import "../Init/SideEffect"; import { Greeter } from "./ReexportStep"; const nativeLib = require("native_mock_plugin") as { ping(this: void): string }; export function Make(who: string) { return new Greeter(who); } export function NativePing(): string { return nativeLib.ping(); } `, }); assert.equal(getErrors(v1).length, 0, formatDiagnostics(getErrors(v1))); writeTranspiledToDir(v1, dir); const v2Cls = transpile({ "Logic/DefaultCls.ts": ` export default class Greeter { who: string; constructor(who: string) { this.who = who; } Hello(): string { return "WELCOME:" + this.who; } } `, }); assert.equal(getErrors(v2Cls).length, 0, formatDiagnostics(getErrors(v2Cls))); fs.writeFileSync( path.join(dir, "Logic", "DefaultCls_v2.lua"), getLuaFile(v2Cls, "Logic/DefaultCls.lua").lua, "utf8" ); runLuaInDir( dir, ` package.preload["native_mock_plugin"] = function() return { ping = function() return "pong" end } end local entry = __MODULE__.Import("Logic.Entry") assert(_G.__SIDE_EFFECT_RAN == 1, "side-effect import did not execute") assert(entry.NativePing() == "pong") local g = entry.Make("UE") assert(g:Hello() == "hi:UE") local f = assert(io.open("Logic/DefaultCls_v2.lua", "rb")) local code = f:read("a"); f:close() local fw = assert(io.open("Logic/DefaultCls.lua", "wb")) fw:write(code); fw:close() assert(__MODULE__.ReimportSafely("Logic.DefaultCls")) assert(g:Hello() == "WELCOME:UE", "default-exported class instance did not hot-reload: " .. g:Hello()) local g2 = entry.Make("Hot") assert(g2:Hello() == "WELCOME:Hot") ` ); }); });