@capyclaw/offline-ddr0 0.0.0-stage → 1.9.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/LICENSE +21 -0
- package/README.md +441 -2
- package/client/client.js +603 -0
- package/cordis.patch.yml +13 -0
- package/docs/STORAGE-MIGRATION.md +136 -0
- package/lib/atomic.mjs +40 -0
- package/lib/http-cache.mjs +42 -0
- package/lib/inbox.mjs +64 -0
- package/lib/media.mjs +242 -0
- package/lib/migrate-json.mjs +101 -0
- package/lib/mirror-index.mjs +105 -0
- package/lib/mirror.mjs +123 -0
- package/lib/proxy.mjs +188 -0
- package/lib/remote.mjs +158 -0
- package/lib/render.mjs +93 -0
- package/lib/repository.mjs +71 -0
- package/lib/store.mjs +610 -0
- package/lib/surface.mjs +74 -0
- package/lib/sync-ui.mjs +108 -0
- package/lib/sync.mjs +433 -0
- package/lib/wire.mjs +211 -0
- package/lib/workstore-repository.mjs +316 -0
- package/lib/workstore.mjs +338 -0
- package/mirror/files/00001.html +2045 -0
- package/mirror/files/00002.json +1 -0
- package/mirror/files/00003.json +1 -0
- package/mirror/files/00004.json +1 -0
- package/mirror/files/00005.json +1 -0
- package/mirror/files/00006.json +1 -0
- package/mirror/files/00007.json +1 -0
- package/mirror/files/00008.json +1 -0
- package/mirror/files/00009.json +1 -0
- package/mirror/files/00010.json +1 -0
- package/mirror/files/00011.json +1 -0
- package/mirror/files/00012.json +1 -0
- package/mirror/files/00013.json +1 -0
- package/mirror/files/00014.json +1 -0
- package/mirror/files/00015.json +1 -0
- package/mirror/files/00016.json +1 -0
- package/mirror/files/00017.json +1 -0
- package/mirror/files/00018.json +1 -0
- package/mirror/files/00019.json +1 -0
- package/mirror/files/00020.json +1 -0
- package/mirror/files/00021.json +1 -0
- package/mirror/files/00022.json +1 -0
- package/mirror/files/00023.js +205 -0
- package/mirror/files/00024.json +1 -0
- package/mirror/files/00025.json +1 -0
- package/mirror/files/00026.json +1 -0
- package/mirror/files/00027.js +51 -0
- package/mirror/files/00028.json +1 -0
- package/mirror/files/00029.json +1 -0
- package/mirror/files/00030.json +1 -0
- package/mirror/files/00031.json +1 -0
- package/mirror/files/00032.json +1 -0
- package/mirror/files/00033.json +1 -0
- package/mirror/files/00034.json +1 -0
- package/mirror/files/00035.json +1 -0
- package/mirror/files/00036.json +1 -0
- package/mirror/files/00037.json +1 -0
- package/mirror/files/00038.json +1 -0
- package/mirror/files/00039.json +1 -0
- package/mirror/files/00040.js +2311 -0
- package/mirror/files/00041.json +1 -0
- package/mirror/files/00042.json +1 -0
- package/mirror/files/00043.json +1 -0
- package/mirror/files/00044.json +1 -0
- package/mirror/files/00045.js +575 -0
- package/mirror/files/00046.json +1 -0
- package/mirror/files/00047.js +575 -0
- package/mirror/files/00048.js +575 -0
- package/mirror/files/00049.json +1 -0
- package/mirror/files/00050.json +1 -0
- package/mirror/files/00051.json +1 -0
- package/mirror/files/00052.json +1 -0
- package/mirror/files/00053.js +575 -0
- package/mirror/files/00054.json +1 -0
- package/mirror/files/00055.json +1 -0
- package/mirror/files/00056.js +575 -0
- package/mirror/files/00057.json +1 -0
- package/mirror/files/00058.json +1 -0
- package/mirror/files/00059.js +360 -0
- package/mirror/files/00060.json +1 -0
- package/mirror/files/00061.json +1 -0
- package/mirror/files/00062.json +1 -0
- package/mirror/files/00063.json +1 -0
- package/mirror/files/00064.json +1 -0
- package/mirror/files/00065.js +144 -0
- package/mirror/files/00066.js +7 -0
- package/mirror/files/00067.json +1 -0
- package/mirror/files/00068.json +1 -0
- package/mirror/files/00069.json +1 -0
- package/mirror/files/00070.json +1 -0
- package/mirror/files/00071.json +1 -0
- package/mirror/files/00072.json +1 -0
- package/mirror/files/00073.js +1 -0
- package/mirror/files/00074.json +1 -0
- package/mirror/files/00075.json +1 -0
- package/mirror/files/00076.json +1 -0
- package/mirror/files/00077.js +45 -0
- package/mirror/files/00078.js +1348 -0
- package/mirror/files/00079.json +1 -0
- package/mirror/files/00080.json +1 -0
- package/mirror/files/00081.js +1 -0
- package/mirror/files/00082.json +1 -0
- package/mirror/files/00083.json +1 -0
- package/mirror/files/00084.js +7 -0
- package/mirror/files/00085.json +1 -0
- package/mirror/files/00086.json +1 -0
- package/mirror/files/00087.js +7 -0
- package/mirror/files/00088.json +1 -0
- package/mirror/files/00089.json +1 -0
- package/mirror/files/00090.js +7 -0
- package/mirror/files/00091.json +1 -0
- package/mirror/files/00092.json +1 -0
- package/mirror/files/00093.js +102 -0
- package/mirror/files/00094.json +1 -0
- package/mirror/files/00095.json +1 -0
- package/mirror/files/00096.json +1 -0
- package/mirror/files/00097.json +1 -0
- package/mirror/files/00098.json +1 -0
- package/mirror/files/00099.json +1 -0
- package/mirror/files/00100.json +1 -0
- package/mirror/files/00101.js +102 -0
- package/mirror/files/00102.json +1 -0
- package/mirror/files/00103.json +1 -0
- package/mirror/files/00104.json +1 -0
- package/mirror/files/00105.json +1 -0
- package/mirror/files/00106.json +1 -0
- package/mirror/files/00107.js +110 -0
- package/mirror/files/00108.json +1 -0
- package/mirror/files/00109.json +1 -0
- package/mirror/files/00110.json +1 -0
- package/mirror/files/00111.json +1 -0
- package/mirror/files/00112.json +1 -0
- package/mirror/files/00113.json +1 -0
- package/mirror/files/00114.json +1 -0
- package/mirror/files/00115.json +1 -0
- package/mirror/files/00116.json +1 -0
- package/mirror/files/00117.json +1 -0
- package/mirror/files/00118.json +1 -0
- package/mirror/files/00119.json +1 -0
- package/mirror/files/00120.json +1 -0
- package/mirror/files/00121.json +1 -0
- package/mirror/files/00122.json +1 -0
- package/mirror/files/00123.json +1 -0
- package/mirror/files/00124.json +1 -0
- package/mirror/files/00125.json +1 -0
- package/mirror/files/00126.json +1 -0
- package/mirror/files/00127.json +1 -0
- package/mirror/files/00128.json +1 -0
- package/mirror/files/00129.json +1 -0
- package/mirror/files/00130.json +1 -0
- package/mirror/files/00131.json +1 -0
- package/mirror/files/00132.js +110 -0
- package/mirror/files/00133.json +1 -0
- package/mirror/files/00134.json +1 -0
- package/mirror/files/00135.json +1 -0
- package/mirror/files/00136.json +1 -0
- package/mirror/files/00137.js +26 -0
- package/mirror/files/00138.json +1 -0
- package/mirror/files/00139.json +1 -0
- package/mirror/files/00140.json +1 -0
- package/mirror/files/00141.json +1 -0
- package/mirror/files/00142.json +1 -0
- package/mirror/files/00143.json +1 -0
- package/mirror/files/00144.js +26 -0
- package/mirror/files/00145.json +1 -0
- package/mirror/files/00146.json +1 -0
- package/mirror/files/00147.js +29 -0
- package/mirror/files/00148.json +1 -0
- package/mirror/files/00149.json +1 -0
- package/mirror/files/00150.js +23 -0
- package/mirror/files/00151.json +1 -0
- package/mirror/files/00152.json +1 -0
- package/mirror/files/00153.js +719 -0
- package/mirror/files/00154.js +9575 -0
- package/mirror/files/00155.js +108 -0
- package/mirror/files/00156.js +379 -0
- package/mirror/files/00157.js +48 -0
- package/mirror/files/00158.json +16 -0
- package/mirror/manifest.json +1582 -0
- package/node_modules/@capyclaw/asset-service/README.md +48 -0
- package/node_modules/@capyclaw/asset-service/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/asset-service/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/asset-service/lib/host.mjs +14 -0
- package/node_modules/@capyclaw/asset-service/package.json +59 -0
- package/node_modules/@capyclaw/asset-service/src/index.mjs +223 -0
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +68 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +87 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +139 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/node_modules/@capyclaw/service-host/README.md +86 -0
- package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
- package/node_modules/@capyclaw/service-host/package.json +60 -0
- package/node_modules/@capyclaw/service-host/src/index.mjs +571 -0
- package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
- package/node_modules/@capyclaw/suite-kit/README.md +238 -0
- package/node_modules/@capyclaw/suite-kit/bin/dsh-domain.mjs +98 -0
- package/node_modules/@capyclaw/suite-kit/bin/dsh-suite.mjs +174 -0
- package/node_modules/@capyclaw/suite-kit/client/embed.js +35 -0
- package/node_modules/@capyclaw/suite-kit/domain.schema.json +129 -0
- package/node_modules/@capyclaw/suite-kit/package.json +54 -0
- package/node_modules/@capyclaw/suite-kit/src/activation-registry.mjs +184 -0
- package/node_modules/@capyclaw/suite-kit/src/artifacts.mjs +131 -0
- package/node_modules/@capyclaw/suite-kit/src/capability.mjs +181 -0
- package/node_modules/@capyclaw/suite-kit/src/compose.mjs +201 -0
- package/node_modules/@capyclaw/suite-kit/src/domain.mjs +138 -0
- package/node_modules/@capyclaw/suite-kit/src/embed.mjs +81 -0
- package/node_modules/@capyclaw/suite-kit/src/index.mjs +10 -0
- package/node_modules/@capyclaw/suite-kit/src/manifest.mjs +263 -0
- package/node_modules/@capyclaw/suite-kit/src/orchestration.mjs +100 -0
- package/node_modules/@capyclaw/suite-kit/src/profile.mjs +584 -0
- package/node_modules/@capyclaw/suite-kit/src/surface.mjs +28 -0
- package/node_modules/@capyclaw/suite-kit/suite.schema.json +112 -0
- package/node_modules/@capyclaw/work-store/README.md +83 -0
- package/node_modules/@capyclaw/work-store/STANDARD.md +257 -0
- package/node_modules/@capyclaw/work-store/cordis.patch.yml +3 -0
- package/node_modules/@capyclaw/work-store/dsh-suite.json +26 -0
- package/node_modules/@capyclaw/work-store/icon.svg +7 -0
- package/node_modules/@capyclaw/work-store/lib/host.mjs +21 -0
- package/node_modules/@capyclaw/work-store/package.json +68 -0
- package/node_modules/@capyclaw/work-store/src/backend.mjs +89 -0
- package/node_modules/@capyclaw/work-store/src/db.mjs +199 -0
- package/node_modules/@capyclaw/work-store/src/envelope.mjs +132 -0
- package/node_modules/@capyclaw/work-store/src/index.mjs +570 -0
- package/node_modules/@capyclaw/work-store/src/interop.mjs +70 -0
- package/node_modules/@capyclaw/work-store/src/refs.mjs +99 -0
- package/node_modules/@capyclaw/work-store/src/routes.mjs +135 -0
- package/package.json +82 -4
- package/plugin.mjs +636 -0
- package/static/index.html +2068 -0
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 离线镜像索引 —— manifest 的单一读取/索引实现(mirror.mjs 与 workstore.mjs 共读)。
|
|
3
|
+
*
|
|
4
|
+
* 过去 mirror.mjs 建 exact/byPath/bundles 三索引,workstore.mjs 的 readMirrorCode
|
|
5
|
+
* 又各自 JSON.parse 整份 manifest 找代码包——同一份清单知识维护两处。这里收敛:
|
|
6
|
+
* - load():按 manifest mtime 缓存三索引(精确 / 同 path / 同作品任意版本产物);
|
|
7
|
+
* - readFile(entry, s):读快照响应体,≤2MB 小件缓存(>128 条清空),大件现读现发;
|
|
8
|
+
* - codeFor(workNum, exts):按作品号取 /js 或 /decorator.js 代码包(bundles O(1) 查找)。
|
|
9
|
+
*
|
|
10
|
+
* 宿主半(plugin.mjs)建一个实例注入 mirror 与 workstore,整份 manifest 只解析一次。
|
|
11
|
+
* 未注入时各消费方也可自建(传 mirrorDir),行为一致。
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
|
|
16
|
+
export function createMirrorIndex(dir, { log } = {}) {
|
|
17
|
+
const manifestFile = path.join(dir, 'manifest.json')
|
|
18
|
+
const fileDir = path.join(dir, 'files')
|
|
19
|
+
let state = null
|
|
20
|
+
let warned = false
|
|
21
|
+
|
|
22
|
+
function load() {
|
|
23
|
+
let stat
|
|
24
|
+
try {
|
|
25
|
+
stat = fs.statSync(manifestFile)
|
|
26
|
+
} catch {
|
|
27
|
+
if (!warned) {
|
|
28
|
+
warned = true
|
|
29
|
+
log?.info?.('offline-ddr0: 没有离线镜像,退回反代上游')
|
|
30
|
+
}
|
|
31
|
+
state = { enabled: false }
|
|
32
|
+
return null
|
|
33
|
+
}
|
|
34
|
+
if (state && state.enabled && state.mtime === stat.mtimeMs) return state
|
|
35
|
+
try {
|
|
36
|
+
const list = JSON.parse(fs.readFileSync(manifestFile, 'utf8'))
|
|
37
|
+
const exact = new Map()
|
|
38
|
+
const byPath = new Map()
|
|
39
|
+
const bundles = new Map()
|
|
40
|
+
for (const entry of list) {
|
|
41
|
+
if (!entry || entry.status !== 200 || !entry.file) continue
|
|
42
|
+
exact.set(`${entry.method} ${entry.path}`, entry)
|
|
43
|
+
if (entry.method !== 'GET') continue
|
|
44
|
+
const bare = entry.path.split('?')[0]
|
|
45
|
+
if (!byPath.has(bare)) byPath.set(bare, entry)
|
|
46
|
+
const m = /^\/api\/works\/works\/(\d+)\/version\/\d+\/([a-z.]+)$/.exec(bare)
|
|
47
|
+
if (m) bundles.set(`${m[1]}/${m[2]}`, entry)
|
|
48
|
+
}
|
|
49
|
+
const total = list.reduce((n, e) => n + (e.size || 0), 0)
|
|
50
|
+
state = { enabled: true, mtime: stat.mtimeMs, exact, byPath, bundles, cache: new Map(), count: list.length }
|
|
51
|
+
log?.info?.(`offline-ddr0: 离线镜像就绪 ${list.length} 条 / ${(total / 1048576).toFixed(1)}MB`)
|
|
52
|
+
return state
|
|
53
|
+
} catch (error) {
|
|
54
|
+
log?.error?.(`offline-ddr0: 读取离线镜像清单失败: ${error.message}`)
|
|
55
|
+
state = { enabled: false }
|
|
56
|
+
return null
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function readFile(entry, s = load()) {
|
|
61
|
+
if (!s || !s.enabled || !entry) return null
|
|
62
|
+
const cacheKey = entry.file
|
|
63
|
+
const hit = s.cache.get(cacheKey)
|
|
64
|
+
if (hit) return hit
|
|
65
|
+
let body
|
|
66
|
+
try {
|
|
67
|
+
body = fs.readFileSync(path.join(fileDir, entry.file))
|
|
68
|
+
} catch (error) {
|
|
69
|
+
log?.warn?.(`offline-ddr0: 镜像文件缺失 ${entry.file}: ${error.message}`)
|
|
70
|
+
return null
|
|
71
|
+
}
|
|
72
|
+
// 只缓存 2MB 以下的小件,作品代码现读现发,避免常驻几十 MB。
|
|
73
|
+
if (body.length <= 2 * 1024 * 1024) {
|
|
74
|
+
if (s.cache.size > 128) s.cache.clear()
|
|
75
|
+
s.cache.set(cacheKey, body)
|
|
76
|
+
}
|
|
77
|
+
return body
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 按作品号取代码包:exts 依序尝试(如 ['js','decorator.js']),命中非空即返回。 */
|
|
81
|
+
function codeFor(workNum, exts) {
|
|
82
|
+
const s = load()
|
|
83
|
+
if (!s || !s.enabled) return null
|
|
84
|
+
for (const ext of exts) {
|
|
85
|
+
const entry = s.bundles.get(`${workNum}/${ext}`)
|
|
86
|
+
if (!entry) continue
|
|
87
|
+
const buf = readFile(entry, s)
|
|
88
|
+
if (buf && buf.length) return buf
|
|
89
|
+
}
|
|
90
|
+
return null
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
load,
|
|
95
|
+
readFile,
|
|
96
|
+
codeFor,
|
|
97
|
+
get enabled() {
|
|
98
|
+
return Boolean(load()?.enabled)
|
|
99
|
+
},
|
|
100
|
+
stats() {
|
|
101
|
+
const s = load()
|
|
102
|
+
return s && s.enabled ? { entries: s.count, bytes: [...s.exact.values()].reduce((n, e) => n + e.size, 0) } : null
|
|
103
|
+
},
|
|
104
|
+
}
|
|
105
|
+
}
|
package/lib/mirror.mjs
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 离线镜像:把 2026-11-15 从 ddr0.com 真源站(162.251.95.51)抓下来的
|
|
3
|
+
* 「接口快照 + 作品代码」直接由宿主半直出,**不再有任何上游请求**。
|
|
4
|
+
*
|
|
5
|
+
* 目录结构(抓取脚本 .scratch/build-mirror.mjs 产出):
|
|
6
|
+
* mirror/manifest.json 条目表:{ key:'GET /api/x?y=1', method, path, status, contentType, file, size }
|
|
7
|
+
* mirror/files/NNNNN.ext 原始响应体
|
|
8
|
+
*
|
|
9
|
+
* 清单索引/文件读取统一走 lib/mirror-index.mjs(与 workstore 桥共读同一份 manifest)。
|
|
10
|
+
* 查找顺序(全部命中即返回,未命中给温和空载荷,绝不 502/404 打断前端):
|
|
11
|
+
* 1. 精确 `METHOD path?search`
|
|
12
|
+
* 2. 同 pathname 的 GET(参数不同,例如 limit/offset 变了)
|
|
13
|
+
* 3. 同作品的任意版本产物 `/api/works/works/{id}/version/{v}/{js,decorator.js,...}`
|
|
14
|
+
* 4. 空载荷
|
|
15
|
+
*/
|
|
16
|
+
import { offlinePatch, PATCHED_PATHS } from './proxy.mjs'
|
|
17
|
+
import { sendCached } from './http-cache.mjs'
|
|
18
|
+
import { createMirrorIndex } from './mirror-index.mjs'
|
|
19
|
+
|
|
20
|
+
const LISTISH = /^\/api\/(community\/category\/|my\/favorites|worklist|search|works\b)/
|
|
21
|
+
|
|
22
|
+
function emptyPayload(pathname) {
|
|
23
|
+
if (LISTISH.test(pathname)) {
|
|
24
|
+
return { status: 'ok', items: [], total: 0, has_more: false, offset: 0, offline: true }
|
|
25
|
+
}
|
|
26
|
+
if (/\/mine$/.test(pathname)) return { status: 'ok', mine: null, offline: true }
|
|
27
|
+
return { status: 'ok', ok: true, offline: true }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function createMirror(dir, { log, transform, index } = {}) {
|
|
31
|
+
// 宿主半注入共享索引时整份 manifest 只解析一次;未注入则自建(行为一致)。
|
|
32
|
+
const idx = index || createMirrorIndex(dir, { log })
|
|
33
|
+
|
|
34
|
+
function header(res, status, type, length, extra = {}) {
|
|
35
|
+
res.writeHead(status, {
|
|
36
|
+
'content-type': type,
|
|
37
|
+
'content-length': length,
|
|
38
|
+
'x-offline-mirror': '1',
|
|
39
|
+
...extra,
|
|
40
|
+
})
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function sendJson(req, res, status, value, extra) {
|
|
44
|
+
const body = Buffer.from(JSON.stringify(value), 'utf8')
|
|
45
|
+
header(res, status, 'application/json; charset=utf-8', body.length, extra)
|
|
46
|
+
res.end(req.method === 'HEAD' ? undefined : body)
|
|
47
|
+
return true
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function sendEntry(req, res, s, entry, { pathname, search, mount }) {
|
|
51
|
+
let body = idx.readFile(entry, s)
|
|
52
|
+
if (!body) return sendJson(req, res, 200, emptyPayload(pathname))
|
|
53
|
+
// 与反代回程同一套修补:config.json 的 apiBaseUrl 改成本次请求的公共前缀,
|
|
54
|
+
// gate/bootstrap/me 补 community.read(根会话快照本来就带,属幂等)。
|
|
55
|
+
const bare = pathname.split('?')[0]
|
|
56
|
+
if (PATCHED_PATHS.has(bare) && entry.contentType.includes('json')) {
|
|
57
|
+
body = offlinePatch(body, mount, bare)
|
|
58
|
+
}
|
|
59
|
+
// 宿主半的合并钩子:把本地作品库塞进列表/收藏等 JSON 响应(只读改写,失败不影响直出)。
|
|
60
|
+
if (typeof transform === 'function' && entry.contentType.includes('json') && req.method === 'GET') {
|
|
61
|
+
try {
|
|
62
|
+
const parsed = JSON.parse(body.toString('utf8'))
|
|
63
|
+
const merged = transform(bare, parsed, search)
|
|
64
|
+
if (merged && merged !== parsed) body = Buffer.from(JSON.stringify(merged), 'utf8')
|
|
65
|
+
} catch { /* 非 JSON 或钩子出错:原样直出 */ }
|
|
66
|
+
}
|
|
67
|
+
const type = entry.contentType.includes('charset')
|
|
68
|
+
? entry.contentType
|
|
69
|
+
: `${entry.contentType}; charset=utf-8`
|
|
70
|
+
const immutable = /javascript|image|font/.test(entry.contentType)
|
|
71
|
+
return sendCached(req, res, {
|
|
72
|
+
buf: body,
|
|
73
|
+
type,
|
|
74
|
+
cacheControl: immutable ? 'public, max-age=86400' : 'no-cache',
|
|
75
|
+
extra: { 'x-offline-mirror': '1', 'content-location': `${pathname}${search}` },
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 返回 true 表示「已经处理完,不要再走反代」;返回 false 只在镜像目录不存在时,
|
|
81
|
+
* 那时保持旧行为(反代上游)。
|
|
82
|
+
*/
|
|
83
|
+
function serve(req, res, { pathname = '/', search = '', mount = '' } = {}) {
|
|
84
|
+
const s = idx.load()
|
|
85
|
+
if (!s || !s.enabled) return false
|
|
86
|
+
|
|
87
|
+
const method = String(req.method || 'GET').toUpperCase()
|
|
88
|
+
const bare = pathname
|
|
89
|
+
|
|
90
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
91
|
+
return sendJson(req, res, 200, { status: 'ok', ok: true, offline: true })
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
let entry = s.exact.get(`GET ${bare}${search}`)
|
|
95
|
+
if (!entry) {
|
|
96
|
+
const offset = /[?&]offset=(\d+)/.exec(search || '')
|
|
97
|
+
const pageMiss = offset && Number(offset[1]) > 0
|
|
98
|
+
const byPath = s.byPath.get(bare)
|
|
99
|
+
if (byPath && !pageMiss) entry = byPath
|
|
100
|
+
// 深翻页没有快照:给空页,别把第一页重复端出去(否则前端无限滚动死循环)。
|
|
101
|
+
if (!entry && pageMiss && byPath) {
|
|
102
|
+
return sendJson(req, res, 200, { ...emptyPayload(bare), offset: Number(offset[1]) })
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (!entry) {
|
|
106
|
+
const m = /^\/api\/works\/works\/(\d+)\/version\/\d+\/([a-z.]+)$/.exec(bare)
|
|
107
|
+
if (m) entry = s.bundles.get(`${m[1]}/${m[2]}`)
|
|
108
|
+
}
|
|
109
|
+
if (entry) return sendEntry(req, res, s, entry, { pathname: bare, search, mount })
|
|
110
|
+
return sendJson(req, res, 200, emptyPayload(bare))
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
serve,
|
|
115
|
+
/** 镜像是否存在(浏览器半据此显示「离线」标记)。 */
|
|
116
|
+
get enabled() {
|
|
117
|
+
return idx.enabled
|
|
118
|
+
},
|
|
119
|
+
stats() {
|
|
120
|
+
return idx.stats()
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
}
|
package/lib/proxy.mjs
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 反代:把挂载点内的后端请求转到离线镜像(默认 https://ddr0.com/apps/works/3904)。
|
|
3
|
+
*
|
|
4
|
+
* 除透传外只做两处回程修补(都是「离线包」与「在线主站」的差异,不透传就会坏):
|
|
5
|
+
* 1. `/config.json` 的 `apiBaseUrl` 改成挂载点——离线站前端会用它覆盖
|
|
6
|
+
* `window.__apiBaseUrl`,不改就会被拉回主站的 `/apps/works/3904` 前缀;
|
|
7
|
+
* 2. `/api/gate`、`/api/bootstrap` 的 `viewer_caps` 补 `community.read`——新版前端
|
|
8
|
+
* 用 `Caps.requireCommunityRead()` 闸住社区浏览,而主站游客快照里没有这个能力,
|
|
9
|
+
* 零登录的离线站会整页显示「登录后可浏览内容」。后端没有对应的服务端校验,
|
|
10
|
+
* 数据本来就是公开快照,所以补能力只放开界面。
|
|
11
|
+
*/
|
|
12
|
+
import { request as httpRequest } from 'node:http'
|
|
13
|
+
import { request as httpsRequest } from 'node:https'
|
|
14
|
+
|
|
15
|
+
const HOP_BY_HOP = new Set([
|
|
16
|
+
'connection',
|
|
17
|
+
'keep-alive',
|
|
18
|
+
'proxy-authenticate',
|
|
19
|
+
'proxy-authorization',
|
|
20
|
+
'te',
|
|
21
|
+
'trailer',
|
|
22
|
+
'transfer-encoding',
|
|
23
|
+
'upgrade',
|
|
24
|
+
])
|
|
25
|
+
|
|
26
|
+
function readBody(req) {
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
const chunks = []
|
|
29
|
+
req.on('data', (chunk) => chunks.push(chunk))
|
|
30
|
+
req.on('end', () => resolve(Buffer.concat(chunks)))
|
|
31
|
+
req.on('error', reject)
|
|
32
|
+
})
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function collect(upstream) {
|
|
36
|
+
return new Promise((resolve, reject) => {
|
|
37
|
+
const chunks = []
|
|
38
|
+
upstream.on('data', (chunk) => chunks.push(chunk))
|
|
39
|
+
upstream.on('end', () => resolve(Buffer.concat(chunks)))
|
|
40
|
+
upstream.on('error', reject)
|
|
41
|
+
})
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 给一个带 viewer_caps 的对象补上 community.read;没有该字段就当作不用改。 */
|
|
45
|
+
function grantCommunityRead(container) {
|
|
46
|
+
if (!container || typeof container !== 'object') return false
|
|
47
|
+
const caps = container.viewer_caps
|
|
48
|
+
if (!Array.isArray(caps) || caps.includes('community.read')) return false
|
|
49
|
+
caps.push('community.read')
|
|
50
|
+
return true
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 回程 JSON 修补:解析失败或无需改动时原样返回。镜像直出时复用同一套规则。 */
|
|
54
|
+
export function offlinePatch(payload, mount, rest) {
|
|
55
|
+
let body
|
|
56
|
+
try {
|
|
57
|
+
body = JSON.parse(payload.toString('utf8'))
|
|
58
|
+
} catch {
|
|
59
|
+
return payload
|
|
60
|
+
}
|
|
61
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) return payload
|
|
62
|
+
|
|
63
|
+
if (rest === '/config.json') {
|
|
64
|
+
body.apiBaseUrl = mount || '/'
|
|
65
|
+
return Buffer.from(JSON.stringify(body), 'utf8')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
let changed = false
|
|
69
|
+
if (rest === '/api/gate' || rest === '/api/auth/me') {
|
|
70
|
+
changed = grantCommunityRead(body)
|
|
71
|
+
} else if (rest === '/api/bootstrap') {
|
|
72
|
+
const gateChanged = grantCommunityRead(body.gate)
|
|
73
|
+
const meChanged = grantCommunityRead(body.me)
|
|
74
|
+
changed = gateChanged || meChanged
|
|
75
|
+
}
|
|
76
|
+
return changed ? Buffer.from(JSON.stringify(body), 'utf8') : payload
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 需要回程修补的路径(镜像直出与反代共用单一定义,见 offlinePatch)。 */
|
|
80
|
+
export const PATCHED_PATHS = new Set(['/config.json', '/api/gate', '/api/auth/me', '/api/bootstrap'])
|
|
81
|
+
|
|
82
|
+
export function createProxyHandler({ backendUrl, mount = '', log } = {}) {
|
|
83
|
+
const backend = String(backendUrl || '').replace(/\/+$/, '')
|
|
84
|
+
const defaultPrefix = String(mount || '').replace(/\/+$/, '')
|
|
85
|
+
|
|
86
|
+
// 挂载点内的路径由调用方算好传进来(plugin.mjs 的 splitMount):宿主可能已经剥掉
|
|
87
|
+
// 前缀,也可能把整条路径原样递下来,这里不做二次猜测。
|
|
88
|
+
return async function proxy(req, res, url, options = {}) {
|
|
89
|
+
const prefix = String(options.mount ?? defaultPrefix).replace(/\/+$/, '')
|
|
90
|
+
const rest = options.pathname ?? url.pathname ?? '/'
|
|
91
|
+
|
|
92
|
+
let target
|
|
93
|
+
try {
|
|
94
|
+
target = new URL(`${backend}${rest}${url.search || ''}`)
|
|
95
|
+
} catch (error) {
|
|
96
|
+
log?.error?.(`offline-ddr0: 后端地址非法 ${backend}: ${error.message}`)
|
|
97
|
+
res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
|
|
98
|
+
res.end(JSON.stringify({ ok: false, error: 'backend misconfigured' }))
|
|
99
|
+
return true
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const headers = {}
|
|
103
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
104
|
+
const name = key.toLowerCase()
|
|
105
|
+
if (HOP_BY_HOP.has(name) || name === 'host' || name === 'content-length') continue
|
|
106
|
+
if (value !== undefined) headers[name] = value
|
|
107
|
+
}
|
|
108
|
+
headers.host = target.host
|
|
109
|
+
// 不让后端压缩回程,/config.json 需要明文改写。
|
|
110
|
+
headers['accept-encoding'] = 'identity'
|
|
111
|
+
|
|
112
|
+
let body
|
|
113
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
114
|
+
try {
|
|
115
|
+
body = await readBody(req)
|
|
116
|
+
} catch (error) {
|
|
117
|
+
log?.error?.(`offline-ddr0: 读取请求体失败: ${error.message}`)
|
|
118
|
+
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
119
|
+
res.end(JSON.stringify({ ok: false, error: 'request body unreadable' }))
|
|
120
|
+
return true
|
|
121
|
+
}
|
|
122
|
+
headers['content-length'] = String(body.length)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const sendRequest = target.protocol === 'https:' ? httpsRequest : httpRequest
|
|
126
|
+
const retryable = req.method === 'GET' || req.method === 'HEAD'
|
|
127
|
+
|
|
128
|
+
// 镜像链路偶发 TLS/连接抖动,读请求失败时重试一次再报 502。
|
|
129
|
+
function attempt(tries) {
|
|
130
|
+
const upstreamReq = sendRequest(target, { method: req.method, headers })
|
|
131
|
+
|
|
132
|
+
upstreamReq.setTimeout(20000, () => {
|
|
133
|
+
upstreamReq.destroy(new Error('upstream timeout'))
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
upstreamReq.on('response', async (upstream) => {
|
|
137
|
+
const responseHeaders = {}
|
|
138
|
+
for (const [key, value] of Object.entries(upstream.headers)) {
|
|
139
|
+
const name = key.toLowerCase()
|
|
140
|
+
if (HOP_BY_HOP.has(name) || name === 'content-encoding' || name === 'content-length') continue
|
|
141
|
+
if (value !== undefined) responseHeaders[name] = value
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (PATCHED_PATHS.has(rest)) {
|
|
145
|
+
try {
|
|
146
|
+
const payload = offlinePatch(await collect(upstream), prefix, rest)
|
|
147
|
+
responseHeaders['content-length'] = String(payload.length)
|
|
148
|
+
res.writeHead(upstream.statusCode || 200, responseHeaders)
|
|
149
|
+
res.end(payload)
|
|
150
|
+
} catch (error) {
|
|
151
|
+
log?.error?.(`offline-ddr0: 改写 ${rest} 失败: ${error.message}`)
|
|
152
|
+
if (!res.headersSent) {
|
|
153
|
+
res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
|
|
154
|
+
res.end(JSON.stringify({ ok: false, error: 'config rewrite failed' }))
|
|
155
|
+
} else {
|
|
156
|
+
res.destroy()
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
res.writeHead(upstream.statusCode || 200, responseHeaders)
|
|
163
|
+
upstream.pipe(res)
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
upstreamReq.on('error', (error) => {
|
|
167
|
+
if (retryable && tries < 2 && !res.headersSent) {
|
|
168
|
+
log?.warn?.(`offline-ddr0: 反代 ${target.pathname} 失败,重试一次: ${error.message}`)
|
|
169
|
+
attempt(tries + 1)
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
log?.warn?.(`offline-ddr0: 反代 ${target.pathname} 失败: ${error.message}`)
|
|
173
|
+
if (!res.headersSent) {
|
|
174
|
+
res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
|
|
175
|
+
res.end(JSON.stringify({ ok: false, error: 'backend request failed' }))
|
|
176
|
+
} else {
|
|
177
|
+
res.destroy()
|
|
178
|
+
}
|
|
179
|
+
})
|
|
180
|
+
|
|
181
|
+
if (body && body.length) upstreamReq.write(body)
|
|
182
|
+
upstreamReq.end()
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
attempt(1)
|
|
186
|
+
return true
|
|
187
|
+
}
|
|
188
|
+
}
|
package/lib/remote.mjs
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 主站远程客户端 —— 同步功能的传输层(lib/sync.mjs 消费)。
|
|
3
|
+
*
|
|
4
|
+
* 与 scripts/capture-mirror.mjs 同一套「直连源站」姿势:
|
|
5
|
+
* ddr0.com 的 CDN 到期后一律 512,但源站还活着。用 SNI=originHost + Host 头
|
|
6
|
+
* 直连源站 IP 绕开 CDN。这是**唯一**会出网的模块,且只在用户显式触发同步时调用
|
|
7
|
+
* (离线优先:serving 永远走 mirror/work-store,不依赖这里)。
|
|
8
|
+
*
|
|
9
|
+
* 可测试性:request 可注入(测试给 mock,不打真网络);默认实现用 node:https。
|
|
10
|
+
* 返回 { status, headers, body:Buffer, error? };status=0 表示网络层失败。
|
|
11
|
+
*/
|
|
12
|
+
import https from 'node:https'
|
|
13
|
+
import http from 'node:http'
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_ORIGIN_IP = '162.251.95.51'
|
|
16
|
+
export const DEFAULT_ORIGIN_HOST = 'ddr0.com'
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {object} opts
|
|
20
|
+
* @param {string} [opts.originIp] 源站 IP(env DDR0_ORIGIN_IP 覆盖)
|
|
21
|
+
* @param {string} [opts.originHost] SNI/Host(env DDR0_ORIGIN_HOST 覆盖)
|
|
22
|
+
* @param {string} [opts.token] x-session-token(env DSH_DDR0_SESSION;公开读可空)
|
|
23
|
+
* @param {number} [opts.timeoutMs] 单请求超时(缺省 60s,与 capture 一致)
|
|
24
|
+
* @param {Function} [opts.request] 注入传输 (pathWithSearch, method) => Promise<{status,headers,body,error?}>
|
|
25
|
+
* @param {object} [opts.log]
|
|
26
|
+
*/
|
|
27
|
+
export function createRemoteClient({
|
|
28
|
+
originIp = DEFAULT_ORIGIN_IP,
|
|
29
|
+
originHost = DEFAULT_ORIGIN_HOST,
|
|
30
|
+
token = '',
|
|
31
|
+
timeoutMs = 60000,
|
|
32
|
+
request: injectedRequest,
|
|
33
|
+
log,
|
|
34
|
+
} = {}) {
|
|
35
|
+
const IP = String(originIp || DEFAULT_ORIGIN_IP)
|
|
36
|
+
const HOST = String(originHost || DEFAULT_ORIGIN_HOST)
|
|
37
|
+
const TOKEN = String(token || '')
|
|
38
|
+
|
|
39
|
+
/** 默认传输:直连源站 IP,SNI/Host=originHost,跟随重定向 ≤4。 */
|
|
40
|
+
function defaultRequest(pathWithSearch, method = 'GET', redirects = 0) {
|
|
41
|
+
return new Promise((resolve) => {
|
|
42
|
+
const req = https.request(
|
|
43
|
+
{
|
|
44
|
+
host: IP,
|
|
45
|
+
servername: HOST,
|
|
46
|
+
port: 443,
|
|
47
|
+
path: pathWithSearch,
|
|
48
|
+
method,
|
|
49
|
+
rejectUnauthorized: false,
|
|
50
|
+
headers: {
|
|
51
|
+
Host: HOST,
|
|
52
|
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ddr0-offline-sync/1.0',
|
|
53
|
+
Accept: '*/*',
|
|
54
|
+
...(TOKEN ? { 'x-session-token': TOKEN } : {}),
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
(res) => {
|
|
58
|
+
const chunks = []
|
|
59
|
+
res.on('data', (c) => chunks.push(c))
|
|
60
|
+
res.on('end', () => {
|
|
61
|
+
const body = Buffer.concat(chunks)
|
|
62
|
+
const loc = res.headers.location
|
|
63
|
+
if (res.statusCode >= 300 && res.statusCode < 400 && loc && redirects < 4) {
|
|
64
|
+
let next = loc
|
|
65
|
+
if (loc.startsWith('http')) {
|
|
66
|
+
try { const u = new URL(loc); next = u.pathname + u.search } catch { /* 保留 loc */ }
|
|
67
|
+
}
|
|
68
|
+
return resolve(defaultRequest(next, method, redirects + 1))
|
|
69
|
+
}
|
|
70
|
+
resolve({ status: res.statusCode, headers: res.headers, body })
|
|
71
|
+
})
|
|
72
|
+
},
|
|
73
|
+
)
|
|
74
|
+
req.setTimeout(timeoutMs, () => req.destroy(new Error('timeout')))
|
|
75
|
+
req.on('error', (e) => resolve({ status: 0, headers: {}, body: Buffer.alloc(0), error: e.message }))
|
|
76
|
+
req.end()
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const request = typeof injectedRequest === 'function' ? injectedRequest : defaultRequest
|
|
81
|
+
|
|
82
|
+
/** GET 一个路径,返回 {status,headers,body,error?}。 */
|
|
83
|
+
async function get(pathWithSearch) {
|
|
84
|
+
return request(pathWithSearch, 'GET')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** GET 并解析 JSON;非 200 或解析失败返回 null(调用方据此判失败)。 */
|
|
88
|
+
async function getJson(pathWithSearch) {
|
|
89
|
+
const r = await get(pathWithSearch)
|
|
90
|
+
if (r.status !== 200) return null
|
|
91
|
+
try { return JSON.parse(r.body.toString('utf8')) } catch (err) {
|
|
92
|
+
log?.warn?.(`[remote] JSON 解析失败 ${pathWithSearch}: ${err?.message || err}`)
|
|
93
|
+
return null
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* GET 一个**绝对外部 URL**(媒体物化用:图床/视频外链不在源站上,不能走直连源站姿势)。
|
|
99
|
+
* 普通 http(s) 请求到 URL 自己的 host,跟随重定向 ≤4(可跨 host)。
|
|
100
|
+
* 注入 request 的 mock 客户端:fetchUrl 也走注入(测试统一 mock,不打真网络)。
|
|
101
|
+
*/
|
|
102
|
+
function defaultFetchUrl(url, redirects = 0) {
|
|
103
|
+
return new Promise((resolve) => {
|
|
104
|
+
let u
|
|
105
|
+
try { u = new URL(String(url)) } catch (e) {
|
|
106
|
+
return resolve({ status: 0, headers: {}, body: Buffer.alloc(0), error: `非法 URL: ${e.message}` })
|
|
107
|
+
}
|
|
108
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') {
|
|
109
|
+
return resolve({ status: 0, headers: {}, body: Buffer.alloc(0), error: `不支持的协议: ${u.protocol}` })
|
|
110
|
+
}
|
|
111
|
+
const mod = u.protocol === 'http:' ? http : https
|
|
112
|
+
const req = mod.request(
|
|
113
|
+
{
|
|
114
|
+
host: u.hostname,
|
|
115
|
+
port: u.port || (u.protocol === 'http:' ? 80 : 443),
|
|
116
|
+
servername: u.hostname,
|
|
117
|
+
path: u.pathname + u.search,
|
|
118
|
+
method: 'GET',
|
|
119
|
+
headers: {
|
|
120
|
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ddr0-offline-sync/1.0',
|
|
121
|
+
Accept: '*/*',
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
(res) => {
|
|
125
|
+
const chunks = []
|
|
126
|
+
res.on('data', (c) => chunks.push(c))
|
|
127
|
+
res.on('end', () => {
|
|
128
|
+
const body = Buffer.concat(chunks)
|
|
129
|
+
const loc = res.headers.location
|
|
130
|
+
if (res.statusCode >= 300 && res.statusCode < 400 && loc && redirects < 4) {
|
|
131
|
+
let next = loc
|
|
132
|
+
try { next = new URL(loc, u).toString() } catch { /* 保留 loc */ }
|
|
133
|
+
return resolve(defaultFetchUrl(next, redirects + 1))
|
|
134
|
+
}
|
|
135
|
+
resolve({ status: res.statusCode, headers: res.headers, body })
|
|
136
|
+
})
|
|
137
|
+
},
|
|
138
|
+
)
|
|
139
|
+
req.setTimeout(timeoutMs, () => req.destroy(new Error('timeout')))
|
|
140
|
+
req.on('error', (e) => resolve({ status: 0, headers: {}, body: Buffer.alloc(0), error: e.message }))
|
|
141
|
+
req.end()
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function fetchUrl(url) {
|
|
146
|
+
if (typeof injectedRequest === 'function') return injectedRequest(String(url), 'GET')
|
|
147
|
+
return defaultFetchUrl(url)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return {
|
|
151
|
+
get,
|
|
152
|
+
getJson,
|
|
153
|
+
fetchUrl,
|
|
154
|
+
get originHost() { return HOST },
|
|
155
|
+
get originIp() { return IP },
|
|
156
|
+
get hasToken() { return Boolean(TOKEN) },
|
|
157
|
+
}
|
|
158
|
+
}
|
package/lib/render.mjs
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 作品渲染层(STANDARD v2 附录 A:消费方 render 层)。
|
|
3
|
+
*
|
|
4
|
+
* 把「内容 → work-v1 可运行代码」的表现逻辑从存储层(store.mjs)剥离:
|
|
5
|
+
* - wrapHtml:完整 HTML → work-v1 契约(iframe srcdoc + Work.register);
|
|
6
|
+
* - wrapSession:会话消息体 → 自包含聊天查看器(含「在 DSH 中继续对话」深链);
|
|
7
|
+
* - defaultContinueUrl:会话深链缺省值(DSH_WEB_URL/?session=<id>)。
|
|
8
|
+
*
|
|
9
|
+
* 纯函数、无存储状态。存储层只负责把渲染产物当字节落盘,不关心 HTML/CSS/JS 模板。
|
|
10
|
+
* 注入防护:内容里的 `<` 统一转义为 \u003c,`</script>` 不会提前闭合脚本块。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export function wrapHtml(html) {
|
|
14
|
+
// 转义 < 防止内容里的 </script> 提前闭合脚本块(破坏/XSS)。
|
|
15
|
+
const doc = JSON.stringify(html).replace(/</g, '\\u003c')
|
|
16
|
+
return [
|
|
17
|
+
'(function () {',
|
|
18
|
+
` var DOC = ${doc};`,
|
|
19
|
+
' function fill(stage) {',
|
|
20
|
+
' var f = document.createElement("iframe");',
|
|
21
|
+
' f.setAttribute("style", "width:100%;height:100%;border:0;display:block;background:#fff");',
|
|
22
|
+
' f.srcdoc = DOC;',
|
|
23
|
+
' stage.appendChild(f);',
|
|
24
|
+
' }',
|
|
25
|
+
' if (typeof window !== "undefined" && window.Work && typeof window.Work.register === "function") {',
|
|
26
|
+
' window.Work.register({',
|
|
27
|
+
' mount: function (t) {',
|
|
28
|
+
' var stage = (t && t.stage) || document.body;',
|
|
29
|
+
' fill(stage);',
|
|
30
|
+
' if (t && typeof t.ready === "function") t.ready();',
|
|
31
|
+
' },',
|
|
32
|
+
' destroy: function () {}',
|
|
33
|
+
' });',
|
|
34
|
+
' } else {',
|
|
35
|
+
' document.open(); document.write(DOC); document.close();',
|
|
36
|
+
' }',
|
|
37
|
+
'})();',
|
|
38
|
+
].join('\n')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 会话查看器:自包含 HTML,渲染消息 + 「在 DSH 中继续对话」深链。 */
|
|
42
|
+
export function wrapSession(session) {
|
|
43
|
+
const data = JSON.stringify(session).replace(/</g, '\\u003c')
|
|
44
|
+
const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
45
|
+
<style>
|
|
46
|
+
:root{color-scheme:light dark}
|
|
47
|
+
body{margin:0;font:14px/1.6 system-ui,-apple-system,"Segoe UI",sans-serif;background:#f6f7f9;color:#222}
|
|
48
|
+
@media (prefers-color-scheme:dark){body{background:#14161a;color:#e6e6e6}}
|
|
49
|
+
header{position:sticky;top:0;display:flex;align-items:center;gap:8px;padding:10px 14px;background:rgba(128,128,128,.12);backdrop-filter:blur(6px)}
|
|
50
|
+
header h1{font-size:15px;margin:0;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
51
|
+
header .meta{font-size:12px;opacity:.65}
|
|
52
|
+
#log{max-width:860px;margin:0 auto;padding:16px 14px 90px}
|
|
53
|
+
.msg{margin:0 0 14px;display:flex}
|
|
54
|
+
.msg .bubble{max-width:80%;padding:10px 12px;border-radius:12px;white-space:pre-wrap;word-break:break-word;background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.08)}
|
|
55
|
+
@media (prefers-color-scheme:dark){.msg .bubble{background:#1e2126}}
|
|
56
|
+
.msg.user{justify-content:flex-end}
|
|
57
|
+
.msg.user .bubble{background:#d3e5ff;color:#123}
|
|
58
|
+
@media (prefers-color-scheme:dark){.msg.user .bubble{background:#24406b;color:#dce8ff}}
|
|
59
|
+
.msg .role{font-size:11px;opacity:.6;margin-bottom:4px}
|
|
60
|
+
footer{position:fixed;left:0;right:0;bottom:0;display:flex;justify-content:center;padding:12px;background:linear-gradient(transparent,rgba(0,0,0,.15))}
|
|
61
|
+
button{border:0;border-radius:10px;padding:10px 18px;font-size:14px;cursor:pointer;background:#3b82f6;color:#fff}
|
|
62
|
+
</style></head><body>
|
|
63
|
+
<header><h1 id="title"></h1><span class="meta" id="meta"></span></header>
|
|
64
|
+
<div id="log"></div>
|
|
65
|
+
<footer><button id="continue">在 DSH 中继续对话 →</button></footer>
|
|
66
|
+
<script>
|
|
67
|
+
var S = ${data};
|
|
68
|
+
document.getElementById('title').textContent = S.title || '会话记录';
|
|
69
|
+
document.getElementById('meta').textContent = (S.model || '') + ' · ' + (S.messages || []).length + ' 条';
|
|
70
|
+
var log = document.getElementById('log');
|
|
71
|
+
(S.messages || []).forEach(function (m) {
|
|
72
|
+
var row = document.createElement('div'); row.className = 'msg ' + (m.role === 'user' ? 'user' : 'assistant');
|
|
73
|
+
var b = document.createElement('div'); b.className = 'bubble';
|
|
74
|
+
var r = document.createElement('div'); r.className = 'role'; r.textContent = m.role === 'user' ? '我' : 'AI';
|
|
75
|
+
var t = document.createElement('div'); t.textContent = m.content || '';
|
|
76
|
+
b.appendChild(r); b.appendChild(t); row.appendChild(b); log.appendChild(row);
|
|
77
|
+
});
|
|
78
|
+
window.scrollTo(0, document.body.scrollHeight);
|
|
79
|
+
document.getElementById('continue').addEventListener('click', function () {
|
|
80
|
+
if (S.continueUrl) { window.open(S.continueUrl, '_blank'); }
|
|
81
|
+
else { alert('未配置 continueUrl:请在入库时提供 session.continueUrl(DSH 会话深链)。'); }
|
|
82
|
+
});
|
|
83
|
+
</script></body></html>`
|
|
84
|
+
return wrapHtml(html)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 会话「继续对话」深链缺省值:显式 continueUrl > DSH_WEB_URL/?session=<sessionId> > ''。 */
|
|
88
|
+
export function defaultContinueUrl(session) {
|
|
89
|
+
if (session.continueUrl) return session.continueUrl
|
|
90
|
+
const base = process.env.DSH_WEB_URL || ''
|
|
91
|
+
if (base && session.sessionId) return `${base.replace(/\/+$/, '')}/?session=${encodeURIComponent(session.sessionId)}`
|
|
92
|
+
return ''
|
|
93
|
+
}
|