Skip to content

Commit

Permalink
feat(plugin-vite): useUntil to wait rendererUrl set
Browse files Browse the repository at this point in the history
  • Loading branch information
ArcherGu committed Jul 6, 2024
1 parent e7da673 commit b0560eb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ bench/test/*/*/
cypress/videos
cypress/downloads
cypress/screenshots
local-data
34 changes: 29 additions & 5 deletions packages/plugin-vite/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,32 @@ export interface VitePluginDoubleshotConfig extends Omit<InlineConfig, 'renderer
configureForMode: (userConfig: InlineConfig, mode: string) => (void | InlineConfig) | Promise<(void | InlineConfig)>
}

function useUntil(timeout?: number) {
let untilResolve: () => void
let untilReject: (error: Error) => void

const untilPromise = new Promise<void>((resolve, reject) => {
untilResolve = resolve
untilReject = reject
})

let timer: NodeJS.Timeout
if (typeof timeout === 'number' && timeout > 0) {
timer = setTimeout(() => {
untilReject(new Error('Until timeout'))
}, timeout)
}

const done = () => {
timer && clearTimeout(timer)
untilResolve()
}

const until = () => untilPromise

return { until, done }
}

export function VitePluginDoubleshot(userConfig: Partial<VitePluginDoubleshotConfig> = {}): PluginOption[] {
const PLUGIN_NAME = 'vite-plugin-doubleshot'

Expand All @@ -45,20 +71,18 @@ export function VitePluginDoubleshot(userConfig: Partial<VitePluginDoubleshotCon
await configureForMode(resolvedConfig)
},
configureServer(server) {
const { until, done } = useUntil(10 * 1000) // 10s timeout
const printUrls = server.printUrls.bind(server)
let rendererUrlSet = false
// override printUrls to get rendererUrl
server.printUrls = () => {
printUrls()
if (!userConfig.rendererUrl)
userConfig.rendererUrl = server.resolvedUrls!.local[0]
rendererUrlSet = true
done()
}

server?.httpServer?.on('listening', async () => {
while (!rendererUrlSet) {
await new Promise(resolve => setTimeout(resolve, 10));
}
await until()
await dev(userConfig)
})
},
Expand Down

0 comments on commit b0560eb

Please sign in to comment.