Skip to content

Commit

Permalink
fix: remove redundant dependences to reduce the bundled package size
Browse files Browse the repository at this point in the history
  • Loading branch information
arianrhodsandlot committed Aug 19, 2024
1 parent 7b9a80c commit 1a42843
Show file tree
Hide file tree
Showing 8 changed files with 330 additions and 394 deletions.
18 changes: 11 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,24 +47,28 @@
"test:e2e": "playwright test -c tests/e2e",
"test:integration": "vitest -c tests/integration/vitest.config"
},
"devDependencies": {
"@arianrhodsandlot/eslint-config": "0.15.9",
"@astrojs/starlight": "0.25.5",
"@playwright/test": "1.46.0",
"bundleDependencies": ["ini", "path-browserify"],
"dependencies": {
"@types/emscripten": "1.39.13",
"@types/ini": "4.1.1",
"@types/path-browserify": "1.0.2"
},
"devDependencies": {
"@arianrhodsandlot/eslint-config": "0.15.11",
"@astrojs/starlight": "0.26.1",
"@playwright/test": "1.46.1",
"@types/is-ci": "3.0.4",
"@types/node": "22.3.0",
"@types/node": "22.4.1",
"@types/wicg-file-system-access": "2023.10.5",
"astro": "4.14.2",
"browserfs": "1.4.3",
"eslint": "9.9.0",
"happy-dom": "14.12.3",
"ini": "4.1.3",
"is-ci": "3.0.1",
"path-browserify": "1.0.1",
"prettier": "3.3.3",
"serve": "14.2.3",
"sharp": "0.33.4",
"sharp": "0.33.5",
"typescript": "5.5.4",
"vite": "5.4.1",
"vitest": "2.0.5"
Expand Down
580 changes: 282 additions & 298 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

16 changes: 0 additions & 16 deletions src/emscripten.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,5 @@
import { EmscriptenFS, FileSystem, initialize } from 'browserfs'
import type { RetroArchEmscriptenModuleOptions } from './types/retroarch-emscripten'

const raUserdataDir = '/home/web_user/retroarch/userdata'

export function createEmscriptenFS({ ERRNO_CODES, FS, PATH }: any) {
const inMemoryFS = new FileSystem.InMemory()
const mountableFS = new FileSystem.MountableFileSystem()
try {
mountableFS.umount(raUserdataDir)
} catch {}
mountableFS.mount(raUserdataDir, inMemoryFS)

initialize(mountableFS)

return new EmscriptenFS(FS, PATH, ERRNO_CODES)
}

export function getEmscriptenModuleOverrides(overrides: RetroArchEmscriptenModuleOptions) {
let resolveRunDependenciesPromise: () => void
const runDependenciesPromise = new Promise<void>((resolve) => {
Expand Down
67 changes: 25 additions & 42 deletions src/emulator.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,24 @@
import type { EmscriptenFS } from 'browserfs'
import ini from 'ini'
import { coreInfoMap } from './constants/core-info'
import { keyboardCodeMap } from './constants/keyboard-code-map'
import { createEmscriptenFS, getEmscriptenModuleOverrides } from './emscripten'
import { getEmscriptenModuleOverrides } from './emscripten'
import type { EmulatorOptions } from './types/emulator-options'
import type { RetroArchCommand } from './types/retroarch-command'
import type { RetroArchEmscriptenModule } from './types/retroarch-emscripten'
import {
basename,
blobToBuffer,
checkIsAborted,
delay,
dirname,
importCoreJsAsESM,
join,
padZero,
stringToBuffer,
updateStyle,
} from './utils'

const encoder = new TextEncoder()
import { blobToBuffer, checkIsAborted, delay, importCoreJsAsESM, padZero, textEncoder, updateStyle } from './utils'
import { vendors } from './vendors'

const { ini, path } = vendors

const raUserdataDir = '/home/web_user/retroarch/userdata'
const raBundleDir = '/home/web_user/retroarch/bundle'

const raContentDir = join(raUserdataDir, 'content')
const raSystemDir = join(raUserdataDir, 'system')
const raConfigDir = join(raUserdataDir, 'config')
const raShaderDir = join(raBundleDir, 'shaders', 'shaders_glsl')
const raContentDir = path.join(raUserdataDir, 'content')
const raSystemDir = path.join(raUserdataDir, 'system')
const raConfigDir = path.join(raUserdataDir, 'config')
const raShaderDir = path.join(raBundleDir, 'shaders', 'shaders_glsl')

const raConfigPath = join(raUserdataDir, 'retroarch.cfg')
const raCoreConfigPath = join(raUserdataDir, 'retroarch-core-options.cfg')
const raConfigPath = path.join(raUserdataDir, 'retroarch.cfg')
const raCoreConfigPath = path.join(raUserdataDir, 'retroarch-core-options.cfg')

type GameStatus = 'initial' | 'paused' | 'running'

Expand All @@ -47,7 +35,6 @@ export class Emulator {
private gameStatus: GameStatus = 'initial'
private messageQueue: [Uint8Array, number][] = []
private options: EmulatorOptions
browserFS: EmscriptenFS | undefined
emscripten: EmulatorEmscripten | undefined

constructor(options: EmulatorOptions) {
Expand Down Expand Up @@ -159,7 +146,7 @@ export class Emulator {
const { rom, signal } = this.options
if (!Module.arguments && rom.length > 0) {
const [{ fileName }] = rom
raArgs.push(join(raContentDir, fileName))
raArgs.push(path.join(raContentDir, fileName))
}

Module.callMain(raArgs)
Expand Down Expand Up @@ -193,13 +180,9 @@ export class Emulator {

private async setupFileSystem() {
const { Module } = this.getEmscripten()
const { ERRNO_CODES, FS, PATH } = Module
const { FS } = Module
const { bios, rom, signal, state } = this.options

const browserFS = createEmscriptenFS({ ERRNO_CODES, FS, PATH })
this.browserFS = browserFS
FS.mount(browserFS, { root: '/home' }, '/home')

if (rom.length > 0) {
FS.mkdirTree(raContentDir)
}
Expand Down Expand Up @@ -254,13 +237,13 @@ export class Emulator {
if (glslFiles.length === 0) {
return
}
const glslpContent = glslFiles.map((file) => `#reference "${join(raShaderDir, file.fileName)}"`).join('\n')
const glslpContent = glslFiles.map((file) => `#reference "${path.join(raShaderDir, file.fileName)}"`).join('\n')

this.writeTextToDirectory({ directory: raConfigDir, fileContent: glslpContent, fileName: 'global.glslp' })

await Promise.all(
shader.map(async ({ fileContent, fileName }) => {
const directory = fileName.endsWith('.glslp') ? raShaderDir : join(raShaderDir, 'shaders')
const directory = fileName.endsWith('.glslp') ? raShaderDir : path.join(raShaderDir, 'shaders')
await this.writeBlobToDirectory({ directory, fileContent, fileName })
}),
)
Expand Down Expand Up @@ -362,7 +345,7 @@ export class Emulator {
const encoding = 'binary'
const data = FS.readFile(fileName, { encoding })
FS.mkdirTree(directory)
FS.writeFile(join(directory, fileName), data, { encoding })
FS.writeFile(path.join(directory, fileName), data, { encoding })
FS.unlink(fileName)
}

Expand All @@ -376,8 +359,8 @@ export class Emulator {
}
let fileContent = ini.stringify(config, { platform: 'linux', whitespace: true })
fileContent = fileContent.replaceAll('__', '"')
const fileName = basename(path)
const directory = dirname(path)
const fileName = vendors.path.basename(path)
const directory = vendors.path.dirname(path)
this.writeTextToDirectory({ directory, fileContent, fileName })
}

Expand All @@ -392,12 +375,12 @@ export class Emulator {
}) {
const { Module } = this.getEmscripten()
const { FS } = Module
const buffer = stringToBuffer(fileContent)
const buffer = textEncoder.encode(fileContent)
FS.createDataFile('/', fileName, buffer, true, false)
const encoding = 'binary'
const data = FS.readFile(fileName, { encoding })
FS.mkdirTree(directory)
FS.writeFile(join(directory, fileName), data, { encoding })
FS.writeFile(path.join(directory, fileName), data, { encoding })
FS.unlink(fileName)
}

Expand Down Expand Up @@ -553,9 +536,9 @@ export class Emulator {

async screenshot() {
this.sendCommand('SCREENSHOT')
const screenshotDirectory = join(raUserdataDir, 'screenshots')
const screenshotDirectory = path.join(raUserdataDir, 'screenshots')
const screenshotFileName = this.guessScreenshotFileName()
const screenshotPath = join(screenshotDirectory, screenshotFileName)
const screenshotPath = path.join(screenshotDirectory, screenshotFileName)
const buffer = await this.waitForEmscriptenFile(screenshotPath)
const { Module } = this.getEmscripten()
const { FS } = Module
Expand All @@ -565,7 +548,7 @@ export class Emulator {
}

sendCommand(msg: RetroArchCommand) {
const bytes = encoder.encode(`${msg}\n`)
const bytes = textEncoder.encode(`${msg}\n`)
this.messageQueue.push([bytes, 0])
}

Expand All @@ -582,11 +565,11 @@ export class Emulator {
if (!coreFullName) {
throw new Error(`invalid core name: ${core.name}`)
}
return join(raUserdataDir, 'states', coreFullName)
return path.join(raUserdataDir, 'states', coreFullName)
}

private get stateFileName() {
return join(this.stateFileDirectory, `${this.romBaseName}.state`)
return path.join(this.stateFileDirectory, `${this.romBaseName}.state`)
}

private get stateThumbnailFileName() {
Expand Down
10 changes: 0 additions & 10 deletions src/nostalgist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,16 +468,6 @@ export class Nostalgist {
}
}

/**
* Get the BFSEmscriptenFS object of the current running emulator.
*
* @see {@link https://nostalgist.js.org/apis/get-browser-fs/}
*/
getBrowserFS() {
const emulator = this.getEmulator()
return emulator.browserFS
}

/**
* Get the canvas DOM element that the current emulator is using.
*
Expand Down
4 changes: 3 additions & 1 deletion src/options.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { NostalgistOptions } from './types/nostalgist-options'
import type { RetroArchConfig } from './types/retroarch-config'
import { isAbsoluteUrl, path } from './utils'
import { isAbsoluteUrl } from './utils'
import { vendors } from './vendors'

const defaultRetroarchConfig: RetroArchConfig = {
menu_driver: 'rgui',
Expand Down Expand Up @@ -111,6 +112,7 @@ export function getDefaultOptions() {
return []
}

const { path } = vendors
const preset = `${cdnBaseUrl}/${shaderRepo}@${shaderVersion}/${name}.glslp`
const segments = name.split(path.sep)
segments.splice(-1, 0, 'shaders')
Expand Down
25 changes: 7 additions & 18 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { BFSRequire } from 'browserfs'
import { vendors } from './vendors'

const { Buffer } = BFSRequire('buffer')
export const path = BFSRequire('path')
export const { basename, dirname, extname, join, relative } = path
const { path } = vendors

export const textEncoder = new TextEncoder()

export function urlBaseName(url: string) {
let pathname = url
try {
pathname = new URL(url).pathname
} catch {}
const name = basename(pathname)
const name = path.basename(pathname)
try {
return decodeURIComponent(name)
} catch {
Expand All @@ -30,18 +30,7 @@ export function isAbsoluteUrl(string: string) {

export async function blobToBuffer(blob: Blob) {
const arrayBuffer = await blob.arrayBuffer()
return Buffer.from(arrayBuffer)
}

export function stringToBuffer(string: string) {
return Buffer.from(string, 'utf8')
}

export async function toBuffer(file: Blob | string) {
if (typeof file === 'string') {
return stringToBuffer(file)
}
return await blobToBuffer(file)
return new Uint8Array(arrayBuffer)
}

export function updateStyle(element: HTMLElement, style: Partial<CSSStyleDeclaration>) {
Expand Down Expand Up @@ -117,7 +106,7 @@ export async function importCoreJsAsESM({ js, name }: { js: string; name: string
return await import(/* @vite-ignore */ /* webpackIgnore: true */ jsBlobUrl)
} catch {
// a dirty hack for using with SystemJS, for example, in StackBlitz
return await eval('import(jsBlobUrl)')
return await new Function('return import(jsBlobUrl)')()
} finally {
URL.revokeObjectURL(jsBlobUrl)
}
Expand Down
4 changes: 2 additions & 2 deletions src/vendors.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as browserfs from 'browserfs'
import ini from 'ini'
import path from 'path-browserify'

export const vendors = {
browserfs,
ini,
path,
}

0 comments on commit 1a42843

Please sign in to comment.