engine7 7.1.144 → 7.1.146

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.
@@ -1,7 +1,7 @@
1
- // src/travel/oss-return.ts
2
- import { join as join4, isAbsolute } from "node:path";
3
- import { gzipSync as gzipSync2 } from "node:zlib";
4
- import { createHash as createHash3 } from "node:crypto";
1
+ // src/travel/oss-bundle-stream.ts
2
+ import { readFileSync as readFileSync3, existsSync as existsSync3 } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { isAbsolute } from "node:path";
5
5
 
6
6
  // src/travel/chunk-store.ts
7
7
  import { createHash, randomUUID } from "node:crypto";
@@ -21,11 +21,15 @@ import {
21
21
  writeSync,
22
22
  constants
23
23
  } from "node:fs";
24
- import { gunzipSync, gzipSync } from "node:zlib";
24
+ import { gunzipSync, gzip } from "node:zlib";
25
+ import { promisify } from "node:util";
25
26
  import { dirname, join } from "node:path";
26
- var CHUNK_BYTES = 1024 * 1024;
27
+ var CHUNK_BYTES = 4 * 1024 * 1024;
28
+ var DATABASE_CHUNK_BYTES = 64 * 1024;
29
+ var chunkBytesFor = (path) => /\.(db|sqlite)(-wal|-shm)?$/.test(path) ? DATABASE_CHUNK_BYTES : CHUNK_BYTES;
27
30
  var SHA = /^[a-f0-9]{64}$/;
28
31
  var sha256 = (body) => createHash("sha256").update(body).digest("hex");
32
+ var compress = promisify(gzip);
29
33
  function validateChunkRef(ref) {
30
34
  if (!ref || !SHA.test(ref.sha256) || !Number.isSafeInteger(ref.bytes) || ref.bytes < 1 || ref.bytes > CHUNK_BYTES)
31
35
  throw new Error("TRAVEL_INVALID_CHUNK");
@@ -42,6 +46,7 @@ function validateFileManifest(file) {
42
46
  }
43
47
  var ChunkStore = class {
44
48
  dir;
49
+ verified = /* @__PURE__ */ new Map();
45
50
  constructor(dir) {
46
51
  this.dir = dir;
47
52
  mkdirSync(dir, { recursive: true, mode: 448 });
@@ -49,16 +54,22 @@ var ChunkStore = class {
49
54
  chunkPath(sha) {
50
55
  return join(this.dir, sha + ".gz");
51
56
  }
57
+ fingerprint(path) {
58
+ const s = lstatSync(path, { bigint: true });
59
+ if (!s.isFile()) throw Error("TRAVEL_CHUNK_CORRUPT");
60
+ return [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].join(":");
61
+ }
52
62
  /** 幂等:同 sha 已存在直接返回;写盘走 tmp+rename,读者永远看不到半个块。 */
53
63
  async put(body) {
54
64
  if (!(body instanceof Buffer) || body.length < 1 || body.length > CHUNK_BYTES) throw new Error("TRAVEL_INVALID_CHUNK");
55
- const ref = { sha256: sha256(body), bytes: body.length };
65
+ const stable = Buffer.from(body), ref = { sha256: sha256(stable), bytes: stable.length };
56
66
  const path = this.chunkPath(ref.sha256);
57
- if (!existsSync(path)) {
67
+ if (!await this.has(ref.sha256)) {
58
68
  const temp = path + "." + randomUUID() + ".tmp";
59
69
  try {
60
- writeFileSync(temp, gzipSync(body), { flag: "wx", mode: 384 });
70
+ writeFileSync(temp, await compress(stable), { flag: "wx", mode: 384 });
61
71
  renameSync(temp, path);
72
+ this.verified.set(ref.sha256, this.fingerprint(path));
62
73
  } finally {
63
74
  try {
64
75
  if (existsSync(temp)) unlinkSync(temp);
@@ -70,6 +81,12 @@ var ChunkStore = class {
70
81
  }
71
82
  async has(sha) {
72
83
  if (!SHA.test(sha)) throw new Error("TRAVEL_INVALID_CHUNK");
84
+ const known = this.verified.get(sha);
85
+ if (known) try {
86
+ if (this.fingerprint(this.chunkPath(sha)) === known) return true;
87
+ } catch {
88
+ }
89
+ this.verified.delete(sha);
73
90
  if (!existsSync(this.chunkPath(sha))) return false;
74
91
  try {
75
92
  await this.read(sha);
@@ -81,12 +98,20 @@ var ChunkStore = class {
81
98
  async read(sha, bytes = -1) {
82
99
  if (!SHA.test(sha) || !Number.isSafeInteger(bytes) || bytes < -1 || bytes > CHUNK_BYTES) throw new Error("TRAVEL_INVALID_CHUNK");
83
100
  let plain;
101
+ let before;
84
102
  try {
85
- plain = gunzipSync(readFileSync(this.chunkPath(sha)));
103
+ before = this.fingerprint(this.chunkPath(sha));
104
+ plain = gunzipSync(readFileSync(this.chunkPath(sha)), { maxOutputLength: CHUNK_BYTES });
86
105
  } catch {
87
106
  throw new Error("TRAVEL_CHUNK_CORRUPT");
88
107
  }
89
108
  if (sha256(plain) !== sha || bytes >= 0 && plain.length !== bytes) throw new Error("TRAVEL_CHUNK_CORRUPT");
109
+ try {
110
+ if (this.fingerprint(this.chunkPath(sha)) === before) this.verified.set(sha, before);
111
+ else this.verified.delete(sha);
112
+ } catch {
113
+ this.verified.delete(sha);
114
+ }
90
115
  return plain;
91
116
  }
92
117
  /** 读磁盘上的原始 gzip 体(OSS 直传用:线上/磁盘同为 gz,省一次解压重压)。 */
@@ -97,13 +122,13 @@ var ChunkStore = class {
97
122
  /** 捕获 = 边读边入仓。1122 晚(VACUUM 拆除后 raw 直捕实弹):活引擎的库/wal/
98
123
  * jsonl 读到一半被写是常态,一律拒绝会把整个准备打死(晓雯 19:31 实弹
99
124
  * TRAVEL_SOURCE_CHANGED)。策略=重读两轮仍变=活写入者,接受最后一次自洽读
100
- * (sha 与实际读到的字节严格对应;语义撕裂由对端 integrity_check 出声,
101
- * 搬移的权威静止同步随后覆盖)。静止路径(引擎已停)守卫天然不触发。 */
102
- async captureFile(source) {
125
+ * (sha 与实际读到的字节严格对应;预复制只入仓、不落位,正式迁移随后
126
+ * 使用停机后的稳定 DB/WAL 捕获组)。静止路径(引擎已停)守卫天然不触发。 */
127
+ async captureFile(source, onProgress) {
103
128
  let lastError = null;
104
129
  for (let attempt = 0; attempt < 3; attempt++) {
105
130
  try {
106
- return await this.captureFileOnce(source, attempt === 2);
131
+ return await this.captureFileOnce(source, attempt === 2, onProgress);
107
132
  } catch (error) {
108
133
  if (!(error instanceof Error) || error.message !== "TRAVEL_SOURCE_CHANGED") throw error;
109
134
  lastError = error;
@@ -111,13 +136,13 @@ var ChunkStore = class {
111
136
  }
112
137
  throw lastError;
113
138
  }
114
- async captureFileOnce(source, acceptLiveWrite) {
139
+ async captureFileOnce(source, acceptLiveWrite, onProgress) {
115
140
  const fd = openSync(source, constants.O_RDONLY);
116
141
  try {
117
142
  const before = fstatSync(fd, { bigint: true });
118
143
  if (!before.isFile()) throw new Error("TRAVEL_NOT_REGULAR_FILE");
119
144
  const digest = createHash("sha256");
120
- const buffer = Buffer.alloc(Math.min(CHUNK_BYTES, Number(before.size) || 1));
145
+ const buffer = Buffer.alloc(Math.min(chunkBytesFor(source), Number(before.size) || 1));
121
146
  const chunks = [];
122
147
  let bytes = 0;
123
148
  for (; ; ) {
@@ -127,6 +152,7 @@ var ChunkStore = class {
127
152
  digest.update(piece);
128
153
  bytes += count;
129
154
  chunks.push(await this.put(piece));
155
+ onProgress?.(bytes);
130
156
  }
131
157
  const after = fstatSync(fd, { bigint: true });
132
158
  const pathInfo = lstatSync(source, { bigint: true });
@@ -190,188 +216,12 @@ function openChunkStore(dir) {
190
216
  return new ChunkStore(dir);
191
217
  }
192
218
 
193
- // src/travel/tree-manifest.ts
194
- import { lstatSync as lstatSync3, readdirSync } from "node:fs";
195
- import { join as join3 } from "node:path";
196
-
197
- // src/travel/exclusions.ts
198
- var EXCLUDED_NAMES = /* @__PURE__ */ new Set(["node_modules", ".venv", ".venvs", "venv", ".git", "__pycache__", ".cache", "cache", "caches", "tmp", "temp", ".playwright-mcp", ".DS_Store"]);
199
- var EXCLUDED_TOP = /* @__PURE__ */ new Set(["logs", "diagnostics", "node_modules", "CogniFold", "everos-venv", "ollama-models", ".log-baseline.txt"]);
200
- function excludeReason(relPath, isDir) {
201
- const parts = relPath.split("/");
202
- for (let i = 0; i < parts.length - 1; i++) {
203
- const part = parts[i];
204
- if (part === "media" && parts[i + 1] === "inbound") {
205
- i++;
206
- continue;
207
- }
208
- if (EXCLUDED_NAMES.has(part)) return `installed dependency, cache or temporary directory: ${part}`;
209
- }
210
- const name = parts[parts.length - 1];
211
- if (isDir && EXCLUDED_NAMES.has(name)) return `installed dependency, cache or temporary directory: ${name}`;
212
- if (parts.length === 1 && EXCLUDED_TOP.has(name)) return `diagnostics, installed or rebuildable material: ${name}`;
213
- if (/\.lock$/.test(name) || /\.pid$/.test(name) || name === "package-lock.json" || name === "nohup.out") return "lock/pid/junk file";
214
- if (parts.length === 1 && EXCLUDED_NAMES.has(name)) return `installed dependency, cache or temporary file: ${name}`;
215
- if (/\.log$/.test(name) && parts[0] !== "workspace") return "diagnostics log";
216
- const mediaIndex = parts.indexOf("media");
217
- if (mediaIndex >= 0 && parts[mediaIndex + 1] === "generated") return "self-generated media";
218
- return void 0;
219
- }
220
- var WORKSPACE_MEMORY_DIRS = /* @__PURE__ */ new Set(["topics", "memory", "inner-voice", ".calendar", ".proactive", ".system", "docs", "skills"]);
221
- function workspaceTopFileReason(name, size) {
222
- if (!(/\.md$/i.test(name) || name === ".gitignore")) return `workspace \u9876\u5C42\u975E md \u6587\u4EF6\u4E0D\u968F\u884C\uFF08${name}\uFF09`;
223
- if (typeof size === "number" && size > WORKSPACE_BIG_FILE_BYTES) return `workspace \u9876\u5C42 md \u8D85 32MB \u4E0D\u968F\u884C\uFF08${name}\uFF09`;
224
- return void 0;
225
- }
226
- var WORKSPACE_MEDIA_EXT = /\.(mp4|mov|mkv|webm|avi|m4v|flv|wmv|mpg|mpeg|mp3|wav|flac|aac|ogg|opus|m4a|zip|rar|7z|dmg|iso)$/i;
227
- var WORKSPACE_BIG_FILE_BYTES = 32 * 1024 * 1024;
228
- var RETURN_MEDIA_KEEP_MS = 14 * 24 * 3600 * 1e3;
229
- function syncExcludeWith(mediaPolicy) {
230
- return (relPath, isDir, size, mtimeMs) => {
231
- const parts = relPath.split("/");
232
- const name = parts[parts.length - 1];
233
- if (!relPath.includes("/") && (relPath === "config.json" || relPath === "secrets.env")) {
234
- return "\u5BF9\u7AEF\u5B89\u88C5\u4EA7\u7269\u4FDD\u62A4\uFF08config \u8D70 config-remap\uFF0Csecrets \u8D70 travel-setup\uFF09";
235
- }
236
- const isUserMedia = parts[0] === "media" && parts[1] === "inbound" || parts[0] === "chan7-files";
237
- if (isUserMedia) {
238
- if (mediaPolicy === "none") return "\u7528\u6237\u5A92\u4F53\u6863\u6848\u4E0D\u968F\u884C\uFF081122\uFF1A\u4E91\u7AEF\u7FFB\u65E7\u56FE\u8D70\u964D\u7EA7\u5360\u4F4D\uFF09";
239
- if (typeof size === "number" && size > WORKSPACE_BIG_FILE_BYTES) return `\u7528\u6237\u5A92\u4F53\u5927\u6587\u4EF6\u4E0D\u968F\u884C\uFF08${(size / 1048576).toFixed(0)}MB > 32MB\uFF09`;
240
- if (typeof mtimeMs === "number" && Date.now() - mtimeMs > mediaPolicy.windowMs) return `\u7528\u6237\u5A92\u4F53\u4EC5\u8FD1 ${Math.round(mediaPolicy.windowMs / 864e5)} \u5929\u968F\u884C\uFF08\u56DE\u7A0B\u7A97\u53E3\uFF09`;
241
- return void 0;
242
- }
243
- if (parts[0] === "workspace") {
244
- if (parts.length === 1) return isDir ? void 0 : workspaceTopFileReason(name, size);
245
- const second = parts[1];
246
- if (!WORKSPACE_MEMORY_DIRS.has(second)) {
247
- if (parts.length === 2 && !isDir) return workspaceTopFileReason(second, size);
248
- return `workspace \u5DE5\u4F5C\u4EA7\u7269\u4E0D\u968F\u884C\uFF08${second}/\uFF09\u2014\u2014\u53EA\u5E26\u6838\u5FC3\u8BB0\u5FC6\uFF081122 \u7ACB\u6CD5\uFF09`;
249
- }
250
- if (!isDir) {
251
- if (WORKSPACE_MEDIA_EXT.test(name)) return `workspace \u5185\u97F3\u89C6\u9891/\u538B\u7F29\u5305\u4E0D\u968F\u884C\uFF08${name}\uFF09`;
252
- if (second !== ".proactive" && typeof size === "number" && size > WORKSPACE_BIG_FILE_BYTES) return `workspace \u5927\u6587\u4EF6\u4E0D\u968F\u884C\uFF08${(size / 1048576).toFixed(0)}MB > 32MB\uFF09`;
253
- }
254
- return void 0;
255
- }
256
- if (parts[0] === "media" && parts.length >= 2) return `media \u4EC5 inbound\uFF08\u56DE\u7A0B\u8FD1\u7A97\uFF09\u968F\u884C\uFF1A${parts[1]}`;
257
- if (parts[0] === "content") return "\u5185\u5BB9\u4EA7\u7269\u76EE\u5F55\u4E0D\u968F\u884C";
258
- return excludeReason(relPath, isDir);
259
- };
260
- }
261
- var syncExcludeReason = syncExcludeWith("none");
262
- var syncExcludeToCloud = syncExcludeWith("none");
263
- var syncExcludeToLocal = syncExcludeWith({ windowMs: RETURN_MEDIA_KEEP_MS });
264
- function syncExcludeWithDays(days) {
265
- return days > 0 ? syncExcludeWith({ windowMs: days * 864e5 }) : syncExcludeWith("none");
266
- }
267
-
268
- // src/travel/capture-cache.ts
269
- import { existsSync as existsSync2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, realpathSync, renameSync as renameSync2, writeFileSync as writeFileSync2, unlinkSync as unlinkSync2 } from "node:fs";
270
- import { join as join2 } from "node:path";
271
- import { randomUUID as randomUUID2 } from "node:crypto";
272
- function fileFingerprint(file) {
273
- const s = lstatSync2(file, { bigint: true });
274
- if (!s.isFile()) throw Error("TRAVEL_NOT_REGULAR_FILE");
275
- return [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].join(":");
276
- }
277
- function readCaptureCache(root) {
278
- try {
279
- const value = JSON.parse(readFileSync2(join2(root, ".travel/capture-cache.json"), "utf8"));
280
- if (value.version !== 1 || value.root !== realpathSync(root) || !value.entries || typeof value.entries !== "object") return /* @__PURE__ */ new Map();
281
- return new Map(Object.entries(value.entries));
282
- } catch {
283
- return /* @__PURE__ */ new Map();
284
- }
285
- }
286
- function cachedContent(cache2, rel, fingerprint) {
287
- const entry = cache2.get(rel);
288
- if (!entry || entry.fingerprint !== fingerprint) return;
289
- try {
290
- validateFileManifest(entry.content);
291
- return entry.content;
292
- } catch {
293
- return;
294
- }
295
- }
296
- function writeCaptureCache(root, cache2) {
297
- const directory = join2(root, ".travel"), temp = join2(directory, "capture-cache." + randomUUID2() + ".tmp");
298
- try {
299
- mkdirSync2(directory, { recursive: true, mode: 448 });
300
- writeFileSync2(temp, JSON.stringify({ version: 1, root: realpathSync(root), entries: Object.fromEntries(cache2) }), { mode: 384 });
301
- renameSync2(temp, join2(directory, "capture-cache.json"));
302
- } catch {
303
- try {
304
- unlinkSync2(temp);
305
- } catch {
306
- }
307
- }
308
- }
309
- function cachedChunksExist(directory, content) {
310
- return content.chunks.every((ref) => existsSync2(join2(directory, ref.sha256 + ".gz")));
311
- }
312
-
313
- // src/travel/tree-manifest.ts
314
- var TREE_MANIFEST_VERSION = 2;
315
- var SELF_EXCLUDED_TOP = /* @__PURE__ */ new Set([".travel", ".travel-sync-staging"]);
316
- async function buildTreeManifest(root, store, opts = {}) {
317
- const exclude = opts.exclude ?? syncExcludeReason;
318
- const files = [];
319
- const excluded = [];
320
- const previous = readCaptureCache(root), next = /* @__PURE__ */ new Map();
321
- const walk = async (dir, rel) => {
322
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
323
- const childRel = rel ? `${rel}/${entry.name}` : entry.name;
324
- const childPath = join3(dir, entry.name);
325
- if (entry.isSymbolicLink()) {
326
- excluded.push(`${childRel} \u2014 symlink refused`);
327
- continue;
328
- }
329
- if (rel === "" && SELF_EXCLUDED_TOP.has(entry.name)) {
330
- excluded.push(`${childRel} \u2014 travel internal state`);
331
- continue;
332
- }
333
- let size, mtimeMs;
334
- if (entry.isFile()) {
335
- try {
336
- const info2 = lstatSync3(childPath);
337
- size = info2.size;
338
- mtimeMs = info2.mtimeMs;
339
- } catch {
340
- }
341
- }
342
- const reason = exclude(childRel, entry.isDirectory(), size, mtimeMs);
343
- if (reason) {
344
- excluded.push(`${childRel} \u2014 ${reason}`);
345
- continue;
346
- }
347
- if (entry.isDirectory()) {
348
- await walk(childPath, childRel);
349
- continue;
350
- }
351
- if (!entry.isFile()) {
352
- excluded.push(`${childRel} \u2014 not a regular file`);
353
- continue;
354
- }
355
- const info = lstatSync3(childPath);
356
- const before = fileFingerprint(childPath);
357
- let content = cachedContent(previous, childRel, before);
358
- if (!content || !cachedChunksExist(store.dir, content) || fileFingerprint(childPath) !== before) content = await store.captureFile(childPath);
359
- const after = fileFingerprint(childPath);
360
- if (before === after && content.bytes === info.size) next.set(childRel, { fingerprint: after, content });
361
- files.push({ rel: childRel, mode: info.mode & 511, content });
362
- }
363
- };
364
- await walk(root, "");
365
- files.sort((a, b) => a.rel < b.rel ? -1 : 1);
366
- writeCaptureCache(root, next);
367
- return { version: TREE_MANIFEST_VERSION, generatedAt: Date.now(), files, excluded };
368
- }
369
-
370
219
  // src/travel/oss-transport.ts
371
220
  import { createHmac, createHash as createHash2 } from "node:crypto";
372
221
 
373
222
  // src/travel/oss-broker.ts
374
223
  var cache = /* @__PURE__ */ new WeakMap();
224
+ var signingQueues = /* @__PURE__ */ new WeakMap();
375
225
  var cacheKey = (o) => JSON.stringify([o.method, o.key, o.contentMD5 ?? "", o.contentType ?? ""]);
376
226
  function validateAuthorization(config, value, operations) {
377
227
  if (!value || !Number.isSafeInteger(value.expiresAt) || value.expiresAt > Date.now() / 1e3 + 960 || !Array.isArray(value.objects) || value.objects.length !== operations.length) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
@@ -391,7 +241,7 @@ function validateAuthorization(config, value, operations) {
391
241
  }
392
242
  config.broker.tokenId = tokenId;
393
243
  }
394
- async function authorize(config, operations) {
244
+ async function authorizeHttp(config, operations) {
395
245
  const broker = config.broker;
396
246
  let result;
397
247
  try {
@@ -408,7 +258,31 @@ async function authorize(config, operations) {
408
258
  }
409
259
  return result;
410
260
  }
411
- async function prepareOssRequests(config, operations) {
261
+ async function authorize(config, operations, background = false) {
262
+ const broker = config.broker;
263
+ let queue = signingQueues.get(broker);
264
+ if (!queue) {
265
+ queue = { tail: Promise.resolve(), last: 0 };
266
+ signingQueues.set(broker, queue);
267
+ }
268
+ const current = queue;
269
+ const result = current.tail.catch(() => {
270
+ }).then(async () => {
271
+ const wait = 1e3 - (Date.now() - current.last);
272
+ if (wait > 0) await new Promise((resolve2) => {
273
+ const timer = setTimeout(resolve2, wait);
274
+ if (background) timer.unref();
275
+ });
276
+ try {
277
+ return await authorizeHttp(config, operations);
278
+ } finally {
279
+ current.last = Date.now();
280
+ }
281
+ });
282
+ current.tail = result;
283
+ return result;
284
+ }
285
+ async function prepareOssRequests(config, operations, background = false) {
412
286
  if (!config.broker) return;
413
287
  let entries = cache.get(config);
414
288
  if (!entries) {
@@ -417,10 +291,21 @@ async function prepareOssRequests(config, operations) {
417
291
  }
418
292
  const missing = operations.filter((o) => (entries.get(cacheKey(o))?.expiresAt ?? 0) <= Date.now() / 1e3 + 30);
419
293
  for (let i = 0; i < missing.length; i += 128) {
420
- const batch = missing.slice(i, i + 128), result = await authorize(config, batch);
294
+ const batch = missing.slice(i, i + 128), result = await authorize(config, batch, background);
421
295
  for (const [index, object] of result.objects.entries()) entries.set(cacheKey(batch[index]), { object, expiresAt: result.expiresAt });
422
296
  }
423
297
  }
298
+ async function withOssBatches(config, items, operation, transfer, background = false) {
299
+ for (let i = 0; i < items.length; i += 128) {
300
+ const batch = items.slice(i, i + 128), operations = batch.map(operation);
301
+ try {
302
+ await prepareOssRequests(config, operations, background);
303
+ await transfer(batch);
304
+ } finally {
305
+ for (const op of operations) cache.get(config)?.delete(cacheKey(op));
306
+ }
307
+ }
308
+ }
424
309
  async function signedOssRequest(config, operation, refresh = false) {
425
310
  if (refresh) cache.get(config)?.delete(cacheKey(operation));
426
311
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -432,6 +317,18 @@ async function signedOssRequest(config, operation, refresh = false) {
432
317
  }
433
318
 
434
319
  // src/travel/oss-transport.ts
320
+ function ossFailureCode(error) {
321
+ const message = error instanceof Error ? error.message : "";
322
+ const code = /^TRAVEL_[A-Z_0-9]+/.exec(message)?.[0];
323
+ if (code) {
324
+ const status = code === "TRAVEL_OSS_ERROR" ? /→ ([0-9]{3})/.exec(message)?.[1] : void 0;
325
+ return status ? `${code}_HTTP_${status}` : code;
326
+ }
327
+ const system = error?.code;
328
+ if (system === "Z_DATA_ERROR" || system === "Z_BUF_ERROR") return "TRAVEL_BUNDLE_CORRUPT";
329
+ if (["ENOSPC", "EACCES", "EROFS", "ETIMEDOUT"].includes(system ?? "")) return "TRAVEL_OSS_RECEIVE_" + system;
330
+ return "TRAVEL_OSS_BUNDLE_RECEIVE_FAILED";
331
+ }
435
332
  function internalEndpointOf(endpoint) {
436
333
  if (endpoint.includes("-internal.")) return endpoint;
437
334
  const at = endpoint.indexOf(".aliyuncs.com");
@@ -505,59 +402,235 @@ function objectPath(key) {
505
402
  if (!/^[A-Za-z0-9/_.-]+$/.test(key) || key.startsWith("/") || key.includes("..")) throw Error("TRAVEL_OSS_INVALID_OBJECT_KEY");
506
403
  return "/" + key;
507
404
  }
508
- async function ossPutObject(config, key, body) {
509
- await ossFetch(config, "PUT", objectPath(key), body, { "Content-Type": "application/octet-stream", "Content-MD5": md5Base64(body) });
405
+ async function ossGetObject(config, key, maxBytes = 64 * 1048576) {
406
+ const response = await ossFetch(config, "GET", objectPath(key));
407
+ if (Number(response.headers.get("content-length")) > maxBytes) {
408
+ await response.body?.cancel();
409
+ throw Error("TRAVEL_OSS_OBJECT_TOO_LARGE");
410
+ }
411
+ const reader = response.body?.getReader();
412
+ if (!reader) return Buffer.alloc(0);
413
+ let bytes = 0;
414
+ const parts = [];
415
+ try {
416
+ for (; ; ) {
417
+ const next = await reader.read();
418
+ if (next.done) break;
419
+ bytes += next.value.length;
420
+ if (bytes > maxBytes) {
421
+ await reader.cancel();
422
+ throw Error("TRAVEL_OSS_OBJECT_TOO_LARGE");
423
+ }
424
+ parts.push(Buffer.from(next.value));
425
+ }
426
+ return Buffer.concat(parts);
427
+ } finally {
428
+ reader.releaseLock();
429
+ }
430
+ }
431
+
432
+ // src/travel/oss-bundle.ts
433
+ import { createHash as createHash3 } from "node:crypto";
434
+ import { gzip as gzip2, gunzip } from "node:zlib";
435
+ import { promisify as promisify2 } from "node:util";
436
+ var BUNDLE_GZIP_MAX = 8 * 1048576;
437
+ var BUNDLE_RAW_MAX = 32 * 1048576;
438
+ var BUNDLE_HEADER_MAX = 256 * 1024;
439
+ var BUNDLE_REFS_MAX = 2048;
440
+ var MAGIC = Buffer.from([69, 55, 80, 75, 0, 0, 0, 1]);
441
+ var zip = promisify2(gzip2);
442
+ var unzip = promisify2(gunzip);
443
+ function validateBundleRef(value) {
444
+ if (!value || !/^[a-f0-9]{64}$/.test(value.sha256) || !Number.isSafeInteger(value.plainBytes) || value.plainBytes < 12 || value.plainBytes > BUNDLE_RAW_MAX + BUNDLE_HEADER_MAX + 12 || !Array.isArray(value.refs) || !value.refs.length || value.refs.length > BUNDLE_REFS_MAX) throw Error("TRAVEL_INVALID_BUNDLE");
445
+ const seen = /* @__PURE__ */ new Set();
446
+ let bytes = 0;
447
+ for (const ref of value.refs) {
448
+ validateChunkRef(ref);
449
+ if (seen.has(ref.sha256)) throw Error("TRAVEL_INVALID_BUNDLE");
450
+ seen.add(ref.sha256);
451
+ bytes += ref.bytes;
452
+ }
453
+ if (bytes > BUNDLE_RAW_MAX) throw Error("TRAVEL_INVALID_BUNDLE");
454
+ }
455
+ async function unpackBundle(body, expected) {
456
+ if (body.length > BUNDLE_GZIP_MAX || !/^[a-f0-9]{64}$/.test(expected.sha256) || !Number.isSafeInteger(expected.plainBytes) || expected.plainBytes > BUNDLE_RAW_MAX + BUNDLE_HEADER_MAX + 12) throw Error("TRAVEL_INVALID_BUNDLE");
457
+ const plain = await unzip(body, { maxOutputLength: BUNDLE_RAW_MAX + BUNDLE_HEADER_MAX + 12 });
458
+ if (plain.length !== expected.plainBytes || createHash3("sha256").update(plain).digest("hex") !== expected.sha256 || !plain.subarray(0, 8).equals(MAGIC)) throw Error("TRAVEL_BUNDLE_CORRUPT");
459
+ const size = plain.readUInt32BE(8);
460
+ if (!size || size > BUNDLE_HEADER_MAX || 12 + size > plain.length) throw Error("TRAVEL_BUNDLE_CORRUPT");
461
+ const header = JSON.parse(plain.subarray(12, 12 + size).toString());
462
+ if (header.version !== 1) throw Error("TRAVEL_INVALID_BUNDLE");
463
+ if (expected.refsDigest && createHash3("sha256").update(JSON.stringify(header.refs)).digest("hex") !== expected.refsDigest) throw Error("TRAVEL_BUNDLE_CORRUPT");
464
+ const bundle = { ...expected, refs: header.refs };
465
+ validateBundleRef(bundle);
466
+ const parts = [];
467
+ let offset = 12 + size;
468
+ for (const ref of bundle.refs) {
469
+ const part = plain.subarray(offset, offset + ref.bytes);
470
+ if (part.length !== ref.bytes || createHash3("sha256").update(part).digest("hex") !== ref.sha256) throw Error("TRAVEL_CHUNK_CORRUPT");
471
+ parts.push({ ref, body: part });
472
+ offset += ref.bytes;
473
+ }
474
+ if (offset !== plain.length) throw Error("TRAVEL_BUNDLE_CORRUPT");
475
+ return parts;
510
476
  }
511
- async function ossDeleteObject(config, key) {
512
- await ossFetch(config, "DELETE", objectPath(key), void 0, {}, [204]);
477
+
478
+ // src/travel/apply-transaction.ts
479
+ import { closeSync as closeSync2, existsSync as existsSync2, fsyncSync as fsyncSync2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync2, readSync as readSync2, renameSync as renameSync2, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
480
+ import { dirname as dirname2, join as join2, resolve } from "node:path";
481
+ var safeRel = (rel) => !!rel && !/[\\:\x00-\x1f]/.test(rel) && rel.split("/").every((p) => p && p !== "." && p !== "..");
482
+ function assertPath(root, rel) {
483
+ if (!safeRel(rel)) throw Error("TRAVEL_UNSAFE_PATH");
484
+ let path = root;
485
+ for (const part of rel.split("/")) {
486
+ path = join2(path, part);
487
+ try {
488
+ if (lstatSync2(path).isSymbolicLink()) throw Error("TRAVEL_UNSAFE_PATH");
489
+ } catch (e) {
490
+ if (e.code !== "ENOENT") throw e;
491
+ }
492
+ }
493
+ return path;
513
494
  }
514
495
 
515
- // src/travel/oss-return.ts
516
- async function pool(items, fn) {
517
- let cursor = 0;
518
- const results = await Promise.allSettled(Array.from({ length: 12 }, async () => {
496
+ // src/travel/oss-bundle-stream.ts
497
+ var bootstrap = `import{createInterface}from'node:readline';const rl=createInterface({input:process.stdin,crlfDelay:Infinity}),it=rl[Symbol.asyncIterator]();try{const first=await it.next(),x=JSON.parse(first.value),m=await import('data:text/javascript;base64,'+Buffer.from(x.module).toString('base64'));await m.runOssBundleStream(x.root,x.config,it,p=>process.stdout.write(JSON.stringify(p)+'\\n'))}catch(e){console.error(e.message);process.exitCode=1}`;
498
+ var quote = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
499
+ function makeBundleReceiver(root, config) {
500
+ if (!isAbsolute(root)) throw Error("TRAVEL_UNSAFE_PATH");
501
+ const store = openChunkStore(assertPath(root, ".travel/chunks"));
502
+ let active = 0;
503
+ const waiters = [];
504
+ const acquire = async () => {
505
+ if (active < 4) {
506
+ active++;
507
+ return;
508
+ }
509
+ await new Promise((r) => waiters.push(r));
510
+ }, release = () => {
511
+ const next = waiters.shift();
512
+ if (next) next();
513
+ else active--;
514
+ };
515
+ return async (bundles) => {
516
+ const result = { bundles: 0, chunks: 0, bytes: 0, failed: [] };
517
+ await withOssBatches(config, bundles, (b) => ({ method: "GET", key: "chunks/" + b.sha256 + ".gz" }), async (batch) => {
518
+ await Promise.all(batch.map(async (bundle) => {
519
+ await acquire();
520
+ try {
521
+ const chunks = await unpackBundle(await ossGetObject(config, "chunks/" + bundle.sha256 + ".gz", BUNDLE_GZIP_MAX), bundle);
522
+ for (const chunk of chunks) await store.put(chunk.body);
523
+ result.bundles++;
524
+ result.chunks += chunks.length;
525
+ result.bytes += chunks.reduce((n, c) => n + c.ref.bytes, 0);
526
+ } catch (error) {
527
+ result.failed.push({ sha256: bundle.sha256, code: ossFailureCode(error) });
528
+ } finally {
529
+ release();
530
+ }
531
+ }));
532
+ });
533
+ return result;
534
+ };
535
+ }
536
+ async function runOssBundleStream(root, initial, lines, send) {
537
+ const receive = makeBundleReceiver(root, { ...initial, endpoint: internalEndpointOf(initial.endpoint) }), jobs = /* @__PURE__ */ new Set();
538
+ send({ ready: true });
539
+ for await (const line of lines) {
540
+ const input = JSON.parse(line);
541
+ if (!Number.isSafeInteger(input.id) || input.id < 1 || !Array.isArray(input.bundles) || input.bundles.length < 1 || input.bundles.length > 8) throw Error("TRAVEL_OSS_BUNDLE_PROTOCOL");
542
+ const job = receive(input.bundles).then((result) => send({ id: input.id, result }), (error) => send({ id: input.id, error: ossFailureCode(error) }));
543
+ jobs.add(job);
544
+ void job.finally(() => jobs.delete(job));
545
+ if (jobs.size >= 2) await Promise.race(jobs);
546
+ }
547
+ await Promise.all(jobs);
548
+ }
549
+ function openBundleStream(options) {
550
+ let source = options.source;
551
+ if (!source) {
552
+ for (const url of [new URL("./travel-oss-bundle-stream.mjs", import.meta.url), new URL("../../dist/travel-oss-bundle-stream.mjs", import.meta.url)]) if (existsSync3(fileURLToPath(url))) {
553
+ source = readFileSync3(url, "utf8");
554
+ break;
555
+ }
556
+ }
557
+ if (!source) throw Error("TRAVEL_OSS_HELPER_MISSING");
558
+ const child = options.spawn("node --input-type=module -e " + quote(bootstrap)), pending = /* @__PURE__ */ new Map();
559
+ let sequence = 0, text = "", settled = false, closed = false, resolveReady, rejectReady;
560
+ const ready = new Promise((resolve2, reject) => {
561
+ resolveReady = resolve2;
562
+ rejectReady = reject;
563
+ });
564
+ const fail = () => {
565
+ closed = true;
566
+ const error = Error("TRAVEL_OSS_BUNDLE_CONNECTION_CLOSED");
567
+ if (!settled) {
568
+ settled = true;
569
+ rejectReady(error);
570
+ }
571
+ for (const p of pending.values()) p.reject(error);
572
+ pending.clear();
573
+ };
574
+ child.on("error", fail);
575
+ child.on("close", fail);
576
+ child.stdin.on("error", fail);
577
+ child.stderr.on("data", (b) => options.log("[bundle-receiver] " + b.toString().trim()));
578
+ child.stdout.on("data", (b) => {
579
+ text += b.toString();
519
580
  for (; ; ) {
520
- const i = cursor++;
521
- if (i >= items.length) return;
581
+ const i = text.indexOf("\n");
582
+ if (i < 0) break;
583
+ const line = text.slice(0, i);
584
+ text = text.slice(i + 1);
522
585
  try {
523
- await fn(items[i]);
586
+ const value = JSON.parse(line);
587
+ if (value.ready) {
588
+ settled = true;
589
+ resolveReady();
590
+ continue;
591
+ }
592
+ const p = pending.get(value.id);
593
+ if (p) {
594
+ pending.delete(value.id);
595
+ value.error ? p.reject(Error(value.error)) : p.resolve(value.result);
596
+ }
524
597
  } catch {
525
- await fn(items[i]);
598
+ fail();
526
599
  }
527
600
  }
528
- }));
529
- const failed = results.find((r) => r.status === "rejected");
530
- if (failed?.status === "rejected") throw failed.reason;
531
- }
532
- async function runOssReturn(request, progress) {
533
- if (!request || !isAbsolute(request.stateDir) || !/^chunks\/return\/[a-f0-9]{64}$/.test(request.prefix) || !request.config?.accessKeySecret && !request.config?.broker) throw Error("TRAVEL_OSS_RETURN_INVALID_REQUEST");
534
- const config = { ...request.config, endpoint: internalEndpointOf(request.config.endpoint) };
535
- if (request.op === "cleanup") {
536
- const keys = request.keys ?? [];
537
- if (keys.some((key) => !key.startsWith(request.prefix + "/"))) throw Error("TRAVEL_OSS_RETURN_INVALID_KEY");
538
- await prepareOssRequests(config, keys.map((key) => ({ method: "DELETE", key })));
539
- await pool(keys, (key) => ossDeleteObject(config, key));
540
- return { deleted: keys.length };
541
- }
542
- const store = openChunkStore(join4(request.stateDir, ".travel/chunks"));
543
- if (request.op === "capture") {
544
- const manifest = await buildTreeManifest(request.stateDir, store, { exclude: syncExcludeWithDays(14) }), body = Buffer.from(JSON.stringify(manifest)), objectKey = request.prefix + "/manifest.gz";
545
- await ossPutObject(config, objectKey, gzipSync2(body));
546
- return { objectKey, sha256: createHash3("sha256").update(body).digest("hex"), files: manifest.files.length };
547
- }
548
- if (request.op !== "upload" || !Array.isArray(request.refs)) throw Error("TRAVEL_OSS_RETURN_INVALID_REQUEST");
549
- for (const ref of request.refs) validateChunkRef(ref);
550
- await prepareOssRequests(config, request.refs.map((ref) => ({ method: "PUT", key: request.prefix + "/chunks/" + ref.sha256 + ".gz", contentMD5: md5Base64(store.readGzipRaw(ref.sha256)), contentType: "application/octet-stream" })));
551
- let done = 0, bytes = 0;
552
- await pool(request.refs, async (ref) => {
553
- await store.read(ref.sha256, ref.bytes);
554
- await ossPutObject(config, request.prefix + "/chunks/" + ref.sha256 + ".gz", store.readGzipRaw(ref.sha256));
555
- done++;
556
- bytes += ref.bytes;
557
- if (done % 50 === 0 || done === request.refs.length) progress?.({ done, total: request.refs.length, bytes });
558
601
  });
559
- return { uploaded: done, bytes };
602
+ child.stdin.write(JSON.stringify({ module: source, root: options.root, config: options.config }) + "\n");
603
+ const deadline = setTimeout(() => {
604
+ child.kill();
605
+ fail();
606
+ }, 30 * 6e4);
607
+ child.once("close", () => clearTimeout(deadline));
608
+ return { ready, receive: async (bundles) => {
609
+ await ready;
610
+ if (closed) throw Error("TRAVEL_OSS_BUNDLE_CONNECTION_CLOSED");
611
+ const id = ++sequence;
612
+ return new Promise((resolve2, reject) => {
613
+ pending.set(id, { resolve: resolve2, reject });
614
+ child.stdin.write(JSON.stringify({ id, bundles }) + "\n", (error) => {
615
+ if (error) {
616
+ pending.delete(id);
617
+ reject(error);
618
+ }
619
+ });
620
+ });
621
+ }, close: async () => {
622
+ if (!closed) {
623
+ child.stdin.end();
624
+ await Promise.race([new Promise((r) => child.once("close", () => r())), new Promise((r) => setTimeout(() => {
625
+ child.kill();
626
+ r();
627
+ }, 5e3))]);
628
+ }
629
+ clearTimeout(deadline);
630
+ } };
560
631
  }
561
632
  export {
562
- runOssReturn
633
+ makeBundleReceiver,
634
+ openBundleStream,
635
+ runOssBundleStream
563
636
  };