@chainlesschain/personal-data-hub 0.4.2 → 0.4.4

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.
@@ -0,0 +1,305 @@
1
+ "use strict";
2
+
3
+ import { describe, it, expect } from "vitest";
4
+ const fs = require("node:fs");
5
+ const path = require("node:path");
6
+ const os = require("node:os");
7
+ const crypto = require("node:crypto");
8
+
9
+ const {
10
+ BaiduMapAdapter,
11
+ NAME,
12
+ VERSION,
13
+ SNAPSHOT_SCHEMA_VERSION,
14
+ } = require("../../lib/adapters/travel-baidu-map");
15
+
16
+ function writeTmp(content, ext = "json") {
17
+ const p = path.join(
18
+ os.tmpdir(),
19
+ `cc-baidumap-test-${crypto.randomUUID()}.${ext}`,
20
+ );
21
+ fs.writeFileSync(p, content, "utf-8");
22
+ return p;
23
+ }
24
+
25
+ async function collect(gen) {
26
+ const out = [];
27
+ for await (const x of gen) out.push(x);
28
+ return out;
29
+ }
30
+
31
+ function makeFakeDriverFactory(tables, log = {}) {
32
+ return () =>
33
+ class FakeDb {
34
+ constructor(dbPath, opts) {
35
+ log.opened = { dbPath, opts };
36
+ }
37
+ prepare(sql) {
38
+ for (const [needle, rows] of Object.entries(tables)) {
39
+ if (sql.includes(needle)) return { all: () => rows };
40
+ }
41
+ throw new Error(`no such table in: ${sql}`);
42
+ }
43
+ close() {
44
+ log.closed = true;
45
+ }
46
+ };
47
+ }
48
+
49
+ const SNAPSHOT = {
50
+ schemaVersion: SNAPSHOT_SCHEMA_VERSION,
51
+ snapshottedAt: 1716383021000,
52
+ vendor: "baidu-map",
53
+ account: { uid: "U1", displayName: "Alice" },
54
+ events: [
55
+ {
56
+ kind: "favourite",
57
+ id: "fav-1",
58
+ capturedAt: 1716383021000,
59
+ name: "家",
60
+ address: "幸福路1号",
61
+ lat: 31.23,
62
+ lng: 121.47,
63
+ category: "home",
64
+ },
65
+ {
66
+ kind: "search",
67
+ id: "search-2",
68
+ time: 1716383021, // seconds — parseTime must upgrade to ms
69
+ query: "咖啡店",
70
+ city: "上海",
71
+ },
72
+ {
73
+ kind: "route",
74
+ id: "route-3",
75
+ capturedAt: 1716383021000,
76
+ from: { name: "家", lat: 31.23, lng: 121.47 },
77
+ to: { name: "公司", lat: 31.2, lng: 121.44 },
78
+ mode: "drive",
79
+ },
80
+ { kind: "alien", id: "x" },
81
+ ],
82
+ };
83
+
84
+ describe("constants", () => {
85
+ it("exposes name/version/schema", () => {
86
+ expect(NAME).toBe("travel-baidu-map");
87
+ expect(VERSION).toBe("0.6.0");
88
+ expect(SNAPSHOT_SCHEMA_VERSION).toBe(1);
89
+ });
90
+ });
91
+
92
+ describe("authenticate", () => {
93
+ it("snapshot mode ok / unreadable", async () => {
94
+ const p = writeTmp("{}");
95
+ try {
96
+ const a = new BaiduMapAdapter();
97
+ expect(await a.authenticate({ inputPath: p })).toEqual({
98
+ ok: true,
99
+ mode: "snapshot-file",
100
+ });
101
+ const bad = await a.authenticate({
102
+ inputPath: path.join(os.tmpdir(), "nonexistent-baidu.json"),
103
+ });
104
+ expect(bad.reason).toBe("INPUT_PATH_UNREADABLE");
105
+ } finally {
106
+ fs.unlinkSync(p);
107
+ }
108
+ });
109
+
110
+ it("sqlite mode requires account.deviceId; NO_INPUT otherwise", async () => {
111
+ const noAcc = new BaiduMapAdapter({ dbPath: "x.db" });
112
+ expect((await noAcc.authenticate({})).reason).toBe("NO_ACCOUNT_DEVICE_ID");
113
+ const withAcc = new BaiduMapAdapter({
114
+ dbPath: "x.db",
115
+ account: { deviceId: "DEV1" },
116
+ });
117
+ expect(await withAcc.authenticate({})).toEqual({
118
+ ok: true,
119
+ account: "DEV1",
120
+ mode: "sqlite",
121
+ });
122
+ expect((await new BaiduMapAdapter().authenticate({})).reason).toBe(
123
+ "NO_INPUT",
124
+ );
125
+ });
126
+ });
127
+
128
+ describe("sync — snapshot mode", () => {
129
+ it("yields 3 kinds with prefixed originalId + account attached, skips unknown kind", async () => {
130
+ const p = writeTmp(JSON.stringify(SNAPSHOT));
131
+ try {
132
+ const a = new BaiduMapAdapter();
133
+ const items = await collect(a.sync({ inputPath: p }));
134
+ expect(items).toHaveLength(3);
135
+ expect(items.map((i) => i.originalId)).toEqual([
136
+ "baidu-map:favourite:fav-1",
137
+ "baidu-map:search:search-2",
138
+ "baidu-map:route:route-3",
139
+ ]);
140
+ // every payload carries the snapshot account for bookkeeping
141
+ for (const i of items) {
142
+ expect(i.payload.account).toEqual({ uid: "U1", displayName: "Alice" });
143
+ }
144
+ // ev.time in seconds upgraded to ms
145
+ expect(items[1].capturedAt).toBe(1716383021 * 1000);
146
+ } finally {
147
+ fs.unlinkSync(p);
148
+ }
149
+ });
150
+
151
+ it("throws on schemaVersion mismatch; honors include gate + limit", async () => {
152
+ const bad = writeTmp(JSON.stringify({ schemaVersion: 9, events: [] }));
153
+ const good = writeTmp(JSON.stringify(SNAPSHOT));
154
+ try {
155
+ const a = new BaiduMapAdapter();
156
+ await expect(collect(a.sync({ inputPath: bad }))).rejects.toThrow(
157
+ /schemaVersion mismatch/,
158
+ );
159
+ expect(
160
+ await collect(a.sync({ inputPath: good, include: { search: false } })),
161
+ ).toHaveLength(2);
162
+ expect(
163
+ await collect(a.sync({ inputPath: good, limit: 1 })),
164
+ ).toHaveLength(1);
165
+ } finally {
166
+ fs.unlinkSync(bad);
167
+ fs.unlinkSync(good);
168
+ }
169
+ });
170
+ });
171
+
172
+ describe("sync — sqlite mode (fake driver)", () => {
173
+ const ROUTE_ROW = {
174
+ _id: 5,
175
+ type: "transit",
176
+ start_name: "人民广场",
177
+ end_name: "虹桥火车站",
178
+ start_lat: 31.23,
179
+ start_lng: 121.47,
180
+ time: 1716383021, // seconds
181
+ };
182
+ const SEARCH_ROW = { _id: 6, key: "火锅", city: "成都", time: "1716383021" };
183
+
184
+ it("requires account.deviceId", async () => {
185
+ const a = new BaiduMapAdapter({ dbPath: "x.db" });
186
+ await expect(collect(a.sync({}))).rejects.toThrow(
187
+ /account\.deviceId required/,
188
+ );
189
+ });
190
+
191
+ it("yields route (transit→bus) + search records, closes db", async () => {
192
+ const p = writeTmp("fake", "db");
193
+ const log = {};
194
+ try {
195
+ const a = new BaiduMapAdapter({
196
+ dbPath: p,
197
+ account: { deviceId: "DEV1" },
198
+ dbDriverFactory: makeFakeDriverFactory(
199
+ { route_history: [ROUTE_ROW], search_history: [SEARCH_ROW] },
200
+ log,
201
+ ),
202
+ });
203
+ const items = await collect(a.sync({}));
204
+ expect(items).toHaveLength(2);
205
+ expect(items[0].payload.record).toMatchObject({
206
+ vendorId: "baidumap",
207
+ recordId: "route-5",
208
+ vehicleType: "bus",
209
+ carrier: "百度地图",
210
+ departureMs: 1716383021 * 1000,
211
+ });
212
+ expect(items[1].payload.record).toMatchObject({
213
+ recordId: "search-6",
214
+ vehicleType: "visit",
215
+ departureMs: 1716383021 * 1000, // string seconds upgraded
216
+ });
217
+ expect(items[1].payload.record.to).toMatchObject({
218
+ name: "火锅",
219
+ city: "成都",
220
+ });
221
+ expect(log.opened.opts).toEqual({ readonly: true });
222
+ expect(log.closed).toBe(true);
223
+ } finally {
224
+ fs.unlinkSync(p);
225
+ }
226
+ });
227
+
228
+ it("falls back to bd_route_history legacy table; missing db file silent", async () => {
229
+ const p = writeTmp("fake", "db");
230
+ try {
231
+ const a = new BaiduMapAdapter({
232
+ dbPath: p,
233
+ account: { deviceId: "DEV1" },
234
+ dbDriverFactory: makeFakeDriverFactory({
235
+ bd_route_history: [ROUTE_ROW],
236
+ search_history: [],
237
+ }),
238
+ });
239
+ expect(await collect(a.sync({}))).toHaveLength(1);
240
+
241
+ const gone = new BaiduMapAdapter({
242
+ dbPath: path.join(os.tmpdir(), "nonexistent-baidu.db"),
243
+ account: { deviceId: "DEV1" },
244
+ dbDriverFactory: makeFakeDriverFactory({}),
245
+ });
246
+ expect(await collect(gone.sync({}))).toEqual([]);
247
+ } finally {
248
+ fs.unlinkSync(p);
249
+ }
250
+ });
251
+ });
252
+
253
+ describe("normalize", () => {
254
+ it("snapshot favourite → visit trip titled by place name", async () => {
255
+ const p = writeTmp(JSON.stringify(SNAPSHOT));
256
+ try {
257
+ const a = new BaiduMapAdapter();
258
+ const [fav, search, route] = await collect(a.sync({ inputPath: p }));
259
+
260
+ const favBatch = a.normalize(fav);
261
+ expect(favBatch.events[0].subtype).toBe("trip");
262
+ expect(favBatch.events[0].content.title).toBe("visit: → 家");
263
+ expect(favBatch.events[0].extra.vendorExtras.category).toBe("home");
264
+ expect(favBatch.places[0].coordinates).toEqual({
265
+ lat: 31.23,
266
+ lng: 121.47,
267
+ });
268
+
269
+ // search has city → city wins over name in the title
270
+ expect(a.normalize(search).events[0].content.title).toBe("visit: → 上海");
271
+
272
+ const routeBatch = a.normalize(route);
273
+ expect(routeBatch.events[0].content.title).toBe("car: 家 → 公司");
274
+ expect(routeBatch.places).toHaveLength(2);
275
+ const merchant = routeBatch.persons.find((x) => x.subtype === "merchant");
276
+ expect(merchant.names).toEqual(["百度地图"]);
277
+ } finally {
278
+ fs.unlinkSync(p);
279
+ }
280
+ });
281
+
282
+ it("sqlite-mode record payload passes through travel-base", () => {
283
+ const a = new BaiduMapAdapter();
284
+ const batch = a.normalize({
285
+ payload: {
286
+ record: {
287
+ vendorId: "baidumap",
288
+ recordId: "route-9",
289
+ vehicleType: "car",
290
+ from: { name: "A" },
291
+ to: { name: "B" },
292
+ carrier: "百度地图",
293
+ },
294
+ kind: "route",
295
+ },
296
+ });
297
+ expect(batch.events[0].content.title).toBe("car: A → B");
298
+ });
299
+
300
+ it("throws on missing payload", () => {
301
+ expect(() => new BaiduMapAdapter().normalize(null)).toThrow(
302
+ /payload missing/,
303
+ );
304
+ });
305
+ });
@@ -0,0 +1,205 @@
1
+ "use strict";
2
+
3
+ import { describe, it, expect } from "vitest";
4
+
5
+ const {
6
+ normalizeTravelRecord,
7
+ parseChineseDateTime,
8
+ placeIdFor,
9
+ slug,
10
+ } = require("../../lib/adapters/travel-base");
11
+
12
+ describe("normalizeTravelRecord", () => {
13
+ const fullRecord = {
14
+ vendorId: "12306",
15
+ recordId: "E123456789",
16
+ vehicleType: "train",
17
+ from: { station: "上海虹桥", city: "上海" },
18
+ to: { station: "北京南", city: "北京" },
19
+ departureMs: 1716383021000,
20
+ arrivalMs: 1716401021000,
21
+ carrier: "12306",
22
+ vehicleNumber: "G35",
23
+ totalCost: { value: 553.5, currency: "CNY" },
24
+ traveler: "张三",
25
+ confirmationCode: "E123456789",
26
+ bookedAt: 1716000000000,
27
+ extras: { seat: "二等座" },
28
+ };
29
+
30
+ it("throws without rec / recordId", () => {
31
+ expect(() => normalizeTravelRecord(null)).toThrow(/rec required/);
32
+ expect(() => normalizeTravelRecord({})).toThrow(/recordId required/);
33
+ });
34
+
35
+ it("emits 1 trip event with title, amount, vehicle metadata", () => {
36
+ const batch = normalizeTravelRecord(fullRecord, {
37
+ adapterName: "travel-12306",
38
+ adapterVersion: "0.6.0",
39
+ });
40
+ expect(batch.events).toHaveLength(1);
41
+ const ev = batch.events[0];
42
+ expect(ev.type).toBe("event");
43
+ expect(ev.subtype).toBe("trip");
44
+ expect(ev.occurredAt).toBe(1716383021000); // departureMs wins
45
+ expect(ev.content.title).toBe("train: 上海虹桥 → 北京南");
46
+ expect(ev.content.amount).toEqual({
47
+ value: 553.5,
48
+ currency: "CNY",
49
+ direction: "out",
50
+ });
51
+ expect(ev.source).toMatchObject({
52
+ adapter: "travel-12306",
53
+ adapterVersion: "0.6.0",
54
+ originalId: "E123456789",
55
+ });
56
+ expect(ev.extra).toMatchObject({
57
+ vehicleType: "train",
58
+ vendorId: "12306",
59
+ from: "上海虹桥",
60
+ to: "北京南",
61
+ vehicleNumber: "G35",
62
+ confirmationCode: "E123456789",
63
+ arrivalMs: 1716401021000,
64
+ bookedAt: 1716000000000,
65
+ });
66
+ });
67
+
68
+ it("emits from/to places with stable dedup-able ids", () => {
69
+ const batch = normalizeTravelRecord(fullRecord, {
70
+ adapterName: "travel-12306",
71
+ });
72
+ expect(batch.places).toHaveLength(2);
73
+ expect(batch.places[0].name).toBe("上海虹桥");
74
+ expect(batch.places[0].type).toBe("place");
75
+ // same station on another trip → same place id (cross-trip dedup)
76
+ const again = normalizeTravelRecord(
77
+ { ...fullRecord, recordId: "OTHER" },
78
+ { adapterName: "travel-12306" },
79
+ );
80
+ expect(again.places[0].id).toBe(batch.places[0].id);
81
+ });
82
+
83
+ it("emits carrier as merchant person + traveler as contact person", () => {
84
+ const batch = normalizeTravelRecord(fullRecord, {
85
+ adapterName: "travel-12306",
86
+ });
87
+ const merchant = batch.persons.find((p) => p.subtype === "merchant");
88
+ const contact = batch.persons.find((p) => p.subtype === "contact");
89
+ expect(merchant.names).toEqual(["12306"]);
90
+ expect(contact.names).toEqual(["张三"]);
91
+ // traveler becomes the actor; self + traveler + carrier participate
92
+ const ev = batch.events[0];
93
+ expect(ev.actor).toBe(contact.id);
94
+ expect(ev.participants).toEqual(["person-self", contact.id, merchant.id]);
95
+ });
96
+
97
+ it("suppresses traveler person when traveler is self", () => {
98
+ const batch = normalizeTravelRecord(fullRecord, {
99
+ adapterName: "travel-12306",
100
+ selfName: "张三",
101
+ });
102
+ expect(batch.persons.find((p) => p.subtype === "contact")).toBeUndefined();
103
+ expect(batch.events[0].actor).toBe("person-self");
104
+ });
105
+
106
+ it("falls back occurredAt: departureMs → bookedAt → now", () => {
107
+ const noDeparture = normalizeTravelRecord({
108
+ recordId: "R1",
109
+ bookedAt: 1716000000000,
110
+ });
111
+ expect(noDeparture.events[0].occurredAt).toBe(1716000000000);
112
+ const before = Date.now();
113
+ const bare = normalizeTravelRecord({ recordId: "R2" });
114
+ expect(bare.events[0].occurredAt).toBeGreaterThanOrEqual(before);
115
+ });
116
+
117
+ it("builds partial titles when from/to missing", () => {
118
+ const toOnly = normalizeTravelRecord({
119
+ recordId: "R1",
120
+ vehicleType: "visit",
121
+ to: { name: "咖啡店" },
122
+ });
123
+ expect(toOnly.events[0].content.title).toBe("visit: → 咖啡店");
124
+ const neither = normalizeTravelRecord({
125
+ recordId: "R2",
126
+ carrier: "高德地图",
127
+ });
128
+ expect(neither.events[0].content.title).toBe("trip: 高德地图");
129
+ });
130
+
131
+ it("omits amount when totalCost.value not finite", () => {
132
+ const batch = normalizeTravelRecord({
133
+ recordId: "R1",
134
+ totalCost: { value: NaN },
135
+ });
136
+ expect(batch.events[0].content.amount).toBeUndefined();
137
+ });
138
+ });
139
+
140
+ describe("parseChineseDateTime", () => {
141
+ it("parses YYYY-MM-DD HH:MM:SS (local time)", () => {
142
+ expect(parseChineseDateTime("2026-04-15 14:30:00")).toBe(
143
+ new Date(2026, 3, 15, 14, 30, 0).getTime(),
144
+ );
145
+ });
146
+
147
+ it("parses YYYY/MM/DD HH:MM", () => {
148
+ expect(parseChineseDateTime("2026/4/15 14:30")).toBe(
149
+ new Date(2026, 3, 15, 14, 30).getTime(),
150
+ );
151
+ });
152
+
153
+ it("parses 2026年4月15日 14:30", () => {
154
+ expect(parseChineseDateTime("2026年4月15日 14:30")).toBe(
155
+ new Date(2026, 3, 15, 14, 30).getTime(),
156
+ );
157
+ });
158
+
159
+ it("parses 2026年4月15日 (date only)", () => {
160
+ expect(parseChineseDateTime("2026年4月15日")).toBe(
161
+ new Date(2026, 3, 15).getTime(),
162
+ );
163
+ });
164
+
165
+ it("parses ISO-with-Z via the first regex AS LOCAL TIME (documented quirk)", () => {
166
+ // The YYYY-MM-DD[T ]HH:MM regex matches before the Date.parse fallback
167
+ // and ignores the Z suffix — Chinese app dumps are local-time anyway.
168
+ expect(parseChineseDateTime("2026-04-15T06:30:00.000Z")).toBe(
169
+ new Date(2026, 3, 15, 6, 30, 0).getTime(),
170
+ );
171
+ });
172
+
173
+ it("falls back to Date.parse for formats no regex matches", () => {
174
+ expect(parseChineseDateTime("Apr 15, 2026")).toBe(
175
+ Date.parse("Apr 15, 2026"),
176
+ );
177
+ });
178
+
179
+ it("returns null for garbage / empty / non-string", () => {
180
+ expect(parseChineseDateTime("not a date")).toBe(null);
181
+ expect(parseChineseDateTime("")).toBe(null);
182
+ expect(parseChineseDateTime(42)).toBe(null);
183
+ });
184
+ });
185
+
186
+ describe("placeIdFor + slug", () => {
187
+ it("keys by station first, lowercased + slugged", () => {
188
+ expect(placeIdFor({ station: "北京南", city: "北京" }, "travel-12306")).toBe(
189
+ "place-travel-12306-北京南",
190
+ );
191
+ expect(placeIdFor({ city: "Shanghai HongQiao" }, "a")).toBe(
192
+ "place-a-shanghai-hongqiao",
193
+ );
194
+ });
195
+
196
+ it("returns null for empty place", () => {
197
+ expect(placeIdFor(null, "a")).toBe(null);
198
+ });
199
+
200
+ it("slug strips punctuation, keeps CJK + word chars + dash", () => {
201
+ expect(slug("高德地图")).toBe("高德地图");
202
+ expect(slug("Air China! (CA)")).toBe("air-china-ca");
203
+ expect(slug("")).toBe("");
204
+ });
205
+ });
@@ -0,0 +1,203 @@
1
+ "use strict";
2
+
3
+ import { describe, it, expect } from "vitest";
4
+ const fs = require("node:fs");
5
+ const path = require("node:path");
6
+ const os = require("node:os");
7
+ const crypto = require("node:crypto");
8
+
9
+ const {
10
+ CtripAdapter,
11
+ parseRecords,
12
+ TYPE_MAP,
13
+ NAME,
14
+ VERSION,
15
+ } = require("../../lib/adapters/travel-ctrip");
16
+
17
+ function writeTmp(content) {
18
+ const p = path.join(os.tmpdir(), `cc-ctrip-test-${crypto.randomUUID()}.json`);
19
+ fs.writeFileSync(p, content, "utf-8");
20
+ return p;
21
+ }
22
+
23
+ async function collect(gen) {
24
+ const out = [];
25
+ for await (const x of gen) out.push(x);
26
+ return out;
27
+ }
28
+
29
+ const FLIGHT_ORDER = {
30
+ orderId: "CT1",
31
+ type: "flight",
32
+ fromCity: "上海",
33
+ toCity: "北京",
34
+ departureTime: 1716383021000,
35
+ arrivalTime: 1716390000000,
36
+ airline: "国航",
37
+ flightNumber: "CA1234",
38
+ price: "1280.00",
39
+ passengerName: "张三",
40
+ pnr: "ABC123",
41
+ };
42
+
43
+ describe("constants + TYPE_MAP", () => {
44
+ it("exposes name/version", () => {
45
+ expect(NAME).toBe("travel-ctrip");
46
+ expect(VERSION).toBe("0.6.0");
47
+ });
48
+
49
+ it("maps ctrip order types to vehicleType", () => {
50
+ expect(TYPE_MAP.flight).toBe("flight");
51
+ expect(TYPE_MAP.airline).toBe("flight");
52
+ expect(TYPE_MAP.hotel).toBe("hotel");
53
+ expect(TYPE_MAP.train).toBe("train");
54
+ expect(TYPE_MAP.cruise).toBe("cruise");
55
+ });
56
+ });
57
+
58
+ describe("parseRecords", () => {
59
+ it("parses flight order with aliases (airline → carrier, pnr → confirmation)", () => {
60
+ const recs = parseRecords(JSON.stringify([FLIGHT_ORDER]));
61
+ expect(recs).toHaveLength(1);
62
+ expect(recs[0]).toMatchObject({
63
+ vendorId: "ctrip",
64
+ recordId: "CT1",
65
+ vehicleType: "flight",
66
+ from: { city: "上海" },
67
+ to: { city: "北京" },
68
+ departureMs: 1716383021000,
69
+ carrier: "国航",
70
+ vehicleNumber: "CA1234",
71
+ traveler: "张三",
72
+ confirmationCode: "ABC123",
73
+ });
74
+ expect(recs[0].totalCost).toEqual({ value: 1280, currency: "CNY" });
75
+ });
76
+
77
+ it("hotel order: hotelCity → to, hotelName → carrier, checkIn/Out → times", () => {
78
+ const recs = parseRecords(
79
+ JSON.stringify([
80
+ {
81
+ id: "H1",
82
+ type: "hotel",
83
+ hotelCity: "杭州",
84
+ hotelName: "西湖宾馆",
85
+ checkIn: "2026年4月15日",
86
+ checkOut: "2026年4月17日",
87
+ guestName: "李四",
88
+ nights: 2,
89
+ },
90
+ ]),
91
+ );
92
+ expect(recs[0]).toMatchObject({
93
+ recordId: "H1",
94
+ vehicleType: "hotel",
95
+ to: { city: "杭州" },
96
+ carrier: "西湖宾馆",
97
+ traveler: "李四",
98
+ });
99
+ expect(recs[0].from).toBe(null);
100
+ expect(recs[0].departureMs).toBe(new Date(2026, 3, 15).getTime());
101
+ expect(recs[0].extras.nights).toBe(2);
102
+ });
103
+
104
+ it("unknown type falls back to trip + default carrier 携程", () => {
105
+ const recs = parseRecords(JSON.stringify([{ order_no: "X1" }]));
106
+ expect(recs[0].vehicleType).toBe("trip");
107
+ expect(recs[0].carrier).toBe("携程");
108
+ });
109
+
110
+ it("accepts {orders:[...]} envelope + JSONL fallback, drops id-less rows", () => {
111
+ expect(
112
+ parseRecords(JSON.stringify({ orders: [FLIGHT_ORDER] })),
113
+ ).toHaveLength(1);
114
+ const jsonl = `${JSON.stringify(FLIGHT_ORDER)}\ngarbage line\n${JSON.stringify({ ...FLIGHT_ORDER, orderId: "CT2" })}`;
115
+ expect(parseRecords(jsonl).map((r) => r.recordId)).toEqual(["CT1", "CT2"]);
116
+ expect(parseRecords(JSON.stringify([{ type: "flight" }]))).toHaveLength(0);
117
+ });
118
+ });
119
+
120
+ describe("CtripAdapter", () => {
121
+ it("authenticate ok in ready mode without account (v0.6 optional)", async () => {
122
+ const a = new CtripAdapter();
123
+ expect(await a.authenticate({})).toEqual({
124
+ ok: true,
125
+ account: null,
126
+ mode: "ready",
127
+ });
128
+ });
129
+
130
+ it("authenticate validates inputPath readability", async () => {
131
+ const p = writeTmp("[]");
132
+ try {
133
+ const a = new CtripAdapter();
134
+ expect((await a.authenticate({ inputPath: p })).mode).toBe(
135
+ "snapshot-file",
136
+ );
137
+ const bad = await a.authenticate({
138
+ inputPath: path.join(os.tmpdir(), "nonexistent-ctrip.json"),
139
+ });
140
+ expect(bad.ok).toBe(false);
141
+ expect(bad.reason).toBe("INPUT_PATH_UNREADABLE");
142
+ } finally {
143
+ fs.unlinkSync(p);
144
+ }
145
+ });
146
+
147
+ it("sync yields orders from file (inputPath alias) + normalize end-to-end", async () => {
148
+ const p = writeTmp(JSON.stringify([FLIGHT_ORDER]));
149
+ try {
150
+ const a = new CtripAdapter();
151
+ const items = await collect(a.sync({ inputPath: p }));
152
+ expect(items).toHaveLength(1);
153
+ expect(items[0]).toMatchObject({ adapter: NAME, originalId: "CT1" });
154
+ const batch = a.normalize(items[0]);
155
+ const ev = batch.events[0];
156
+ expect(ev.subtype).toBe("trip");
157
+ expect(ev.content.title).toBe("flight: 上海 → 北京");
158
+ expect(ev.content.amount).toEqual({
159
+ value: 1280,
160
+ currency: "CNY",
161
+ direction: "out",
162
+ });
163
+ expect(
164
+ batch.persons.find((x) => x.subtype === "merchant").names,
165
+ ).toEqual(["国航"]);
166
+ } finally {
167
+ fs.unlinkSync(p);
168
+ }
169
+ });
170
+
171
+ it("sync returns silently when no path / missing file", async () => {
172
+ const a = new CtripAdapter();
173
+ expect(await collect(a.sync({}))).toEqual([]);
174
+ expect(
175
+ await collect(
176
+ a.sync({ inputPath: path.join(os.tmpdir(), "nope-ctrip.json") }),
177
+ ),
178
+ ).toEqual([]);
179
+ });
180
+
181
+ it("sync throws on broken {-line; pure garbage degrades to empty (JSONL filter)", async () => {
182
+ const broken = writeTmp("{broken json line");
183
+ const garbage = writeTmp("not json at all");
184
+ try {
185
+ const a = new CtripAdapter();
186
+ await expect(collect(a.sync({ inputPath: broken }))).rejects.toThrow(
187
+ /parse failed/,
188
+ );
189
+ // no line starts with "{" → JSONL filter yields [] rather than throwing
190
+ expect(await collect(a.sync({ inputPath: garbage }))).toEqual([]);
191
+ } finally {
192
+ fs.unlinkSync(broken);
193
+ fs.unlinkSync(garbage);
194
+ }
195
+ });
196
+
197
+ it("normalize throws on missing record", () => {
198
+ const a = new CtripAdapter();
199
+ expect(() => a.normalize({ payload: {} })).toThrow(
200
+ /payload\.record missing/,
201
+ );
202
+ });
203
+ });