https -> http2

pull/1/head
yutent 2023-06-13 15:32:19 +08:00
parent 9966e3ac9a
commit aba20ae873
4 changed files with 64 additions and 47 deletions

View File

@ -6,16 +6,11 @@
import fs from 'iofs' import fs from 'iofs'
import scss from '@bytedo/sass' import scss from '@bytedo/sass'
import { createHash, randomUUID } from 'node:crypto'
import Es from 'esbuild' import Es from 'esbuild'
import { join } from 'node:path'
import { compile } from '@vue/compiler-dom' import { compile } from '@vue/compiler-dom'
import { red, cyan, blue } from 'kolorist' import { red, cyan, blue } from 'kolorist'
function uuid() {
return randomUUID().slice(-8)
}
import { import {
JS_EXP, JS_EXP,
STYLE_EXP, STYLE_EXP,
@ -25,23 +20,13 @@ import {
PERCENT_EXP, PERCENT_EXP,
SHEETS_DEF SHEETS_DEF
} from './constants.js' } from './constants.js'
import { createHmrScript } from './utils.js' import { createHmrScript, md5, uuid, urlJoin } from './utils.js'
const OPTIONS = { const OPTIONS = {
style: 'compressed' style: 'compressed'
} }
// 修正路径合并 避免在windows下被转义 // 处理css中的 :deep()
function urlJoin(...args) {
return join(...args).replace(/\\/g, '/')
}
function md5(str = '') {
let sum = createHash('md5')
sum.update(str, 'utf8')
return sum.digest('hex').slice(0, 8)
}
function parseVDeep(curr, val, scoped) { function parseVDeep(curr, val, scoped) {
let res = V_DEEP.exec(curr) let res = V_DEEP.exec(curr)
if (res) { if (res) {
@ -52,6 +37,7 @@ function parseVDeep(curr, val, scoped) {
} }
} }
// 处理style中的scoped属性
function scopeCss(css = '', hash) { function scopeCss(css = '', hash) {
return css.replace(CSS_SHEET_EXP, (m, selector) => { return css.replace(CSS_SHEET_EXP, (m, selector) => {
if (!selector.startsWith('@')) { if (!selector.startsWith('@')) {
@ -415,16 +401,22 @@ function render(_ctx, _cache) {
/** /**
* 解析模板html * 解析模板html
*/ */
export function parseHtml(html, { page, imports, entry, LEGACY_MODE }) { export function parseHtml(
html,
{ page, imports, entry, LEGACY_MODE, session }
) {
return html return html
.replace(/\r\n/g, '\n') .replace(/\r\n/g, '\n')
.replace( .replace(
'</head>', '</head>',
`${ `${
process.env.NODE_ENV === 'development' process.env.NODE_ENV === 'development'
? ` <script>${Es.transformSync(createHmrScript(LEGACY_MODE), { ? ` <script>${Es.transformSync(
createHmrScript(LEGACY_MODE, session),
{
minify: true minify: true
}).code.trim()}</script>\n` }
).code.trim()}</script>\n`
: '' : ''
}</head>` }</head>`
) )

View File

@ -1,5 +1,5 @@
import http from 'node:http' import http from 'node:http'
import https from 'node:https' import https from 'node:http2'
import fs from 'iofs' import fs from 'iofs'
import { join, dirname } from 'node:path' import { join, dirname } from 'node:path'
import { parse } from 'node:url' import { parse } from 'node:url'
@ -7,7 +7,7 @@ import socket from './ws.js'
import chokidar from 'chokidar' import chokidar from 'chokidar'
import { red } from 'kolorist' import { red } from 'kolorist'
import { friendlyErrors, isCustomElement } from './utils.js' import { friendlyErrors, isCustomElement, md5 } from './utils.js'
import { compileScss, parseJs, compileVue, parseHtml } from './compile-vue.js' import { compileScss, parseJs, compileVue, parseHtml } from './compile-vue.js'
@ -15,7 +15,7 @@ import MIME_TYPES from './mime-tpyes.js'
import { COMMON_HEADERS } from './constants.js' import { COMMON_HEADERS } from './constants.js'
const noc = Buffer.from('') const noc = Buffer.from('')
const SERVER_OPTIONS = {} const SERVER_OPTIONS = { allowHTTP1: true }
const CACHE = {} //文件缓存, 用于hmr const CACHE = {} //文件缓存, 用于hmr
function readFile(file) { function readFile(file) {
@ -50,7 +50,7 @@ export default async function createServer(root = '', conf = {}) {
} }
const server = (USE_HTTPS ? https : http) const server = (USE_HTTPS ? https : http)
.createServer(SERVER_OPTIONS) [USE_HTTPS ? 'createSecureServer' : 'createServer'](SERVER_OPTIONS)
.listen(PORT) .listen(PORT)
const ws = socket(server) const ws = socket(server)
@ -80,7 +80,7 @@ export default async function createServer(root = '', conf = {}) {
if (prefix && req.url === '/') { if (prefix && req.url === '/') {
res.setHeader('Location', DEPLOY_PATH) res.setHeader('Location', DEPLOY_PATH)
res.writeHead(302, 'Redirect') res.writeHead(302, USE_HTTPS ? void 0 : 'Redirect')
return res.end('') return res.end('')
} }
@ -105,7 +105,7 @@ export default async function createServer(root = '', conf = {}) {
pageName = tmp.join('.') pageName = tmp.join('.')
// 页面不存在时输出404, 避免进程崩溃退出 // 页面不存在时输出404, 避免进程崩溃退出
if (!conf.pages[pageName]) { if (!conf.pages[pageName]) {
res.writeHead(404, 'Not Found') res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
return res.end(`Oops!!! 404 Not Found`) return res.end(`Oops!!! 404 Not Found`)
} }
@ -143,7 +143,7 @@ export default async function createServer(root = '', conf = {}) {
if (isIndex) { if (isIndex) {
res.setHeader('content-type', MIME_TYPES.html) res.setHeader('content-type', MIME_TYPES.html)
res.writeHead(200, 'OK') res.writeHead(200, USE_HTTPS ? void 0 : 'OK')
res.end( res.end(
'<div>注意: 你看到这个页面, 仅在开发时可见。<br>仅为了方便开发多页应用时访问自己想要修改的页面, 而不需要手动输入地址。</div><ul>' + '<div>注意: 你看到这个页面, 仅在开发时可见。<br>仅为了方便开发多页应用时访问自己想要修改的页面, 而不需要手动输入地址。</div><ul>' +
indexPage + indexPage +
@ -175,7 +175,8 @@ export default async function createServer(root = '', conf = {}) {
page, page,
imports: conf.imports, imports: conf.imports,
entry, entry,
LEGACY_MODE LEGACY_MODE,
session: md5(page.entry)
}) })
} }
@ -198,7 +199,7 @@ export default async function createServer(root = '', conf = {}) {
} }
if (!fs.isfile(file)) { if (!fs.isfile(file)) {
friendlyErrors(pathname, ext) friendlyErrors(pathname, ext)
res.writeHead(404, 'Not Found') res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
res.end('') res.end('')
return return
} }
@ -227,14 +228,14 @@ export default async function createServer(root = '', conf = {}) {
if (!fs.isfile(file)) { if (!fs.isfile(file)) {
friendlyErrors(pathname, ext) friendlyErrors(pathname, ext)
res.writeHead(404, 'Not Found') res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
res.end('') res.end('')
return return
} }
} }
if (file === conf.inject?.scss) { if (file === conf.inject?.scss) {
console.log(red('设置为注入的样式文件不可被vue/js文件引用\n')) console.log(red('设置为注入的样式文件不可被vue/js文件引用\n'))
res.writeHead(404, 'Not Found') res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
res.end('') res.end('')
return return
} }
@ -265,7 +266,7 @@ export default async function createServer(root = '', conf = {}) {
code = fs.cat(join(PUBLIC_DIR, rpath)) code = fs.cat(join(PUBLIC_DIR, rpath))
} else { } else {
friendlyErrors(rpath, ext) friendlyErrors(rpath, ext)
res.writeHead(404, 'Not Found') res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
res.end('') res.end('')
return return
} }
@ -308,7 +309,7 @@ export default async function createServer(root = '', conf = {}) {
} }
if (code === null) { if (code === null) {
friendlyErrors(pathname, ext) friendlyErrors(pathname, ext)
res.writeHead(404, 'Not Found') res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
res.end('') res.end('')
return return
} }
@ -316,7 +317,7 @@ export default async function createServer(root = '', conf = {}) {
} }
res.setHeader('content-length', Buffer.byteLength(code || noc)) res.setHeader('content-length', Buffer.byteLength(code || noc))
res.writeHead(200, 'OK') res.writeHead(200, USE_HTTPS ? void 0 : 'OK')
res.end(code || noc) res.end(code || noc)
} }
}) })

View File

@ -4,8 +4,25 @@
* @date 2023/05/22 14:52:00 * @date 2023/05/22 14:52:00
*/ */
import { red, cyan, blue } from 'kolorist' import { createHash, randomUUID } from 'node:crypto'
import { join } from 'node:path'
import { Worker } from 'node:worker_threads' import { Worker } from 'node:worker_threads'
import { red, cyan, blue } from 'kolorist'
// 修正路径合并 避免在windows下被转义
export function urlJoin(...args) {
return join(...args).replace(/\\/g, '/')
}
export function uuid() {
return randomUUID().slice(-8)
}
export function md5(str = '') {
let sum = createHash('md5')
sum.update(str, 'utf8')
return sum.digest('hex').slice(0, 8)
}
export function friendlyErrors(pathname, ext = '') { export function friendlyErrors(pathname, ext = '') {
console.log(cyan(pathname), red(`not found!!!`)) console.log(cyan(pathname), red(`not found!!!`))
@ -15,10 +32,10 @@ export function friendlyErrors(pathname, ext = '') {
) )
} }
export function createHmrScript(legacy) { export function createHmrScript(legacy, session = '') {
return ` return `
!(function vue_live_hmr(){ !(function vue_live_hmr(){
var ws = new WebSocket(\`ws\${location.protocol === 'https:' ? 's' : ''}://\${location.host}/ws-fite-hmr\`) var ws = new WebSocket(\`ws\${location.protocol === 'https:' ? 's' : ''}://\${location.host}/ws-fite-hmr?session=${session}\`)
ws.addEventListener('open', function (r) { ws.addEventListener('open', function (r) {
if(vue_live_hmr.closed){ if(vue_live_hmr.closed){

View File

@ -6,17 +6,22 @@
import { WebSocketServer } from 'ws' import { WebSocketServer } from 'ws'
class WebSocket { class WebSocket {
#ws = null // ws实例 #clients = new Map()
#queue = [] // 消息队列 #queue = [] // 消息队列
constructor(server) { constructor(server) {
if (server.listening) { if (server.listening) {
let conn = new WebSocketServer({ server, path: '/ws-fite-hmr' }) let conn = new WebSocketServer({ server, path: '/ws-fite-hmr' })
conn.on('connection', ws => { conn.on('connection', (client, req) => {
this.#ws = ws let params = new URLSearchParams(req.url.slice(req.url.indexOf('?')))
// ws.on('message', data => { let session = params.get('session')
// console.log(data + '');
// }) this.#clients.set(session, client)
client.once('close', _ => {
this.#clients.delete(session)
})
while (this.#queue.length) { while (this.#queue.length) {
let msg = this.#queue.shift() let msg = this.#queue.shift()
this.send(msg) this.send(msg)
@ -26,8 +31,10 @@ class WebSocket {
} }
send(msg = {}) { send(msg = {}) {
if (this.#ws) { if (this.#clients.size) {
this.#ws.send(JSON.stringify(msg)) for (let [key, client] of this.#clients.entries()) {
client.send(JSON.stringify(msg))
}
} else { } else {
this.#queue.push(msg) this.#queue.push(msg)
} }