// Copyright 2024 The Lynx Authors. All rights reserved. // Licensed under the Apache License Version 2.0 that can be found in the // LICENSE file in the root directory of this source tree. import type { RsbuildPluginAPI } from '@rsbuild/core' import type { ExposedAPI } from '@lynx-js/rspeedy' import generateDevUrls from './generateDevUrls.js' import type { CustomizedSchemaFn } from './index.js' const gExistingShortcuts = new WeakSet() interface Options { api: RsbuildPluginAPI entries: string[] schema: CustomizedSchemaFn port: number /** * Whether to render the ASCII QR code in the terminal. * * When `false`, the plugin still prints the URL(s) and keeps the interactive * shortcuts working, but skips the QR code block. Useful for hosts that * always launch via a schema / deep link and don't need the scan flow, or * for terminals where the QR block is visually noisy. * * @defaultValue `true` */ showQRCode?: boolean | undefined customShortcuts?: Record< string, { value: string, label: string, hint?: string, action?(): Promise } > onPrint?: ((url: string) => Promise) | undefined } export async function registerConsoleShortcuts( options: Options, ): Promise<() => void> { // Non-TTY: print structured list of all entries and return early if (!(process.stdin.isTTY && process.stdout.isTTY)) { await printNonTTY(options) return () => {/* noop */} } const [ { default: showQRCode }, ] = await Promise.all([ import('./showQRCode.js'), ]) const shouldShowQRCode = options.showQRCode ?? true const currentEntry = options.entries[0]! const devUrls = generateDevUrls( options.api, currentEntry, options.schema, options.port, ) const value: string | symbol = Object.values(devUrls)[0]! await options.onPrint?.(value) if (shouldShowQRCode) { showQRCode(value) } gExistingShortcuts.add(options) // We should not `await` on this since it would block the NodeJS main thread. void loop(options, value, devUrls) function off() { gExistingShortcuts.delete(options) } return off } async function printNonTTY(options: Options): Promise { const lines: string[] = [] const urls: string[] = [] for (const entry of options.entries) { const devUrls = generateDevUrls( options.api, entry, options.schema, options.port, ) lines.push(entry) for (const [schemaName, url] of Object.entries(devUrls)) { lines.push(` ${schemaName}: ${url}`) urls.push(url) } } process.stdout.write(lines.join('\n') + '\n') for (const url of urls) { await options.onPrint?.(url) } } async function loop( options: Options, value: string | symbol, devUrls: Record, ) { const [ { autocomplete, select, selectKey, isCancel, cancel }, { default: showQRCode }, ] = await Promise.all([ import('@clack/prompts'), import('./showQRCode.js'), ]) const shouldShowQRCode = options.showQRCode ?? true const selectFn = (length: number) => length > 5 ? autocomplete : select let currentEntry = options.entries[0]! let currentSchema = Object.keys(devUrls)[0]! // A loop whose dev server has already been closed (`off()` ran) must not // prompt again: it would consume the answer meant for the loop that // replaced it. while (!isCancel(value) && gExistingShortcuts.has(options)) { const name = await selectKey({ message: 'Usage', options: [ { value: 'r', label: 'Switch entries' }, { value: 'a', label: 'Switch schema' }, { value: 'h', label: 'Help' }, ...Object.values(options.customShortcuts ?? {}), { value: 'q', label: 'Quit' }, ], initialValue: 'q' as string, }) if ( // User cancel, exit the process isCancel(name) || name === 'q' // Auto restart, stop the loop but avoid exiting the process || !gExistingShortcuts.has(options) ) { break } if (name === 'r') { const selection = await selectFn(options.entries.length)({ message: 'Select entry', options: options.entries.map(entry => ({ value: entry, label: entry, hint: generateDevUrls( options.api, entry, options.schema, options.port, )[currentSchema]!, })), initialValue: currentEntry, }) if (isCancel(selection)) { break } currentEntry = selection value = getCurrentUrl() } else if (name === 'a') { const devUrls = generateDevUrls( options.api, currentEntry, options.schema, options.port, ) const selection = await selectFn(Object.keys(devUrls).length)({ message: 'Select schema', options: Object.entries(devUrls).map(([name, url]) => ({ value: name, label: name, hint: url, })), initialValue: currentSchema, }) if (isCancel(selection)) { break } currentSchema = selection value = getCurrentUrl() } else if (options.customShortcuts?.[name]) { await options.customShortcuts[name].action?.() } if (!gExistingShortcuts.has(options)) { // The dev server closed while a selection was pending; its URL is gone. break } await options.onPrint?.(value) if (!gExistingShortcuts.has(options)) { // ...or while `onPrint` was pending. break } if (shouldShowQRCode) { showQRCode(value) } } // If the `options` is not deleted from `gExistingShortcuts`, means that this is an explicitly // exiting requested by the user. We should exit the process. // Otherwise, this is exit by devServer restart, we should not exit the process. if (gExistingShortcuts.has(options)) { await exit(1) } return function getCurrentUrl(): string { return generateDevUrls( options.api, currentEntry, options.schema, options.port, )[currentSchema]! } function exit(code?: number) { cancel('exiting...') // biome-ignore lint/correctness/useHookAtTopLevel: not react hooks const rspeedy = options.api.useExposed( Symbol.for('rspeedy.api'), ) if (rspeedy) { return rspeedy.exit(code) } // eslint-disable-next-line n/no-process-exit process.exit(code) } }