hexo-swpp 2.8.9 → 3.0.0-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,265 +0,0 @@
1
- // noinspection JSIgnoredPromiseFromCall
2
-
3
- (() => {
4
- /** 缓存库名称 */
5
- const CACHE_NAME = '@$$[cacheName]'
6
- /** 控制信息存储地址(必须以`/`结尾) */
7
- const CTRL_PATH = 'https://id.v3/'
8
-
9
- // [insertion site] values
10
-
11
- /** 控制信息读写操作 */
12
- const dbVersion = {
13
- write: (id) => caches.open(CACHE_NAME)
14
- .then(cache => cache.put(CTRL_PATH, new Response(JSON.stringify(id)))),
15
- read: () => caches.match(CTRL_PATH).then(response => response?.json())
16
- }
17
-
18
- self.addEventListener('install', () => {
19
- self.skipWaiting()
20
- const escape = '@$$[escape]'
21
- dbVersion.read().then(oldVersion => {
22
- if (oldVersion && oldVersion.escape !== escape) {
23
- oldVersion.escape = escape
24
- // noinspection JSUnresolvedVariable
25
- caches.delete(CACHE_NAME)
26
- .then(() => clients.matchAll())
27
- .then(list => list.forEach(client => client.postMessage({type: 'escape'})))
28
- }
29
- })
30
- })
31
-
32
- // sw 激活后立即对所有页面生效,而非等待刷新
33
- // noinspection JSUnresolvedReference
34
- self.addEventListener('activate', event => event.waitUntil(clients.claim()))
35
-
36
- // noinspection JSFileReferences
37
- const { cacheList, fetchFile, getSpareUrls } = require('../sw-rules')
38
-
39
- // 检查请求是否成功
40
- // noinspection JSUnusedLocalSymbols
41
- const checkResponse = response => response.ok || [301, 302, 307, 308].includes(response.status)
42
-
43
- /**
44
- * 删除指定缓存
45
- * @param list 要删除的缓存列表
46
- * @return {Promise<string[]>} 删除的缓存的URL列表
47
- */
48
- const deleteCache = list => caches.open(CACHE_NAME).then(cache => cache.keys()
49
- .then(keys => Promise.all(
50
- keys.map(async it => {
51
- const url = it.url
52
- if (url !== CTRL_PATH && list.match(url)) {
53
- // [debug delete]
54
- // noinspection ES6MissingAwait
55
- cache.delete(it)
56
- return url
57
- }
58
- return null
59
- })
60
- )).then(list => list.filter(it => it))
61
- )
62
-
63
- self.addEventListener('fetch', event => {
64
- let request = event.request
65
- if (request.method !== 'GET' || !request.url.startsWith('http')) return
66
- // [modifyRequest call]
67
- const url = new URL(request.url)
68
- // [blockRequest call]
69
- const cacheRule = findCache(url)
70
- if (cacheRule) {
71
- let key = `https://${url.host}${url.pathname}`
72
- if (key.endsWith('/index.html')) key = key.substring(0, key.length - 10)
73
- if (cacheRule.search) key += url.search
74
- event.respondWith(caches.match(key)
75
- .then(cache => cache ?? fetchFile(request, true)
76
- .then(response => {
77
- if (checkResponse(response)) {
78
- const clone = response.clone()
79
- caches.open(CACHE_NAME).then(it => it.put(key, clone))
80
- // [debug put]
81
- }
82
- return response
83
- })
84
- )
85
- )
86
- } else {
87
- const spare = getSpareUrls(request.url)
88
- if (spare) event.respondWith(fetchFile(request, false, spare))
89
- // [modifyRequest else-if]
90
- }
91
- })
92
-
93
- self.addEventListener('message', event => {
94
- // [debug message]
95
- if (event.data === 'update')
96
- updateJson().then(info =>
97
- // noinspection JSUnresolvedVariable
98
- event.source.postMessage({
99
- type: 'update',
100
- update: info.list,
101
- version: info.version,
102
- })
103
- )
104
- })
105
-
106
- /** 判断指定url击中了哪一种缓存,都没有击中则返回null */
107
- function findCache(url) {
108
- if (url.hostname === 'localhost') return
109
- for (let key in cacheList) {
110
- const value = cacheList[key]
111
- if (value.match(url)) return value
112
- }
113
- }
114
-
115
- /**
116
- * 根据JSON删除缓存
117
- * @returns {Promise<{version, list}>}
118
- */
119
- function updateJson() {
120
- /**
121
- * 解析elements,并把结果输出到list中
122
- * @return boolean 是否刷新全站缓存
123
- */
124
- const parseChange = (list, elements, ver) => {
125
- for (let element of elements) {
126
- const {version, change} = element
127
- if (version === ver) return false
128
- if (change) {
129
- for (let it of change)
130
- list.push(new CacheChangeExpression(it))
131
- }
132
- }
133
- // 跨版本幅度过大,直接清理全站
134
- return true
135
- }
136
- /** 解析字符串 */
137
- const parseJson = json => dbVersion.read().then(oldVersion => {
138
- const {info, global} = json
139
- const newVersion = {global, local: info[0].version, escape: oldVersion?.escape}
140
- //新用户不进行更新操作
141
- if (!oldVersion) {
142
- dbVersion.write(newVersion)
143
- return newVersion
144
- }
145
- let list = new VersionList()
146
- let refresh = parseChange(list, info, oldVersion.local)
147
- dbVersion.write(newVersion)
148
- // [debug escape]
149
- //如果需要清理全站
150
- if (refresh) {
151
- if (global !== oldVersion.global) list.refresh = true
152
- else list.clean(new CacheChangeExpression({'flag': 'all'}))
153
- }
154
- return {list, version: newVersion}
155
- })
156
- return fetchFile(new Request('/update.json'), false)
157
- .then(response => {
158
- if (checkResponse(response))
159
- return response.json().then(json =>
160
- parseJson(json).then(result => {
161
- return result.list ? deleteCache(result.list)
162
- .then(list => list.length === 0 ? null : list)
163
- .then(list => ({list, version: result.version}))
164
- : {version: result}
165
- }
166
- )
167
- )
168
- else throw `加载 update.json 时遇到异常,状态码:${response.status}`
169
- })
170
- }
171
-
172
- /**
173
- * 版本列表
174
- * @constructor
175
- */
176
- function VersionList() {
177
-
178
- const list = []
179
-
180
- /**
181
- * 推送一个表达式
182
- * @param element {CacheChangeExpression} 要推送的表达式
183
- */
184
- this.push = element => {
185
- list.push(element)
186
- }
187
-
188
- /**
189
- * 清除列表,并将指定元素推入列表中
190
- * @param element {CacheChangeExpression} 要推入的元素,留空表示不推入
191
- */
192
- this.clean = element => {
193
- list.length = 0
194
- if (!element) this.push(element)
195
- }
196
-
197
- /**
198
- * 判断指定 URL 是否和某一条规则匹配
199
- * @param url {string} URL
200
- * @return {boolean}
201
- */
202
- this.match = url => {
203
- if (this.refresh) return true
204
- else {
205
- for (let it of list) {
206
- if (it.match(url)) return true
207
- }
208
- }
209
- return false
210
- }
211
-
212
- }
213
-
214
- // noinspection SpellCheckingInspection
215
- /**
216
- * 缓存更新匹配规则表达式
217
- * @param json 格式{"flag": ..., "value": ...}
218
- * @see https://kmar.top/posts/bcfe8408/#23bb4130
219
- * @constructor
220
- */
221
- function CacheChangeExpression(json) {
222
- const checkCache = url => {
223
- const cache = findCache(new URL(url))
224
- return !cache || cache.clean
225
- }
226
- /**
227
- * 遍历所有value
228
- * @param action {function(string): boolean} 接受value并返回bool的函数
229
- * @return {boolean} 如果value只有一个则返回`action(value)`,否则返回所有运算的或运算(带短路)
230
- */
231
- const forEachValues = action => {
232
- const value = json.value
233
- if (Array.isArray(value)) {
234
- for (let it of value) {
235
- if (action(it)) return true
236
- }
237
- return false
238
- } else return action(value)
239
- }
240
- switch (json['flag']) {
241
- case 'all':
242
- this.match = checkCache
243
- break
244
- case 'html':
245
- this.match = url => url.match(/(\/|\.html)$/)
246
- break
247
- case 'page':
248
- this.match = url => forEachValues(
249
- // \/xxx(\/|\.html)$
250
- value => url.match(new RegExp(`\\/${value}(\\/|\\.html)\$`))
251
- )
252
- break
253
- case 'file':
254
- this.match = url => forEachValues(value => url.endsWith(value))
255
- break
256
- case 'str':
257
- this.match = url => forEachValues(value => url.includes(value))
258
- break
259
- case 'reg':
260
- this.match = url => forEachValues(value => url.match(new RegExp(value, 'i')))
261
- break
262
- default: throw `未知表达式:${JSON.stringify(json)}`
263
- }
264
- }
265
- })()
package/lib/swBuilder.js DELETED
@@ -1,193 +0,0 @@
1
- module.exports = (hexo, hexoConfig, rules, ejectValues) => {
2
- const {config} = rules
3
- const nodePath = require('path')
4
- const fs = require('fs')
5
- const root = hexoConfig.url + (hexoConfig.root ?? '/')
6
-
7
- // noinspection JSUnresolvedVariable
8
- hexo.extend.generator.register('build_service_worker', () => {
9
- if (!config.serviceWorker) return
10
- return {
11
- path: 'sw.js',
12
- data: buildServiceWorker(rules, ejectValues)
13
- }
14
- })
15
-
16
- // 生成注册 sw 的代码
17
- const registerConfig = config.register
18
- if (registerConfig) {
19
- // noinspection JSUnresolvedVariable
20
- hexo.extend.injector.register('head_begin', () => registerConfig.builder(root, hexoConfig, config), "default")
21
- }
22
-
23
- // 插入 sw-dom.js
24
- const domConfig = config.dom
25
- if (domConfig) {
26
- // noinspection JSUnresolvedVariable,HtmlUnknownTarget
27
- hexo.extend.injector.register('body_begin', () => `<script src="/sw-dom.js"></script>`)
28
- // noinspection JSUnresolvedVariable
29
- hexo.extend.generator.register('buildDomJs', () => {
30
- const absPath = module.path + '/sw-dom.js'
31
- const rootPath = nodePath.resolve('./')
32
- const relativePath = nodePath.relative(rootPath, absPath)
33
- const template = fs.readFileSync(relativePath, 'utf-8')
34
- .replaceAll('// ${onSuccess}', `(${domConfig.onsuccess.toString()})()`)
35
- return {
36
- path: 'sw-dom.js',
37
- data: template
38
- }
39
- })
40
- }
41
- }
42
-
43
- /**
44
- * 构建 ServiceWorker 的代码
45
- * @return {string}
46
- */
47
- function buildServiceWorker(rules, ejectValues) {
48
- const nodePath = require('path')
49
- const fs = require('fs')
50
- const {getSource} = require('./utils')
51
- const {
52
- modifyRequest,
53
- fetchNoCache,
54
- getCdnList,
55
- getSpareUrls,
56
- blockRequest,
57
- config
58
- } = rules
59
- const absPath = module.path + '/sw-template.js'
60
- const rootPath = nodePath.resolve('./')
61
- const relativePath = nodePath.relative(rootPath, absPath)
62
- const serviceWorkerConfig = config.serviceWorker
63
- // 获取拓展文件
64
- let cache = getSource(rules, '\n\n', [
65
- 'cacheList', 'modifyRequest', 'getCdnList', 'getSpareUrls', 'blockRequest',
66
- ...('external' in rules && Array.isArray(rules.external) ? rules.external : [])
67
- ])
68
- if (!fetchNoCache) {
69
- if (getCdnList)
70
- cache += JS_CODE_GET_CDN_LIST
71
- else if (getSpareUrls)
72
- cache += JS_CODE_GET_SPARE_URLS
73
- else
74
- cache += JS_CODE_DEF_FETCH_FILE
75
- }
76
- if (!getSpareUrls) cache += `\nconst getSpareUrls = _ => {}`
77
- if ('afterJoin' in rules)
78
- cache += `(${getSource(rules.afterJoin)})()\n`
79
- if ('afterTheme' in rules)
80
- cache += `(${getSource(rules.afterTheme)})()\n`
81
- const keyword = "const { cacheList, fetchFile, getSpareUrls } = require('../sw-rules')"
82
- // noinspection JSUnresolvedVariable
83
- let swContent = fs.readFileSync(relativePath, 'utf8')
84
- .replaceAll("// [insertion site] values", ejectValues ?? '')
85
- .replaceAll(keyword, cache)
86
- .replaceAll("'@$$[escape]'", (serviceWorkerConfig.escape).toString())
87
- .replaceAll("'@$$[cacheName]'", `'${serviceWorkerConfig.cacheName}'`)
88
- if (modifyRequest) {
89
- swContent = swContent.replaceAll('// [modifyRequest call]', `
90
- const modify = modifyRequest(request)
91
- if (modify) request = modify
92
- `).replaceAll('// [modifyRequest else-if]', `
93
- else if (modify) event.respondWith(fetch(request))
94
- `)
95
- }
96
- if (blockRequest) {
97
- swContent = swContent.replace('// [blockRequest call]', `
98
- if (blockRequest(url))
99
- return event.respondWith(new Response(null, {status: 208}))
100
- `)
101
- }
102
- // noinspection JSUnresolvedVariable
103
- if (serviceWorkerConfig.debug) {
104
- swContent = swContent.replaceAll('// [debug delete]', `
105
- console.debug(\`delete cache: \${url}\`)
106
- `).replaceAll('// [debug put]', `
107
- console.debug(\`put cache: \${key}\`)
108
- `).replaceAll('// [debug message]', `
109
- console.debug(\`receive: \${event.data}\`)
110
- `).replaceAll('// [debug escape]', `
111
- console.debug(\`escape: \${aid}\`)
112
- `)
113
- }
114
- return swContent
115
- }
116
-
117
- // 缺省的 fetchFile 函数的代码
118
- const JS_CODE_DEF_FETCH_FILE = `
119
- const fetchFile = (request, banCache) => fetch(request, {
120
- cache: banCache ? "no-store" : "default",
121
- mode: 'cors',
122
- credentials: 'same-origin'
123
- })
124
- `
125
-
126
- // getCdnList 函数的代码
127
- const JS_CODE_GET_CDN_LIST = `
128
- const fetchFile = (request, banCache) => {
129
- const fetchArgs = {
130
- cache: banCache ? 'no-store' : 'default',
131
- mode: 'cors',
132
- credentials: 'same-origin'
133
- }
134
- const list = getCdnList(request.url)
135
- if (!list || !Promise.any) return fetch(request, fetchArgs)
136
- const res = list.map(url => new Request(url, request))
137
- const controllers = []
138
- return Promise.any(res.map(
139
- (it, index) => fetch(it, Object.assign(
140
- {signal: (controllers[index] = new AbortController()).signal},
141
- fetchArgs
142
- )).then(response => checkResponse(response) ? {index, response} : Promise.reject())
143
- )).then(it => {
144
- for (let i in controllers) {
145
- if (i != it.index) controllers[i].abort()
146
- }
147
- return it.response
148
- })
149
- }
150
- `
151
-
152
- // getSpareUrls 函数的代码
153
- const JS_CODE_GET_SPARE_URLS = `
154
- const fetchFile = (request, banCache, spare = null) => {
155
- const fetchArgs = {
156
- cache: banCache ? 'no-store' : 'default',
157
- mode: 'cors',
158
- credentials: 'same-origin'
159
- }
160
- if (!spare) spare = getSpareUrls(request.url)
161
- if (!spare) return fetch(request, fetchArgs)
162
- const list = spare.list
163
- const controllers = []
164
- let error = 0
165
- return new Promise((resolve, reject) => {
166
- const pull = () => {
167
- const flag = controllers.length
168
- if (flag === list.length) return
169
- const plusError = () => {
170
- if (++error === list.length) reject(\`请求 \${request.url} 失败\`)
171
- else if (flag + 1 === controllers.length) {
172
- clearTimeout(controllers[flag].id)
173
- pull()
174
- }
175
- }
176
- controllers.push({
177
- ctrl: new AbortController(),
178
- id: setTimeout(pull, spare.timeout)
179
- })
180
- fetch(new Request(list[flag], request), fetchArgs).then(response => {
181
- if (checkResponse(response)) {
182
- for (let i in controllers) {
183
- if (i !== flag) controllers[i].ctrl.abort()
184
- clearTimeout(controllers[i].id)
185
- }
186
- resolve(response)
187
- } else plusError()
188
- }).catch(plusError)
189
- }
190
- pull()
191
- })
192
- }
193
- `
package/lib/utils.js DELETED
@@ -1,50 +0,0 @@
1
- const logger = require('hexo-log')()
2
-
3
- /**
4
- * 获取任意对象(symbol 类型除外)的源码
5
- * @param any {any} 对象
6
- * @param separator {string} 分隔符
7
- * @param whiteList {string[]?} 白名单
8
- * @param mapper {?function(string):string} 输出转换函数
9
- * @return {string}
10
- */
11
- function getSource(any, separator = '\n', whiteList = null, mapper = null) {
12
- let result
13
- switch (typeof any) {
14
- case 'undefined':
15
- result = `undefined${separator}`
16
- break
17
- case 'object': {
18
- result = whiteList ? '' : '{\n'
19
- result += Object.getOwnPropertyNames(any)
20
- .filter(key => !whiteList || whiteList.includes(key))
21
- .map(key => {
22
- const value = any[key]
23
- let nextMapper = null
24
- if (whiteList && ['cacheList', 'modifyRequest'].includes(key)) {
25
- nextMapper = str => str.replace(/\(\s*(.*?)\s*,\s*\$eject\s*\)/g, "$1")
26
- .replaceAll(/\$eject\.(\w+)/g, (_, match) => `eject${match[0].toUpperCase()}${match.substring(1)}`)
27
- }
28
- return whiteList ? `const ${key} = ${getSource(value, '', null, nextMapper)}` : `${key}: ${getSource(value, '')}`
29
- }).join(whiteList ? '\n' : ',\n')
30
- result += (whiteList ? '' : '\n}') + separator
31
- break
32
- }
33
- case 'string':
34
- result = `'${any}'${separator}`
35
- break
36
- case 'bigint':
37
- result = `${any.toString()}n${separator}`
38
- break
39
- default:
40
- result = any.toString() + separator
41
- break
42
- case 'symbol':
43
- logger.error("[SWPP ServiceWorkerBuilder] 不支持写入 symbol 类型,请从 sw-rules.js 中移除相关内容!")
44
- throw '不支持写入 symbol 类型'
45
- }
46
- if (mapper) result = mapper(result)
47
- return result
48
- }
49
-
50
- module.exports = { getSource }