@chainlesschain/personal-data-hub 0.4.23 → 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 (37) hide show
  1. package/__tests__/adapters/bank-family.test.js +125 -0
  2. package/__tests__/adapters/car-mercedesme.test.js +74 -0
  3. package/__tests__/adapters/finance-dcep.test.js +74 -0
  4. package/__tests__/adapters/fitness-joyrun.test.js +82 -0
  5. package/__tests__/adapters/gov-12123.test.js +103 -0
  6. package/__tests__/adapters/music-qq.test.js +112 -0
  7. package/__tests__/adapters/reading-family.test.js +108 -0
  8. package/__tests__/adapters/travel-didi-consumer.test.js +66 -0
  9. package/__tests__/audio-ximalaya-snapshot.test.js +279 -0
  10. package/__tests__/fitness-keep-snapshot.test.js +224 -0
  11. package/__tests__/shopping-eleme-snapshot.test.js +454 -0
  12. package/__tests__/shopping-vipshop-snapshot.test.js +425 -0
  13. package/__tests__/shopping-xianyu-snapshot.test.js +451 -0
  14. package/__tests__/social-douban-snapshot.test.js +351 -0
  15. package/lib/adapter-guide.js +19 -1
  16. package/lib/adapters/_bank-base.js +405 -0
  17. package/lib/adapters/_reading-base.js +315 -0
  18. package/lib/adapters/audio-ximalaya/index.js +414 -0
  19. package/lib/adapters/bank-bankcomm/index.js +27 -0
  20. package/lib/adapters/bank-boc/index.js +26 -0
  21. package/lib/adapters/bank-cmbc/index.js +26 -0
  22. package/lib/adapters/bank-icbc/index.js +27 -0
  23. package/lib/adapters/car-mercedesme/index.js +225 -0
  24. package/lib/adapters/finance-dcep/index.js +302 -0
  25. package/lib/adapters/fitness-joyrun/index.js +295 -0
  26. package/lib/adapters/fitness-keep/index.js +343 -0
  27. package/lib/adapters/gov-12123/index.js +391 -0
  28. package/lib/adapters/music-qq/index.js +372 -0
  29. package/lib/adapters/reading-fanqie/index.js +61 -0
  30. package/lib/adapters/reading-qimao/index.js +61 -0
  31. package/lib/adapters/shopping-eleme/index.js +441 -0
  32. package/lib/adapters/shopping-vipshop/index.js +429 -0
  33. package/lib/adapters/shopping-xianyu/index.js +454 -0
  34. package/lib/adapters/social-douban/index.js +564 -0
  35. package/lib/adapters/travel-didi-consumer/index.js +148 -0
  36. package/lib/index.js +36 -0
  37. package/package.json +1 -1
@@ -0,0 +1,454 @@
1
+ "use strict";
2
+
3
+ import { describe, it, expect, beforeEach } from "vitest";
4
+
5
+ const fs = require("node:fs");
6
+ const path = require("node:path");
7
+ const os = require("node:os");
8
+
9
+ const {
10
+ ElemeAdapter,
11
+ SNAPSHOT_SCHEMA_VERSION,
12
+ VALID_SNAPSHOT_KINDS,
13
+ orderToRecord,
14
+ extractOrders,
15
+ } = require("../lib/adapters/shopping-eleme");
16
+ const { assertAdapter } = require("../lib/adapter-spec");
17
+ const { validateBatch } = require("../lib/batch");
18
+
19
+ // 饿了么 (Ele.me) — Alibaba-owned #2 food-delivery; mirrors shopping-meituan
20
+ // (the sibling 外卖 platform) with a snapshot + cookie-api dual path. The mtop
21
+ // signing is injected (signProvider) so the adapter stays pure-Node.
22
+
23
+ function writeSnapshot(dir, snapshot) {
24
+ const p = path.join(dir, "shopping-eleme.json");
25
+ fs.writeFileSync(p, JSON.stringify(snapshot), "utf-8");
26
+ return p;
27
+ }
28
+
29
+ function writeRaw(dir, fileName, content) {
30
+ const p = path.join(dir, fileName);
31
+ fs.writeFileSync(p, content, "utf-8");
32
+ return p;
33
+ }
34
+
35
+ describe("ElemeAdapter snapshot mode", () => {
36
+ let tmpDir;
37
+ beforeEach(() => {
38
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "eleme-snap-"));
39
+ });
40
+
41
+ it("exports SNAPSHOT_SCHEMA_VERSION = 1 and VALID_SNAPSHOT_KINDS = [order]", () => {
42
+ expect(SNAPSHOT_SCHEMA_VERSION).toBe(1);
43
+ expect(VALID_SNAPSHOT_KINDS).toEqual(["order"]);
44
+ });
45
+
46
+ it("authenticate(inputPath) ok when readable", async () => {
47
+ const p = writeSnapshot(tmpDir, {
48
+ schemaVersion: 1,
49
+ snapshottedAt: Date.now(),
50
+ events: [],
51
+ });
52
+ const a = new ElemeAdapter();
53
+ const res = await a.authenticate({ inputPath: p });
54
+ expect(res.ok).toBe(true);
55
+ expect(res.mode).toBe("snapshot-file");
56
+ });
57
+
58
+ it("authenticate(inputPath) fails when path unreadable", async () => {
59
+ const a = new ElemeAdapter();
60
+ const res = await a.authenticate({ inputPath: path.join(tmpDir, "missing.json") });
61
+ expect(res.ok).toBe(false);
62
+ expect(res.reason).toBe("INPUT_PATH_UNREADABLE");
63
+ });
64
+
65
+ it("authenticate() with no inputPath returns NO_INPUT", async () => {
66
+ const a = new ElemeAdapter();
67
+ const res = await a.authenticate({});
68
+ expect(res.ok).toBe(false);
69
+ expect(res.reason).toBe("NO_INPUT");
70
+ expect(res.message).toMatch(/snapshot mode/);
71
+ });
72
+
73
+ it("sync() without inputPath throws with signing hint", async () => {
74
+ const a = new ElemeAdapter();
75
+ let threw = null;
76
+ try {
77
+ for await (const _r of a.sync({})) { /* drain */ }
78
+ } catch (err) {
79
+ threw = err;
80
+ }
81
+ expect(threw).toBeTruthy();
82
+ expect(String(threw.message)).toMatch(/signProvider/);
83
+ });
84
+
85
+ it("rejects non-JSON inputPath", async () => {
86
+ const p = writeRaw(tmpDir, "orders.html", "<html><body>not json</body></html>");
87
+ const a = new ElemeAdapter();
88
+ let threw = null;
89
+ try {
90
+ for await (const _r of a.sync({ inputPath: p })) { /* drain */ }
91
+ } catch (err) {
92
+ threw = err;
93
+ }
94
+ expect(threw).toBeTruthy();
95
+ expect(String(threw.message)).toMatch(/snapshot must be JSON/);
96
+ });
97
+
98
+ it("rejects schemaVersion mismatch", async () => {
99
+ const p = writeSnapshot(tmpDir, {
100
+ schemaVersion: 99,
101
+ snapshottedAt: Date.now(),
102
+ events: [],
103
+ });
104
+ const a = new ElemeAdapter();
105
+ let threw = null;
106
+ try {
107
+ for await (const _r of a.sync({ inputPath: p })) { /* drain */ }
108
+ } catch (err) {
109
+ threw = err;
110
+ }
111
+ expect(threw).toBeTruthy();
112
+ expect(String(threw.message)).toMatch(/schemaVersion mismatch/);
113
+ });
114
+
115
+ it("empty events array yields nothing (no crash)", async () => {
116
+ const p = writeSnapshot(tmpDir, {
117
+ schemaVersion: 1,
118
+ snapshottedAt: Date.now(),
119
+ events: [],
120
+ });
121
+ const a = new ElemeAdapter();
122
+ const raws = [];
123
+ for await (const r of a.sync({ inputPath: p })) raws.push(r);
124
+ expect(raws.length).toBe(0);
125
+ });
126
+
127
+ it("order event round-trips normalize cleanly", async () => {
128
+ const now = Date.now();
129
+ const p = writeSnapshot(tmpDir, {
130
+ schemaVersion: 1,
131
+ snapshottedAt: now,
132
+ vendor: "eleme",
133
+ account: { userId: "u-alice", displayName: "alice" },
134
+ events: [
135
+ {
136
+ kind: "order",
137
+ id: "order-ELM-9001",
138
+ capturedAt: now - 1000,
139
+ orderId: "ELM-9001",
140
+ merchantName: "沙县小吃(人民路店)",
141
+ placedAt: now - 86400_000,
142
+ paidAt: now - 86400_000 + 5_000,
143
+ status: "已送达",
144
+ items: [
145
+ { name: "蒸饺", quantity: 2, unitPrice: 8.0 },
146
+ { name: "拌面", quantity: 1, unitPrice: 7.5 },
147
+ ],
148
+ totalAmount: { value: 23.5, currency: "CNY" },
149
+ recipient: "张三",
150
+ shippingAddress: "上海市浦东新区...",
151
+ },
152
+ ],
153
+ });
154
+ const a = new ElemeAdapter();
155
+ const raws = [];
156
+ for await (const r of a.sync({ inputPath: p })) raws.push(r);
157
+ expect(raws.length).toBe(1);
158
+ expect(raws[0].kind).toBe("order");
159
+ expect(raws[0].originalId).toBe("eleme:order:order-ELM-9001");
160
+
161
+ const batch = a.normalize(raws[0]);
162
+ expect(validateBatch(batch).valid).toBe(true);
163
+ expect(batch.events.length).toBeGreaterThan(0);
164
+ expect(JSON.stringify(batch)).toContain("蒸饺");
165
+ expect(JSON.stringify(batch)).toContain("张三");
166
+ });
167
+
168
+ it("status mapping handles ele.me-typical strings", async () => {
169
+ const now = Date.now();
170
+ const cases = [
171
+ { status: "配送中", expect: "shipped" },
172
+ { status: "已送达", expect: "delivered" },
173
+ { status: "已完成", expect: "delivered" },
174
+ { status: "退款成功", expect: "refunded" },
175
+ { status: "已取消", expect: "cancelled" },
176
+ { status: "等待商家接单", expect: "placed" },
177
+ ];
178
+ for (const c of cases) {
179
+ const p = writeSnapshot(tmpDir, {
180
+ schemaVersion: 1,
181
+ snapshottedAt: now,
182
+ events: [
183
+ {
184
+ kind: "order", id: `o-${c.status}`,
185
+ orderId: `o-${c.status}`, merchantName: "m",
186
+ placedAt: now, paidAt: now, status: c.status,
187
+ items: [{ name: "x", quantity: 1, unitPrice: 1 }],
188
+ totalAmount: { value: 1, currency: "CNY" },
189
+ },
190
+ ],
191
+ });
192
+ const a = new ElemeAdapter();
193
+ const raws = [];
194
+ for await (const r of a.sync({ inputPath: p })) raws.push(r);
195
+ const batch = a.normalize(raws[0]);
196
+ expect(JSON.stringify(batch)).toContain(c.expect);
197
+ }
198
+ });
199
+
200
+ it("respects per-kind include opt-out", async () => {
201
+ const now = Date.now();
202
+ const p = writeSnapshot(tmpDir, {
203
+ schemaVersion: 1,
204
+ snapshottedAt: now,
205
+ events: [
206
+ { kind: "order", id: "o1", orderId: "o1", merchantName: "m", placedAt: now,
207
+ items: [], totalAmount: { value: 1, currency: "CNY" } },
208
+ ],
209
+ });
210
+ const a = new ElemeAdapter();
211
+ const raws = [];
212
+ for await (const r of a.sync({ inputPath: p, include: { order: false } })) {
213
+ raws.push(r);
214
+ }
215
+ expect(raws.length).toBe(0);
216
+ });
217
+
218
+ it("respects opts.limit", async () => {
219
+ const now = Date.now();
220
+ const events = Array.from({ length: 5 }, (_, i) => ({
221
+ kind: "order", id: `o${i}`, orderId: `o${i}`, merchantName: "m",
222
+ placedAt: now - i * 1000,
223
+ items: [], totalAmount: { value: 1, currency: "CNY" },
224
+ }));
225
+ const p = writeSnapshot(tmpDir, { schemaVersion: 1, snapshottedAt: now, events });
226
+ const a = new ElemeAdapter();
227
+ const raws = [];
228
+ for await (const r of a.sync({ inputPath: p, limit: 2 })) raws.push(r);
229
+ expect(raws.length).toBe(2);
230
+ });
231
+
232
+ it("filters out unknown kinds (forward compat)", async () => {
233
+ const now = Date.now();
234
+ const p = writeSnapshot(tmpDir, {
235
+ schemaVersion: 1,
236
+ snapshottedAt: now,
237
+ events: [
238
+ { kind: "order", id: "o1", orderId: "o1", merchantName: "m", placedAt: now,
239
+ items: [], totalAmount: { value: 1, currency: "CNY" } },
240
+ { kind: "refund", id: "r1", orderId: "o1" },
241
+ { kind: "future-kind", id: "x" },
242
+ ],
243
+ });
244
+ const a = new ElemeAdapter();
245
+ const raws = [];
246
+ for await (const r of a.sync({ inputPath: p })) raws.push(r);
247
+ expect(raws.length).toBe(1);
248
+ expect(raws[0].kind).toBe("order");
249
+ });
250
+
251
+ it("snapshottedAt fallback when event capturedAt missing", async () => {
252
+ const ts = 1700000000000;
253
+ const p = writeSnapshot(tmpDir, {
254
+ schemaVersion: 1,
255
+ snapshottedAt: ts,
256
+ events: [
257
+ { kind: "order", id: "o1", orderId: "o1", merchantName: "m", items: [],
258
+ totalAmount: { value: 1, currency: "CNY" } },
259
+ ],
260
+ });
261
+ const a = new ElemeAdapter();
262
+ const raws = [];
263
+ for await (const r of a.sync({ inputPath: p })) raws.push(r);
264
+ expect(raws[0].capturedAt).toBe(ts);
265
+ });
266
+
267
+ it("advertises both snapshot and cookie-api capabilities", () => {
268
+ const a = new ElemeAdapter();
269
+ expect(a.capabilities).toContain("sync:snapshot");
270
+ expect(a.capabilities).toContain("sync:cookie-api");
271
+ expect(assertAdapter(a).ok).toBe(true);
272
+ });
273
+ });
274
+
275
+ describe("ElemeAdapter cookie-api mode", () => {
276
+ it("authenticate(cookie) ok when userId + cookies present", async () => {
277
+ const a = new ElemeAdapter({ account: { userId: "u-1", cookies: "USERID=ok" } });
278
+ const res = await a.authenticate();
279
+ expect(res.ok).toBe(true);
280
+ expect(res.mode).toBe("cookie");
281
+ expect(res.account).toBe("u-1");
282
+ });
283
+
284
+ it("authenticate(cookie) requires account.userId", async () => {
285
+ const a = new ElemeAdapter({ account: { cookies: "USERID=ok" } });
286
+ const res = await a.authenticate();
287
+ expect(res.ok).toBe(false);
288
+ expect(res.reason).toBe("NO_ACCOUNT_USER_ID");
289
+ });
290
+
291
+ it("sync yields normalized records from fetchFn fixture (元)", async () => {
292
+ const fetchFn = async () => ({
293
+ orders: [
294
+ {
295
+ order_id: "ELM-COOKIE-1",
296
+ restaurant_name: "兰州拉面",
297
+ status_bar_text: "已送达",
298
+ total_amount: 28.5,
299
+ order_time: 1700000000, // sec
300
+ pay_time: 1700000010,
301
+ consignee: "李四",
302
+ address: "广州市天河区...",
303
+ basket: [
304
+ { name: "牛肉拉面", quantity: 2, price: 14.25 },
305
+ ],
306
+ },
307
+ ],
308
+ });
309
+ const a = new ElemeAdapter({
310
+ account: { userId: "u-1", cookies: "USERID=ok" },
311
+ fetchFn,
312
+ });
313
+ const raws = [];
314
+ for await (const r of a.sync({ sinceWatermark: 0 })) raws.push(r);
315
+ expect(raws.length).toBe(1);
316
+ expect(raws[0].originalId).toBe("ELM-COOKIE-1");
317
+ expect(raws[0].payload.record.totalAmount.value).toBe(28.5);
318
+ expect(raws[0].payload.record.items[0].unitPrice).toBe(14.25);
319
+ expect(raws[0].payload.record.status).toBe("delivered");
320
+
321
+ const batch = a.normalize(raws[0]);
322
+ expect(validateBatch(batch).valid).toBe(true);
323
+ expect(JSON.stringify(batch)).toContain("牛肉拉面");
324
+ expect(JSON.stringify(batch)).toContain("李四");
325
+ });
326
+
327
+ it("invokes signProvider and passes sign to fetchFn", async () => {
328
+ let seenSign = null;
329
+ const signProvider = async () => "SIGN-XYZ";
330
+ const fetchFn = async (opts) => {
331
+ seenSign = opts.sign;
332
+ return { orders: [] };
333
+ };
334
+ const a = new ElemeAdapter({
335
+ account: { userId: "u-1", cookies: "USERID=ok" },
336
+ fetchFn,
337
+ signProvider,
338
+ });
339
+ for await (const _r of a.sync({ sinceWatermark: 0 })) { /* drain */ }
340
+ expect(seenSign).toBe("SIGN-XYZ");
341
+ });
342
+
343
+ it("passes sign: null when no signProvider configured", async () => {
344
+ let seen = "unset";
345
+ const fetchFn = async (opts) => {
346
+ seen = opts.sign;
347
+ return { orders: [] };
348
+ };
349
+ const a = new ElemeAdapter({
350
+ account: { userId: "u-1", cookies: "USERID=ok" },
351
+ fetchFn,
352
+ });
353
+ for await (const _r of a.sync({ sinceWatermark: 0 })) { /* drain */ }
354
+ expect(seen).toBe(null);
355
+ });
356
+
357
+ it("paginates with offset and stops at sinceWatermark", async () => {
358
+ const pages = {
359
+ 0: [
360
+ { order_id: "p1-a", restaurant_name: "m", order_time: 1700000000, total_amount: 10, basket: [] },
361
+ { order_id: "p1-b", restaurant_name: "m", order_time: 1699000000, total_amount: 10, basket: [] },
362
+ ],
363
+ 2: [
364
+ { order_id: "p2-a", restaurant_name: "m", order_time: 1698000000, total_amount: 10, basket: [] },
365
+ ],
366
+ };
367
+ const seenOffsets = [];
368
+ const fetchFn = async (opts) => {
369
+ seenOffsets.push(opts.query.offset);
370
+ return { orders: pages[opts.query.offset] || [] };
371
+ };
372
+ const a = new ElemeAdapter({
373
+ account: { userId: "u-1", cookies: "USERID=ok" },
374
+ fetchFn,
375
+ });
376
+ const raws = [];
377
+ for await (const r of a.sync({ sinceWatermark: 1699500000 * 1000, pageSize: 2 })) {
378
+ raws.push(r);
379
+ }
380
+ expect(raws.map((r) => r.originalId)).toEqual(["p1-a"]);
381
+ // stopped inside page 1 (offset 0) — never fetched offset 2
382
+ expect(seenOffsets).toEqual([0]);
383
+ });
384
+
385
+ it("respects per-kind include opt-out in cookie mode (no fetch)", async () => {
386
+ let called = false;
387
+ const fetchFn = async () => {
388
+ called = true;
389
+ return { orders: [] };
390
+ };
391
+ const a = new ElemeAdapter({
392
+ account: { userId: "u-1", cookies: "USERID=ok" },
393
+ fetchFn,
394
+ });
395
+ const raws = [];
396
+ for await (const r of a.sync({ include: { order: false } })) raws.push(r);
397
+ expect(raws.length).toBe(0);
398
+ expect(called).toBe(false);
399
+ });
400
+
401
+ it("orderToRecord maps ele.me fields (元 amounts)", () => {
402
+ const rec = orderToRecord({
403
+ order_id: "ELM-9",
404
+ restaurant_name: "黄焖鸡米饭",
405
+ status_bar_text: "已完成",
406
+ total_amount: 18.0,
407
+ order_time: 1700000000,
408
+ basket: [{ name: "黄焖鸡", quantity: 1, price: 18.0 }],
409
+ });
410
+ expect(rec.orderId).toBe("ELM-9");
411
+ expect(rec.merchantName).toBe("黄焖鸡米饭");
412
+ expect(rec.status).toBe("delivered");
413
+ expect(rec.totalAmount.value).toBe(18.0);
414
+ expect(rec.items[0].name).toBe("黄焖鸡");
415
+ expect(rec.extras.capturedBy).toBe("cookie-api");
416
+ });
417
+
418
+ it("extractOrders tolerates nested response shapes", () => {
419
+ expect(extractOrders({ orders: [1] })).toEqual([1]);
420
+ expect(extractOrders({ order_list: [2] })).toEqual([2]);
421
+ expect(extractOrders({ list: [3] })).toEqual([3]);
422
+ expect(extractOrders({ data: { orders: [4] } })).toEqual([4]);
423
+ expect(extractOrders([5])).toEqual([5]);
424
+ expect(extractOrders({})).toEqual([]);
425
+ expect(extractOrders(null)).toEqual([]);
426
+ });
427
+
428
+ it("uses opts.ordersUrl override when provided", async () => {
429
+ let seenUrl = null;
430
+ const fetchFn = async (opts) => {
431
+ seenUrl = opts.url;
432
+ return { orders: [] };
433
+ };
434
+ const a = new ElemeAdapter({
435
+ account: { userId: "u-1", cookies: "USERID=ok" },
436
+ fetchFn,
437
+ ordersUrl: "https://custom.example/orders",
438
+ });
439
+ for await (const _r of a.sync({ sinceWatermark: 0 })) { /* drain */ }
440
+ expect(seenUrl).toBe("https://custom.example/orders");
441
+ });
442
+
443
+ it("default fetchFn throws a legible error when cookie mode used without injection", async () => {
444
+ const a = new ElemeAdapter({ account: { userId: "u-1", cookies: "USERID=ok" } });
445
+ let threw = null;
446
+ try {
447
+ for await (const _r of a.sync({ sinceWatermark: 0 })) { /* drain */ }
448
+ } catch (err) {
449
+ threw = err;
450
+ }
451
+ expect(threw).toBeTruthy();
452
+ expect(String(threw.message)).toMatch(/no fetchFn configured/);
453
+ });
454
+ });