hexo-swpp 2.2.3 → 2.3.0-beta.0

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/index.js CHANGED
@@ -2,659 +2,17 @@
2
2
 
3
3
  "use strict"
4
4
 
5
- const fs = require('fs')
6
- const logger = require('hexo-log')()
7
- const fetch = require('node-fetch')
8
- const nodePath = require('path')
9
- const crypto = require("crypto")
10
- const cheerio = require('cheerio')
11
- const postcss = require('postcss')
12
-
13
- const findScript = () => nodePath.resolve('./', 'sw-rules')
14
-
15
5
  const config = hexo.config
16
6
  const pluginConfig = config.swpp || hexo.theme.config
17
- const root = config.url + (config.root ?? '/')
18
- const domain = new URL(root).hostname
19
- const {
20
- cacheList,
21
- modifyRequest,
22
- fetchNoCache,
23
- getCdnList,
24
- getSpareUrls
25
- } = pluginConfig?.enable ? require(findScript()) : {}
26
7
 
27
8
  if (pluginConfig?.enable) {
28
- // 排序
29
- (() => {
30
- const compare = (a, b) => {
31
- const result = a.length === b.length ? a < b : a.length < b.length
32
- return result ? -1 : 1
33
- }
34
- const sort = (obj, value) => {
35
- if (!obj) return
36
- const target = obj.data ?? obj
37
- if (!target.sort) return
38
- if (value !== false) target.sort((a, b) => compare(a[value], b[value]))
39
- else target.sort(compare)
40
- }
41
- const list = {
42
- posts: 'title',
43
- pages: 'title',
44
- tags: 'name',
45
- categories: 'name'
46
- }
47
- Object.assign(list, pluginConfig.sort)
48
- const Locals = require(`${nodePath.resolve('./', 'node_modules/hexo/lib/hexo/locals')}`).prototype
49
- const get = Locals.get
50
- Locals.get = function(name) {
51
- const result = get.call(this, name)
52
- if (name in list) sort(result, list[name])
53
- if ('forEach' in result) {
54
- result.forEach(it => {
55
- for (let tag in list)
56
- sort(it[tag], list[tag])
57
- })
58
- }
59
- return result
60
- }
61
- })()
9
+ const nodePath = require('path')
10
+ const rules = require(nodePath.resolve('./', 'sw-rules'))
62
11
 
12
+ // 排序
13
+ require('/lib/sort')(pluginConfig)
63
14
  // 生成 update.json
64
- hexo.extend.console.register('swpp', '生成前端更新需要的 json 文件以及相关缓存', {}, async () => {
65
- if (!fs.existsSync(config.public_dir))
66
- return logger.info('未检测到发布目录,跳过 swpp 执行')
67
- const cachePath = 'cacheList.json'
68
- const updatePath = 'update.json'
69
- const oldCache = await getJsonFromNetwork(cachePath)
70
- const oldUpdate = await getJsonFromNetwork(updatePath)
71
- const newCache = await buildNewJson(cachePath)
72
- const dif = compare(oldCache, newCache)
73
- buildUpdateJson(updatePath, dif, oldUpdate)
74
- })
75
-
15
+ require('/lib/json')(config, pluginConfig, rules)
76
16
  // 生成 sw.js
77
- hexo.extend.generator.register('buildSw', () => {
78
- if (pluginConfig.sw.custom) return
79
- const absPath = module.path + '/sw-template.js'
80
- const rootPath = nodePath.resolve('./')
81
- const relativePath = nodePath.relative(rootPath, absPath)
82
- // 获取拓展文件
83
- let cache = fs.readFileSync('sw-rules.js', 'utf8')
84
- .replaceAll('module.exports.', 'const ')
85
- if (!fetchNoCache) {
86
- if (pluginConfig.sw.cdnRacing && getCdnList) {
87
- cache +=`
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
- } else if (pluginConfig.sw.spareUrl && getSpareUrls) {
112
- cache += `
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
- }
144
- clearTimeout(controllers[controllers.length - 1].id)
145
- resolve(response)
146
- } else plusError()
147
- }).catch(plusError)
148
- }
149
- pull()
150
- })
151
- }
152
- `
153
- } else cache += `
154
- const fetchFile = (request, banCache) => fetch(request, {
155
- cache: banCache ? "no-store" : "default",
156
- mode: 'cors',
157
- credentials: 'same-origin'
158
- })
159
- `
160
- }
161
- if (!modifyRequest) cache += '\nconst modifyRequest = _ => {}'
162
- if (!getSpareUrls) cache += `\nconst getSpareUrls = _ => {}`
163
- const swContent = fs.readFileSync(relativePath, 'utf8')
164
- .replaceAll("const { cacheList, modifyRequest, fetchFile, getSpareUrls } = require('../sw-rules')", cache)
165
- .replaceAll("'@$$[escape]'", (pluginConfig.sw.escape ?? 0).toString())
166
- .replaceAll("'@$$[cacheName]'", `'${pluginConfig.sw.cacheName ?? 'kmarBlogCache'}'`)
167
- return {
168
- path: 'sw.js',
169
- data: swContent
170
- }
171
- })
172
-
173
- // 生成注册 sw 的代码
174
- hexo.extend.injector.register('head_begin', () => {
175
- return `<script>
176
- (() => {
177
- const sw = navigator.serviceWorker
178
- const error = () => ${pluginConfig.sw.onerror}
179
- if (!sw?.register('${new URL(root).pathname}sw.js')?.then(() => {
180
- if (!sw.controller) ${pluginConfig.sw.onsuccess}
181
- })?.catch(error)) error()
182
- })()
183
- </script>`
184
- }, "default")
185
-
186
- // 插入 sw-dom.js
187
- if (!pluginConfig.dom?.custom) {
188
- hexo.extend.injector.register('body_begin', () => {
189
- // noinspection HtmlUnknownTarget
190
- return `<script src="/sw-dom.js"></script>`
191
- })
192
- hexo.extend.generator.register('buildDomJs', () => {
193
- const absPath = module.path + '/sw-dom.js'
194
- const rootPath = nodePath.resolve('./')
195
- const relativePath = nodePath.relative(rootPath, absPath)
196
- const template = fs.readFileSync(relativePath, 'utf-8')
197
- .replaceAll('// ${onSuccess}', pluginConfig.dom.onsuccess)
198
- return {
199
- path: 'sw-dom.js',
200
- data: template
201
- }
202
- })
203
- }
204
- }
205
-
206
- /** 遍历指定目录下的所有文件 */
207
- const eachAllFile = (root, cb) => {
208
- const stats = fs.statSync(root)
209
- if (stats.isFile()) cb(root)
210
- else {
211
- const files = fs.readdirSync(root)
212
- files.forEach(it => eachAllFile(nodePath.join(root, it), cb))
213
- }
214
- }
215
-
216
- /** 判断指定文件是否需要排除 */
217
- const isExclude = pathname => {
218
- for (let reg of pluginConfig.json.exclude) {
219
- if (pathname.match(new RegExp(reg, 'i'))) return true
220
- }
221
- return false
222
- }
223
-
224
- const isSkipFetch = url => {
225
- const skipList = pluginConfig.external?.skip
226
- if (!skipList) return false
227
- for (let reg of skipList) {
228
- if (url.match(new RegExp(reg))) return true
229
- }
230
- return false
231
- }
232
-
233
- /**
234
- * 构建 md5 缓存表并写入到发布目录中
235
- *
236
- * 格式为 `{"[path]": "[md5Value]"}`
237
- *
238
- * @param path 相对于根目录的路径
239
- * @return {Promise<Object>} 生成的 json 对象
240
- */
241
- const buildNewJson = path => new Promise(resolve => {
242
- const result = {} // 存储新的 MD5 表
243
- const removeIndex = config.pretty_urls?.trailing_index
244
- const removeHtml = config.pretty_urls?.trailing_html
245
- const taskList = [] // 拉取任务列表
246
- const cache = new Set() // 已经计算过的文件
247
- eachAllFile(config.public_dir, path => {
248
- if (!fs.existsSync(path)) return logger.error(`${path} 不存在!`)
249
- let endIndex
250
- if (removeIndex && path.endsWith('/index.html')) endIndex = path.length - 10
251
- else if (removeHtml && path.endsWith('.html')) endIndex = path.length - 5
252
- else endIndex = path.length
253
- const url = new URL(nodePath.join(root, path.substring(7, endIndex)))
254
- if (isExclude(url.href)) return
255
- let content = null
256
- if (findCache(url)) {
257
- content = fs.readFileSync(path, 'utf-8')
258
- const key = decodeURIComponent(url.pathname)
259
- result[key] = crypto.createHash('md5').update(content).digest('hex')
260
- }
261
- // 外链监控
262
- const external = pluginConfig.external
263
- if (!pluginConfig.external?.enable) return
264
- const indexOf = (str, ...chars) => {
265
- let result = str.length
266
- chars.forEach(it => {
267
- const index = str.indexOf(it)
268
- result = Math.min(result, index < 0 ? result : index)
269
- })
270
- return result
271
- }
272
- const lastIndexOf = (str, ...chars) => {
273
- let result = -1
274
- chars.forEach(it => result = Math.max(result, str.lastIndexOf(it)))
275
- return result
276
- }
277
- // 处理指定链接
278
- const handleLink = link => {
279
- // 跳过本地文件的计算
280
- if (!link.match(/^(http|\/\/)/) || cache.has(link)) return
281
- cache.add(link)
282
- const url = new URL(link.startsWith('/') ? `http:${link}` : link)
283
- if (url.hostname === domain || !findCache(url) || isExclude(url.href)) return
284
- if (isSkipFetch(url.href)) result[decodeURIComponent(link)] = '0'
285
- else taskList.push(
286
- fetchFile(link)
287
- .then(response => response.text())
288
- .then(text => {
289
- const key = decodeURIComponent(link)
290
- result[key] = crypto.createHash('md5').update(text).digest('hex')
291
- if (key.endsWith('.js')) handleJsContent(text)
292
- else if (key.endsWith('.css')) handleCssContent(text)
293
- }).catch(err => logger.error(`拉取 ${err.url} 时出现 ${err.status ?? '未知'} 异常:${err}`))
294
- )
295
- }
296
- // 处理指定 JS
297
- const handleJsContent = text => {
298
- if (!external.js) return
299
- if (cache.has(text)) return
300
- cache.add(text)
301
- external.js.forEach(it => {
302
- const reg = new RegExp(`${it.head}(['"\`])(.*?)\\1${it.tail}`, 'mg')
303
- text.match(reg)?.forEach(content => {
304
- try {
305
- const start = indexOf(content, "'", '"', '`') + 1
306
- const end = lastIndexOf(content, "'", '"', '`')
307
- const link = content.substring(start, end)
308
- if (!link.match(/['"$`]/)) handleLink(link)
309
- } catch (e) {
310
- logger.error(`SwppJsHandler: 处理 ${content} 时出现异常`)
311
- logger.error(e)
312
- }
313
- })
314
- })
315
- }
316
- // 处理 CSS 内容
317
- const handleCssContent = text => {
318
- if (cache.has(text)) return
319
- cache.add(text)
320
- postcss.parse(text).walkDecls(decl => {
321
- if (decl.value.includes('url')) {
322
- decl.value.match(/url\(([^)]+)\)/g)
323
- .map(it => it.match(/^(url\(['"])/) ? it.substring(5, it.length - 2) : it.substring(4, it.length - 1))
324
- .forEach(link => handleLink(link))
325
- }
326
- })
327
- }
328
- // 如果是 html 则获取所有 script 和 link 标签拉取的文件
329
- if (path.endsWith('/') || path.endsWith('.html')) {
330
- if (!content) content = fs.readFileSync(path, 'utf-8')
331
- const html = cheerio.load(content)
332
- html('script[src]')
333
- .map((i, ele) => html(ele).attr('src'))
334
- .each((i, it) => handleLink(it))
335
- html('link[href]')
336
- .map((i, ele) => html(ele).attr('href'))
337
- .each((i, it) => handleLink(it))
338
- html('script:not([src])')
339
- .map((i, ele) => html(ele).text())
340
- .each((i, text) => handleJsContent(text))
341
- html('style')
342
- .map((i, ele) => html(ele).text())
343
- .each((i, text) => handleCssContent(text))
344
- } else if (path.endsWith('.js')) {
345
- if (!content) content = fs.readFileSync(path, 'utf-8')
346
- handleJsContent(content)
347
- } else if (path.endsWith('.css')) {
348
- if (!content) content = fs.readFileSync(path, 'utf-8')
349
- handleCssContent(content)
350
- }
351
- })
352
- Promise.all(taskList).then(() => {
353
- const publicRoot = config.public_dir
354
- fs.writeFileSync(nodePath.join(publicRoot, path), JSON.stringify(result), 'utf-8')
355
- logger.info(`Generated: ${path}`)
356
- resolve(result)
357
- })
358
- })
359
-
360
- /**
361
- * 从网络拉取一个文件
362
- * @param link 文件链接
363
- * @returns {Promise<*>} response
364
- */
365
- const fetchFile = link => new Promise((resolve, reject) => {
366
- link = replaceDevRequest(link)
367
- // noinspection SpellCheckingInspection
368
- fetch(link, {
369
- headers: {
370
- referer: new URL(link).hostname,
371
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.62'
372
- },
373
- timeout: pluginConfig.external.timeout ?? 1500
374
- }).then(response => {
375
- switch (response.status) {
376
- case 200: case 301: case 302:
377
- resolve(response)
378
- break
379
- default:
380
- reject(response)
381
- break
382
- }
383
- }).catch(err => {
384
- err.url = link
385
- reject(err)
386
- })
387
- })
388
-
389
- /**
390
- * 从网络拉取 json 文件
391
- * @param path 文件路径(相对于根目录)
392
- */
393
- const getJsonFromNetwork = path => new Promise(resolve => {
394
- const url = nodePath.join(root, path)
395
- fetchFile(url)
396
- .then(response => resolve(response.json()))
397
- .catch(err => {
398
- if (err.status === 404) {
399
- logger.error(`拉取 ${err.url} 时出现 404,如果您是第一次构建请忽略这个错误`)
400
- resolve()
401
- } else throw err
402
- })
403
- })
404
-
405
- /**
406
- * 对比两个 md5 缓存表的区别
407
- * @return [string] 需要更新的文件路径
408
- */
409
- const compare = (oldCache, newCache) => {
410
- const result = []
411
- if (!oldCache) return result
412
- for (let path in oldCache) {
413
- if (newCache[path] !== oldCache[path]) result.push(path)
414
- }
415
- return result
416
- }
417
-
418
- /** 判断指定资源是否需要合并 */
419
- const isMerge = (pathname, tidied) => {
420
- const optional = pluginConfig.json.merge
421
- if (!optional) return false
422
- if (pathname.includes(`/${config.tag_dir}/`)) {
423
- if (optional.tags ?? true)
424
- return tidied.tags = true
425
- } else if (pathname.includes(`/${config.archive_dir}/`)) {
426
- if (optional.archives ?? true)
427
- return tidied.archives = true
428
- } else if (pathname.includes(`/${config.category_dir}/`)) {
429
- if (optional.categories ?? true)
430
- return tidied.categories = true
431
- } else if (pathname.startsWith('/page/') || pathname.length <= 1) {
432
- if (optional.index ?? true)
433
- return tidied.index = true
434
- } else {
435
- const list = optional.custom
436
- if (!list) return false
437
- for (let reg of list) {
438
- if (pathname.startsWith(`/${reg}/`))
439
- return tidied.custom[reg] = true
440
- }
441
- }
442
- }
443
-
444
- /**
445
- * 从一个字符串中提取最后两个 / 之间的内容
446
- * @param it {string} 要操作的字符串
447
- * @param keep {boolean} 是否保留最后一个 / 及其后面的内容
448
- */
449
- const clipPageName = (it, keep) => {
450
- const end = it.lastIndexOf('/')
451
- let index = end - 1
452
- for (; index > 0; --index) {
453
- if (it[index] === '/') break
454
- }
455
- return it.substring(index + 1, keep ? it.length : end)
456
- }
457
-
458
- /** 构建新的 update.json */
459
- const buildUpdateJson = (name, dif, oldUpdate) => {
460
- /** 将对象写入文件,如果对象为 null 或 undefined 则跳过写入 */
461
- const writeJson = json => {
462
- if (json) {
463
- logger.info(`Generated: ${name}`)
464
- fs.writeFileSync(`public/${name}`, JSON.stringify(json), 'utf-8')
465
- }
466
- }
467
- // 读取拓展 json
468
- const expand = fs.existsSync(name) ? JSON.parse(fs.readFileSync(name, 'utf-8')) : undefined
469
- // 获取上次最新的版本
470
- let oldVersion = oldUpdate?.info?.at(0)?.version ?? 0
471
- if (typeof oldVersion !== 'number') {
472
- // 当上次最新的版本号不是数字是尝试对其进行转换,如果无法转换则直接置零
473
- if (oldVersion.match('\D')) oldVersion = 0
474
- else oldVersion = Number.parseInt(oldVersion)
475
- }
476
- // 存储本次更新的内容
477
- const newInfo = {
478
- version: oldVersion + 1,
479
- change: expand?.change ?? []
480
- }
481
- // 整理更新的数据
482
- const tidied = tidyDiff(dif, expand)
483
- if (expand?.all) return writeJson({
484
- global: (oldUpdate?.global ?? 0) + (tidied.updateGlobal ? 1 : 0),
485
- info: [newInfo]
486
- })
487
- // 如果没有更新的文件就直接退出
488
- if (
489
- tidied.page.size === 0 && tidied.file.size === 0 &&
490
- !(tidied.archives || tidied.categories || tidied.tags || tidied.index)
491
- ) return writeJson(oldUpdate ?? {
492
- global: 0,
493
- info: [{version: 0}]
494
- })
495
- pushUpdateToInfo(newInfo, tidied)
496
- const result = mergeUpdateWithOld(newInfo, oldUpdate, tidied)
497
- return writeJson(result)
498
- }
499
-
500
- const mergeUpdateWithOld = (newInfo, oldUpdate, tidied) => {
501
- const result = {
502
- global: (oldUpdate?.global ?? 0) + (tidied.updateGlobal ? 1 : 0),
503
- info: [newInfo]
504
- }
505
- const charLimit = pluginConfig.json.charLimit ?? 1024
506
- if (JSON.stringify(result).length > charLimit) {
507
- return {
508
- global: result.global,
509
- info: [{version: newInfo.version}]
510
- }
511
- }
512
- if (!oldUpdate) return result
513
- for (let it of oldUpdate.info) {
514
- if (it.change) it.change = zipInfo(newInfo, it)
515
- result.info.push(it)
516
- if (JSON.stringify(result).length > charLimit) {
517
- result.info.pop()
518
- break
519
- }
520
- }
521
- return result
522
- }
523
-
524
- // 压缩相同项目
525
- const zipInfo = (newInfo, oldInfo) => {
526
- oldInfo = oldInfo.change
527
- newInfo = newInfo.change
528
- const result = []
529
- for (let i = oldInfo.length - 1; i !== -1; --i) {
530
- const value = oldInfo[i]
531
- if (value.flag === 'page' && newInfo.find(it => it.flag === 'html')) continue
532
- const newValue = newInfo.find(it => it.flag === value.flag)
533
- if (!newValue) {
534
- result.push(value)
535
- continue
536
- }
537
- if (!value.value) continue
538
- const isArray = Array.isArray(newValue.value)
539
- if (Array.isArray(value.value)) {
540
- const array = value.value
541
- .filter(it => isArray ? !newValue.value.find(that => that === it) : it !== newValue.value)
542
- if (array.length === 0) continue
543
- result.push({flag: value.flag, value: array.length === 1 ? array[0] : array})
544
- } else if (isArray) {
545
- if (!newValue.value.find(it => it === value.value))
546
- result.push(value)
547
- } else {
548
- if (newValue.value !== value.value)
549
- result.push(value)
550
- }
551
- }
552
- return result.length === 0 ? undefined : result
553
- }
554
-
555
- // 将更新推送到 info
556
- const pushUpdateToInfo = (info, tidied) => {
557
- const merges = [] // 要合并的更新
558
- // 推送页面更新
559
- if (tidied.page.size > (pluginConfig.json.maxHtml ?? 15)) {
560
- // 如果 html 数量超过阈值就直接清掉所有 html
561
- info.change.push({flag: 'html'})
562
- } else {
563
- const pages = [] // 独立更新
564
- tidied.page.forEach(it => pages.push(it))
565
- if (tidied.tags) merges.push(config.tag_dir)
566
- if (tidied.archives) merges.push(config.archive_dir)
567
- if (tidied.categories) merges.push(config.category_dir)
568
- if (tidied.index) {
569
- pages.push(clipPageName(root, false))
570
- merges.push('page')
571
- }
572
- if (pages.length > 0)
573
- info.change.push({flag: 'page', value: pages})
574
- }
575
- for (let key in tidied.custom) merges.push(key)
576
- if (merges.length > 0)
577
- info.change.push({flag: 'str', value: merges.map(it => `/${it}/`)})
578
- // 推送文件更新
579
- if (tidied.file.size > 0) {
580
- const list = []
581
- tidied.file.forEach(it => list.push(it))
582
- info.change.push({flag: 'file', value: list})
583
- }
584
- }
585
-
586
- // 将 diff 整理分类
587
- const tidyDiff = (dif, expand) => {
588
- const tidied = {
589
- /** 所有 HTML 页面 */
590
- page: new Set(),
591
- /** 所有文件 */
592
- file: new Set(),
593
- /** 标记 tags 是否更新 */
594
- tags: false,
595
- /** 标记 archives 是否更新 */
596
- archives: false,
597
- /** 标记 categories 是否更新 */
598
- categories: false,
599
- /** 标记 index 是否更新 */
600
- index: false,
601
- /** 自定义配置项 */
602
- custom: {},
603
- /** 标记是否更新 global 版本号 */
604
- updateGlobal: expand?.global
605
- }
606
- const mode = pluginConfig.json.precisionMode
607
- for (let it of dif) {
608
- const url = new URL(nodePath.join(root, it)) // 当前文件的 URL
609
- const cache = findCache(url) // 查询缓存
610
- if (!cache) {
611
- logger.error(`[buildUpdate] 指定 URL(${url.pathname}) 未查询到缓存规则!`)
612
- continue
613
- }
614
- if (!cache.clean) tidied.updateGlobal = true
615
- if (isMerge(url.pathname, tidied)) continue
616
- if (it.match(/(\/|\.html)$/)) { // 判断缓存是否是 html
617
- if (mode.html ?? false) tidied.page.add(url.pathname)
618
- else tidied.page.add(clipPageName(url.href, !it.endsWith('/')))
619
- } else {
620
- const extendedName = (it.includes('.') ? it.match(/[^.]+$/)[0] : null) ?? 'default'
621
- const setting = mode[extendedName] ?? (mode.default ?? false)
622
- if (setting) tidied.file.add(url.pathname)
623
- else {
624
- let name = url.href.match(/[^/]+$/)[0]
625
- if (!name) throw `${url.href} 格式错误`
626
- tidied.file.add(name)
627
- }
628
- }
629
- }
630
- return tidied
631
- }
632
-
633
- function findCache(url) {
634
- url = new URL(replaceRequest(url.href))
635
- for (let key in cacheList) {
636
- const value = cacheList[key]
637
- if (value.match(url)) return value
638
- }
639
- return null
640
- }
641
-
642
- function replaceRequest(url) {
643
- if (!modifyRequest) return url
644
- const request = new Request(url)
645
- const newRequest = modifyRequest(request)
646
- return newRequest?.url ?? url
647
- }
648
-
649
- function replaceDevRequest(url) {
650
- const external = pluginConfig.external
651
- if (!external?.enable || !external.replace) return url
652
- for (let value of external.replace) {
653
- for (let source of value.source) {
654
- if (url.match(source)) {
655
- url = url.replace(source, value.dist)
656
- }
657
- }
658
- }
659
- return url
17
+ require('/lib/sw')(config, pluginConfig, rules)
660
18
  }