Skip to content

Commit

Permalink
Revert "feat: spawn main function as entrypoint in the entrypoint f…
Browse files Browse the repository at this point in the history
…ile` (#563)" (#566)

This reverts commit 7a39b8e.
  • Loading branch information
leanmendoza authored May 4, 2023
1 parent 59379e3 commit 77c4945
Show file tree
Hide file tree
Showing 22 changed files with 91 additions and 153 deletions.
2 changes: 1 addition & 1 deletion packages/@dcl/playground-assets/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"scripts": {
"build": "npm run build-playground && node_modules/.bin/api-extractor run",
"build-local": "npm run build-playground && node_modules/.bin/api-extractor run --local --verbose --diagnostics",
"build-playground": "./../sdk-commands/dist/index.js build --production --emitDeclaration --customEntryPoint"
"build-playground": "./../sdk-commands/dist/index.js build --production --emitDeclaration"
},
"tsdoc": {
"tsdocFlavor": "AEDoc"
Expand Down
4 changes: 2 additions & 2 deletions packages/@dcl/sdk-commands/src/commands/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export async function buildScene(options: Options, project: SceneProject) {

const watch = !!options.args['--watch']

const { sceneJson, inputs } = await bundleProject(
const { sceneJson } = await bundleProject(
options.components,
{
workingDirectory: project.workingDirectory,
Expand All @@ -84,6 +84,6 @@ export async function buildScene(options: Options, project: SceneProject) {
options.components.analytics.track('Build scene', {
projectHash: await b64HashingFunction(project.workingDirectory),
coords,
isWorkspace: inputs.length > 1
isWorkspace: false
})
}
114 changes: 43 additions & 71 deletions packages/@dcl/sdk-commands/src/logic/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import child_process from 'child_process'
import esbuild from 'esbuild'
import { future } from 'fp-future'
import { globSync } from 'glob'
import { basename, dirname, join } from 'path'
import { dirname, join } from 'path'
import { pathToFileURL } from 'url'
import { CliComponents } from '../components'
import { colors } from '../components/log'
Expand Down Expand Up @@ -39,34 +39,6 @@ export type CompileOptions = {

const MAX_STEP = 2

/**
* Generate the entry-point code for a given original entry-point
* @param entrypointPath - file to be imported as original entry point
* @param forceCustomExport
* @returns the Typescript code
*/

function getEntrypointCode(entrypointPath: string, forceCustomExport: boolean) {
if (forceCustomExport) return `export * from '${entrypointPath}'`

return `// BEGIN AUTO GENERATED CODE "~sdk/scene-entrypoint"
import * as entrypoint from '${entrypointPath}'
import { engine } from '@dcl/sdk/ecs'
import * as sdk from '@dcl/sdk'
if ((entrypoint as any).main !== undefined) {
async function _INTERNAL_startup_system() {
await (entrypoint as any).main()
engine.removeSystem(_INTERNAL_startup_system)
}
engine.addSystem(_INTERNAL_startup_system, Infinity)
}
export * from '@dcl/sdk'
export * from '${entrypointPath}'
`
}

export async function bundleProject(components: BundleComponents, options: CompileOptions, sceneJson: Scene) {
const tsconfig = join(options.workingDirectory, 'tsconfig.json')

Expand All @@ -85,42 +57,24 @@ export async function bundleProject(components: BundleComponents, options: Compi
throw new CliError(`File ${tsconfig} must exist to compile the Typescript project`)
}

const entrypointSource = options.single ?? 'src/index.ts'
const entrypoints = globSync(entrypointSource, { cwd: options.workingDirectory, absolute: true })
const input = globSync(options.single ?? 'src/index.ts', { cwd: options.workingDirectory, absolute: true }) // entryPoints.map((item) => item.dest)

/* istanbul ignore if */
if (!entrypoints.length) throw new CliError(`There are no input files to build: ${entrypointSource}`)

const inputs: { entrypoint: string; outputFile: string }[] = options.single
? entrypoints.map((entrypoint) => ({ entrypoint, outputFile: entrypoint.replace(/\.ts$/, '.js') }))
: [{ entrypoint: entrypoints[0], outputFile: sceneJson.main }]

for (const input of inputs) {
await bundleSingleProject(components, {
...options,
tsconfig,
...input
})
}
if (!input.length) throw new CliError(`There are no input files to build: ${options.single ?? 'src/index.ts'}`)

return { sceneJson, inputs }
}

type SingleProjectOptions = CompileOptions & {
tsconfig: string
entrypoint: string
outputFile: string
}
const output = !options.single ? sceneJson.main : options.single.replace(/\.ts$/, '.js')
const outfile = join(options.workingDirectory, output)

export async function bundleSingleProject(components: BundleComponents, options: SingleProjectOptions) {
printProgressStep(components.logger, `Bundling file ${colors.bold(options.entrypoint)}`, 1, MAX_STEP)
printProgressStep(components.logger, `Bundling file ${colors.bold(input.join(','))}`, 1, MAX_STEP)

const context = await esbuild.context({
entryPoints: input,
bundle: true,
platform: 'browser',
format: 'cjs',
preserveSymlinks: false,
outfile: options.outputFile,
outfile: input.length > 1 ? undefined : outfile,
outdir: input.length > 1 ? dirname(outfile) : undefined,
allowOverwrite: false,
sourcemap: options.production ? 'external' : 'inline',
minify: options.production,
Expand All @@ -133,42 +87,40 @@ export async function bundleSingleProject(components: BundleComponents, options:
target: 'es2020',
external: ['~system/*', '@dcl/inspector', '@dcl/inspector/*' /* ban importing the inspector from the SDK */],
// convert filesystem paths into file:// to enable VSCode debugger
sourceRoot: pathToFileURL(dirname(options.outputFile)).toString(),
sourceRoot: pathToFileURL(dirname(outfile)).toString(),
define: {
document: 'undefined',
window: 'undefined',
DEBUG: options.production ? 'false' : 'true',
'globalThis.DEBUG': options.production ? 'false' : 'true',
'process.env.NODE_ENV': JSON.stringify(options.production ? 'production' : 'development')
},
tsconfig: options.tsconfig,
tsconfig: join(options.workingDirectory, 'tsconfig.json'),
supported: {
'import-assertions': false,
'import-meta': false,
'dynamic-import': false,
hashbang: false
},
logOverride: {
'import-is-undefined': 'silent'
},
plugins: [compositeLoader(components, options)],
stdin: {
contents: getEntrypointCode(options.entrypoint, options.customEntryPoint),
resolveDir: dirname(options.entrypoint),
sourcefile: basename(options.entrypoint) + '.entry-point.ts',
loader: 'ts'
}
plugins: [entryPointLoader(components, input, options), compositeLoader(components, options)]
})

/* istanbul ignore if */
if (options.watch) {
await context.watch({})

printProgressInfo(components.logger, `Bundle saved ${colors.bold(options.outputFile)}`)
printProgressInfo(components.logger, `Bundle saved ${colors.bold(output)}`)
} else {
try {
await context.rebuild()
printProgressInfo(components.logger, `Bundle saved ${colors.bold(options.outputFile)}`)
const ctx = await context.rebuild()
printProgressInfo(
components.logger,
`Bundle saved ${colors.bold(
Object.keys(ctx.metafile.outputs)
.filter((_) => _.endsWith('.js'))
.join(',') || outfile
)}`
)
} catch (err: any) {
/* istanbul ignore next */
throw new CliError(err.toString())
Expand All @@ -180,6 +132,8 @@ export async function bundleSingleProject(components: BundleComponents, options:
if (options.watch) printProgressInfo(components.logger, `The compiler is watching for changes`)

await runTypeChecker(components, options)

return { context, sceneJson }
}

function runTypeChecker(components: BundleComponents, options: CompileOptions) {
Expand Down Expand Up @@ -221,7 +175,7 @@ function runTypeChecker(components: BundleComponents, options: CompileOptions) {
return typeCheckerFuture
}

function compositeLoader(components: BundleComponents, options: SingleProjectOptions): esbuild.Plugin {
function compositeLoader(components: BundleComponents, options: CompileOptions): esbuild.Plugin {
let shouldReload = true
let contents = `export const compositeFromLoader = {}` // default exports nothing
let watchFiles: string[] = [] // no files to watch
Expand Down Expand Up @@ -286,3 +240,21 @@ async function getAllComposite(

return { compositeLines, watchFiles }
}

function entryPointLoader(components: BundleComponents, inputs: string[], options: CompileOptions): esbuild.Plugin {
const escapedInputs = inputs.map(($) => $.replace(/\\/g, '\\\\'))
const filter = new RegExp(`(${escapedInputs.join('|')})`)
return {
name: 'entry-point-loader',
setup(build) {
build.onLoad({ filter }, async (args) => {
const exportSdk = options.customEntryPoint ? '' : `;export * from '@dcl/sdk';`
const contents = exportSdk + (await components.fs.readFile(args.path))
return {
loader: 'ts',
contents
}
})
}
}
}
1 change: 0 additions & 1 deletion test/build-ecs/sourcemaps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ export function assertFilesExist(map: BasicSourceMapConsumer) {

// TODO: what should we do with virtual files?
if (file.endsWith('sdk-composite:all-composites')) continue
if (file.endsWith('entry-point.ts')) continue

const fileExist = existsSync(fileURLToPath(file)) ? file : 'does not exit'
expect(fileExist).toBe(file)
Expand Down
2 changes: 1 addition & 1 deletion test/sdk-commands/commands/build/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ describe('build command', () => {
.mockResolvedValue({ kind: 'scene', scene: {} as any, workingDirectory: process.cwd() })
jest.spyOn(projectValidation, 'needsDependencies').mockResolvedValue(false)
const sceneJson = { scene: { base: '0,0' } } as any
const tsBuildSpy = jest.spyOn(dclCompiler, 'bundleProject').mockResolvedValue({ sceneJson, inputs: [] })
const tsBuildSpy = jest.spyOn(dclCompiler, 'bundleProject').mockResolvedValue({ sceneJson, context: null as any })

await build.main({
args: { _: [], '--watch': false, '--production': true },
Expand Down
5 changes: 0 additions & 5 deletions test/snapshots.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,6 @@ describe('Runs the snapshots', () => {
path.resolve('test/snapshots'),
ENV
)
itExecutes(
`npm run build -- --production --ignoreComposite "--single=production-bundles/with-main-function.ts"`,
path.resolve('test/snapshots'),
ENV
)
itExecutes(
`npm run build -- --customEntryPoint --ignoreComposite "--single=development-bundles/*.ts"`,
path.resolve('test/snapshots'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,4 @@ CALL onUpdate(0.1)
OPCODES ~= 2k
MALLOC_COUNT = -3
ALIVE_OBJS_DELTA ~= 0.00k
MEMORY_USAGE_COUNT ~= 962.77k bytes
MEMORY_USAGE_COUNT ~= 962.76k bytes
2 changes: 1 addition & 1 deletion test/snapshots/development-bundles/testing-fw.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { withRenderer } from '../helpers/with-renderer'
import { assert } from '../helpers/assertions'
export * from '@dcl/sdk'

export const onServerUpdate = withRenderer((engine) => {
withRenderer((engine) => {
// this helper creates a second engine and prints all the messages to emulate
// the renderer counterpart of the CRDT
const Transform = components.Transform(engine)
Expand Down
8 changes: 4 additions & 4 deletions test/snapshots/development-bundles/testing-fw.test.ts.crdt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
SCENE_COMPILED_JS_SIZE_PROD=354.4k bytes
SCENE_COMPILED_JS_SIZE_PROD=354.3k bytes
THE BUNDLE HAS SOURCEMAPS
(start empty vm 0.21.0-3680274614.commit-1808aa1)
OPCODES ~= 0k
Expand All @@ -11,8 +11,8 @@ EVAL test/snapshots/development-bundles/testing-fw.test.js
REQUIRE: ~system/EngineApi
REQUIRE: ~system/EngineApi
OPCODES ~= 30k
MALLOC_COUNT = 9889
ALIVE_OBJS_DELTA ~= 1.85k
MALLOC_COUNT = 9881
ALIVE_OBJS_DELTA ~= 1.84k
CALL onStart()
LOG: ["Adding one to position.y=0"]
Renderer: PUT_COMPONENT e=0x0 c=1 t=1 data={"position":{"x":1,"y":0,"z":0},"rotation":{"x":0,"y":0,"z":0,"w":1},"scale":{"x":9,"y":9,"z":9},"parent":0}
Expand Down Expand Up @@ -64,4 +64,4 @@ CALL onUpdate(0.1)
OPCODES ~= 4k
MALLOC_COUNT = -40
ALIVE_OBJS_DELTA ~= -0.01k
MEMORY_USAGE_COUNT ~= 962.73k bytes
MEMORY_USAGE_COUNT ~= 962.50k bytes
2 changes: 1 addition & 1 deletion test/snapshots/development-bundles/two-way-crdt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { withRenderer } from '../helpers/with-renderer'
import { assert } from '../helpers/assertions'
export * from '@dcl/sdk'

export const onServerUpdate = withRenderer((engine) => {
withRenderer((engine) => {
// this helper creates a second engine and prints all the messages to emulate
// the renderer counterpart of the CRDT
const Transform = components.Transform(engine)
Expand Down
8 changes: 4 additions & 4 deletions test/snapshots/development-bundles/two-way-crdt.test.ts.crdt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
SCENE_COMPILED_JS_SIZE_PROD=354.4k bytes
SCENE_COMPILED_JS_SIZE_PROD=354.3k bytes
THE BUNDLE HAS SOURCEMAPS
(start empty vm 0.21.0-3680274614.commit-1808aa1)
OPCODES ~= 0k
Expand All @@ -11,8 +11,8 @@ EVAL test/snapshots/development-bundles/two-way-crdt.test.js
REQUIRE: ~system/EngineApi
REQUIRE: ~system/EngineApi
OPCODES ~= 30k
MALLOC_COUNT = 9889
ALIVE_OBJS_DELTA ~= 1.85k
MALLOC_COUNT = 9881
ALIVE_OBJS_DELTA ~= 1.84k
CALL onStart()
LOG: ["Adding one to position.y=0"]
Renderer: PUT_COMPONENT e=0x0 c=1 t=1 data={"position":{"x":1,"y":0,"z":0},"rotation":{"x":0,"y":0,"z":0,"w":1},"scale":{"x":9,"y":9,"z":9},"parent":0}
Expand Down Expand Up @@ -64,4 +64,4 @@ CALL onUpdate(0.1)
OPCODES ~= 4k
MALLOC_COUNT = -40
ALIVE_OBJS_DELTA ~= -0.01k
MEMORY_USAGE_COUNT ~= 962.73k bytes
MEMORY_USAGE_COUNT ~= 962.50k bytes
3 changes: 2 additions & 1 deletion test/snapshots/helpers/with-renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Transport } from '@dcl/ecs'
import { IEngine, Engine } from '@dcl/ecs/dist/engine'

let called = false
declare const module: any

export function withRenderer(cb: (engine: IEngine) => void) {
if (called) throw new Error('Only call withRenderer once')
Expand All @@ -25,7 +26,7 @@ export function withRenderer(cb: (engine: IEngine) => void) {
engine.addTransport(rendererTransport)

cb(engine)
return async function (data: Uint8Array) {
;(module as any).exports.onServerUpdate = async function (data: Uint8Array) {
if (rendererTransport.onmessage) {
rendererTransport.onmessage(data)

Expand Down
2 changes: 1 addition & 1 deletion test/snapshots/production-bundles/append-value-crdt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export * from '@dcl/sdk'

const entity = 512 as Entity

export const onServerUpdate = withRenderer((engine) => {
withRenderer((engine) => {
const PointerEventsResult = components.PointerEventsResult(engine)

let count = 0
Expand Down
6 changes: 3 additions & 3 deletions test/snapshots/production-bundles/append-value-crdt.ts.crdt
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ EVAL test/snapshots/production-bundles/append-value-crdt.js
REQUIRE: long
REQUIRE: ~system/EngineApi
REQUIRE: ~system/EngineApi
OPCODES ~= 31k
MALLOC_COUNT = 8714
OPCODES ~= 32k
MALLOC_COUNT = 8705
ALIVE_OBJS_DELTA ~= 1.86k
CALL onStart()
Renderer: APPEND_VALUE e=0x200 c=1063 t=0 data={"button":0,"hit":{"position":{"x":1,"y":2,"z":3},"globalOrigin":{"x":1,"y":2,"z":3},"direction":{"x":1,"y":2,"z":3},"normalHit":{"x":1,"y":2,"z":3},"length":10,"meshName":"mesh","entityId":512},"state":1,"timestamp":1,"analog":5,"tickNumber":0}
Expand Down Expand Up @@ -55,4 +55,4 @@ CALL onUpdate(0.1)
OPCODES ~= 13k
MALLOC_COUNT = 31
ALIVE_OBJS_DELTA ~= 0.01k
MEMORY_USAGE_COUNT ~= 711.07k bytes
MEMORY_USAGE_COUNT ~= 710.85k bytes
2 changes: 1 addition & 1 deletion test/snapshots/production-bundles/billboard.ts.crdt
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ EVAL test/snapshots/production-bundles/billboard.js
REQUIRE: long
REQUIRE: ~system/EngineApi
REQUIRE: ~system/EngineApi
OPCODES ~= 41k
OPCODES ~= 42k
MALLOC_COUNT = 11021
ALIVE_OBJS_DELTA ~= 2.31k
CALL onStart()
Expand Down
5 changes: 5 additions & 0 deletions test/snapshots/production-bundles/composite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { engine, MeshRenderer, Transform } from '@dcl/sdk/ecs'

const cube = engine.addEntity()
Transform.create(cube)
MeshRenderer.setBox(cube)
Loading

0 comments on commit 77c4945

Please sign in to comment.