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.

refactor: unify script compilation pipeline with ScriptCompiler

esengine6a4cad1ac5b8
diff --git a/editor/src/builder/ArtifactBuilder.ts b/editor/src/builder/ArtifactBuilder.ts
index 1445347ec..c5de7c6e4 100644
--- a/editor/src/builder/ArtifactBuilder.ts
+++ b/editor/src/builder/ArtifactBuilder.ts
@@ -350,8 +350,6 @@ function embedTextureImporterSettings(sceneData: Record<string, unknown>, assetL
// Shared esbuild utilities
// =============================================================================
-export type SdkModuleLoader = (path: string) => Promise<{ contents: string; loader: esbuild.Loader }>;
-
let esbuildInitialized = false;
export async function initializeEsbuild(): Promise<void> {
@@ -644,99 +642,3 @@ function rewritePrefabAtlasRefs(
}
}
-export function createBuildVirtualFsPlugin(
- fs: NativeFS,
- projectDir: string,
- loadSdkModule: SdkModuleLoader,
- preferEsmEntry = true
-): esbuild.Plugin {
- return {
- name: 'virtual-fs',
- setup(build) {
- build.onResolve({ filter: /^esengine(\/wasm)?$/ }, (args) => ({
- path: args.path,
- namespace: 'esengine-sdk',
- }));
-
- build.onResolve({ filter: /^\./ }, (args) => {
- if (args.namespace !== 'esengine-sdk') return undefined;
- const baseDir = args.importer.includes('/')
- ? args.importer.substring(0, args.importer.lastIndexOf('/'))
- : '';
- const resolved = baseDir ? `${baseDir}/${args.path}` : args.path;
- const normalized = resolved.replace(/^\.\//, '').replace(/\/\.\//g, '/').replace(/[^/]+\/\.\.\//g, '');
- return { path: normalized, namespace: 'esengine-sdk' };
- });
-
- build.onLoad({ filter: /.*/, namespace: 'esengine-sdk' }, async (args) => {
- return loadSdkModule(args.path);
- });
-
- build.onResolve({ filter: /.*/ }, async (args) => {
- if (args.kind === 'entry-point') {
- return { path: args.path, namespace: 'virtual' };
- }
-
- let resolvedPath = args.path;
-
- if (isAbsolutePath(args.path)) {
- resolvedPath = normalizePath(args.path);
- } else if (args.path.startsWith('.')) {
- const baseDir = args.importer ? getParentDir(args.importer) : args.resolveDir;
- resolvedPath = joinPath(baseDir, args.path);
- } else {
- const pkgPath = joinPath(projectDir, 'node_modules', args.path, 'package.json');
- const pkgContent = await fs.readFile(pkgPath);
- if (pkgContent) {
- try {
- const pkg = JSON.parse(pkgContent);
- let entry = preferEsmEntry
- ? (pkg.module || pkg.main || 'index.js')
- : (pkg.main || 'index.js');
- if (pkg.exports) {
- const root = pkg.exports['.'];
- if (typeof root === 'string') {
- entry = root;
- } else if (root?.import) {
- entry = root.import;
- } else if (root?.default) {
- entry = root.default;
- }
- }
- resolvedPath = joinPath(projectDir, 'node_modules', args.path, entry);
- } catch {
- throw new Error(`Failed to parse package.json for: ${args.path}`);
- }
- } else {
- throw new Error(`Module not found: ${args.path}. Please install it with npm.`);
- }
- }
-
- if (!resolvedPath.endsWith('.ts') && !resolvedPath.endsWith('.js')) {
- if (await fs.exists(resolvedPath + '.ts')) {
- resolvedPath += '.ts';
- } else if (await fs.exists(resolvedPath + '.js')) {
- resolvedPath += '.js';
- } else if (await fs.exists(joinPath(resolvedPath, 'index.ts'))) {
- resolvedPath = joinPath(resolvedPath, 'index.ts');
- } else if (await fs.exists(joinPath(resolvedPath, 'index.js'))) {
- resolvedPath = joinPath(resolvedPath, 'index.js');
- } else {
- resolvedPath += '.ts';
- }
- }
-
- return { path: resolvedPath, namespace: 'virtual' };
- });
-
- build.onLoad({ filter: /.*/, namespace: 'virtual' }, async (args) => {
- const content = await fs.readFile(args.path);
- if (content === null) {
- return { contents: '', loader: 'ts' };
- }
- const loader = args.path.endsWith('.ts') ? 'ts' : 'js';
- return { contents: content, loader };
- });
- },
- };
-}
diff --git a/editor/src/builder/EmitterUtils.ts b/editor/src/builder/EmitterUtils.ts
index a46684ffe..b2128b2f2 100644
--- a/editor/src/builder/EmitterUtils.ts
+++ b/editor/src/builder/EmitterUtils.ts
@@ -3,16 +3,14 @@
* @brief Shared utilities for platform emitters (Playable, WeChat)
*/
-import * as esbuild from 'esbuild-wasm/esm/browser';
import type { BuildArtifact } from './PlatformEmitter';
import type { BuildContext } from './BuildService';
import type { EngineModules } from '../types/BuildTypes';
import type { NativeFS } from '../types/NativeFS';
-import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';
+import type { SdkModuleLoader } from '../scripting/types';
+import { ScriptCompiler } from '../scripting/ScriptCompiler';
import { joinPath } from '../utils/path';
-import { discoverPluginPackages } from '../extension/pluginDiscovery';
import { isUUID, getComponentRefFields } from '../asset/AssetLibrary';
-import { initializeEsbuild, createBuildVirtualFsPlugin, type SdkModuleLoader } from './ArtifactBuilder';
import { toBuildPath } from 'esengine';
// =============================================================================
@@ -145,39 +143,13 @@ export async function compileUserScripts(
context: BuildContext,
options: CompileOptions,
): Promise<string> {
- const defines = buildDefinesMap(context.config.defines);
-
- await initializeEsbuild();
-
- const plugin = createBuildVirtualFsPlugin(
- fs,
- projectDir,
- options.sdkResolver,
- options.preferEsmEntry ?? true,
- );
-
- const result = await esbuild.build({
- stdin: {
- contents: options.entryContent,
- loader: 'ts',
- resolveDir: options.resolveDir,
- },
- bundle: true,
+ const compiler = new ScriptCompiler();
+ return compiler.compile(fs, projectDir, options.entryContent, {
format: 'iife',
- write: false,
- platform: 'browser',
- target: 'es2020',
- treeShaking: true,
+ sdk: { type: 'loader', load: options.sdkResolver, preferEsmEntry: options.preferEsmEntry ?? true },
minify: options.minify,
- define: defines,
- plugins: [plugin],
+ defines: buildDefinesMap(context.config.defines),
});
-
- const output = result.outputFiles?.[0]?.text;
- if (!output) {
- throw new Error('esbuild produced no output');
- }
- return output;
}
// =============================================================================
@@ -236,26 +208,13 @@ export async function collectUserScriptImports(
fs: NativeFS,
projectDir: string,
): Promise<{ imports: string; hasSrcDir: boolean }> {
+ const compiler = new ScriptCompiler();
const scriptsPath = joinPath(projectDir, 'src');
const hasSrcDir = await fs.exists(scriptsPath);
- const parts: string[] = [];
-
- try {
- const plugins = await discoverPluginPackages(fs, projectDir, 'main');
- for (const p of plugins) {
- parts.push(`import "${p.entryPath}";`);
- }
- } catch {
- // plugin discovery is best-effort in production builds
- }
-
- if (hasSrcDir) {
- const scripts = await findTsFiles(fs, scriptsPath, EDITOR_ONLY_DIRS);
- for (const p of scripts) {
- parts.push(`import "${p}";`);
- }
- }
+ const plugins = await compiler.discoverPlugins(fs, projectDir, 'main');
+ const scripts = hasSrcDir ? await compiler.discoverScripts(fs, projectDir) : [];
+ const imports = compiler.buildEntry(plugins, scripts);
- return { imports: parts.join('\n'), hasSrcDir: hasSrcDir || parts.length > 0 };
+ return { imports, hasSrcDir: hasSrcDir || plugins.length > 0 };
}
diff --git a/editor/src/builder/index.ts b/editor/src/builder/index.ts
index d11605c2e..085788de9 100644
--- a/editor/src/builder/index.ts
+++ b/editor/src/builder/index.ts
@@ -5,7 +5,9 @@
export { BuildSettingsDialog, showBuildSettingsDialog } from './BuildSettingsDialog';
export { BuildService, type BuildResult, type BuildContext, type BuildOptions, type OutputFileEntry } from './BuildService';
-export { buildArtifact, initializeEsbuild, createBuildVirtualFsPlugin, arrayBufferToBase64, generateAddressableManifest, generateCatalog, type SdkModuleLoader, type CatalogJson, type CatalogEntry } from './ArtifactBuilder';
+export { buildArtifact, initializeEsbuild, arrayBufferToBase64, generateAddressableManifest, generateCatalog, type CatalogJson, type CatalogEntry } from './ArtifactBuilder';
+export { virtualFsPlugin, sdkResolvePlugin } from '../scripting/esbuildPlugins';
+export type { SdkModuleLoader } from '../scripting/types';
export { PLAYABLE_HTML_TEMPLATE, generateWeChatGameJs, type WeChatGameJsParams } from './templates';
export { BuildCache, type BuildCacheData, type FileHash, type FileChangeResult } from './BuildCache';
diff --git a/editor/src/scripting/ScriptCompiler.ts b/editor/src/scripting/ScriptCompiler.ts
new file mode 100644
index 000000000..43b885ed5
--- /dev/null
+++ b/editor/src/scripting/ScriptCompiler.ts
@@ -0,0 +1,177 @@
+/**
+ * @file ScriptCompiler.ts
+ * @brief Unified script compilation pipeline for Play Mode and Build export
+ */
+
+import * as esbuild from 'esbuild-wasm/esm/browser';
+import type { NativeFS, CompileTarget } from './types';
+import { sdkResolvePlugin, virtualFsPlugin } from './esbuildPlugins';
+import { findTsFiles, EDITOR_ONLY_DIRS } from './ScriptLoader';
+import { discoverPluginPackages, type DiscoveredPlugin } from '../extension/pluginDiscovery';
+import { joinPath } from '../utils/path';
+import { initializeEsbuild } from '../builder/ArtifactBuilder';
+
+// =============================================================================
+// ScriptCompiler
+// =============================================================================
+
+export class ScriptCompiler {
+ private ctx_: esbuild.BuildContext | null = null;
+ private lastEntry_: string | null = null;
+ private lastTargetKey_: string | null = null;
+
+ // =========================================================================
+ // Script & Plugin Discovery
+ // =========================================================================
+
+ async discoverScripts(fs: NativeFS, projectDir: string): Promise<string[]> {
+ const srcPath = joinPath(projectDir, 'src');
+ try {
+ if (!await fs.exists(srcPath)) return [];
+ return await findTsFiles(fs, srcPath, EDITOR_ONLY_DIRS);
+ } catch (err) {
+ console.error('ScriptCompiler: Failed to discover scripts:', err);
+ return [];
+ }
+ }
+
+ async discoverPlugins(
+ fs: NativeFS,
+ projectDir: string,
+ entry: 'main' | 'editor',
+ ): Promise<DiscoveredPlugin[]> {
+ try {
+ return await discoverPluginPackages(fs, projectDir, entry);
+ } catch (err) {
+ console.warn('ScriptCompiler: Plugin discovery failed:', err);
+ return [];
+ }
+ }
+
+ buildEntry(
+ plugins: DiscoveredPlugin[],
+ scriptPaths: string[],
+ preamble?: string,
+ ): string {
+ const parts: string[] = [];
+ if (preamble) parts.push(preamble);
+ for (const p of plugins) {
+ parts.push(`import "${p.entryPath}";`);
+ }
+ for (const s of scriptPaths) {
+ parts.push(`import "${s}";`);
+ }
+ return parts.join('\n');
+ }
+
+ // =========================================================================
+ // One-shot Compilation (Build export path)
+ // =========================================================================
+
+ async compile(
+ fs: NativeFS,
+ projectDir: string,
+ entryContent: string,
+ target: CompileTarget,
+ ): Promise<string> {
+ await initializeEsbuild();
+
+ const result = await esbuild.build({
+ ...this.buildOptions_(fs, projectDir, entryContent, target),
+ });
+
+ const output = result.outputFiles?.[0]?.text;
+ if (!output) {
+ throw new Error('esbuild produced no output');
+ }
+ return output;
+ }
+
+ // =========================================================================
+ // Incremental Compilation (Play Mode path)
+ // =========================================================================
+
+ async compileIncremental(
+ fs: NativeFS,
+ projectDir: string,
+ entryContent: string,
+ target: CompileTarget,
+ ): Promise<esbuild.BuildResult> {
+ await initializeEsbuild();
+
+ const targetKey = this.targetKey_(target);
+ const entryChanged = entryContent !== this.lastEntry_;
+ const targetChanged = targetKey !== this.lastTargetKey_;
+
+ if (this.ctx_ && (entryChanged || targetChanged)) {
+ await this.ctx_.dispose();
+ this.ctx_ = null;
+ }
+
+ if (!this.ctx_) {
+ this.ctx_ = await esbuild.context({
+ ...this.buildOptions_(fs, projectDir, entryContent, target),
+ });
+ this.lastEntry_ = entryContent;
+ this.lastTargetKey_ = targetKey;
+ }
+
+ return this.ctx_.rebuild();
+ }
+
+ invalidateIncremental(): void {
+ // Force context recreation on next compileIncremental call
+ this.lastEntry_ = null;
+ }
+
+ async dispose(): Promise<void> {
+ if (this.ctx_) {
+ await this.ctx_.dispose();
+ this.ctx_ = null;
+ }
+ this.lastEntry_ = null;
+ this.lastTargetKey_ = null;
+ }
+
+ // =========================================================================
+ // Private
+ // =========================================================================
+
+ private buildOptions_(
+ fs: NativeFS,
+ projectDir: string,
+ entryContent: string,
+ target: CompileTarget,
+ ): esbuild.BuildOptions {
+ const preferEsm = target.sdk.type === 'loader'
+ ? (target.sdk.preferEsmEntry ?? true)
+ : true;
+
+ const plugins: esbuild.Plugin[] = [
+ sdkResolvePlugin(target.sdk),
+ virtualFsPlugin({ fs, projectDir, preferEsmEntry: preferEsm }),
+ ];
+
+ return {
+ stdin: {
+ contents: entryContent,
+ loader: 'ts',
+ resolveDir: joinPath(projectDir, 'src'),
+ },
+ bundle: true,
+ format: target.format,
+ write: false,
+ platform: 'browser',
+ target: 'es2020',
+ treeShaking: true,
+ sourcemap: target.sourcemap,
+ minify: target.minify,
+ define: target.defines,
+ plugins,
+ };
+ }
+
+ private targetKey_(target: CompileTarget): string {
+ return `${target.format}|${target.sdk.type}|${target.minify ?? false}|${target.sourcemap ?? false}`;
+ }
+}
diff --git a/editor/src/scripting/ScriptLoader.ts b/editor/src/scripting/ScriptLoader.ts
index 9d926674a..e6700749e 100644
--- a/editor/src/scripting/ScriptLoader.ts
+++ b/editor/src/scripting/ScriptLoader.ts
@@ -3,12 +3,11 @@
* @brief Load and compile user TypeScript scripts for preview
*/
-import * as esbuild from 'esbuild-wasm/esm/browser';
import * as esengineModule from 'esengine';
-import { virtualFsPlugin, playModeShimPlugin } from './esbuildPlugins';
-import type { NativeFS, ScriptLoaderOptions, CompileError } from './types';
+import type { NativeFS, ScriptLoaderOptions, CompileError, CompileTarget } from './types';
import { ComponentSwapper } from './ComponentSwapper';
import type { ScriptContent } from './ComponentSwapper';
+import { ScriptCompiler } from './ScriptCompiler';
import {
extractComponentDefs,
registerComponentEntries,
@@ -17,9 +16,7 @@ import {
type ComponentDefEntry,
} from './componentExtraction';
import { getEditorContext } from '../context/EditorContext';
-import { initializeEsbuild } from '../builder/ArtifactBuilder';
import { normalizePath, joinPath, getProjectDir } from '../utils/path';
-import { discoverPluginPackages } from '../extension/pluginDiscovery';
// =============================================================================
// Native FS Access
@@ -29,6 +26,21 @@ function getNativeFS(): NativeFS | null {
return getEditorContext().fs ?? null;
}
+// =============================================================================
+// Play Mode Compile Target
+// =============================================================================
+
+const PLAY_MODE_TARGET: CompileTarget = {
+ format: 'esm',
+ sdk: {
+ type: 'shim',
+ modules: new Map<string, Record<string, unknown>>([
+ ['esengine', esengineModule as unknown as Record<string, unknown>],
+ ]),
+ },
+ sourcemap: 'inline',
+};
+
// =============================================================================
// Script Loader
// =============================================================================
@@ -51,7 +63,6 @@ export class ScriptLoader {
async initialize(): Promise<void> {
if (this.initialized_) return;
- await initializeEsbuild();
this.initialized_ = true;
}
@@ -61,16 +72,7 @@ export class ScriptLoader {
console.warn('ScriptLoader: NativeFS not available');
return [];
}
-
- const srcPath = joinPath(this.projectDir_, 'src');
-
- try {
- if (!await fs.exists(srcPath)) return [];
- return await findTsFiles(fs, srcPath, EDITOR_ONLY_DIRS);
- } catch (err) {
- console.error('ScriptLoader: Failed to discover scripts:', err);
- return [];
- }
+ return this.compiler_.discoverScripts(fs, this.projectDir_);
}
async compile(): Promise<boolean> {
@@ -99,19 +101,10 @@ export class ScriptLoader {
return false;
}
- const scripts = await this.discoverScripts();
+ const scripts = await this.compiler_.discoverScripts(fs, this.projectDir_);
+ const plugins = await this.compiler_.discoverPlugins(fs, this.projectDir_, 'main');
- const pluginImports: string[] = [];
- try {
- const plugins = await discoverPluginPackages(fs, this.projectDir_, 'main');
- for (const p of plugins) {
- pluginImports.push(`import "${p.entryPath}";`);
- }
- } catch (err) {
- console.warn('ScriptLoader: Plugin discovery failed:', err);
- }
-
- if (scripts.length === 0 && pluginImports.length === 0) {
+ if (scripts.length === 0 && plugins.length === 0) {
this.swapper_.prepare([]);
this.swapper_.swap();
this.lastCompiled_ = null;
@@ -120,33 +113,14 @@ export class ScriptLoader {
}
try {
- const localImports = scripts.map(p => `import "${p}";`).join('\n');
- const entryContent = pluginImports.join('\n') + '\n' + localImports;
-
- const shimModules = new Map<string, Record<string, unknown>>([
- ['esengine', esengineModule as unknown as Record<string, unknown>],
- ]);
-
- const result = await esbuild.build({
- stdin: {
- contents: entryContent,
- loader: 'ts',
- resolveDir: joinPath(this.projectDir_, 'src'),
- },
- bundle: true,
- format: 'esm',
- write: false,
- sourcemap: 'inline',
- platform: 'browser',
- target: 'es2020',
- plugins: [
- playModeShimPlugin(shimModules),
- virtualFsPlugin({
- fs,
- projectDir: this.projectDir_,
- }),
- ],
- });
+ const entryContent = this.compiler_.buildEntry(plugins, scripts);
+
+ const result = await this.compiler_.compileIncremental(
+ fs,
+ this.projectDir_,
+ entryContent,
+ PLAY_MODE_TARGET,
+ );
if (result.errors.length > 0) {
const errors: CompileError[] = result.errors.map(e => ({
@@ -168,7 +142,7 @@ export class ScriptLoader {
return true;
} catch (err: any) {
console.error('ScriptLoader: Compilation failed:', err);
- const esbuildErrors = err?.errors as esbuild.Message[] | undefined;
+ const esbuildErrors = err?.errors as Array<{ location?: { file?: string; line?: number; column?: number }; text: string }> | undefined;
const errors: CompileError[] = esbuildErrors?.length
? esbuildErrors.map(e => ({
file: e.location?.file || 'unknown',
@@ -183,6 +157,7 @@ export class ScriptLoader {
}
async reload(): Promise<boolean> {
+ this.compiler_.invalidateIncremental();
return this.compile();
}
@@ -226,6 +201,7 @@ export class ScriptLoader {
dispose(): void {
this.unwatch();
+ void this.compiler_.dispose();
}
// =========================================================================
@@ -257,6 +233,7 @@ export class ScriptLoader {
private recompileTimer_: number | null = null;
private compiling_ = false;
private pendingCompile_ = false;
+ private compiler_ = new ScriptCompiler();
private swapper_ = new ComponentSwapper();
private onCompileError_?: (errors: CompileError[]) => void;
private onCompileSuccess_?: () => void;
@@ -295,7 +272,6 @@ async function findTsFiles(
export { findTsFiles, IGNORED_SCRIPT_DIRS, EDITOR_ONLY_DIRS };
-// Re-export for backward compatibility (used in tests)
function extractAndRegisterComponents(source: string): string[] {
const entries = extractComponentDefs(source);
registerComponentEntries(entries);
diff --git a/editor/src/scripting/esbuildPlugins.ts b/editor/src/scripting/esbuildPlugins.ts
index 140acbe4a..761fad00a 100644
--- a/editor/src/scripting/esbuildPlugins.ts
+++ b/editor/src/scripting/esbuildPlugins.ts
@@ -1,11 +1,11 @@
/**
* @file esbuildPlugins.ts
- * @brief esbuild plugins for virtual file system and SDK shim
+ * @brief esbuild plugins for virtual file system and SDK resolution
*/
import type * as esbuild from 'esbuild-wasm';
-import type { NativeFS } from './types';
-import { normalizePath, joinPath, getParentDir } from '../utils/path';
+import type { NativeFS, SdkResolveStrategy } from './types';
+import { normalizePath, joinPath, getParentDir, isAbsolutePath } from '../utils/path';
// =============================================================================
// Path Utilities
@@ -127,24 +127,72 @@ export function playModeShimPlugin(
};
}
+// =============================================================================
+// SDK Resolve Plugin (unified shim / loader strategy)
+// =============================================================================
+
+export function sdkResolvePlugin(strategy: SdkResolveStrategy): esbuild.Plugin {
+ if (strategy.type === 'shim') {
+ return playModeShimPlugin(strategy.modules);
+ }
+
+ const { load, preferEsmEntry } = strategy;
+ return {
+ name: 'sdk-resolve',
+ setup(build) {
+ build.onResolve({ filter: /^esengine(\/wasm)?$/ }, (args) => ({
+ path: args.path,
+ namespace: 'esengine-sdk',
+ }));
+
+ build.onResolve({ filter: /^\./ }, (args) => {
+ if (args.namespace !== 'esengine-sdk') return undefined;
+ const baseDir = args.importer.includes('/')
+ ? args.importer.substring(0, args.importer.lastIndexOf('/'))
+ : '';
+ const resolved = baseDir ? `${baseDir}/${args.path}` : args.path;
+ const normalized = resolved
+ .replace(/^\.\//, '')
+ .replace(/\/\.\//g, '/')
+ .replace(/[^/]+\/\.\.\//g, '');
+ return { path: normalized, namespace: 'esengine-sdk' };
+ });
+
+ build.onLoad({ filter: /.*/, namespace: 'esengine-sdk' }, async (args) => {
+ return load(args.path);
+ });
+
+ if (preferEsmEntry !== undefined) {
+ (build as any).__sdkPreferEsm = preferEsmEntry;
+ }
+ },
+ };
+}
+
// =============================================================================
// Virtual FS Plugin
// =============================================================================
-export interface VirtualFsPluginOptions {
+export interface VirtualFsOptions {
fs: NativeFS;
projectDir: string;
+ preferEsmEntry?: boolean;
}
-export function virtualFsPlugin(options: VirtualFsPluginOptions): esbuild.Plugin {
- const { fs, projectDir } = options;
+export function virtualFsPlugin(options: VirtualFsOptions): esbuild.Plugin {
+ const { fs, projectDir, preferEsmEntry = true } = options;
const nodeModulesPath = joinPath(projectDir, 'node_modules');
const NS = 'virtual';
return {
name: 'virtual-fs',
setup(build) {
- // Absolute paths must be resolved before npm packages filter matches them
+ const esmPref = (build as any).__sdkPreferEsm ?? preferEsmEntry;
+
+ // -----------------------------------------------------------------
+ // Absolute path resolution (Unix + Windows)
+ // -----------------------------------------------------------------
+
build.onResolve({ filter: /^\// }, (args) => {
return { path: args.path, namespace: NS };
});
@@ -153,6 +201,10 @@ export function virtualFsPlugin(options: VirtualFsPluginOptions): esbuild.Plugin
return { path: normalizePath(args.path), namespace: NS };
});
+ // -----------------------------------------------------------------
+ // Bare specifier (npm package) resolution
+ // -----------------------------------------------------------------
+
build.onResolve({ filter: /^[^./]/ }, async (args) => {
if (/^[A-Za-z]:/.test(args.path)) return undefined;
@@ -172,8 +224,27 @@ export function virtualFsPlugin(options: VirtualFsPluginOptions): esbuild.Plugin
return { errors: [{ text: `Package not found: ${pkgName}. Please install it with npm.` }] };
}
- const pkgJson = JSON.parse(pkgJsonContent);
- const entryFile = subpath || pkgJson.module || pkgJson.main || 'index.js';
+ const pkg = JSON.parse(pkgJsonContent);
+
+ let entryFile: string;
+ if (subpath) {
+ entryFile = subpath;
+ } else {
+ entryFile = esmPref
+ ? (pkg.module || pkg.main || 'index.js')
+ : (pkg.main || 'index.js');
+ if (pkg.exports) {
+ const root = pkg.exports['.'];
+ if (typeof root === 'string') {
+ entryFile = root;
+ } else if (root?.import && esmPref) {
+ entryFile = root.import;
+ } else if (root?.default) {
+ entryFile = root.default;
+ }
+ }
+ }
+
const entryPath = joinPath(nodeModulesPath, pkgName, entryFile);
return { path: entryPath, namespace: NS };
} catch {
@@ -181,31 +252,38 @@ export function virtualFsPlugin(options: VirtualFsPluginOptions): esbuild.Plugin
}
});
+ // -----------------------------------------------------------------
+ // Relative path resolution
+ // -----------------------------------------------------------------
+
build.onResolve({ filter: /^\./, namespace: NS }, async (args) => {
let resolved = resolvePath(args.importer || args.resolveDir, args.path);
if (!resolved.match(/\.(ts|tsx|js|jsx|json|mjs|cjs)$/)) {
- const tsPath = resolved + '.ts';
- if (await fs.exists(tsPath)) {
- resolved = tsPath;
- } else {
- const jsPath = resolved + '.js';
- if (await fs.exists(jsPath)) {
- resolved = jsPath;
- } else {
- const indexTsPath = joinPath(resolved, 'index.ts');
- if (await fs.exists(indexTsPath)) {
- resolved = indexTsPath;
- } else {
- resolved = resolved + '.ts';
- }
- }
- }
+ resolved = await resolveExtension(fs, resolved);
}
return { path: resolved, namespace: NS };
});
+ // -----------------------------------------------------------------
+ // Entry point
+ // -----------------------------------------------------------------
+
+ build.onResolve({ filter: /.*/ }, (args) => {
+ if (args.kind === 'entry-point') {
+ return { path: args.path, namespace: NS };
+ }
+ if (isAbsolutePath(args.path)) {
+ return { path: normalizePath(args.path), namespace: NS };
+ }
+ return undefined;
+ });
+
+ // -----------------------------------------------------------------
+ // File loading
+ // -----------------------------------------------------------------
+
build.onLoad({ filter: /.*/, namespace: NS }, async (args) => {
let content = await fs.readFile(args.path);
if (content === null) {
@@ -236,3 +314,27 @@ export function virtualFsPlugin(options: VirtualFsPluginOptions): esbuild.Plugin
},
};
}
+
+// =============================================================================
+// Extension Resolution Helper
+// =============================================================================
+
+async function resolveExtension(
+ fs: { exists(path: string): Promise<boolean> },
+ basePath: string,
+): Promise<string> {
+ const tsPath = basePath + '.ts';
+ if (await fs.exists(tsPath)) return tsPath;
+
+ const jsPath = basePath + '.js';
+ if (await fs.exists(jsPath)) return jsPath;
+
+ const indexTsPath = joinPath(basePath, 'index.ts');
+ if (await fs.exists(indexTsPath)) return indexTsPath;
+
+ const indexJsPath = joinPath(basePath, 'index.js');
+ if (await fs.exists(indexJsPath)) return indexJsPath;
+
+ return tsPath;
+}
+
diff --git a/editor/src/scripting/index.ts b/editor/src/scripting/index.ts
index 47cac6af2..638925537 100644
--- a/editor/src/scripting/index.ts
+++ b/editor/src/scripting/index.ts
@@ -4,4 +4,5 @@
*/
export { ScriptLoader } from './ScriptLoader';
-export type { ScriptLoaderOptions, CompileError, CompileResult } from './types';
+export { ScriptCompiler } from './ScriptCompiler';
+export type { ScriptLoaderOptions, CompileError, CompileResult, CompileTarget, SdkResolveStrategy, SdkModuleLoader } from './types';
diff --git a/editor/src/scripting/types.ts b/editor/src/scripting/types.ts
index fc47eb7f8..839d14cea 100644
--- a/editor/src/scripting/types.ts
+++ b/editor/src/scripting/types.ts
@@ -1,12 +1,36 @@
/**
* @file types.ts
- * @brief Script loader type definitions
+ * @brief Script compiler & loader type definitions
*/
+import type * as esbuild from 'esbuild-wasm';
+
export type { NativeFS, DirectoryEntry, FileStats } from '../types/NativeFS';
// =============================================================================
-// Script Loader Types
+// SDK Module Resolution
+// =============================================================================
+
+export type SdkModuleLoader = (path: string) => Promise<{ contents: string; loader: esbuild.Loader }>;
+
+export type SdkResolveStrategy =
+ | { type: 'shim'; modules: Map<string, Record<string, unknown>> }
+ | { type: 'loader'; load: SdkModuleLoader; preferEsmEntry?: boolean };
+
+// =============================================================================
+// Compile Target
+// =============================================================================
+
+export interface CompileTarget {
+ format: 'esm' | 'iife';
+ sdk: SdkResolveStrategy;
+ minify?: boolean;
+ sourcemap?: boolean | 'inline';
+ defines?: Record<string, string>;
+}
+
+// =============================================================================
+// Compile Result & Errors
// =============================================================================
export interface CompileResult {
@@ -22,6 +46,10 @@ export interface CompileError {
message: string;
}
+// =============================================================================
+// Script Loader Options
+// =============================================================================
+
export interface ScriptLoaderOptions {
projectPath: string;
onCompileError?: (errors: CompileError[]) => void;