-
Notifications
You must be signed in to change notification settings - Fork 44
/
sw.js
248 lines (216 loc) · 5.08 KB
/
sw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
'use strict'
let mStopFlag = true
let mRootDirHandle
function formatSize(n) {
let i = 0
while (n >= 1024) {
n /= 1024
i++
}
if (i === 0) {
return n + 'B'
}
return n.toFixed(1) + 'kMGTP'[i - 1]
}
function escEntity(str, reg) {
return str.replace(reg, s => '&#' + s.charCodeAt(0) + ';')
}
function escHtml(str) {
return escEntity(str, /&|<|>/g)
.replace(/\s/g, ' ')
}
function escAttr(str) {
return escEntity(str, /&|"/g)
}
async function listDir(dirHandle, dirPath) {
const DIR_PREFIX = '\x00' // for sort
const keys = []
const sizeMap = {}
if (dirPath !== '/') {
keys[0] = DIR_PREFIX + '..'
}
for await (const [name, handle] of dirHandle) {
if (handle.kind === 'file') {
keys.push(name)
const file = await handle.getFile()
sizeMap[name] = file.size
} else {
keys.push(DIR_PREFIX + name)
}
}
const tableRows = keys.sort().map(key => {
let icon, size, name
if (key.startsWith(DIR_PREFIX)) {
icon = '📂'
size = ''
name = key.substr(DIR_PREFIX.length) + '/'
} else {
icon = '📄'
size = formatSize(sizeMap[key])
name = key
}
return `\
<tr>
<td class="icon">${icon}</td>
<td class="size">${size}</td>
<td class="name"><a href="${escAttr(name)}">${escHtml(name)}</a></td>
</tr>`
})
const now = new Date().toLocaleString()
const html = `\
<!doctype html>
<html>
<head>
<title>Index of ${escHtml(dirPath)}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<style>
td {
font-family: monospace;
}
td.size {
text-align: right;
width: 4em;
}
td.name {
padding-left: 1em;
}
</style>
</head>
<body>
<h1>Index of ${escHtml(dirPath)}</h1>
<table>
${tableRows.join('\n')}
</table>
<br>
<address>Powered by Service Worker (${now})</address>
</body>
</html>`
return new Response(html, {
headers: {
'content-type': 'text/html',
},
})
}
async function find404(dirHandles) {
for (const dirHandle of dirHandles.reverse()) {
const fileHandle = await getSubFile(dirHandle, '404.html')
if (fileHandle) {
const file = await fileHandle.getFile()
return new Response(file.stream(), {
status: 404,
headers: {
'content-type': file.type,
},
})
}
}
}
function make404() {
return new Response('404 Not Found', {
status: 404,
})
}
async function getSubDir(dirHandle, dirName) {
try {
return await dirHandle.getDirectoryHandle(dirName)
} catch {
}
}
async function getSubFile(dirHandle, fileName) {
try {
return await dirHandle.getFileHandle(fileName)
} catch {
}
}
async function getSubFileOrDir(dirHandle, fileName) {
return await getSubFile(dirHandle, fileName) ||
await getSubDir(dirHandle, fileName)
}
/**
* @param {URL} url
* @param {Request} req
*/
async function respond(url, req) {
if (url.search === '?stop' && req.mode === 'navigate') {
console.log('[sw] stop server')
mStopFlag = true
return Response.redirect('/')
}
if (await mRootDirHandle.queryPermission({mode: 'read'}) !== 'granted') {
console.log('[sw] permission expired')
mStopFlag = true
return Response.redirect('/')
}
const dirNames = decodeURI(url.pathname).replace(/^\/+/, '').split(/\/+/)
const fileName = dirNames.pop() || 'index.html'
const dirHandles = [mRootDirHandle]
let dirHandle = mRootDirHandle
let dirPath = '/'
for (const dir of dirNames) {
dirHandle = await getSubDir(dirHandle, dir)
if (!dirHandle) {
return await find404(dirHandles) || make404()
}
dirHandles.push(dirHandle)
dirPath += `${dir}/`
}
const handle = await getSubFileOrDir(dirHandle, fileName)
if (!handle) {
const res = await find404(dirHandles)
if (res) {
return res
}
return fileName === 'index.html'
? listDir(dirHandle, dirPath)
: make404()
}
if (handle.kind === 'directory') {
return Response.redirect(dirPath + fileName + '/')
}
/** @type {File} */
let file = await handle.getFile()
/** @type {ResponseInit} */
const resOpt = {
headers: {
'content-type': file.type || 'text/plain',
},
}
const range = req.headers.get('range')
if (range) {
// only consider `bytes=begin-end` or `bytes=begin-`
const m = range.match(/bytes=(\d+)-(\d*)/)
if (m) {
const size = file.size
const begin = +m[1]
const end = +m[2] || size
file = file.slice(begin, end)
resOpt.status = 206
resOpt.headers['content-range'] = `bytes ${begin}-${end-1}/${size}`
}
}
resOpt.headers['content-length'] = file.size
return new Response(file.stream(), resOpt)
}
onfetch = (e) => {
if (mStopFlag) {
return
}
console.assert(mRootDirHandle)
const req = e.request
const url = new URL(req.url)
if (url.origin !== location.origin) {
return
}
e.respondWith(respond(url, req))
}
onmessage = (e) => {
if (mStopFlag) {
mRootDirHandle = e.data
mStopFlag = false
e.source.postMessage('GOT')
}
}
onactivate = () => {
clients.claim()
}