Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit 2f8fa6a

Browse files
committed
Clean up
1 parent 0058f6c commit 2f8fa6a

File tree

4 files changed

+63
-68
lines changed

4 files changed

+63
-68
lines changed

bundler/mod.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ export class Bundler {
145145
mod.specifier,
146146
source.code,
147147
{
148-
...this.#aleph.commonCompileOptions,
148+
...this.#aleph.commonCompilerOptions,
149149
swcOptions: {
150150
sourceType: source.type,
151151
},

server/aleph.ts

Lines changed: 40 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,7 @@ import cssPlugin, { cssLoader, isCSS } from '../plugins/css.ts'
1414
import { ensureTextFile, existsDir, existsFile, lazyRemove } from '../shared/fs.ts'
1515
import log, { Measure } from '../shared/log.ts'
1616
import util from '../shared/util.ts'
17-
import type {
18-
Aleph as IAleph, ImportMap, LoadInput, LoadOutput, RouterURL, ResolveResult,
19-
TransformOutput, TransformInput
20-
} from '../types.ts'
17+
import type { Aleph as IAleph, ImportMap, LoadInput, LoadOutput, RouterURL, ResolveResult, TransformOutput, TransformInput } from '../types.ts'
2118
import { VERSION } from '../version.ts'
2219
import { Analyzer } from './analyzer.ts'
2320
import { cache } from './cache.ts'
@@ -29,7 +26,7 @@ import {
2926
} from './helper.ts'
3027
import { getContentType } from './mime.ts'
3128
import type { SSRData } from './renderer.ts'
32-
import { Renderer } from './renderer.ts'
29+
import { createHtml, Renderer } from './renderer.ts'
3330

3431
/** A module includes the compilation details. */
3532
export type Module = {
@@ -470,7 +467,7 @@ export class Aleph implements IAleph {
470467
return null
471468
}
472469

473-
/** get api route by given location. */
470+
/** get api route by the given location. */
474471
async getAPIRoute(location: { pathname: string, search?: string }): Promise<[RouterURL, Module] | null> {
475472
const router = this.#apiRouting.createRouter(location)
476473
if (router !== null) {
@@ -539,7 +536,7 @@ export class Aleph implements IAleph {
539536
this.#dists.add(pathname)
540537
}
541538

542-
/** get ssr data */
539+
/** get ssr data by the given location(page), return `null` if no data defined */
543540
async getSSRData(loc: { pathname: string, search?: string }): Promise<Record<string, SSRData> | null> {
544541
const [router, nestedModules] = this.#pageRouting.createRouter(loc)
545542
const { routePath } = router
@@ -591,34 +588,34 @@ export class Aleph implements IAleph {
591588
return data
592589
}
593590

594-
/** get page ssr html */
595-
async getPageHTML(loc: { pathname: string, search?: string }): Promise<[number, string]> {
591+
/** render page to HTML by the given location */
592+
async renderPage(loc: { pathname: string, search?: string }): Promise<[number, string]> {
596593
const [router, nestedModules] = this.#pageRouting.createRouter(loc)
597594
const { routePath } = router
598595
const path = loc.pathname + (loc.search || '')
599596

600597
if (!this.isSSRable(loc.pathname)) {
601598
const [html] = await this.#renderer.cache('-', 'spa-index', async () => {
602-
return [await this.#renderer.renderSPAIndexPage(), null]
599+
return [this.createSPAIndexHtml(), null]
603600
})
604601
return [200, html]
605602
}
606603

607604
if (routePath === '') {
608605
const [html] = await this.#renderer.cache('404', path, async () => {
609606
const [_, nestedModules] = this.#pageRouting.createRouter({ pathname: '/404' })
610-
return await this.renderPage(router, nestedModules.slice(0, 1))
607+
return await this.#renderPage(router, nestedModules.slice(0, 1))
611608
})
612609
return [404, html]
613610
}
614611

615612
const [html] = await this.#renderer.cache(routePath, path, async () => {
616-
return await this.renderPage(router, nestedModules)
613+
return await this.#renderPage(router, nestedModules)
617614
})
618615
return [200, html]
619616
}
620617

621-
private async renderPage(url: RouterURL, nestedModules: string[]): Promise<[string, Record<string, SSRData> | null]> {
618+
async #renderPage(url: RouterURL, nestedModules: string[]): Promise<[string, Record<string, SSRData> | null]> {
622619
const href = url.toString()
623620
let [html, data] = await this.#renderer.renderPage(url, nestedModules)
624621
for (const callback of this.#ssrListeners) {
@@ -682,11 +679,24 @@ export class Aleph implements IAleph {
682679
return code
683680
}
684681

685-
/** get ssr html scripts */
686-
getSSRHTMLScripts(entryFile?: string) {
682+
/** create the index html for SPA mode. */
683+
private createSPAIndexHtml(): string {
684+
// todo: render custom fallback page
685+
return createHtml({
686+
lang: this.config.i18n.defaultLocale,
687+
head: [],
688+
scripts: this.getScripts(),
689+
body: '<div id="__aleph"></div>',
690+
minify: !this.isDev
691+
})
692+
}
693+
694+
/** get scripts for html output */
695+
getScripts(entryFile?: string) {
687696
const { framework } = this.config
688697
const basePath = util.trimSuffix(this.config.basePath, '/')
689698
const alephPkgPath = getAlephPkgUri().replace('https://', '').replace('http://localhost:', 'http_localhost_')
699+
const syncChunks = this.#bundler.getSyncChunks()
690700

691701
if (this.isDev) {
692702
const preload: string[] = [
@@ -715,7 +725,7 @@ export class Aleph implements IAleph {
715725

716726
return [
717727
simpleJSMinify(bundlerRuntimeCode),
718-
... this.#bundler.getSyncChunks().map(filename => ({
728+
...syncChunks.map(filename => ({
719729
src: `${basePath}/_aleph/${filename}`
720730
}))
721731
]
@@ -739,7 +749,7 @@ export class Aleph implements IAleph {
739749
}
740750

741751
/** common compiler options */
742-
get commonCompileOptions(): TransformOptions {
752+
get commonCompilerOptions(): TransformOptions {
743753
return {
744754
workingDir: this.workingDir,
745755
alephPkgUri: getAlephPkgUri(),
@@ -895,7 +905,7 @@ export class Aleph implements IAleph {
895905
return await import(`file://${join(this.buildDir, jsFile)}#${(hash || sourceHash).slice(0, 6)}`)
896906
}
897907

898-
async readModuleJS(module: Module, injectHMRCode = false): Promise<Uint8Array | null> {
908+
async getModuleJS(module: Module, injectHMRCode = false): Promise<Uint8Array | null> {
899909
const { specifier, jsFile, jsBuffer } = module
900910
if (!jsBuffer) {
901911
const cacheFp = join(this.buildDir, jsFile)
@@ -918,6 +928,7 @@ export class Aleph implements IAleph {
918928
if ('csrCode' in module) {
919929
code = (module as any).csrCode
920930
} else {
931+
[code] = util.splitBy(code, '\n//# sourceMappingURL=', true)
921932
const { code: csrCode } = await stripSsrCode(specifier, code, { sourceMap: true, swcOptions: { sourceType: SourceType.JS } })
922933
// cache csr code
923934
Object.assign(module, { csrCode })
@@ -1134,7 +1145,7 @@ export class Aleph implements IAleph {
11341145
const ms = new Measure()
11351146
const encoder = new TextEncoder()
11361147
const { code, deps, denoHooks, ssrPropsFn, ssgPathsFn, starExports, map } = await transform(specifier, source.code, {
1137-
...this.commonCompileOptions,
1148+
...this.commonCompilerOptions,
11381149
sourceMap: this.isDev,
11391150
swcOptions: {
11401151
sourceType: source.type
@@ -1246,12 +1257,7 @@ export class Aleph implements IAleph {
12461257

12471258
if (module.deps.length > 0) {
12481259
let fsync = false
1249-
const encoder = new TextEncoder()
12501260
const hasher = createHash('md5').update(module.sourceHash)
1251-
// preload js buffer
1252-
if (module.deps.findIndex(dep => dep.hashLoc !== undefined) >= 0) {
1253-
await this.readModuleJS(module)
1254-
}
12551261
await Promise.all(module.deps.map(async ({ specifier, hashLoc }) => {
12561262
let depModule: Module | null
12571263
if (ignoreDeps) {
@@ -1277,7 +1283,7 @@ export class Aleph implements IAleph {
12771283
}))
12781284
module.hash = hasher.toString()
12791285
if (fsync) {
1280-
await this.writeModule(module)
1286+
await this.cacheModule(module)
12811287
}
12821288
} else {
12831289
module.hash = module.sourceHash
@@ -1315,7 +1321,7 @@ export class Aleph implements IAleph {
13151321
mod.hash = hasher.toString()
13161322
callback(mod)
13171323
this.applyCompilationSideEffect(mod, callback)
1318-
this.writeModule(mod)
1324+
this.cacheModule(mod)
13191325
}
13201326
}
13211327
}
@@ -1324,9 +1330,9 @@ export class Aleph implements IAleph {
13241330
/** replace dep hash in the `jsBuffer` and remove `csrCode` cache if it exits */
13251331
private async replaceDepHash(module: Module, hashLoc: number, hash: string) {
13261332
const hashData = (new TextEncoder()).encode(hash.substr(0, 6))
1327-
await this.readModuleJS(module)
1328-
if (module.jsBuffer && !equals(hashData, module.jsBuffer.slice(hashLoc, hashLoc + 6))) {
1329-
copy(hashData, module.jsBuffer, hashLoc)
1333+
const jsBuffer = await this.getModuleJS(module)
1334+
if (jsBuffer && !equals(hashData, jsBuffer.slice(hashLoc, hashLoc + 6))) {
1335+
copy(hashData, jsBuffer, hashLoc)
13301336
if ('csrCode' in module) {
13311337
Reflect.deleteProperty(module, 'csrCode')
13321338
}
@@ -1344,7 +1350,7 @@ export class Aleph implements IAleph {
13441350
}
13451351
}
13461352

1347-
private async writeModule(module: Module) {
1353+
private async cacheModule(module: Module) {
13481354
const { specifier, jsBuffer, jsFile } = module
13491355
if (jsBuffer) {
13501356
const cacheFp = join(this.buildDir, jsFile)
@@ -1378,9 +1384,10 @@ export class Aleph implements IAleph {
13781384
const outputDir = join(this.workingDir, this.config.build.outputDir)
13791385

13801386
if (ssr === false) {
1381-
const html = await this.#renderer.renderSPAIndexPage()
1387+
const html = this.createSPAIndexHtml()
13821388
await ensureTextFile(join(outputDir, 'index.html'), html)
13831389
await ensureTextFile(join(outputDir, '404.html'), html)
1390+
// todo: 500 page
13841391
return
13851392
}
13861393

@@ -1422,7 +1429,7 @@ export class Aleph implements IAleph {
14221429
const [router, nestedModules] = this.#pageRouting.createRouter({ pathname, search })
14231430
if (router.routePath !== '') {
14241431
const href = router.toString()
1425-
const [html, data] = await this.renderPage(router, nestedModules)
1432+
const [html, data] = await this.#renderPage(router, nestedModules)
14261433
await ensureTextFile(join(outputDir, pathname, 'index.html' + (search || '')), html)
14271434
if (data) {
14281435
const dataFile = join(
@@ -1442,7 +1449,7 @@ export class Aleph implements IAleph {
14421449
if (nestedModules.length > 0) {
14431450
await this.compile(nestedModules[0])
14441451
}
1445-
const [html] = await this.renderPage(router, nestedModules.slice(0, 1))
1452+
const [html] = await this.#renderPage(router, nestedModules.slice(0, 1))
14461453
await ensureTextFile(join(outputDir, '404.html'), html)
14471454
}
14481455
}

server/renderer.ts

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ export class Renderer {
145145
type: 'application/json',
146146
innerText: JSON.stringify(data, undefined, isDev ? 2 : 0),
147147
} : '',
148-
...this.#aleph.getSSRHTMLScripts(state.entryFile),
148+
...this.#aleph.getScripts(state.entryFile),
149149
...scripts.map((script: Record<string, any>) => {
150150
if (script.innerText && !isDev) {
151151
return { ...script, innerText: script.innerText }
@@ -160,18 +160,6 @@ export class Renderer {
160160
]
161161
}
162162

163-
/** render the index page for SPA mode. */
164-
async renderSPAIndexPage(): Promise<string> {
165-
// todo: render custom fallback page
166-
return createHtml({
167-
lang: this.#aleph.config.i18n.defaultLocale,
168-
head: [],
169-
scripts: this.#aleph.getSSRHTMLScripts(),
170-
body: '<div id="__aleph"></div>',
171-
minify: !this.#aleph.isDev
172-
})
173-
}
174-
175163
private async lookupStyleModules(...specifiers: string[]): Promise<Record<string, { css?: string, href?: string }>> {
176164
const mods: Module[] = []
177165
specifiers.forEach(specifier => {
@@ -193,7 +181,7 @@ export class Renderer {
193181
}
194182

195183
/** create html content by given arguments */
196-
function createHtml({
184+
export function createHtml({
197185
body,
198186
lang = 'en',
199187
head = [],

0 commit comments

Comments
 (0)