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

Commit 7668135

Browse files
author
Je
committed
refactor: cleanup
1 parent 616551d commit 7668135

File tree

5 files changed

+56
-50
lines changed

5 files changed

+56
-50
lines changed

head.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ const serverHeadElements: Array<{ type: string, props: Record<string, any> }> =
66
const serverStyles: Map<string, { css: string, asLink: boolean }> = new Map()
77

88
export async function renderHead(styles?: { url: string, hash: string, async?: boolean }[]) {
9-
const { build: { appRoot, buildID } } = (window as any).ALEPH_ENV as AlephEnv
9+
const { __appRoot, __buildID } = (window as any).ALEPH_ENV as AlephEnv
1010
const tags: string[] = []
1111
serverHeadElements.forEach(({ type, props }) => {
1212
if (type === 'title') {
@@ -30,7 +30,7 @@ export async function renderHead(styles?: { url: string, hash: string, async?: b
3030
}
3131
})
3232
await Promise.all(styles?.filter(({ async }) => !!async).map(({ url, hash }) => {
33-
return import('file://' + util.cleanPath(`${appRoot}/.aleph/build-${buildID}/${url}.${hash.slice(0, hashShort)}.js`))
33+
return import('file://' + util.cleanPath(`${__appRoot}/.aleph/build-${__buildID}/${url}.${hash.slice(0, hashShort)}.js`))
3434
}) || [])
3535
styles?.forEach(({ url }) => {
3636
if (serverStyles.has(url)) {

hooks.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ export function useData(key: string) {
77
return data[key]
88
}
99

10+
export function usePageMeta<T = any>(): T {
11+
const { pagePath } = useContext(RouterContext)
12+
return {} as T
13+
}
14+
1015
export function useRouter() {
1116
return useContext(RouterContext)
1217
}

project.ts

Lines changed: 43 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,11 @@ interface Module {
1616
id: string
1717
url: string
1818
isRemote: boolean
19-
deps: { url: string, hash: string, async?: boolean }[]
19+
asPage?: { meta: Record<string, any> }
2020
sourceFilePath: string
2121
sourceType: string
2222
sourceHash: string
23+
deps: { url: string, hash: string, async?: boolean }[]
2324
jsFile: string
2425
jsContent: string
2526
jsSourceMap: string
@@ -33,13 +34,10 @@ interface RenderResult {
3334
}
3435

3536
export interface AlephEnv {
36-
version: string
37-
build: {
38-
mode: 'development' | 'production'
39-
buildID: string
40-
appRoot: string
41-
config: Config
42-
}
37+
[key: string]: string
38+
__version: string
39+
__appRoot: string
40+
__buildID: string
4341
}
4442

4543
export default class Project {
@@ -68,7 +66,8 @@ export default class Project {
6866
sourceMap: false,
6967
importMap: {
7068
imports: {}
71-
}
69+
},
70+
env: {}
7271
}
7372
this.ready = (async () => {
7473
const t = performance.now()
@@ -222,7 +221,7 @@ export default class Project {
222221
return html
223222
}
224223

225-
async getData() {
224+
async getStaticData() {
226225
const mod = this.#modules.get('/data.js')
227226
if (mod) {
228227
try {
@@ -233,11 +232,10 @@ export default class Project {
233232
}
234233
if (util.isPlainObject(data)) {
235234
return data
236-
} else {
237-
log.warn(`module '${mod.url}' should return a plain object as default`)
238235
}
236+
log.warn(`module '${mod.url}' should return a plain object as default`)
239237
} catch (error) {
240-
log.error(error)
238+
log.error('getStaticData:', error)
241239
}
242240
}
243241
return {}
@@ -295,7 +293,7 @@ export default class Project {
295293
// write static data
296294
if (this.#modules.has('/data.js')) {
297295
const { hash } = this.#modules.get('/data.js')!
298-
const data = this.getData()
296+
const data = this.getStaticData()
299297
await writeTextFile(path.join(distDir, `data.${hash.slice(0, hashShort)}.js`), `export default ${JSON.stringify(data)}`)
300298
}
301299

@@ -354,10 +352,11 @@ export default class Project {
354352
srcDir,
355353
ouputDir,
356354
baseUrl,
357-
ssr,
358355
buildTarget,
359356
sourceMap,
360-
defaultLocale
357+
defaultLocale,
358+
ssr,
359+
env
361360
} = config
362361
if (util.isNEString(srcDir)) {
363362
Object.assign(this.config, { srcDir: util.cleanPath(srcDir) })
@@ -368,6 +367,12 @@ export default class Project {
368367
if (util.isNEString(baseUrl)) {
369368
Object.assign(this.config, { baseUrl: util.cleanPath(encodeURI(baseUrl)) })
370369
}
370+
if (/^es(20\d{2}|next)$/i.test(buildTarget)) {
371+
Object.assign(this.config, { buildTarget: buildTarget.toLowerCase() })
372+
}
373+
if (typeof sourceMap === 'boolean') {
374+
Object.assign(this.config, { sourceMap })
375+
}
371376
if (util.isNEString(defaultLocale)) {
372377
Object.assign(this.config, { defaultLocale })
373378
}
@@ -379,11 +384,8 @@ export default class Project {
379384
const exclude = util.isArray(ssr.exclude) ? ssr.exclude : []
380385
Object.assign(this.config, { ssr: { fallback, include, exclude } })
381386
}
382-
if (/^es(20\d{2}|next)$/i.test(buildTarget)) {
383-
Object.assign(this.config, { buildTarget: buildTarget.toLowerCase() })
384-
}
385-
if (typeof sourceMap === 'boolean') {
386-
Object.assign(this.config, { sourceMap })
387+
if (util.isPlainObject(env)) {
388+
Object.assign(this.config, { env })
387389
}
388390

389391
// Gen build ID after config loaded
@@ -401,13 +403,10 @@ export default class Project {
401403

402404
Object.assign(globalThis, {
403405
ALEPH_ENV: {
404-
version,
405-
build: {
406-
appRoot: this.appRoot,
407-
buildID: this.buildID,
408-
config: this.config,
409-
mode: this.mode,
410-
}
406+
...this.config.env,
407+
__version: version,
408+
__appRoot: this.appRoot,
409+
__buildID: this.buildID,
411410
} as AlephEnv,
412411
document: new Document(),
413412
innerWidth: 1920,
@@ -620,7 +619,7 @@ export default class Project {
620619
const config: Record<string, any> = {
621620
baseUrl,
622621
defaultLocale,
623-
locales: {},
622+
locales: [],
624623
routing: {}
625624
}
626625
const module = this._moduleFromURL('/main.js')
@@ -853,18 +852,20 @@ export default class Project {
853852
mod.hash = hash
854853
} else if (mod.sourceType === 'sass' || mod.sourceType === 'scss') {
855854
// todo: support sass
855+
} else if (mod.sourceType === 'md' || mod.sourceType === 'mdx') {
856+
const { __content, ...props } = loadFront(sourceContent)
857+
const html = marked.parse(__content)
858+
mod.jsContent = [
859+
`import React from ${JSON.stringify(relativePath(path.dirname(mod.sourceFilePath), '/-/esm.sh/react.js'))};`,
860+
`export default function Markdown() {`,
861+
` return React.createElement("div", ${JSON.stringify({ className: 'markdown', dangerouslySetInnerHTML: { __html: html } })});`,
862+
`}`,
863+
`Markdown.meta = ${JSON.stringify(props, undefined, this.isDev ? 4 : undefined)};`,
864+
this.isDev && `$RefreshReg$(Markdown, "Markdown");`,
865+
].filter(Boolean).join(this.isDev ? '\n' : '')
866+
mod.jsSourceMap = ''
867+
mod.hash = (new Sha1).update(mod.jsContent).hex()
856868
} else {
857-
if (mod.sourceType === 'md' || mod.sourceType === 'mdx') {
858-
const { __content, ...props } = loadFront(sourceContent)
859-
const html = marked.parse(__content)
860-
sourceContent = [
861-
`import React from 'https://esm.sh/react';`,
862-
`export const pageProps = ${JSON.stringify(props, undefined, 4)};`,
863-
`export default function Marked() {`,
864-
` return React.createElement('div', ${JSON.stringify({ className: 'marked', dangerouslySetInnerHTML: { __html: html } }, undefined, 4)});`,
865-
`}`
866-
].join('\n')
867-
}
868869
const compileOptions = {
869870
target: this.config.buildTarget,
870871
mode: this.mode,
@@ -1088,8 +1089,8 @@ export default class Project {
10881089
const { renderPage, renderHead } = await import("file://" + this.#modules.get('//deno.land/x/aleph/renderer.js')!.jsFile)
10891090
const { default: App } = appModule ? await import("file://" + appModule.jsFile) : {} as any
10901091
const { default: Page } = await import("file://" + pageModule.jsFile)
1091-
const data = await this.getData()
1092-
const html = renderPage(data, url, appModule ? App : undefined, Page)
1092+
const data = await this.getStaticData()
1093+
const html = renderPage(url, data, appModule ? App : undefined, Page)
10931094
const head = await renderHead([
10941095
appModule ? this._lookupStyleDeps(appModule.id) : [],
10951096
this._lookupStyleDeps(pageModule.id),

renderer.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ import util from './util.ts'
88
export { renderHead } from './head.ts'
99

1010
export function renderPage(
11-
data: Record<string, any>,
1211
url: RouterURL,
12+
data: Record<string, any>,
1313
App: ComponentType<any> | undefined,
1414
Page: ComponentType<any>,
1515
) {

server/server.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,8 @@ export async function start(appDir: string, port: number, isDev = false) {
106106
}
107107
}
108108
} else {
109-
const reqMap = pathname.endsWith('.js.map')
110-
const mod = project.getModuleByPath(reqMap ? pathname.slice(0, -4) : pathname)
109+
const reqSourceMap = pathname.endsWith('.js.map')
110+
const mod = project.getModuleByPath(reqSourceMap ? pathname.slice(0, -4) : pathname)
111111
if (mod) {
112112
const etag = req.headers.get('If-None-Match')
113113
if (etag && etag === mod.hash) {
@@ -117,7 +117,7 @@ export async function start(appDir: string, port: number, isDev = false) {
117117

118118
let body = ''
119119
if (mod.id === '/data.js') {
120-
const data = await project.getData()
120+
const data = await project.getStaticData()
121121
if (project.isDev) {
122122
body = [
123123
`import { createHotContext } from "./-/deno.land/x/aleph/hmr.js";`,
@@ -129,7 +129,7 @@ export async function start(appDir: string, port: number, isDev = false) {
129129
} else {
130130
body = `export default ${JSON.stringify(data)}`
131131
}
132-
} else if (reqMap) {
132+
} else if (reqSourceMap) {
133133
body = mod.jsSourceMap
134134
} else {
135135
body = mod.jsContent
@@ -140,7 +140,7 @@ export async function start(appDir: string, port: number, isDev = false) {
140140
req.respond({
141141
status: 200,
142142
headers: new Headers({
143-
'Content-Type': `application/${reqMap ? 'json' : 'javascript'}; charset=utf-8`,
143+
'Content-Type': `application/${reqSourceMap ? 'json' : 'javascript'}; charset=utf-8`,
144144
'ETag': mod.hash
145145
}),
146146
body

0 commit comments

Comments
 (0)