@chainlesschain/personal-data-hub 0.4.18 → 0.4.24

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.
Files changed (53) hide show
  1. package/__tests__/adapters/bank-family.test.js +125 -0
  2. package/__tests__/adapters/biz-tianyancha.test.js +159 -0
  3. package/__tests__/adapters/car-mercedesme.test.js +74 -0
  4. package/__tests__/adapters/doc-camscanner.test.js +147 -0
  5. package/__tests__/adapters/finance-dcep.test.js +74 -0
  6. package/__tests__/adapters/fitness-joyrun.test.js +82 -0
  7. package/__tests__/adapters/gov-12123.test.js +103 -0
  8. package/__tests__/adapters/gov-ixiamen.test.js +150 -0
  9. package/__tests__/adapters/gov-tax.test.js +135 -0
  10. package/__tests__/adapters/health-meiyou.test.js +125 -0
  11. package/__tests__/adapters/music-qq.test.js +112 -0
  12. package/__tests__/adapters/reading-family.test.js +108 -0
  13. package/__tests__/adapters/social-dongchedi.test.js +165 -0
  14. package/__tests__/adapters/travel-didi-consumer.test.js +66 -0
  15. package/__tests__/adapters/video-xigua.test.js +106 -0
  16. package/__tests__/adapters/wework-pc.test.js +124 -0
  17. package/__tests__/audio-ximalaya-snapshot.test.js +279 -0
  18. package/__tests__/fitness-keep-snapshot.test.js +224 -0
  19. package/__tests__/shopping-eleme-snapshot.test.js +454 -0
  20. package/__tests__/shopping-vipshop-snapshot.test.js +425 -0
  21. package/__tests__/shopping-xianyu-snapshot.test.js +451 -0
  22. package/__tests__/social-douban-snapshot.test.js +351 -0
  23. package/lib/adapter-guide.js +31 -3
  24. package/lib/adapters/_bank-base.js +405 -0
  25. package/lib/adapters/_reading-base.js +315 -0
  26. package/lib/adapters/audio-ximalaya/index.js +414 -0
  27. package/lib/adapters/bank-bankcomm/index.js +27 -0
  28. package/lib/adapters/bank-boc/index.js +26 -0
  29. package/lib/adapters/bank-cmbc/index.js +26 -0
  30. package/lib/adapters/bank-icbc/index.js +27 -0
  31. package/lib/adapters/biz-tianyancha/index.js +348 -0
  32. package/lib/adapters/car-mercedesme/index.js +225 -0
  33. package/lib/adapters/doc-camscanner/index.js +102 -0
  34. package/lib/adapters/finance-dcep/index.js +302 -0
  35. package/lib/adapters/fitness-joyrun/index.js +295 -0
  36. package/lib/adapters/fitness-keep/index.js +343 -0
  37. package/lib/adapters/gov-12123/index.js +391 -0
  38. package/lib/adapters/gov-ixiamen/index.js +380 -0
  39. package/lib/adapters/gov-tax/index.js +451 -0
  40. package/lib/adapters/health-meiyou/index.js +393 -0
  41. package/lib/adapters/music-qq/index.js +372 -0
  42. package/lib/adapters/reading-fanqie/index.js +61 -0
  43. package/lib/adapters/reading-qimao/index.js +61 -0
  44. package/lib/adapters/shopping-eleme/index.js +441 -0
  45. package/lib/adapters/shopping-vipshop/index.js +429 -0
  46. package/lib/adapters/shopping-xianyu/index.js +454 -0
  47. package/lib/adapters/social-dongchedi/index.js +360 -0
  48. package/lib/adapters/social-douban/index.js +564 -0
  49. package/lib/adapters/travel-didi-consumer/index.js +148 -0
  50. package/lib/adapters/video-xigua/index.js +68 -0
  51. package/lib/adapters/wework-pc/index.js +31 -0
  52. package/lib/index.js +52 -0
  53. package/package.json +1 -1
@@ -0,0 +1,302 @@
1
+ /**
2
+ * §12.1 Phase 13+ ⭐⭐⭐ — 数字人民币 (DCEP / e-CNY, cn.gov.pbc.dcep) adapter,
3
+ * "DCEP 交易". BEST-EFFORT SCAFFOLD (user-requested).
4
+ *
5
+ * ⚠️ MAXIMALLY SENSITIVE (central-bank digital-currency wallet, real-name +
6
+ * strong-auth). The DCEP app has NO documented public API; the cookie-api
7
+ * endpoint below is a FABRICATED placeholder (overridable via opts.listUrl,
8
+ * NOT field-verified — FAMILY-23 playbook) and cannot authenticate without the
9
+ * app's real login. **snapshot mode is the reliable path**; cookie path
10
+ * surfaces auth.unverified=true. Gated sensitivity:"high" + legalGate:true.
11
+ *
12
+ * One record kind: 钱包交易 (wallet transactions):
13
+ * { txId, time, amount, direction(pay付款/receive收款), counterparty, walletType(子钱包) }
14
+ * → EVENT(PAYMENT).
15
+ *
16
+ * Snapshot schema (schemaVersion 1):
17
+ * {
18
+ * "schemaVersion": 1, "snapshottedAt": <ms>,
19
+ * "account": { "userId": "...", "name": "..." },
20
+ * "events": [
21
+ * { "kind": "transaction", "id": "tx-<id>", "txId": "...", "time": <s|ms>,
22
+ * "amount": 12.5, "direction": "pay", "counterparty": "某商户",
23
+ * "walletType": "中国银行子钱包" }
24
+ * ]
25
+ * }
26
+ */
27
+
28
+ "use strict";
29
+
30
+ const fs = require("node:fs");
31
+ const { newId } = require("../../ids");
32
+ const { ENTITY_TYPES, EVENT_SUBTYPES, CAPTURED_BY } = require("../../constants");
33
+ const { CookieAuth } = require("../shopping-base");
34
+
35
+ const NAME = "finance-dcep";
36
+ const VERSION = "0.1.0";
37
+ const SNAPSHOT_SCHEMA_VERSION = 1;
38
+ const KIND_TX = "transaction";
39
+ const VALID_SNAPSHOT_KINDS = Object.freeze([KIND_TX]);
40
+ const DCEP_LIST_URL = "https://dcep.pbc.gov.cn/api/v1/wallet/transactions";
41
+ const PAGE_SIZE = 30;
42
+
43
+ function parseTime(v) {
44
+ if (Number.isFinite(v)) return v > 1e12 ? v : v >= 1e9 ? v * 1000 : v;
45
+ if (typeof v === "string") {
46
+ if (/^\d+$/.test(v)) {
47
+ const n = parseInt(v, 10);
48
+ return n > 1e12 ? n : n >= 1e9 ? n * 1000 : n;
49
+ }
50
+ const t = Date.parse(v);
51
+ return Number.isFinite(t) ? t : null;
52
+ }
53
+ return null;
54
+ }
55
+
56
+ function toAmount(v) {
57
+ if (Number.isFinite(v)) return v;
58
+ if (typeof v === "string") {
59
+ const n = parseFloat(v.replace(/[,,¥\s]/g, ""));
60
+ return Number.isFinite(n) ? n : null;
61
+ }
62
+ return null;
63
+ }
64
+
65
+ function normDirection(raw) {
66
+ const d = String(raw.direction || raw.type || raw.dcFlag || "").toLowerCase();
67
+ if (/receive|收款|收入|入账|贷|\+/.test(d)) return "receive";
68
+ if (/pay|付款|支出|出账|借|-/.test(d)) return "pay";
69
+ const amt = toAmount(raw.amount);
70
+ if (Number.isFinite(amt)) return amt < 0 ? "pay" : "receive";
71
+ return "pay";
72
+ }
73
+
74
+ function mapTx(raw) {
75
+ if (!raw || typeof raw !== "object") return null;
76
+ const id = raw.txId || raw.tx_id || raw.id || raw.serialNo || raw.orderNo;
77
+ if (id == null) return null;
78
+ const amt = toAmount(raw.amount != null ? raw.amount : raw.amt);
79
+ return {
80
+ txId: String(id),
81
+ timeMs: parseTime(raw.time || raw.tradeTime || raw.trade_time || raw.date),
82
+ amount: amt != null ? Math.abs(amt) : null,
83
+ direction: normDirection(raw),
84
+ counterparty: raw.counterparty || raw.merchant || raw.payee || raw.oppName || null,
85
+ walletType: raw.walletType || raw.wallet_type || raw.subWallet || raw.bank || null,
86
+ };
87
+ }
88
+
89
+ function extractList(resp) {
90
+ if (!resp || typeof resp !== "object") return [];
91
+ if (Array.isArray(resp.list)) return resp.list;
92
+ if (Array.isArray(resp.data)) return resp.data;
93
+ const d = resp.data;
94
+ if (d && typeof d === "object") {
95
+ if (Array.isArray(d.list)) return d.list;
96
+ if (Array.isArray(d.records)) return d.records;
97
+ }
98
+ return [];
99
+ }
100
+
101
+ function stableOriginalId(id) {
102
+ const safe =
103
+ (typeof id === "string" && id.length > 0 && id) ||
104
+ (typeof id === "number" && Number.isFinite(id) && String(id)) ||
105
+ `unknown-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
106
+ return `dcep:transaction:${safe}`;
107
+ }
108
+
109
+ class DcepAdapter {
110
+ constructor(opts = {}) {
111
+ this.account = opts.account || null;
112
+ this._cookieAuth =
113
+ opts.account && opts.account.cookies ? new CookieAuth({ platform: "dcep", cookies: opts.account.cookies }) : null;
114
+ this._fetchFn = typeof opts.fetchFn === "function" ? opts.fetchFn : defaultFetch;
115
+ this._signProvider = typeof opts.signProvider === "function" ? opts.signProvider : null;
116
+ this._listUrl = typeof opts.listUrl === "string" && opts.listUrl.length > 0 ? opts.listUrl : DCEP_LIST_URL;
117
+
118
+ this.name = NAME;
119
+ this.version = VERSION;
120
+ this.capabilities = ["sync:snapshot", "sync:cookie-api", "parse:dcep-transaction"];
121
+ this.extractMode = "web-api";
122
+ this.rateLimits = { perMinute: 5, perDay: 60 };
123
+ this.dataDisclosure = {
124
+ fields: ["dcep:transaction (time / amount / direction / counterparty / walletType)"],
125
+ sensitivity: "high",
126
+ legalGate: true,
127
+ defaultInclude: { transaction: true },
128
+ };
129
+ this._deps = { fs };
130
+ }
131
+
132
+ async authenticate(ctx = {}) {
133
+ if (ctx && typeof ctx.inputPath === "string" && ctx.inputPath.length > 0) {
134
+ try {
135
+ this._deps.fs.accessSync(ctx.inputPath, this._deps.fs.constants.R_OK);
136
+ } catch (err) {
137
+ return { ok: false, reason: "INPUT_PATH_UNREADABLE", message: `snapshot not readable at ${ctx.inputPath}: ${err.message}` };
138
+ }
139
+ return { ok: true, mode: "snapshot-file" };
140
+ }
141
+ if (this._cookieAuth) {
142
+ const ok = await this._cookieAuth.validate();
143
+ if (!ok) return { ok: false, reason: "INVALID_COOKIE", error: "cookies missing" };
144
+ return { ok: true, account: (this.account && this.account.userId) || null, mode: "cookie", unverified: true };
145
+ }
146
+ return {
147
+ ok: false,
148
+ reason: "NO_INPUT",
149
+ message: "finance-dcep.authenticate: needs opts.inputPath (snapshot mode) OR opts.account.cookies (cookie-api mode, best-effort/unverified)",
150
+ };
151
+ }
152
+
153
+ async healthCheck() {
154
+ if (this._cookieAuth) {
155
+ const r = await this.authenticate();
156
+ return r.ok ? { ok: true, lastChecked: Date.now(), unverified: true } : { ok: false, reason: r.reason, error: r.error };
157
+ }
158
+ return { ok: true, lastChecked: Date.now() };
159
+ }
160
+
161
+ async *sync(opts = {}) {
162
+ if (typeof opts.inputPath === "string" && opts.inputPath.length > 0) {
163
+ yield* this._syncViaSnapshot(opts);
164
+ return;
165
+ }
166
+ if (this._cookieAuth) {
167
+ yield* this._syncViaCookie(opts);
168
+ return;
169
+ }
170
+ throw new Error("finance-dcep.sync: needs opts.inputPath (snapshot mode) OR opts.account.cookies (cookie-api mode)");
171
+ }
172
+
173
+ async *_syncViaSnapshot(opts) {
174
+ const raw = this._deps.fs.readFileSync(opts.inputPath, "utf-8");
175
+ const snapshot = JSON.parse(raw);
176
+ if (!snapshot || typeof snapshot !== "object" || snapshot.schemaVersion !== SNAPSHOT_SCHEMA_VERSION) {
177
+ throw new Error(`finance-dcep.sync: snapshot schemaVersion mismatch (got ${snapshot && snapshot.schemaVersion}, expected ${SNAPSHOT_SCHEMA_VERSION})`);
178
+ }
179
+ const fallbackCapturedAt =
180
+ Number.isFinite(snapshot.snapshottedAt) && snapshot.snapshottedAt > 0 ? Math.floor(snapshot.snapshottedAt) : Date.now();
181
+ const account = snapshot.account && typeof snapshot.account === "object" ? snapshot.account : null;
182
+ const include = opts.include || {};
183
+ const limit = Number.isInteger(opts.limit) && opts.limit > 0 ? opts.limit : Infinity;
184
+
185
+ const events = Array.isArray(snapshot.events) ? snapshot.events : [];
186
+ let emitted = 0;
187
+ for (const ev of events) {
188
+ if (emitted >= limit) return;
189
+ if (!ev || typeof ev !== "object") continue;
190
+ if (!VALID_SNAPSHOT_KINDS.includes(ev.kind)) continue;
191
+ if (include[ev.kind] === false) continue;
192
+ const rec = mapTx(ev);
193
+ if (!rec) continue;
194
+ const capturedAt = parseTime(ev.capturedAt) || rec.timeMs || fallbackCapturedAt;
195
+ yield {
196
+ adapter: NAME,
197
+ kind: KIND_TX,
198
+ originalId: stableOriginalId(rec.txId),
199
+ capturedAt,
200
+ payload: { record: rec, account },
201
+ };
202
+ emitted += 1;
203
+ }
204
+ }
205
+
206
+ async *_syncViaCookie(opts = {}) {
207
+ if (!(await this._cookieAuth.validate())) return;
208
+ const cookies = this._cookieAuth.toHeader();
209
+ const include = opts.include || {};
210
+ if (include[KIND_TX] === false) return;
211
+ const limit = Number.isInteger(opts.limit) && opts.limit > 0 ? opts.limit : Infinity;
212
+ const maxPages = Number.isInteger(opts.maxPages) && opts.maxPages > 0 ? opts.maxPages : 12;
213
+
214
+ let emitted = 0;
215
+ let page = 1;
216
+ while (page <= maxPages) {
217
+ const query = { page, size: PAGE_SIZE };
218
+ let sign = null;
219
+ if (this._signProvider) sign = await this._signProvider({ url: this._listUrl, query, cookies });
220
+ const resp = await this._fetchFn({ url: this._listUrl, cookies, query, sign });
221
+ const items = extractList(resp);
222
+ if (!items.length) break;
223
+ for (const it of items) {
224
+ const rec = mapTx(it);
225
+ if (!rec) continue;
226
+ if (emitted >= limit) return;
227
+ yield {
228
+ adapter: NAME,
229
+ kind: KIND_TX,
230
+ originalId: stableOriginalId(rec.txId),
231
+ capturedAt: rec.timeMs || Date.now(),
232
+ payload: { record: rec, cookie: true },
233
+ };
234
+ emitted += 1;
235
+ }
236
+ if (items.length < PAGE_SIZE) break;
237
+ page += 1;
238
+ }
239
+ }
240
+
241
+ normalize(raw) {
242
+ if (!raw || !raw.payload || !raw.payload.record) {
243
+ throw new Error("DcepAdapter.normalize: payload.record missing");
244
+ }
245
+ const rec = raw.payload.record;
246
+ const ingestedAt = Date.now();
247
+ const occurredAt = rec.timeMs || raw.capturedAt || ingestedAt;
248
+ const source = {
249
+ adapter: NAME,
250
+ adapterVersion: VERSION,
251
+ originalId: raw.originalId,
252
+ capturedAt: raw.capturedAt || occurredAt,
253
+ capturedBy: CAPTURED_BY.API,
254
+ };
255
+ const arrow = rec.direction === "receive" ? "收款" : "付款";
256
+ return {
257
+ events: [
258
+ {
259
+ id: newId(),
260
+ type: ENTITY_TYPES.EVENT,
261
+ subtype: EVENT_SUBTYPES.PAYMENT,
262
+ occurredAt,
263
+ actor: "person-self",
264
+ content: {
265
+ title: `数字人民币${arrow}${rec.counterparty ? `: ${rec.counterparty}` : ""}`.slice(0, 80),
266
+ text: rec.counterparty || "数字人民币交易",
267
+ },
268
+ ingestedAt,
269
+ source,
270
+ extra: {
271
+ platform: "dcep",
272
+ kind: KIND_TX,
273
+ amount: rec.amount,
274
+ direction: rec.direction,
275
+ counterparty: rec.counterparty || null,
276
+ walletType: rec.walletType || null,
277
+ },
278
+ },
279
+ ],
280
+ persons: [],
281
+ places: [],
282
+ items: [],
283
+ topics: [],
284
+ };
285
+ }
286
+ }
287
+
288
+ async function defaultFetch(_opts) {
289
+ throw new Error("finance-dcep: no fetchFn configured for cookie-api mode");
290
+ }
291
+
292
+ module.exports = {
293
+ DcepAdapter,
294
+ mapTx,
295
+ extractList,
296
+ normDirection,
297
+ parseTime,
298
+ NAME,
299
+ VERSION,
300
+ SNAPSHOT_SCHEMA_VERSION,
301
+ VALID_SNAPSHOT_KINDS,
302
+ };
@@ -0,0 +1,295 @@
1
+ /**
2
+ * §12.1 Phase 13+ — 悦跑圈 (Joyrun, co.runner.app) adapter, "跑步记录".
3
+ * Device-discovered gap (2026-06-15), new `fitness-` category.
4
+ *
5
+ * BEST-EFFORT SCAFFOLD: thejoyrun.com endpoints are FABRICATED placeholders
6
+ * (overridable via opts.listUrl, NOT field-verified — FAMILY-23 playbook);
7
+ * snapshot mode is the reliable path; cookie path surfaces auth.unverified=true.
8
+ * Running records carry GPS/route info → sensitivity:"medium" (legalGate off,
9
+ * like the travel adapters).
10
+ *
11
+ * One record kind: 跑步记录 (runs):
12
+ * { runId, time, distanceMeters, durationSec, paceSecPerKm, calories, steps }
13
+ * → EVENT(OTHER) "跑步 X.XX km".
14
+ *
15
+ * Snapshot schema (schemaVersion 1):
16
+ * {
17
+ * "schemaVersion": 1, "snapshottedAt": <ms>,
18
+ * "account": { "userId": "...", "name": "..." },
19
+ * "events": [
20
+ * { "kind": "run", "id": "r-<id>", "runId": "...", "time": <s|ms>,
21
+ * "distanceMeters": 5230, "durationSec": 1800, "paceSecPerKm": 344,
22
+ * "calories": 320, "steps": 6400 }
23
+ * ]
24
+ * }
25
+ */
26
+
27
+ "use strict";
28
+
29
+ const fs = require("node:fs");
30
+ const { newId } = require("../../ids");
31
+ const { ENTITY_TYPES, EVENT_SUBTYPES, CAPTURED_BY } = require("../../constants");
32
+ const { CookieAuth } = require("../shopping-base");
33
+
34
+ const NAME = "fitness-joyrun";
35
+ const VERSION = "0.1.0";
36
+ const SNAPSHOT_SCHEMA_VERSION = 1;
37
+ const KIND_RUN = "run";
38
+ const VALID_SNAPSHOT_KINDS = Object.freeze([KIND_RUN]);
39
+ const RUNS_URL = "https://api.thejoyrun.com/v1/user/runs";
40
+ const PAGE_SIZE = 30;
41
+
42
+ function parseTime(v) {
43
+ if (Number.isFinite(v)) return v > 1e12 ? v : v >= 1e9 ? v * 1000 : v;
44
+ if (typeof v === "string") {
45
+ if (/^\d+$/.test(v)) {
46
+ const n = parseInt(v, 10);
47
+ return n > 1e12 ? n : n >= 1e9 ? n * 1000 : n;
48
+ }
49
+ const t = Date.parse(v);
50
+ return Number.isFinite(t) ? t : null;
51
+ }
52
+ return null;
53
+ }
54
+
55
+ function toNum(v) {
56
+ if (Number.isFinite(v)) return v;
57
+ if (typeof v === "string") {
58
+ const n = parseFloat(v);
59
+ return Number.isFinite(n) ? n : null;
60
+ }
61
+ return null;
62
+ }
63
+
64
+ function mapRun(raw) {
65
+ if (!raw || typeof raw !== "object") return null;
66
+ const id = raw.runId || raw.run_id || raw.id || raw.fid || raw.postRunId;
67
+ if (id == null) return null;
68
+ // distance may arrive in meters or kilometers; meter field wins, else km*1000.
69
+ let meters = toNum(raw.distanceMeters != null ? raw.distanceMeters : raw.meter != null ? raw.meter : raw.distance);
70
+ if (meters != null && meters < 1000 && raw.distanceMeters == null && raw.meter == null) {
71
+ // looked like kilometers
72
+ meters = meters * 1000;
73
+ }
74
+ return {
75
+ runId: String(id),
76
+ timeMs: parseTime(raw.time || raw.starttime || raw.start_time || raw.date || raw.utc),
77
+ distanceMeters: meters,
78
+ durationSec: toNum(raw.durationSec != null ? raw.durationSec : raw.second != null ? raw.second : raw.totaltime),
79
+ paceSecPerKm: toNum(raw.paceSecPerKm != null ? raw.paceSecPerKm : raw.pace),
80
+ calories: toNum(raw.calories != null ? raw.calories : raw.cal != null ? raw.cal : raw.dohas),
81
+ steps: toNum(raw.steps != null ? raw.steps : raw.stepcount),
82
+ };
83
+ }
84
+
85
+ function extractList(resp) {
86
+ if (!resp || typeof resp !== "object") return [];
87
+ if (Array.isArray(resp.list)) return resp.list;
88
+ if (Array.isArray(resp.data)) return resp.data;
89
+ const d = resp.data;
90
+ if (d && typeof d === "object") {
91
+ if (Array.isArray(d.list)) return d.list;
92
+ if (Array.isArray(d.runs)) return d.runs;
93
+ if (Array.isArray(d.records)) return d.records;
94
+ }
95
+ return [];
96
+ }
97
+
98
+ function stableOriginalId(id) {
99
+ const safe =
100
+ (typeof id === "string" && id.length > 0 && id) ||
101
+ (typeof id === "number" && Number.isFinite(id) && String(id)) ||
102
+ `unknown-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
103
+ return `joyrun:run:${safe}`;
104
+ }
105
+
106
+ class JoyrunAdapter {
107
+ constructor(opts = {}) {
108
+ this.account = opts.account || null;
109
+ this._cookieAuth =
110
+ opts.account && opts.account.cookies ? new CookieAuth({ platform: "joyrun", cookies: opts.account.cookies }) : null;
111
+ this._fetchFn = typeof opts.fetchFn === "function" ? opts.fetchFn : defaultFetch;
112
+ this._signProvider = typeof opts.signProvider === "function" ? opts.signProvider : null;
113
+ this._listUrl = typeof opts.listUrl === "string" && opts.listUrl.length > 0 ? opts.listUrl : RUNS_URL;
114
+
115
+ this.name = NAME;
116
+ this.version = VERSION;
117
+ this.capabilities = ["sync:snapshot", "sync:cookie-api", "parse:joyrun-run"];
118
+ this.extractMode = "web-api";
119
+ this.rateLimits = {};
120
+ this.dataDisclosure = {
121
+ fields: ["joyrun:run (distance / duration / pace / calories / steps — carries GPS route)"],
122
+ sensitivity: "medium",
123
+ legalGate: false,
124
+ defaultInclude: { run: true },
125
+ };
126
+ this._deps = { fs };
127
+ }
128
+
129
+ async authenticate(ctx = {}) {
130
+ if (ctx && typeof ctx.inputPath === "string" && ctx.inputPath.length > 0) {
131
+ try {
132
+ this._deps.fs.accessSync(ctx.inputPath, this._deps.fs.constants.R_OK);
133
+ } catch (err) {
134
+ return { ok: false, reason: "INPUT_PATH_UNREADABLE", message: `snapshot not readable at ${ctx.inputPath}: ${err.message}` };
135
+ }
136
+ return { ok: true, mode: "snapshot-file" };
137
+ }
138
+ if (this._cookieAuth) {
139
+ const ok = await this._cookieAuth.validate();
140
+ if (!ok) return { ok: false, reason: "INVALID_COOKIE", error: "cookies missing" };
141
+ return { ok: true, account: (this.account && this.account.userId) || null, mode: "cookie", unverified: true };
142
+ }
143
+ return {
144
+ ok: false,
145
+ reason: "NO_INPUT",
146
+ message: "fitness-joyrun.authenticate: needs opts.inputPath (snapshot mode) OR opts.account.cookies (cookie-api mode, best-effort/unverified)",
147
+ };
148
+ }
149
+
150
+ async healthCheck() {
151
+ if (this._cookieAuth) {
152
+ const r = await this.authenticate();
153
+ return r.ok ? { ok: true, lastChecked: Date.now(), unverified: true } : { ok: false, reason: r.reason, error: r.error };
154
+ }
155
+ return { ok: true, lastChecked: Date.now() };
156
+ }
157
+
158
+ async *sync(opts = {}) {
159
+ if (typeof opts.inputPath === "string" && opts.inputPath.length > 0) {
160
+ yield* this._syncViaSnapshot(opts);
161
+ return;
162
+ }
163
+ if (this._cookieAuth) {
164
+ yield* this._syncViaCookie(opts);
165
+ return;
166
+ }
167
+ throw new Error("fitness-joyrun.sync: needs opts.inputPath (snapshot mode) OR opts.account.cookies (cookie-api mode)");
168
+ }
169
+
170
+ async *_syncViaSnapshot(opts) {
171
+ const raw = this._deps.fs.readFileSync(opts.inputPath, "utf-8");
172
+ const snapshot = JSON.parse(raw);
173
+ if (!snapshot || typeof snapshot !== "object" || snapshot.schemaVersion !== SNAPSHOT_SCHEMA_VERSION) {
174
+ throw new Error(`fitness-joyrun.sync: snapshot schemaVersion mismatch (got ${snapshot && snapshot.schemaVersion}, expected ${SNAPSHOT_SCHEMA_VERSION})`);
175
+ }
176
+ const fallback =
177
+ Number.isFinite(snapshot.snapshottedAt) && snapshot.snapshottedAt > 0 ? Math.floor(snapshot.snapshottedAt) : Date.now();
178
+ const account = snapshot.account && typeof snapshot.account === "object" ? snapshot.account : null;
179
+ const include = opts.include || {};
180
+ const limit = Number.isInteger(opts.limit) && opts.limit > 0 ? opts.limit : Infinity;
181
+ const events = Array.isArray(snapshot.events) ? snapshot.events : [];
182
+ let emitted = 0;
183
+ for (const ev of events) {
184
+ if (emitted >= limit) return;
185
+ if (!ev || typeof ev !== "object" || !VALID_SNAPSHOT_KINDS.includes(ev.kind)) continue;
186
+ if (include[ev.kind] === false) continue;
187
+ const rec = mapRun(ev);
188
+ if (!rec) continue;
189
+ const capturedAt = parseTime(ev.capturedAt) || rec.timeMs || fallback;
190
+ yield {
191
+ adapter: NAME,
192
+ kind: KIND_RUN,
193
+ originalId: stableOriginalId(rec.runId),
194
+ capturedAt,
195
+ payload: { record: rec, account },
196
+ };
197
+ emitted += 1;
198
+ }
199
+ }
200
+
201
+ async *_syncViaCookie(opts = {}) {
202
+ if (!(await this._cookieAuth.validate())) return;
203
+ const cookies = this._cookieAuth.toHeader();
204
+ const include = opts.include || {};
205
+ if (include[KIND_RUN] === false) return;
206
+ const limit = Number.isInteger(opts.limit) && opts.limit > 0 ? opts.limit : Infinity;
207
+ const maxPages = Number.isInteger(opts.maxPages) && opts.maxPages > 0 ? opts.maxPages : 10;
208
+
209
+ let emitted = 0;
210
+ let page = 1;
211
+ while (page <= maxPages) {
212
+ const query = { page, pageSize: PAGE_SIZE };
213
+ let sign = null;
214
+ if (this._signProvider) sign = await this._signProvider({ url: this._listUrl, query, cookies });
215
+ const resp = await this._fetchFn({ url: this._listUrl, cookies, query, sign });
216
+ const items = extractList(resp);
217
+ if (!items.length) break;
218
+ for (const it of items) {
219
+ const rec = mapRun(it);
220
+ if (!rec) continue;
221
+ if (emitted >= limit) return;
222
+ yield {
223
+ adapter: NAME,
224
+ kind: KIND_RUN,
225
+ originalId: stableOriginalId(rec.runId),
226
+ capturedAt: rec.timeMs || Date.now(),
227
+ payload: { record: rec, cookie: true },
228
+ };
229
+ emitted += 1;
230
+ }
231
+ if (items.length < PAGE_SIZE) break;
232
+ page += 1;
233
+ }
234
+ }
235
+
236
+ normalize(raw) {
237
+ if (!raw || !raw.payload || !raw.payload.record) {
238
+ throw new Error("JoyrunAdapter.normalize: payload.record missing");
239
+ }
240
+ const rec = raw.payload.record;
241
+ const ingestedAt = Date.now();
242
+ const occurredAt = rec.timeMs || raw.capturedAt || ingestedAt;
243
+ const source = {
244
+ adapter: NAME,
245
+ adapterVersion: VERSION,
246
+ originalId: raw.originalId,
247
+ capturedAt: raw.capturedAt || occurredAt,
248
+ capturedBy: CAPTURED_BY.API,
249
+ };
250
+ const km = rec.distanceMeters != null ? (rec.distanceMeters / 1000).toFixed(2) : null;
251
+ return {
252
+ events: [
253
+ {
254
+ id: newId(),
255
+ type: ENTITY_TYPES.EVENT,
256
+ subtype: EVENT_SUBTYPES.OTHER,
257
+ occurredAt,
258
+ actor: "person-self",
259
+ content: { title: km != null ? `跑步 ${km} km` : "跑步记录", text: "跑步记录" },
260
+ ingestedAt,
261
+ source,
262
+ extra: {
263
+ platform: "joyrun",
264
+ kind: KIND_RUN,
265
+ distanceMeters: rec.distanceMeters,
266
+ durationSec: rec.durationSec,
267
+ paceSecPerKm: rec.paceSecPerKm,
268
+ calories: rec.calories,
269
+ steps: rec.steps,
270
+ },
271
+ },
272
+ ],
273
+ persons: [],
274
+ places: [],
275
+ items: [],
276
+ topics: [],
277
+ };
278
+ }
279
+ }
280
+
281
+ async function defaultFetch(_opts) {
282
+ throw new Error("fitness-joyrun: no fetchFn configured for cookie-api mode");
283
+ }
284
+
285
+ module.exports = {
286
+ JoyrunAdapter,
287
+ mapRun,
288
+ extractList,
289
+ toNum,
290
+ parseTime,
291
+ NAME,
292
+ VERSION,
293
+ SNAPSHOT_SCHEMA_VERSION,
294
+ VALID_SNAPSHOT_KINDS,
295
+ };