poi-plugin-kcsave-exporter 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.es CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  Button,
7
7
  Callout,
8
8
  Card,
9
+ Checkbox,
9
10
  Divider,
10
11
  Elevation,
11
12
  Intent,
@@ -28,8 +29,9 @@ const KcsaveExporter = () => {
28
29
 
29
30
  const [captured, setCaptured] = useState(() => ({ ...captureStore.data }))
30
31
  const [baseFilePath, setBaseFilePath] = useState('')
32
+ const [inheritOfflineProgress, setInheritOfflineProgress] = useState(true)
31
33
  const [exporting, setExporting] = useState(false)
32
- const [status, setStatus] = useState(null) // { text, intent }
34
+ const [status, setStatus] = useState(null)
33
35
  const [lastStats, setLastStats] = useState(null)
34
36
 
35
37
  useEffect(() => {
@@ -59,7 +61,7 @@ const KcsaveExporter = () => {
59
61
 
60
62
  const handleClearBase = useCallback(() => {
61
63
  setBaseFilePath('')
62
- setStatus({ text: '已清除模板,将使用内置默认模板独立导出。', intent: Intent.NONE })
64
+ setStatus({ text: '已清除模板,将使用内置默认配置独立导出。', intent: Intent.NONE })
63
65
  }, [])
64
66
 
65
67
  const handleClearCache = useCallback(() => {
@@ -75,7 +77,9 @@ const KcsaveExporter = () => {
75
77
  const baseBuf =
76
78
  baseFilePath && fs.existsSync(baseFilePath) ? fs.readFileSync(baseFilePath) : null
77
79
 
78
- const { buffer, stats } = exportToKcsaveBuffer(reduxState, captureStore.data, baseBuf)
80
+ const { buffer, stats } = exportToKcsaveBuffer(reduxState, captureStore.data, baseBuf, {
81
+ inheritOfflineProgress: Boolean(baseBuf && inheritOfflineProgress),
82
+ })
79
83
 
80
84
  const safeName = (stats.nickname || 'admiral').replace(/[\\/:*?"<>|]/g, '_')
81
85
  const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, '')
@@ -106,7 +110,7 @@ const KcsaveExporter = () => {
106
110
  } finally {
107
111
  setExporting(false)
108
112
  }
109
- }, [baseFilePath])
113
+ }, [baseFilePath, inheritOfflineProgress])
110
114
 
111
115
  const capAt = captured.capturedAt || {}
112
116
  const furnitureCount = (captured.furnitureOwned || []).length
@@ -149,10 +153,17 @@ const KcsaveExporter = () => {
149
153
  </Card>
150
154
 
151
155
  <Card elevation={Elevation.ONE}>
152
- <div style={{ fontSize: 12, marginBottom: 10 }}>
156
+ <div style={{ fontSize: 12, marginBottom: 8 }}>
153
157
  <strong>可选基础模板:</strong>
154
158
  {baseFilePath ? path.basename(baseFilePath) : '无(使用内置默认模板独立导出)'}
155
159
  </div>
160
+ <Checkbox
161
+ checked={inheritOfflineProgress}
162
+ disabled={!baseFilePath}
163
+ onChange={(e) => setInheritOfflineProgress(e.currentTarget.checked)}
164
+ label="继承模板中的单机进度(军费、任务进度与历史、活动海域、已探索节点、开发配方、图鉴与单机设置)"
165
+ style={{ fontSize: 12, marginBottom: 10 }}
166
+ />
156
167
  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
157
168
  <Button
158
169
  intent={Intent.PRIMARY}
@@ -185,10 +196,18 @@ const KcsaveExporter = () => {
185
196
  {lastStats && (
186
197
  <Callout title="本次导出明细" intent={Intent.SUCCESS}>
187
198
  <div style={{ fontSize: 12, lineHeight: 1.7 }}>
188
- 提督 {lastStats.nickname} (Lv.{lastStats.level}) | 舰娘 {lastStats.ships} | 装备 {lastStats.equipment} |
189
- 舰队 {lastStats.decks} | 道具 {lastStats.inventory} | 家具 {lastStats.furniture} |
190
- 海域 {lastStats.maps} | 陆航 {lastStats.airBases} | 编成记录 {lastStats.presets} |
191
- 图鉴 {lastStats.albumShips}/{lastStats.albumEquips}
199
+ <div>
200
+ 提督 {lastStats.nickname} (Lv.{lastStats.level}) | 舰娘 {lastStats.ships} | 装备 {lastStats.equipment} |
201
+ 舰队 {lastStats.decks} | 道具 {lastStats.inventory} | 家具 {lastStats.furniture} |
202
+ 海域 {lastStats.maps} | 陆航 {lastStats.airBases} | 编成记录 {lastStats.presets} |
203
+ 图鉴 {lastStats.albumShips}/{lastStats.albumEquips}
204
+ </div>
205
+ {lastStats.inheritedOffline && (
206
+ <div style={{ marginTop: 4 }}>
207
+ 已继承单机进度:军费 {lastStats.inheritedOffline.treasuryBalance} | 任务 {lastStats.inheritedOffline.questsCount}(历史 {lastStats.inheritedOffline.questHistoryCount}) |
208
+ 活动 {lastStats.inheritedOffline.eventsCount} | 探索海域 {lastStats.inheritedOffline.exploredMapsCount}
209
+ </div>
210
+ )}
192
211
  </div>
193
212
  </Callout>
194
213
  )}
package/lib/exporter.js CHANGED
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  const crypto = require('crypto');
4
- const { buildSaveSqlite } = require('./sqlite-writer');
5
- const { buildKcsaveBuffer, parseKcsave5 } = require('./kcsave-packer');
4
+ const { buildSaveSqlite, readSaveJsonFromSqlite } = require('./sqlite-writer');
5
+ const { buildKcsaveBuffer, unpackKcsaveTemplate } = require('./kcsave-packer');
6
6
 
7
7
  function toArray(val) {
8
8
  if (!val) return [];
@@ -22,10 +22,14 @@ function mapQuestPeriod(apiType) {
22
22
  }
23
23
  }
24
24
 
25
+ function deepClone(obj) {
26
+ return obj === undefined ? undefined : JSON.parse(JSON.stringify(obj));
27
+ }
28
+
25
29
  /**
26
- * 将 poi Redux store 与实时捕获的 API 数据合并为完整的单机版 save.json 对象。
30
+ * 将 poi Redux store、实时捕获的 API 数据与可选的旧单机模板进度合并为完整的 save.json 对象。
27
31
  */
28
- function buildCompleteSaveObject(reduxState, capturedData = {}) {
32
+ function buildCompleteSaveObject(reduxState, capturedData = {}, templateSave = null) {
29
33
  const info = (reduxState && reduxState.info) || {};
30
34
  const constData = (reduxState && reduxState.const) || {};
31
35
  const mstShips = constData.$ships || {};
@@ -57,7 +61,7 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
57
61
  api_level: Number(pb.api_level || 1),
58
62
  api_rank: Number(pb.api_rank || 10),
59
63
  api_experience: Number(pb.api_experience || 0),
60
- api_fleetname: pb.api_fleetname || '本地艦隊',
64
+ api_fleetname: pb.api_fleetname || (templateSave && templateSave.basic && templateSave.basic.api_fleetname) || '本地艦隊',
61
65
  api_firstflag: Number(pb.api_firstflag ?? 1),
62
66
  api_st_win: Number(pb.api_st_win || 0),
63
67
  api_st_lose: Number(pb.api_st_lose || 0),
@@ -81,13 +85,13 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
81
85
  api_large_dock: Number(pb.api_large_dock || 0),
82
86
  api_comment: pb.api_comment || '',
83
87
  api_comment_id: String(pb.api_comment_id || '1'),
84
- api_skin_id: Number(capturedData.skinId || 101),
88
+ api_skin_id: Number(capturedData.skinId || (templateSave && templateSave.basic && templateSave.basic.api_skin_id) || 101),
85
89
  api_pvp: Array.isArray(pb.api_pvp) ? pb.api_pvp.map(Number) : [0, 0],
86
90
  api_expedition: [0, 0],
87
91
  api_tutorial_progress: Number(pb.api_tutorial_progress ?? 100),
88
92
  };
89
93
 
90
- // 2. Materials (8 items)
94
+ // 2. Materials
91
95
  let materials = [0, 0, 0, 0, 0, 0, 0, 0];
92
96
  if (Array.isArray(info.resources) && info.resources.length >= 8) {
93
97
  materials = info.resources.slice(0, 8).map(Number);
@@ -189,7 +193,7 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
189
193
  }),
190
194
  }));
191
195
 
192
- // 6. Docks (ndock)
196
+ // 6. Docks
193
197
  const docks = rawRepairs.map((nd) => {
194
198
  const state = Number(nd.api_state || 0);
195
199
  const compTime = Number(nd.api_complete_time || 0);
@@ -232,7 +236,7 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
232
236
  };
233
237
  });
234
238
 
235
- // 8. Inventory (useitems + furniture coins id 44)
239
+ // 8. Inventory
236
240
  const inventory = {};
237
241
  for (const ui of rawUseitems) {
238
242
  if (ui && ui.api_id !== undefined) {
@@ -243,26 +247,47 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
243
247
  inventory['44'] = Number(pb.api_fcoin);
244
248
  }
245
249
 
246
- // 9. Furniture owned
250
+ // 9. Furniture (merge captured + template owned + equipped)
247
251
  const furnSet = new Set(Array.isArray(capturedData.furnitureOwned) ? capturedData.furnitureOwned : []);
252
+ if (templateSave && Array.isArray(templateSave.furniture)) {
253
+ for (const fid of templateSave.furniture) {
254
+ if (Number(fid) > 0) furnSet.add(Number(fid));
255
+ }
256
+ }
248
257
  for (const fid of equippedFurniture) {
249
258
  if (fid > 0) furnSet.add(fid);
250
259
  }
251
260
  const furniture = Array.from(furnSet).sort((a, b) => a - b);
252
261
 
253
- // 10. Map progress (merge Redux info.maps + captured mapinfo)
254
- const mapSource = toArray(info.maps).length > 0 ? toArray(info.maps) : toArray(capturedData.mapInfo);
255
- const mapProgress = mapSource.map((m) => ({
256
- api_id: Number(m.api_id),
257
- api_cleared: Number(m.api_cleared || 0),
258
- api_defeat_count: Number(m.api_defeat_count || 0),
259
- api_air_base_decks: Number(m.api_air_base_decks || 0),
260
- everCleared: Number(m.api_cleared || 0) === 1,
261
- }));
262
+ // 10. Map progress (merge template mapProgress + live info.maps / captured mapInfo)
263
+ const mapById = new Map();
264
+ if (templateSave && Array.isArray(templateSave.mapProgress)) {
265
+ for (const m of templateSave.mapProgress) {
266
+ if (m && m.api_id) mapById.set(Number(m.api_id), deepClone(m));
267
+ }
268
+ }
269
+ const liveMaps = toArray(info.maps).length > 0 ? toArray(info.maps) : toArray(capturedData.mapInfo);
270
+ for (const m of liveMaps) {
271
+ const id = Number(m.api_id);
272
+ const prev = mapById.get(id);
273
+ const cleared = Number(m.api_cleared || 0);
274
+ mapById.set(id, {
275
+ api_id: id,
276
+ api_cleared: cleared,
277
+ api_defeat_count: Number(m.api_defeat_count || 0),
278
+ api_air_base_decks: Number(m.api_air_base_decks || 0),
279
+ everCleared: cleared === 1 || Boolean(prev && prev.everCleared),
280
+ });
281
+ }
282
+ const mapProgress = Array.from(mapById.values()).sort((a, b) => a.api_id - b.api_id);
262
283
 
263
- // 11. Land-Base Air Squadrons (merge Redux info.airbase + captured airBase)
284
+ // 11. Land-Base Air Squadrons
264
285
  const rawAirBases = toArray(info.airbase).length > 0 ? toArray(info.airbase) : toArray(capturedData.airBase);
265
- const airBaseAreas = new Set();
286
+ const airBaseAreas = new Set(
287
+ templateSave && templateSave.operations && Array.isArray(templateSave.operations.airBaseUnlockedAreas)
288
+ ? templateSave.operations.airBaseUnlockedAreas
289
+ : []
290
+ );
266
291
  const airBases = rawAirBases.map((ab) => {
267
292
  const areaId = Number(ab.api_area_id);
268
293
  if (areaId > 0) airBaseAreas.add(areaId);
@@ -292,11 +317,8 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
292
317
  };
293
318
  });
294
319
 
295
- // 12. Presets (merge Redux info.presets.api_deck + captured presets)
296
- const rawPresets =
297
- (info.presets && info.presets.api_deck) ||
298
- capturedData.presets ||
299
- {};
320
+ // 12. Presets
321
+ const rawPresets = (info.presets && info.presets.api_deck) || capturedData.presets || {};
300
322
  const presets = {};
301
323
  for (const [key, pr] of Object.entries(rawPresets)) {
302
324
  if (!pr || typeof pr !== 'object') continue;
@@ -315,29 +337,42 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
315
337
  };
316
338
  }
317
339
 
318
- // 13. Quests (from captured questlist or Redux info.quests.activeQuests)
319
- const quests = [];
340
+ // 13. Quests (preserve template offline quests + overlay live captured quests)
341
+ const questsById = new Map();
342
+ if (templateSave && Array.isArray(templateSave.quests)) {
343
+ for (const q of templateSave.quests) {
344
+ if (q && q.id) questsById.set(Number(q.id), deepClone(q));
345
+ }
346
+ }
320
347
  const capturedQuests = capturedData.quests || {};
321
348
  const activeQuests = (info.quests && info.quests.activeQuests) || {};
322
- const mergedQuestMap = Object.assign({}, capturedQuests);
349
+ const mergedLiveQuests = Object.assign({}, capturedQuests);
323
350
  for (const [qid, qWrap] of Object.entries(activeQuests)) {
324
- if (qWrap && qWrap.detail && !mergedQuestMap[qid]) {
325
- mergedQuestMap[qid] = qWrap.detail;
351
+ if (qWrap && qWrap.detail && !mergedLiveQuests[qid]) {
352
+ mergedLiveQuests[qid] = qWrap.detail;
326
353
  }
327
354
  }
328
- for (const q of Object.values(mergedQuestMap)) {
355
+ for (const q of Object.values(mergedLiveQuests)) {
329
356
  if (!q || !q.api_no) continue;
330
- quests.push({
331
- id: Number(q.api_no),
357
+ const id = Number(q.api_no);
358
+ const prev = questsById.get(id);
359
+ questsById.set(id, {
360
+ id,
332
361
  period: mapQuestPeriod(q.api_type),
333
362
  accepted: Number(q.api_state) === 2 || Number(q.api_state) === 3,
334
- progress: {},
363
+ progress: (prev && prev.progress) || {},
335
364
  unlocked: true,
336
365
  });
337
366
  }
338
-
339
- // 14. Album (merge captured picture_book + all currently owned ships & equips)
340
- const albumShips = Object.assign({}, capturedData.albumShips || {});
367
+ const quests = Array.from(questsById.values());
368
+
369
+ // 14. Album (merge template album + captured picture_book + currently owned)
370
+ const tplOps = (templateSave && templateSave.operations) || {};
371
+ const albumShips = Object.assign(
372
+ {},
373
+ deepClone((tplOps.album && tplOps.album.ships) || {}),
374
+ deepClone(capturedData.albumShips || {})
375
+ );
341
376
  for (const sh of ships) {
342
377
  const k = String(sh.api_ship_id);
343
378
  const prev = albumShips[k] || { normal: true, damaged: false, married: false };
@@ -347,12 +382,16 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
347
382
  married: Boolean(prev.married) || sh.api_lv >= 100,
348
383
  };
349
384
  }
350
- const albumEquips = Object.assign({}, capturedData.albumEquips || {});
385
+ const albumEquips = Object.assign(
386
+ {},
387
+ deepClone((tplOps.album && tplOps.album.equipment) || {}),
388
+ deepClone(capturedData.albumEquips || {})
389
+ );
351
390
  for (const eq of equipment) {
352
391
  albumEquips[String(eq.api_slotitem_id)] = true;
353
392
  }
354
393
 
355
- // 15. Root & head hashes for fresh SQLite lineage/transfer_meta
394
+ // 15. Build operations (inherit offline progress from templateSave if provided, while sanitizing stale ship IDs)
356
395
  const rootId = crypto.randomBytes(20).toString('hex');
357
396
  const headHash = crypto.randomBytes(32).toString('hex');
358
397
 
@@ -361,12 +400,113 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
361
400
  rosters[String(dk.api_id)] = dk.api_ship.join(',') + ':0:1';
362
401
  }
363
402
 
403
+ const defaultOps = {
404
+ developmentPresetCapacity: 4,
405
+ equipmentPresetCapacity: 4,
406
+ treasury: { version: 1, balance: 0, progress: 0, receipts: {} },
407
+ honors: {},
408
+ economy: { version: 2, lastReal: nowMs, lastPayment: nowMs, fractions: [0, 0, 0, 0] },
409
+ moraleRecoveryAt: {},
410
+ remodelCostSettlement: { version: 1, fromRevision: 0, root: rootId, afterRestore: 0, legacyEvents: 0 },
411
+ remodelCostAnchor: { revision: 0, ships: [] },
412
+ remodelCostCursor: { root: rootId, id: 0 },
413
+ practiceV2: { version: 2, serial: 1, highestStage: 0, highestStrength: 0 },
414
+ album: { ships: albumShips, equipment: albumEquips },
415
+ events: {},
416
+ questHistory: {},
417
+ training: { version: 1, balance: 0, targets: [], auto: false, serial: 1, receipts: [] },
418
+ expeditionRuns: {},
419
+ portRepair: { started: nowMs, rosters, last: { at: nowMs, elapsed: 0, repairs: [] } },
420
+ airBases,
421
+ purchasedItems: [],
422
+ resourceHistory: [],
423
+ memorialQuestIdVersion: 1,
424
+ questStateVersion: 2,
425
+ friendlySetting: { api_request_flag: 1, api_request_type: 0 },
426
+ exploredMaps: {},
427
+ acquisition: { version: 2, legacyArchive: null, sequence: 1, receipts: {} },
428
+ battleHistory: [],
429
+ battleSupport: {},
430
+ logisticsReceipts: {},
431
+ portNotices: [],
432
+ materialSpentTotals: [0, 0, 0, 0],
433
+ organizeList: capturedData.ossSetting || { api_oss_items: [1, 0, 0, 0, 0, 0, 0, 0], api_language_type: 0 },
434
+ optimizedQuestRounds: {},
435
+ presets,
436
+ expeditionHistory: Object.assign({}, capturedData.expeditionHistory || {}),
437
+ expeditionReceipts: {},
438
+ remodelPayments: {},
439
+ developmentPresets: {},
440
+ largeConstructionUnlocked: basic.api_large_dock === 1,
441
+ selectedEvent: '',
442
+ strikingFleetUnlocked: true,
443
+ airBaseUnlockedAreas: Array.from(airBaseAreas).sort((a, b) => a - b),
444
+ optimizedMilestones: basic.api_level >= 99 ? { 'first-level-99': true } : {},
445
+ };
446
+
447
+ let operations = defaultOps;
448
+ let inheritedSummary = null;
449
+
450
+ if (templateSave && templateSave.operations && typeof templateSave.operations === 'object') {
451
+ operations = Object.assign({}, defaultOps, deepClone(templateSave.operations));
452
+ // 覆盖必须与当前正式服舰娘/装备一致的字段,并清理旧舰娘 ID 悬空引用
453
+ operations.album = { ships: albumShips, equipment: albumEquips };
454
+ operations.airBases = airBases.length > 0 ? airBases : [];
455
+ operations.airBaseUnlockedAreas = Array.from(airBaseAreas).sort((a, b) => a - b);
456
+ operations.presets = presets;
457
+ operations.expeditionHistory = Object.assign(
458
+ {},
459
+ operations.expeditionHistory || {},
460
+ capturedData.expeditionHistory || {}
461
+ );
462
+ if (capturedData.ossSetting) {
463
+ operations.organizeList = capturedData.ossSetting;
464
+ }
465
+ if (basic.api_large_dock === 1) {
466
+ operations.largeConstructionUnlocked = true;
467
+ }
468
+ operations.moraleRecoveryAt = {};
469
+ operations.expeditionRuns = {};
470
+ if (operations.training && typeof operations.training === 'object') {
471
+ operations.training.targets = [];
472
+ }
473
+ operations.portRepair = {
474
+ started: nowMs,
475
+ rosters,
476
+ last: { at: nowMs, elapsed: 0, repairs: [] },
477
+ };
478
+ delete operations.lastSortie;
479
+ operations.remodelCostSettlement = { version: 1, fromRevision: 0, root: rootId, afterRestore: 0, legacyEvents: 0 };
480
+ operations.remodelCostAnchor = { revision: 0, ships: [] };
481
+ operations.remodelCostCursor = { root: rootId, id: 0 };
482
+
483
+ inheritedSummary = {
484
+ treasuryBalance: operations.treasury ? operations.treasury.balance : 0,
485
+ questHistoryCount: Object.keys(operations.questHistory || {}).length,
486
+ eventsCount: Object.keys(operations.events || {}).length,
487
+ exploredMapsCount: Object.keys(operations.exploredMaps || {}).length,
488
+ questsCount: quests.length,
489
+ };
490
+ }
491
+
492
+ const settings =
493
+ templateSave && templateSave.settings
494
+ ? deepClone(templateSave.settings)
495
+ : {
496
+ sinkingProtection: true,
497
+ repairAuto: false,
498
+ repairThresholdSeconds: 60,
499
+ optimizeFleetSpecialAttacks: false,
500
+ animationScale: 4,
501
+ localMapApproximations: true,
502
+ };
503
+
364
504
  const saveObj = {
365
- schemaVersion: 2,
366
- contentId: '6.3.6.0',
367
- rulesVersion: 'optimized-2',
505
+ schemaVersion: (templateSave && templateSave.schemaVersion) || 2,
506
+ contentId: (templateSave && templateSave.contentId) || '6.3.6.0',
507
+ rulesVersion: (templateSave && templateSave.rulesVersion) || 'optimized-2',
368
508
  revision: 0,
369
- createdAt: nowMs,
509
+ createdAt: (templateSave && templateSave.createdAt) || nowMs,
370
510
  lastSeen: nowMs,
371
511
  nextShipId: maxShipId + 1,
372
512
  nextEquipId: maxEquipId + 1,
@@ -379,59 +519,10 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
379
519
  kdocks,
380
520
  quests,
381
521
  mapProgress,
382
- settings: {
383
- sinkingProtection: true,
384
- repairAuto: false,
385
- repairThresholdSeconds: 60,
386
- optimizeFleetSpecialAttacks: false,
387
- animationScale: 4,
388
- localMapApproximations: true,
389
- },
522
+ settings,
390
523
  clock: { real: nowMs, game: nowMs },
391
524
  sortie: null,
392
- operations: {
393
- developmentPresetCapacity: 4,
394
- equipmentPresetCapacity: 4,
395
- treasury: { version: 1, balance: 0, progress: 0, receipts: {} },
396
- honors: {},
397
- economy: { version: 2, lastReal: nowMs, lastPayment: nowMs, fractions: [0, 0, 0, 0] },
398
- moraleRecoveryAt: {},
399
- remodelCostSettlement: { version: 1, fromRevision: 0, root: rootId, afterRestore: 0, legacyEvents: 0 },
400
- remodelCostAnchor: { revision: 0, ships: [] },
401
- remodelCostCursor: { root: rootId, id: 0 },
402
- practiceV2: { version: 2, serial: 1, highestStage: 0, highestStrength: 0 },
403
- album: { ships: albumShips, equipment: albumEquips },
404
- events: {},
405
- questHistory: {},
406
- training: { version: 1, balance: 0, targets: [], auto: false, serial: 1, receipts: [] },
407
- expeditionRuns: {},
408
- portRepair: { started: nowMs, rosters, last: { at: nowMs, elapsed: 0, repairs: [] } },
409
- airBases,
410
- purchasedItems: [],
411
- resourceHistory: [],
412
- memorialQuestIdVersion: 1,
413
- questStateVersion: 2,
414
- friendlySetting: { api_request_flag: 1, api_request_type: 0 },
415
- exploredMaps: {},
416
- acquisition: { version: 2, legacyArchive: null, sequence: 1, receipts: {} },
417
- battleHistory: [],
418
- battleSupport: {},
419
- logisticsReceipts: {},
420
- portNotices: [],
421
- materialSpentTotals: [0, 0, 0, 0],
422
- organizeList: capturedData.ossSetting || { api_oss_items: [1, 0, 0, 0, 0, 0, 0, 0], api_language_type: 0 },
423
- optimizedQuestRounds: {},
424
- presets,
425
- expeditionHistory: Object.assign({}, capturedData.expeditionHistory || {}),
426
- expeditionReceipts: {},
427
- remodelPayments: {},
428
- developmentPresets: {},
429
- largeConstructionUnlocked: basic.api_large_dock === 1,
430
- selectedEvent: '',
431
- strikingFleetUnlocked: true,
432
- airBaseUnlockedAreas: Array.from(airBaseAreas).sort((a, b) => a - b),
433
- optimizedMilestones: basic.api_level >= 99 ? { 'first-level-99': true } : {},
434
- },
525
+ operations,
435
526
  inventory,
436
527
  furniture,
437
528
  };
@@ -454,37 +545,51 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
454
545
  quests: quests.length,
455
546
  albumShips: Object.keys(albumShips).length,
456
547
  albumEquips: Object.keys(albumEquips).length,
457
- expeditions: Object.keys(saveObj.operations.expeditionHistory).length,
548
+ expeditions: Object.keys(operations.expeditionHistory || {}).length,
549
+ inheritedOffline: inheritedSummary,
458
550
  },
459
551
  };
460
552
  }
461
553
 
462
554
  /**
463
555
  * 直接从 poi 数据生成完整的 .kcsave 二进制 Buffer(零外部依赖)。
464
- * 可选传入 baseKcsaveBuf 以继承原单机存档中的 appearance.json 立绘配置与 contentId。
556
+ * @param {object} reduxState
557
+ * @param {object} capturedData
558
+ * @param {Buffer|null} baseKcsaveBuf
559
+ * @param {object} [options]
560
+ * @param {boolean} [options.inheritOfflineProgress=true] - 是否从模板继承单机专属进度
465
561
  */
466
- function exportToKcsaveBuffer(reduxState, capturedData = {}, baseKcsaveBuf = null) {
467
- const { saveObj, rootId, headHash, stats } = buildCompleteSaveObject(reduxState, capturedData);
562
+ function exportToKcsaveBuffer(
563
+ reduxState,
564
+ capturedData = {},
565
+ baseKcsaveBuf = null,
566
+ options = { inheritOfflineProgress: true }
567
+ ) {
468
568
  let appearance = null;
469
- let contentId = saveObj.contentId;
470
- let rulesVersion = saveObj.rulesVersion;
569
+ let contentId = '6.3.6.0';
570
+ let rulesVersion = 'optimized-2';
571
+ let templateSave = null;
471
572
 
472
573
  if (baseKcsaveBuf) {
473
- try {
474
- const entries = parseKcsave5(baseKcsaveBuf);
475
- const manifest = JSON.parse(entries.get('manifest.json').toString('utf8'));
476
- if (manifest.contentId) contentId = manifest.contentId;
477
- if (manifest.rulesVersion) rulesVersion = manifest.rulesVersion;
478
- const activeId = manifest.activeId || 'legacy';
479
- const appearRaw = entries.get(`profiles/${activeId}/appearance.json`);
480
- if (appearRaw) appearance = JSON.parse(appearRaw.toString('utf8'));
481
- saveObj.contentId = contentId;
482
- saveObj.rulesVersion = rulesVersion;
483
- } catch (_) {
484
- // 忽略无效模板,退回默认配置
574
+ const tpl = unpackKcsaveTemplate(baseKcsaveBuf);
575
+ if (tpl.manifest) {
576
+ if (tpl.manifest.contentId) contentId = tpl.manifest.contentId;
577
+ if (tpl.manifest.rulesVersion) rulesVersion = tpl.manifest.rulesVersion;
578
+ }
579
+ appearance = tpl.appearance;
580
+ if (options && options.inheritOfflineProgress && tpl.sqliteBytes) {
581
+ templateSave = readSaveJsonFromSqlite(tpl.sqliteBytes);
485
582
  }
486
583
  }
487
584
 
585
+ const { saveObj, rootId, headHash, stats } = buildCompleteSaveObject(
586
+ reduxState,
587
+ capturedData,
588
+ templateSave
589
+ );
590
+ saveObj.contentId = contentId;
591
+ saveObj.rulesVersion = rulesVersion;
592
+
488
593
  const saveJson = JSON.stringify(saveObj);
489
594
  const sqliteBytes = buildSaveSqlite({
490
595
  saveJson,
@@ -154,3 +154,85 @@ module.exports = {
154
154
  buildKcsaveBuffer,
155
155
  sha256Hex,
156
156
  };
157
+
158
+ function unpackKcs3(buf) {
159
+ if (buf.subarray(0, 4).toString('ascii') !== 'KCS3') {
160
+ throw new Error('无效的 KCS3 头');
161
+ }
162
+ const hdrLen = buf.readUInt32BE(4);
163
+ const hdrHash = buf.subarray(8, 40);
164
+ const hdrBuf = buf.subarray(40, 40 + hdrLen);
165
+ if (!sha256Buf(hdrBuf).equals(hdrHash)) {
166
+ throw new Error('KCS3 头部校验失败');
167
+ }
168
+ const header = JSON.parse(hdrBuf.toString('utf8'));
169
+ const sqliteBytes = zlib.gunzipSync(buf.subarray(40 + hdrLen));
170
+ return { header, sqliteBytes };
171
+ }
172
+
173
+ function applyKdz5Delta(baseSqliteBytes, deltaBuf) {
174
+ if (deltaBuf.subarray(0, 4).toString('ascii') !== 'KDZ5' || deltaBuf[4] !== 1) {
175
+ throw new Error('无效的 KDZ5 增量头');
176
+ }
177
+ const targetLen = deltaBuf.readUInt32BE(5);
178
+ const expectedHash = deltaBuf.subarray(deltaBuf.length - 32);
179
+ const gzPart = deltaBuf.subarray(9, deltaBuf.length - 32);
180
+ const ops = zlib.gunzipSync(gzPart);
181
+
182
+ const out = Buffer.alloc(targetLen);
183
+ let p = 0;
184
+ let outPos = 0;
185
+ let blkIdx = 0;
186
+ while (p < ops.length && outPos < targetLen) {
187
+ const op = ops[p++];
188
+ const rem = Math.min(256, targetLen - outPos);
189
+ if (op === 0) {
190
+ baseSqliteBytes.copy(out, outPos, blkIdx * 256, blkIdx * 256 + rem);
191
+ } else if (op === 1) {
192
+ ops.copy(out, outPos, p, p + rem);
193
+ p += rem;
194
+ } else if (op === 2) {
195
+ const srcBlk = ops.readUInt32BE(p);
196
+ p += 4;
197
+ baseSqliteBytes.copy(out, outPos, srcBlk * 256, srcBlk * 256 + rem);
198
+ } else {
199
+ throw new Error(`未知 KDZ5 操作码: ${op}`);
200
+ }
201
+ outPos += rem;
202
+ blkIdx += 1;
203
+ }
204
+ if (!sha256Buf(out).equals(expectedHash)) {
205
+ throw new Error('KDZ5 还原后的数据库 SHA-256 校验失败');
206
+ }
207
+ return out;
208
+ }
209
+
210
+ /**
211
+ * 解析基础模板 .kcsave,返回 manifest、appearance 与最新状态的 SQLite Buffer(自动应用 save.delta)。
212
+ */
213
+ function unpackKcsaveTemplate(rawBuf) {
214
+ const entries = parseKcsave5(rawBuf);
215
+ const manifest = JSON.parse(entries.get('manifest.json').toString('utf8'));
216
+ const activeId = manifest.activeId || 'legacy';
217
+ const appearRaw = entries.get(`profiles/${activeId}/appearance.json`);
218
+ const appearance = appearRaw ? JSON.parse(appearRaw.toString('utf8')) : null;
219
+ const slotRaw = entries.get(`profiles/${activeId}/slot-1.json`);
220
+ let sqliteBytes = null;
221
+ if (slotRaw) {
222
+ const { sqliteBytes: slotDb } = unpackKcs3(slotRaw);
223
+ sqliteBytes = slotDb;
224
+ const deltaRaw = entries.get(`profiles/${activeId}/save.delta`);
225
+ if (deltaRaw) {
226
+ try {
227
+ sqliteBytes = applyKdz5Delta(slotDb, deltaRaw);
228
+ } catch (_) {
229
+ // 如果 delta 异常则回退到 slot-1.json
230
+ }
231
+ }
232
+ }
233
+ return { manifest, appearance, sqliteBytes };
234
+ }
235
+
236
+ module.exports.unpackKcs3 = unpackKcs3;
237
+ module.exports.applyKdz5Delta = applyKdz5Delta;
238
+ module.exports.unpackKcsaveTemplate = unpackKcsaveTemplate;
@@ -286,3 +286,165 @@ function buildSaveSqlite({ saveJson, rootId, headHash, revision = 0 }) {
286
286
  }
287
287
 
288
288
  module.exports = { buildSaveSqlite };
289
+
290
+ // ==================== 零依赖纯 JS SQLite 3 读取器 ====================
291
+ // 用于从已有单机版模板 .kcsave 的 SQLite 数据库中读取 save.json(继承单机进度)
292
+
293
+ function readVarint(buf, offset) {
294
+ let val = 0n;
295
+ for (let i = 0; i < 8; i++) {
296
+ const b = buf[offset + i];
297
+ val = (val << 7n) | BigInt(b & 0x7f);
298
+ if ((b & 0x80) === 0) {
299
+ return { value: Number(val), bytes: i + 1 };
300
+ }
301
+ }
302
+ const b8 = buf[offset + 8];
303
+ val = (val << 8n) | BigInt(b8);
304
+ return { value: Number(val), bytes: 9 };
305
+ }
306
+
307
+ function decodeRecord(payload) {
308
+ const { value: hdrSize, bytes: hdrLenBytes } = readVarint(payload, 0);
309
+ const serialTypes = [];
310
+ let pos = hdrLenBytes;
311
+ while (pos < hdrSize) {
312
+ const st = readVarint(payload, pos);
313
+ serialTypes.push(st.value);
314
+ pos += st.bytes;
315
+ }
316
+ let dataPos = hdrSize;
317
+ const values = [];
318
+ for (const st of serialTypes) {
319
+ if (st === 0) {
320
+ values.push(null);
321
+ } else if (st === 1) {
322
+ values.push(payload.readInt8(dataPos));
323
+ dataPos += 1;
324
+ } else if (st === 2) {
325
+ values.push(payload.readInt16BE(dataPos));
326
+ dataPos += 2;
327
+ } else if (st === 3) {
328
+ values.push(payload.readIntBE(dataPos, 3));
329
+ dataPos += 3;
330
+ } else if (st === 4) {
331
+ values.push(payload.readInt32BE(dataPos));
332
+ dataPos += 4;
333
+ } else if (st === 5) {
334
+ values.push(payload.readIntBE(dataPos, 6));
335
+ dataPos += 6;
336
+ } else if (st === 6) {
337
+ values.push(Number(payload.readBigInt64BE(dataPos)));
338
+ dataPos += 8;
339
+ } else if (st === 7) {
340
+ values.push(payload.readDoubleBE(dataPos));
341
+ dataPos += 8;
342
+ } else if (st === 8) {
343
+ values.push(0);
344
+ } else if (st === 9) {
345
+ values.push(1);
346
+ } else if (st >= 12 && st % 2 === 0) {
347
+ const len = (st - 12) / 2;
348
+ values.push(payload.subarray(dataPos, dataPos + len));
349
+ dataPos += len;
350
+ } else if (st >= 13 && st % 2 === 1) {
351
+ const len = (st - 13) / 2;
352
+ values.push(payload.subarray(dataPos, dataPos + len).toString('utf8'));
353
+ dataPos += len;
354
+ } else {
355
+ values.push(null);
356
+ }
357
+ }
358
+ return values;
359
+ }
360
+
361
+ function readTableBTreeRows(dbBuf, pageNum, pageSize, usableSize) {
362
+ const pageOffset = (pageNum - 1) * pageSize;
363
+ const hdrOffset = pageNum === 1 ? 100 : 0;
364
+ const pageType = dbBuf[pageOffset + hdrOffset];
365
+ const cellCount = dbBuf.readUInt16BE(pageOffset + hdrOffset + 3);
366
+ const rows = [];
367
+
368
+ if (pageType === 0x05) {
369
+ // Interior table B-tree page
370
+ const rightMost = dbBuf.readUInt32BE(pageOffset + hdrOffset + 8);
371
+ const ptrStart = pageOffset + hdrOffset + 12;
372
+ for (let i = 0; i < cellCount; i++) {
373
+ const cellOff = dbBuf.readUInt16BE(ptrStart + i * 2);
374
+ const leftChild = dbBuf.readUInt32BE(pageOffset + cellOff);
375
+ rows.push(...readTableBTreeRows(dbBuf, leftChild, pageSize, usableSize));
376
+ }
377
+ rows.push(...readTableBTreeRows(dbBuf, rightMost, pageSize, usableSize));
378
+ } else if (pageType === 0x0d) {
379
+ // Leaf table B-tree page
380
+ const ptrStart = pageOffset + hdrOffset + 8;
381
+ const X = usableSize - 35;
382
+ const M = Math.floor(((usableSize - 12) * 32) / 255) - 23;
383
+ for (let i = 0; i < cellCount; i++) {
384
+ const cellOff = dbBuf.readUInt16BE(ptrStart + i * 2);
385
+ let p = pageOffset + cellOff;
386
+ const pSize = readVarint(dbBuf, p);
387
+ p += pSize.bytes;
388
+ const rowid = readVarint(dbBuf, p);
389
+ p += rowid.bytes;
390
+
391
+ const P = pSize.value;
392
+ let payload;
393
+ if (P <= X) {
394
+ payload = dbBuf.subarray(p, p + P);
395
+ } else {
396
+ const K = M + ((P - M) % (usableSize - 4));
397
+ const localLen = K <= X ? K : M;
398
+ const parts = [dbBuf.subarray(p, p + localLen)];
399
+ let remaining = P - localLen;
400
+ let ovPage = dbBuf.readUInt32BE(p + localLen);
401
+ while (ovPage > 0 && remaining > 0) {
402
+ const ovOff = (ovPage - 1) * pageSize;
403
+ const nextOv = dbBuf.readUInt32BE(ovOff);
404
+ const take = Math.min(remaining, usableSize - 4);
405
+ parts.push(dbBuf.subarray(ovOff + 4, ovOff + 4 + take));
406
+ remaining -= take;
407
+ ovPage = nextOv;
408
+ }
409
+ payload = Buffer.concat(parts);
410
+ }
411
+ rows.push({ rowid: rowid.value, values: decodeRecord(payload) });
412
+ }
413
+ }
414
+ return rows;
415
+ }
416
+
417
+ /**
418
+ * 从 SQLite 3 二进制 Buffer 中读取 save 表 (id=1) 的 json 字段并解析为对象。
419
+ */
420
+ function readSaveJsonFromSqlite(dbBuf) {
421
+ if (!Buffer.isBuffer(dbBuf)) dbBuf = Buffer.from(dbBuf);
422
+ if (dbBuf.subarray(0, 16).toString('ascii') !== 'SQLite format 3\0') {
423
+ throw new Error('无效的 SQLite 3 数据库头');
424
+ }
425
+ let pageSize = dbBuf.readUInt16BE(16);
426
+ if (pageSize === 1) pageSize = 65536;
427
+ const reserved = dbBuf[20];
428
+ const usableSize = pageSize - reserved;
429
+
430
+ const masterRows = readTableBTreeRows(dbBuf, 1, pageSize, usableSize);
431
+ let saveRootPage = 0;
432
+ for (const row of masterRows) {
433
+ if (row.values[0] === 'table' && row.values[1] === 'save') {
434
+ saveRootPage = Number(row.values[3]);
435
+ break;
436
+ }
437
+ }
438
+ if (!saveRootPage) {
439
+ throw new Error('模板 SQLite 中未找到 save 表');
440
+ }
441
+
442
+ const saveRows = readTableBTreeRows(dbBuf, saveRootPage, pageSize, usableSize);
443
+ const target = saveRows.find((r) => r.rowid === 1) || saveRows[0];
444
+ if (!target || typeof target.values[1] !== 'string') {
445
+ throw new Error('模板 save 表中没有有效的 JSON 数据');
446
+ }
447
+ return JSON.parse(target.values[1]);
448
+ }
449
+
450
+ module.exports.readSaveJsonFromSqlite = readSaveJsonFromSqlite;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poi-plugin-kcsave-exporter",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "一键将舰队 Collection 正式服数据完全导出为单机版 .kcsave (KCSAVE5) 存档(适配 poi 12.0.1)",
5
5
  "main": "index.es",
6
6
  "keywords": [