Skip to content

Commit

Permalink
fix: improve type safety of ssrContext and createRenderer (#73)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe authored May 8, 2024
1 parent f080973 commit 2f7996e
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@ export interface ModuleDependencies {
}

export interface SSRContext {
renderResourceHints?: Function
renderScripts?: Function
renderStyles?: Function
renderResourceHints?: (...args: unknown[]) => unknown
renderScripts?: (...args: unknown[]) => unknown
renderStyles?: (...args: unknown[]) => unknown
// @vitejs/plugin-vue: https://vitejs.dev/guide/ssr.html#generating-preload-directives
modules?: Set<string>
// vue-loader (webpack)
_registeredComponents?: Set<string>
// Cache
_requestDependencies?: ModuleDependencies
[key: string]: any
[key: string]: unknown
}

export interface RenderOptions {
Expand Down Expand Up @@ -237,17 +237,22 @@ export function renderScripts (ssrContext: SSRContext, rendererContext: Renderer
})).join('')
}

export type RenderFunction = (ssrContext: SSRContext, rendererContext: RendererContext) => any
export type RenderFunction = (ssrContext: SSRContext, rendererContext: RendererContext) => unknown

export function createRenderer (createApp: any, renderOptions: RenderOptions & { renderToString: Function }) {
type CreateApp<App> = (ssrContext: SSRContext) => App | Promise<App>
type ImportOf<T> = T | { default: T } | Promise<T> | Promise<{ default: T }>

type RenderToString<App> = (app: App, ssrContext: SSRContext) => string | Promise<string>

export function createRenderer<App> (createApp: ImportOf<CreateApp<App>>, renderOptions: RenderOptions & { renderToString: RenderToString<App> }) {
const rendererContext = createRendererContext(renderOptions)

return {
rendererContext,
async renderToString (ssrContext: SSRContext) {
ssrContext._registeredComponents = ssrContext._registeredComponents || new Set()

const _createApp = await Promise.resolve(createApp).then(r => r.default || r)
const _createApp = await Promise.resolve(createApp).then(r => 'default' in r ? r.default : r)
const app = await _createApp(ssrContext)
const html = await renderOptions.renderToString(app, ssrContext)

Expand Down

0 comments on commit 2f7996e

Please sign in to comment.