swpp-backends 0.0.1-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.
- package/LICENSE +661 -0
- package/README.md +5 -0
- package/dist/SwppConfig.js +2 -0
- package/dist/UpdateJsonBuilder.js +281 -0
- package/dist/VersionAnalyzer.js +62 -0
- package/dist/fileAnalyzer.js +448 -0
- package/dist/index.js +35 -0
- package/dist/resources/sw-dom.js +51 -0
- package/dist/resources/sw-template.js +257 -0
- package/dist/serviceWorkerBuilder.js +152 -0
- package/dist/swppRules.js +117 -0
- package/dist/utils.js +188 -0
- package/package.json +37 -0
- package/types/SwppConfig.d.ts +125 -0
- package/types/UpdateJsonBuilder.d.ts +50 -0
- package/types/VersionAnalyzer.d.ts +29 -0
- package/types/fileAnalyzer.d.ts +147 -0
- package/types/index.d.ts +54 -0
- package/types/serviceWorkerBuilder.d.ts +7 -0
- package/types/swppRules.d.ts +101 -0
- package/types/utils.d.ts +41 -0
|
@@ -0,0 +1,257 @@
|
|
|
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,JSCheckFunctionSignatures
|
|
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
|
+
const 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
|
+
const getMatch = () => {
|
|
241
|
+
switch (json['flag']) {
|
|
242
|
+
case 'html':
|
|
243
|
+
return url => url.match(/(\/|\.html)$/)
|
|
244
|
+
case 'end':
|
|
245
|
+
return url => forEachValues(value => url.endsWith(value))
|
|
246
|
+
case 'begin':
|
|
247
|
+
return url => forEachValues(value => url.startsWith(value))
|
|
248
|
+
case 'str':
|
|
249
|
+
return url => forEachValues(value => url.includes(value))
|
|
250
|
+
case 'reg':
|
|
251
|
+
return url => forEachValues(value => url.match(new RegExp(value, 'i')))
|
|
252
|
+
default: throw `未知表达式:${JSON.stringify(json)}`
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
this.match = getMatch()
|
|
256
|
+
}
|
|
257
|
+
})()
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.buildServiceWorker = void 0;
|
|
7
|
+
const SwppRules_1 = require("./SwppRules");
|
|
8
|
+
const Utils_1 = require("./Utils");
|
|
9
|
+
const fs_1 = __importDefault(require("fs"));
|
|
10
|
+
const path_1 = __importDefault(require("path"));
|
|
11
|
+
/**
|
|
12
|
+
* 构建 sw
|
|
13
|
+
*
|
|
14
|
+
* + **执行该函数前必须调用过 [loadRules]**
|
|
15
|
+
* + **执行该函数前必须调用过 [calcEjectValues]**
|
|
16
|
+
*/
|
|
17
|
+
function buildServiceWorker() {
|
|
18
|
+
const rules = (0, SwppRules_1.readRules)();
|
|
19
|
+
const eject = (0, Utils_1.readEjectData)();
|
|
20
|
+
const { modifyRequest, fetchFile, getRaceUrls, getSpareUrls, blockRequest, config } = rules;
|
|
21
|
+
const serviceWorkerConfig = config.serviceWorker;
|
|
22
|
+
const templatePath = path_1.default.resolve('./', module.path, 'sw-template.js');
|
|
23
|
+
// 获取拓展文件
|
|
24
|
+
let cache = (0, Utils_1.getSource)(rules, undefined, [
|
|
25
|
+
'cacheList', 'modifyRequest', 'getCdnList', 'getSpareUrls', 'blockRequest', 'fetchFile',
|
|
26
|
+
...('external' in rules && Array.isArray(rules.external) ? rules.external : [])
|
|
27
|
+
], true) + '\n';
|
|
28
|
+
if (!fetchFile) {
|
|
29
|
+
if (getRaceUrls)
|
|
30
|
+
cache += JS_CODE_GET_CDN_LIST;
|
|
31
|
+
else if (getSpareUrls)
|
|
32
|
+
cache += JS_CODE_GET_SPARE_URLS;
|
|
33
|
+
else
|
|
34
|
+
cache += JS_CODE_DEF_FETCH_FILE;
|
|
35
|
+
}
|
|
36
|
+
if (!getSpareUrls)
|
|
37
|
+
cache += `\nconst getSpareUrls = _ => {}`;
|
|
38
|
+
if ('afterJoin' in rules)
|
|
39
|
+
cache += `(${(0, Utils_1.getSource)(rules['afterJoin'])})()\n`;
|
|
40
|
+
if ('afterTheme' in rules)
|
|
41
|
+
cache += `(${(0, Utils_1.getSource)(rules['afterTheme'])})()\n`;
|
|
42
|
+
const keyword = "const { cacheList, fetchFile, getSpareUrls } = require('../sw-rules')";
|
|
43
|
+
// noinspection JSUnresolvedVariable
|
|
44
|
+
let content = fs_1.default.readFileSync(templatePath, 'utf8')
|
|
45
|
+
.replaceAll("// [insertion site] values", eject.strValue ?? '')
|
|
46
|
+
.replaceAll(keyword, cache)
|
|
47
|
+
.replaceAll("'@$$[escape]'", (serviceWorkerConfig.escape).toString())
|
|
48
|
+
.replaceAll("'@$$[cacheName]'", `'${serviceWorkerConfig.cacheName}'`);
|
|
49
|
+
if (modifyRequest) {
|
|
50
|
+
content = content.replaceAll('// [modifyRequest call]', `
|
|
51
|
+
const modify = modifyRequest(request)
|
|
52
|
+
if (modify) request = modify
|
|
53
|
+
`).replaceAll('// [modifyRequest else-if]', `
|
|
54
|
+
else if (modify) event.respondWith(fetch(request))
|
|
55
|
+
`);
|
|
56
|
+
}
|
|
57
|
+
if (blockRequest) {
|
|
58
|
+
content = content.replace('// [blockRequest call]', `
|
|
59
|
+
if (blockRequest(url))
|
|
60
|
+
return event.respondWith(new Response(null, {status: 208}))
|
|
61
|
+
`);
|
|
62
|
+
}
|
|
63
|
+
// noinspection JSUnresolvedVariable
|
|
64
|
+
if (serviceWorkerConfig.debug) {
|
|
65
|
+
content = content.replaceAll('// [debug delete]', `
|
|
66
|
+
console.debug(\`delete cache: \${url}\`)
|
|
67
|
+
`).replaceAll('// [debug put]', `
|
|
68
|
+
console.debug(\`put cache: \${key}\`)
|
|
69
|
+
`).replaceAll('// [debug message]', `
|
|
70
|
+
console.debug(\`receive: \${event.data}\`)
|
|
71
|
+
`).replaceAll('// [debug escape]', `
|
|
72
|
+
console.debug(\`escape: \${aid}\`)
|
|
73
|
+
`);
|
|
74
|
+
}
|
|
75
|
+
return content;
|
|
76
|
+
}
|
|
77
|
+
exports.buildServiceWorker = buildServiceWorker;
|
|
78
|
+
// 缺省的 fetchFile 函数的代码
|
|
79
|
+
const JS_CODE_DEF_FETCH_FILE = `
|
|
80
|
+
const fetchFile = (request, banCache) => fetch(request, {
|
|
81
|
+
cache: banCache ? "no-store" : "default",
|
|
82
|
+
mode: 'cors',
|
|
83
|
+
credentials: 'same-origin'
|
|
84
|
+
})
|
|
85
|
+
`;
|
|
86
|
+
// getCdnList 函数的代码
|
|
87
|
+
const JS_CODE_GET_CDN_LIST = `
|
|
88
|
+
const fetchFile = (request, banCache) => {
|
|
89
|
+
const fetchArgs = {
|
|
90
|
+
cache: banCache ? 'no-store' : 'default',
|
|
91
|
+
mode: 'cors',
|
|
92
|
+
credentials: 'same-origin'
|
|
93
|
+
}
|
|
94
|
+
const list = getCdnList(request.url)
|
|
95
|
+
if (!list || !Promise.any) return fetch(request, fetchArgs)
|
|
96
|
+
const res = list.map(url => new Request(url, request))
|
|
97
|
+
const controllers = []
|
|
98
|
+
return Promise.any(res.map(
|
|
99
|
+
(it, index) => fetch(it, Object.assign(
|
|
100
|
+
{signal: (controllers[index] = new AbortController()).signal},
|
|
101
|
+
fetchArgs
|
|
102
|
+
)).then(response => checkResponse(response) ? {index, response} : Promise.reject())
|
|
103
|
+
)).then(it => {
|
|
104
|
+
for (let i in controllers) {
|
|
105
|
+
if (i != it.index) controllers[i].abort()
|
|
106
|
+
}
|
|
107
|
+
return it.response
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
`;
|
|
111
|
+
// getSpareUrls 函数的代码
|
|
112
|
+
const JS_CODE_GET_SPARE_URLS = `
|
|
113
|
+
const fetchFile = (request, banCache, spare = null) => {
|
|
114
|
+
const fetchArgs = {
|
|
115
|
+
cache: banCache ? 'no-store' : 'default',
|
|
116
|
+
mode: 'cors',
|
|
117
|
+
credentials: 'same-origin'
|
|
118
|
+
}
|
|
119
|
+
if (!spare) spare = getSpareUrls(request.url)
|
|
120
|
+
if (!spare) return fetch(request, fetchArgs)
|
|
121
|
+
const list = spare.list
|
|
122
|
+
const controllers = []
|
|
123
|
+
let error = 0
|
|
124
|
+
return new Promise((resolve, reject) => {
|
|
125
|
+
const pull = () => {
|
|
126
|
+
const flag = controllers.length
|
|
127
|
+
if (flag === list.length) return
|
|
128
|
+
const plusError = () => {
|
|
129
|
+
if (++error === list.length) reject(\`请求 \${request.url} 失败\`)
|
|
130
|
+
else if (flag + 1 === controllers.length) {
|
|
131
|
+
clearTimeout(controllers[flag].id)
|
|
132
|
+
pull()
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
controllers.push({
|
|
136
|
+
ctrl: new AbortController(),
|
|
137
|
+
id: setTimeout(pull, spare.timeout)
|
|
138
|
+
})
|
|
139
|
+
fetch(new Request(list[flag], request), fetchArgs).then(response => {
|
|
140
|
+
if (checkResponse(response)) {
|
|
141
|
+
for (let i in controllers) {
|
|
142
|
+
if (i !== flag) controllers[i].ctrl.abort()
|
|
143
|
+
clearTimeout(controllers[i].id)
|
|
144
|
+
}
|
|
145
|
+
resolve(response)
|
|
146
|
+
} else plusError()
|
|
147
|
+
}).catch(plusError)
|
|
148
|
+
}
|
|
149
|
+
pull()
|
|
150
|
+
})
|
|
151
|
+
}
|
|
152
|
+
`;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.loadRules = exports.addRulesMapEvent = exports.readRules = void 0;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const defConfig = {
|
|
10
|
+
serviceWorker: {
|
|
11
|
+
escape: 0,
|
|
12
|
+
cacheName: 'kmarBlogCache',
|
|
13
|
+
debug: false
|
|
14
|
+
},
|
|
15
|
+
register: {
|
|
16
|
+
onerror: () => console.error('Service Worker 注册失败!可能是由于您的浏览器不支持该功能!'),
|
|
17
|
+
builder: (root, _, pluginConfig) => {
|
|
18
|
+
const registerConfig = pluginConfig.register;
|
|
19
|
+
const { onerror, onsuccess } = registerConfig;
|
|
20
|
+
return `<script>
|
|
21
|
+
(() => {
|
|
22
|
+
let sw = navigator.serviceWorker
|
|
23
|
+
let error = ${onerror.toString()}
|
|
24
|
+
if (!sw?.register('${new URL(root).pathname}sw.js')
|
|
25
|
+
${onsuccess ? '?.then(' + onsuccess.toString() + ')' : ''}
|
|
26
|
+
?.catch(error)
|
|
27
|
+
) error()
|
|
28
|
+
})()
|
|
29
|
+
</script>`;
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
dom: {},
|
|
33
|
+
json: {
|
|
34
|
+
maxHtml: 15,
|
|
35
|
+
charLimit: 1024,
|
|
36
|
+
merge: [],
|
|
37
|
+
exclude: {
|
|
38
|
+
localhost: [/^\/sw\.js$/],
|
|
39
|
+
other: []
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
external: {
|
|
43
|
+
timeout: 5000,
|
|
44
|
+
js: [],
|
|
45
|
+
stable: [],
|
|
46
|
+
replacer: it => it
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
const eventList = [];
|
|
50
|
+
let _rules;
|
|
51
|
+
/**
|
|
52
|
+
* 读取最后一次构建的 rules
|
|
53
|
+
*
|
|
54
|
+
* **执行该函数前必须调用过 [loadRules]**
|
|
55
|
+
*/
|
|
56
|
+
function readRules() {
|
|
57
|
+
if (!_rules)
|
|
58
|
+
throw 'rules 尚未初始化';
|
|
59
|
+
return _rules;
|
|
60
|
+
}
|
|
61
|
+
exports.readRules = readRules;
|
|
62
|
+
/**
|
|
63
|
+
* 添加一个 rules 映射事件,这个事件允许用户修改 rules 的内容
|
|
64
|
+
*
|
|
65
|
+
* 执行时按照注册的顺序执行
|
|
66
|
+
*/
|
|
67
|
+
function addRulesMapEvent(mapper) {
|
|
68
|
+
eventList.push(mapper);
|
|
69
|
+
}
|
|
70
|
+
exports.addRulesMapEvent = addRulesMapEvent;
|
|
71
|
+
/**
|
|
72
|
+
* 加载 rules 文件
|
|
73
|
+
* @param root 项目根目录
|
|
74
|
+
* @param fileName rules 文件名称
|
|
75
|
+
* @param selects 附加的可选目录,优先级低于 [root]
|
|
76
|
+
*/
|
|
77
|
+
function loadRules(root, fileName, selects) {
|
|
78
|
+
// 支持的拓展名
|
|
79
|
+
const extensions = ['cjs', 'js'];
|
|
80
|
+
// 根目录下的 rules 文件
|
|
81
|
+
const rootPath = extensions.map(it => path_1.default.resolve(root, `${fileName}.${it}`))
|
|
82
|
+
.find(it => fs_1.default.existsSync(it));
|
|
83
|
+
// 其它可选目录下的 rules 文件
|
|
84
|
+
const selectPath = selects.flatMap(value => extensions.map(it => path_1.default.resolve(value, `${fileName}.${it}`))).find(it => fs_1.default.existsSync(it));
|
|
85
|
+
if (!(rootPath || selectPath))
|
|
86
|
+
throw '未查询到 rules 文件';
|
|
87
|
+
const rootRules = rootPath ? { ...require(rootPath) } : {};
|
|
88
|
+
const selectRules = selectPath ? require(selectPath) : {};
|
|
89
|
+
const config = rootRules.config ?? {};
|
|
90
|
+
mergeConfig(config, selectRules.config ?? {});
|
|
91
|
+
mergeConfig(config, defConfig);
|
|
92
|
+
Object.assign(rootRules, selectRules);
|
|
93
|
+
rootRules.config = config;
|
|
94
|
+
for (let event of eventList) {
|
|
95
|
+
event(rootRules);
|
|
96
|
+
}
|
|
97
|
+
return _rules = rootRules;
|
|
98
|
+
}
|
|
99
|
+
exports.loadRules = loadRules;
|
|
100
|
+
/** 合并配置项 */
|
|
101
|
+
function mergeConfig(dist, that) {
|
|
102
|
+
for (let key in that) {
|
|
103
|
+
const distValue = dist[key];
|
|
104
|
+
const thatValue = that[key];
|
|
105
|
+
if (!thatValue)
|
|
106
|
+
continue;
|
|
107
|
+
switch (typeof distValue) {
|
|
108
|
+
case "undefined":
|
|
109
|
+
dist[key] = thatValue;
|
|
110
|
+
break;
|
|
111
|
+
case "object":
|
|
112
|
+
mergeConfig(distValue, thatValue);
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return dist;
|
|
117
|
+
}
|