Импорт: заметная кнопка, адрес в консоли, предупреждение об устаревшей сборке
- ссылка на импорт есть в шапке пульта и в лобби - сервер печатает адрес импорта и выбирает порт по факту запущенного Vite - предупреждение, если dist собран раньше исходников
This commit is contained in:
1 parent
ea2d5d905c
commit
5d3cd9127c
3 files changed
+89
-16
No files matched your search
@@ -5,7 +5,8 @@
|
|||||||
* рассказать в консоли, куда идти. Всё остальное живёт в app.ts и room.ts.
|
* рассказать в консоли, куда идти. Всё остальное живёт в app.ts и room.ts.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { existsSync } from 'node:fs'
|
import { existsSync, readdirSync, statSync } from 'node:fs'
|
||||||
|
import { createConnection } from 'node:net'
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
import { fileURLToPath } from 'node:url'
|
import { fileURLToPath } from 'node:url'
|
||||||
import { buildApp } from './app'
|
import { buildApp } from './app'
|
||||||
@@ -16,6 +17,7 @@ const here = path.dirname(fileURLToPath(import.meta.url))
|
|||||||
const repoRoot = path.resolve(here, '../../..')
|
const repoRoot = path.resolve(here, '../../..')
|
||||||
const contentDir = process.env.QUIZ_CONTENT ?? path.join(repoRoot, 'content')
|
const contentDir = process.env.QUIZ_CONTENT ?? path.join(repoRoot, 'content')
|
||||||
const staticDir = path.join(repoRoot, 'packages/web/dist')
|
const staticDir = path.join(repoRoot, 'packages/web/dist')
|
||||||
|
const webSrc = path.join(repoRoot, 'packages/web/src')
|
||||||
|
|
||||||
const { packs, problems } = loadPacks(contentDir)
|
const { packs, problems } = loadPacks(contentDir)
|
||||||
|
|
||||||
@@ -57,14 +59,56 @@ try {
|
|||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
|
|
||||||
const external = lanAddresses()[0]?.address ?? '127.0.0.1'
|
// ─── Проверки окружения, о которых лучше узнать до игры ────────────────────
|
||||||
|
|
||||||
// Порт интерфейса: если интерфейс собран, его раздаёт этот же сервер;
|
function isPortOpen(target: number): Promise<boolean> {
|
||||||
// иначе его поднимает Vite на 5173.
|
return new Promise((resolve) => {
|
||||||
const hasStatic = existsSync(path.join(staticDir, 'index.html'))
|
const socket = createConnection({ host: '127.0.0.1', port: target })
|
||||||
const uiPort = hasStatic ? port : Number(process.env.QUIZ_UI_PORT ?? 5173)
|
const finish = (value: boolean): void => {
|
||||||
|
socket.destroy()
|
||||||
|
resolve(value)
|
||||||
|
}
|
||||||
|
socket.once('connect', () => finish(true))
|
||||||
|
socket.once('error', () => finish(false))
|
||||||
|
socket.setTimeout(400, () => finish(false))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function newestMtime(dir: string): number {
|
||||||
|
if (!existsSync(dir)) return 0
|
||||||
|
let newest = 0
|
||||||
|
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||||
|
const full = path.join(dir, entry.name)
|
||||||
|
if (entry.isDirectory()) newest = Math.max(newest, newestMtime(full))
|
||||||
|
else newest = Math.max(newest, statSync(full).mtimeMs)
|
||||||
|
}
|
||||||
|
return newest
|
||||||
|
}
|
||||||
|
|
||||||
|
const warnings: string[] = []
|
||||||
|
const indexPath = path.join(staticDir, 'index.html')
|
||||||
|
const hasStatic = existsSync(indexPath)
|
||||||
|
|
||||||
|
// Собранный интерфейс старше исходников — значит, на порту сервера живёт
|
||||||
|
// вчерашняя версия, и кнопок в ней может не быть. Лучше сказать об этом сразу,
|
||||||
|
// чем ловить «а где кнопка?».
|
||||||
|
if (hasStatic) {
|
||||||
|
const builtAt = statSync(indexPath).mtimeMs
|
||||||
|
const srcAt = newestMtime(webSrc)
|
||||||
|
if (srcAt > builtAt) {
|
||||||
|
warnings.push(
|
||||||
|
'интерфейс на порту сервера собран раньше исходников — там старая версия.\n' +
|
||||||
|
' Пересоберите: npm run build (или работайте на dev-порту)',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const devPort = Number(process.env.QUIZ_UI_PORT ?? 5173)
|
||||||
|
const devRunning = !hasStatic || (await isPortOpen(devPort))
|
||||||
|
|
||||||
|
const external = lanAddresses()[0]?.address ?? '127.0.0.1'
|
||||||
|
const uiPort = devRunning ? devPort : port
|
||||||
const ui = `http://${external}:${uiPort}`
|
const ui = `http://${external}:${uiPort}`
|
||||||
const local = `http://localhost:${uiPort}`
|
|
||||||
|
|
||||||
const lines = [
|
const lines = [
|
||||||
' ─────────────────────────────────────────────',
|
' ─────────────────────────────────────────────',
|
||||||
@@ -72,16 +116,25 @@ const lines = [
|
|||||||
` пак: ${built.pack.title}`,
|
` пак: ${built.pack.title}`,
|
||||||
` комната: ${built.roomCode}`,
|
` комната: ${built.roomCode}`,
|
||||||
' ─────────────────────────────────────────────',
|
' ─────────────────────────────────────────────',
|
||||||
` Табло: ${ui}/board`,
|
` табло: ${ui}/board`,
|
||||||
` Пульт: ${ui}/host/${built.hostToken}`,
|
` пульт: ${ui}/host/${built.hostToken}`,
|
||||||
` Игроки: ${ui}/play?room=${built.roomCode}`,
|
` импорт: ${ui}/import/${built.hostToken}`,
|
||||||
|
` игроки: ${ui}/play?room=${built.roomCode}`,
|
||||||
' ─────────────────────────────────────────────',
|
' ─────────────────────────────────────────────',
|
||||||
` на этом компьютере: ${local}/board`,
|
` на этом компьютере: http://localhost:${uiPort}/board`,
|
||||||
hasStatic
|
|
||||||
? ' интерфейс собран; в dev-режиме живой код на порту 5173'
|
|
||||||
: ' интерфейс поднимает Vite: npm run dev',
|
|
||||||
]
|
]
|
||||||
|
|
||||||
|
if (hasStatic && devRunning) {
|
||||||
|
lines.push(` прод-сборка на :${port}: http://localhost:${port}/board`)
|
||||||
|
}
|
||||||
|
if (!devRunning && !hasStatic) {
|
||||||
|
lines.push(' интерфейс поднимает Vite: npm run dev')
|
||||||
|
}
|
||||||
|
|
||||||
console.log(`\n${lines.join('\n')}\n`)
|
console.log(`\n${lines.join('\n')}\n`)
|
||||||
|
if (warnings.length > 0) {
|
||||||
|
console.warn(`⚠ ${warnings.join('\n⚠ ')}\n`)
|
||||||
|
}
|
||||||
|
|
||||||
const shutdown = async (): Promise<void> => {
|
const shutdown = async (): Promise<void> => {
|
||||||
console.log('\nОстанавливаюсь…')
|
console.log('\nОстанавливаюсь…')
|
||||||
|
|||||||
@@ -1019,3 +1019,16 @@ a.ghost {
|
|||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Кнопка импорта должна быть заметной: это единственный вход в контент. */
|
||||||
|
.ghost.accent {
|
||||||
|
border-color: rgba(233, 196, 106, 0.55);
|
||||||
|
color: var(--gold);
|
||||||
|
background: var(--gold-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ghost.accent:hover {
|
||||||
|
border-color: var(--gold);
|
||||||
|
color: #2a1f06;
|
||||||
|
background: linear-gradient(180deg, #f1d288, #d8aa47);
|
||||||
|
}
|
||||||
@@ -147,8 +147,12 @@ function selectCell(key: string): void {
|
|||||||
<span class="spacer" />
|
<span class="spacer" />
|
||||||
<span v-if="room" class="room-tag">комната {{ room }}</span>
|
<span v-if="room" class="room-tag">комната {{ room }}</span>
|
||||||
<span v-if="state" class="phase-badge">{{ label }}</span>
|
<span v-if="state" class="phase-badge">{{ label }}</span>
|
||||||
<RouterLink class="ghost" :to="`/import/${String(route.params.token ?? '')}`" title="Загрузить вопросы из таблицы">
|
<RouterLink
|
||||||
⇪ Импорт
|
class="ghost accent"
|
||||||
|
:to="`/import/${String(route.params.token ?? '')}`"
|
||||||
|
title="Загрузить вопросы из таблицы"
|
||||||
|
>
|
||||||
|
⇪ Импорт вопросов
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
<button v-if="phase !== 'lobby'" class="ghost" title="Начать партию заново" @click="resetGame">
|
<button v-if="phase !== 'lobby'" class="ghost" title="Начать партию заново" @click="resetGame">
|
||||||
⟲ Заново
|
⟲ Заново
|
||||||
@@ -178,6 +182,9 @@ function selectCell(key: string): void {
|
|||||||
<button class="primary big" :disabled="players.length === 0" @click="act({ type: 'startGame' })">
|
<button class="primary big" :disabled="players.length === 0" @click="act({ type: 'startGame' })">
|
||||||
Начать игру
|
Начать игру
|
||||||
</button>
|
</button>
|
||||||
|
<RouterLink class="ghost accent" :to="`/import/${String(route.params.token ?? '')}`">
|
||||||
|
⇪ Загрузить вопросы из таблицы
|
||||||
|
</RouterLink>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<!-- Начало раунда -->
|
<!-- Начало раунда -->
|
||||||
|
|||||||
Reference in new issue
Block a user