@lobehub/cli 0.0.92 → 0.0.94

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/dist/index.js CHANGED
@@ -15,7 +15,7 @@ import { Buffer as Buffer$1 } from "node:buffer";
15
15
  import * as net$1 from "node:net";
16
16
  import net, { BlockList, connect, createServer, isIP } from "node:net";
17
17
  import { scheduler, setImmediate as setImmediate$1, setTimeout as setTimeout$1 } from "node:timers/promises";
18
- import process$1, { cwd, execArgv, execPath, hrtime, platform as platform$1 } from "node:process";
18
+ import _w, { cwd, execArgv, execPath, hrtime, platform as platform$1 } from "node:process";
19
19
  import { URL as URL$1, fileURLToPath, pathToFileURL } from "node:url";
20
20
  import { finished, pipeline } from "node:stream/promises";
21
21
  import { Duplex, PassThrough, Readable, Transform, Writable, getDefaultHighWaterMark, pipeline as pipeline$1 } from "node:stream";
@@ -8956,6 +8956,10 @@ var init_manifest = __esmMin((() => {
8956
8956
  ToolManifestSchema = object$1({
8957
8957
  $schema: string().optional(),
8958
8958
  api: array(LobeChatPluginApiSchema),
8959
+ connectorLinks: object$1({
8960
+ connectorId: string(),
8961
+ param: string()
8962
+ }).optional(),
8959
8963
  author: string().optional(),
8960
8964
  createdAt: string().optional(),
8961
8965
  gateway: string().optional(),
@@ -12052,6 +12056,42 @@ var init_acceptanceReviewRound = __esmMin((() => {
12052
12056
  });
12053
12057
  }));
12054
12058
 
12059
+ //#endregion
12060
+ //#region ../../packages/types/src/connector.ts
12061
+ var init_connector = __esmMin((() => {}));
12062
+
12063
+ //#endregion
12064
+ //#region ../../packages/types/src/inboundWebhook.ts
12065
+ var McpEventsWebhookConfigSchema, McpEventsWebhookStateSchema, InboundWebhookVerificationSchema, InboundWebhookDataSchema;
12066
+ var init_inboundWebhook = __esmMin((() => {
12067
+ init_zod$1();
12068
+ McpEventsWebhookConfigSchema = object$1({
12069
+ arguments: record(string(), unknown()),
12070
+ eventName: string().min(1)
12071
+ }).strict();
12072
+ McpEventsWebhookStateSchema = object$1({
12073
+ cursor: string().nullable().optional(),
12074
+ deliveryStatus: object$1({
12075
+ active: boolean().optional(),
12076
+ failedSince: string().optional(),
12077
+ lastDeliveryAt: string().optional(),
12078
+ lastError: string().nullable().optional(),
12079
+ retryAfterMs: number$1().nonnegative().optional(),
12080
+ throttled: boolean().optional()
12081
+ }).optional(),
12082
+ refreshBefore: datetime({ offset: true }).nullable().optional(),
12083
+ remoteSubscriptionId: string().optional(),
12084
+ truncated: boolean().optional()
12085
+ }).strict();
12086
+ InboundWebhookVerificationSchema = object$1({ scheme: literal("standard_webhooks") }).strict();
12087
+ InboundWebhookDataSchema = discriminatedUnion("kind", [object$1({
12088
+ kind: literal("mcp_events"),
12089
+ config: McpEventsWebhookConfigSchema,
12090
+ state: McpEventsWebhookStateSchema,
12091
+ verification: InboundWebhookVerificationSchema
12092
+ })]);
12093
+ }));
12094
+
12055
12095
  //#endregion
12056
12096
  //#region ../../packages/types/src/oauthApp.ts
12057
12097
  var init_oauthApp = __esmMin((() => {}));
@@ -12190,6 +12230,8 @@ var init_src$2 = __esmMin((() => {
12190
12230
  init_acceptanceReview();
12191
12231
  init_acceptanceReviewRound();
12192
12232
  init_agentRuntime();
12233
+ init_connector();
12234
+ init_inboundWebhook();
12193
12235
  init_oauthApp();
12194
12236
  init_chat();
12195
12237
  init_plugin();
@@ -16853,6 +16895,7 @@ const MAX_MISSED_HEARTBEATS$1 = 3;
16853
16895
  */
16854
16896
  const CONNECT_TIMEOUT = 15e3;
16855
16897
  const METRICS_ACK_TIMEOUT_MS = 15e3;
16898
+ const COMPLETION_ACK_TIMEOUT_MS = 3e4;
16856
16899
  /**
16857
16900
  * Close reason the gateway sends when a newer socket with the same
16858
16901
  * `connectionId` takes over. `connectionId` is persisted per install, so this
@@ -16860,6 +16903,7 @@ const METRICS_ACK_TIMEOUT_MS = 15e3;
16860
16903
  * home) shows up.
16861
16904
  */
16862
16905
  const REPLACED_CLOSE_REASON = "Replaced by new connection";
16906
+ const completionAckKey = (operationId, toolCallId) => `${operationId}:${toolCallId}`;
16863
16907
  const noopLogger$1 = {
16864
16908
  debug: () => {},
16865
16909
  error: () => {},
@@ -16876,6 +16920,7 @@ var GatewayClient = class extends EventEmitter {
16876
16920
  missedHeartbeats = 0;
16877
16921
  status = "disconnected";
16878
16922
  pendingMetricAcks = /* @__PURE__ */ new Map();
16923
+ pendingCompletionAcks = /* @__PURE__ */ new Map();
16879
16924
  intentionalDisconnect = false;
16880
16925
  /**
16881
16926
  * When each socket abandoned mid-handshake was abandoned. Only such a socket
@@ -17010,6 +17055,37 @@ var GatewayClient = class extends EventEmitter {
17010
17055
  });
17011
17056
  });
17012
17057
  }
17058
+ /**
17059
+ * Send the late result of a call the device kept watching, and resolve with
17060
+ * the gateway's verdict. Rejects when not connected, when the connection drops
17061
+ * mid-flight, or when no ack arrives in time — the caller keeps the result and
17062
+ * sends it again, which is safe because the server applies it at most once.
17063
+ */
17064
+ reportToolCallCompletion(completion) {
17065
+ if (this.status !== "connected" || this.ws?.readyState !== wrapper_default.OPEN) return Promise.reject(/* @__PURE__ */ new Error("Gateway not connected"));
17066
+ const key = completionAckKey(completion.operationId, completion.toolCallId);
17067
+ this.pendingCompletionAcks.get(key)?.reject(/* @__PURE__ */ new Error("Superseded by a newer send"));
17068
+ return new Promise((resolve, reject) => {
17069
+ const timer = setTimeout(() => {
17070
+ this.pendingCompletionAcks.delete(key);
17071
+ reject(/* @__PURE__ */ new Error("Timed out waiting for tool_call_completion_ack"));
17072
+ }, COMPLETION_ACK_TIMEOUT_MS);
17073
+ this.pendingCompletionAcks.set(key, {
17074
+ reject: (error) => {
17075
+ clearTimeout(timer);
17076
+ reject(error);
17077
+ },
17078
+ resolve: (ack) => {
17079
+ clearTimeout(timer);
17080
+ resolve(ack);
17081
+ }
17082
+ });
17083
+ this.sendMessage({
17084
+ ...completion,
17085
+ type: "tool_call_completion"
17086
+ });
17087
+ });
17088
+ }
17013
17089
  sendSystemInfoResponse(response) {
17014
17090
  this.sendMessage({
17015
17091
  ...response,
@@ -17134,6 +17210,14 @@ var GatewayClient = class extends EventEmitter {
17134
17210
  this.logger.warn("Received auth_expired from gateway");
17135
17211
  this.emit("auth_expired");
17136
17212
  break;
17213
+ case "tool_call_completion_ack": {
17214
+ const { type: _type, ...ack } = message;
17215
+ const key = completionAckKey(ack.operationId, ack.toolCallId);
17216
+ const pending = this.pendingCompletionAcks.get(key);
17217
+ this.pendingCompletionAcks.delete(key);
17218
+ pending?.resolve(ack);
17219
+ break;
17220
+ }
17137
17221
  case "device_metrics_ack": {
17138
17222
  const pending = this.pendingMetricAcks.get(message.batchId);
17139
17223
  this.pendingMetricAcks.delete(message.batchId);
@@ -17272,6 +17356,8 @@ var GatewayClient = class extends EventEmitter {
17272
17356
  rejectPendingMetricAcks() {
17273
17357
  for (const pending of this.pendingMetricAcks.values()) pending.reject(/* @__PURE__ */ new Error("Gateway connection closed"));
17274
17358
  this.pendingMetricAcks.clear();
17359
+ for (const pending of this.pendingCompletionAcks.values()) pending.reject(/* @__PURE__ */ new Error("Gateway connection closed"));
17360
+ this.pendingCompletionAcks.clear();
17275
17361
  }
17276
17362
  closeWebSocket() {
17277
17363
  this.tunnelHost?.closeAll("DEVICE_DISCONNECTED");
@@ -17308,6 +17394,102 @@ var GatewayClient = class extends EventEmitter {
17308
17394
  }
17309
17395
  };
17310
17396
 
17397
+ //#endregion
17398
+ //#region ../../packages/device-gateway-client/src/completionWatch.ts
17399
+ const LOCAL_SYSTEM_IDENTIFIER = "lobe-local-system";
17400
+ /** Longest a device keeps a finished result it could not deliver. */
17401
+ const DEFAULT_COMPLETION_MAX_AGE_MS = 7200 * 1e3;
17402
+ const INITIAL_RETRY_DELAY_MS = 5e3;
17403
+ const MAX_RETRY_DELAY_MS = 6e4;
17404
+ /**
17405
+ * The shell a `runCommand` reply left running, when the server asked for a
17406
+ * late result. Mirrors the server's park predicate: a background spawn or a
17407
+ * foreground call that outlived its wait window, never a command that already
17408
+ * has an exit code or failed to start.
17409
+ */
17410
+ const resolveWatchableShell = (request, result) => {
17411
+ if (!request.completion?.toolCallId || !request.operationId) return void 0;
17412
+ if (request.toolCall.type === "mcp") return void 0;
17413
+ if (request.toolCall.identifier !== LOCAL_SYSTEM_IDENTIFIER) return void 0;
17414
+ if (request.toolCall.apiName !== "runCommand") return void 0;
17415
+ if (result.success === false) return void 0;
17416
+ const state = result.state;
17417
+ if (!state || typeof state !== "object") return void 0;
17418
+ if (typeof state.commandId !== "string" || !state.commandId) return void 0;
17419
+ if (state.error) return void 0;
17420
+ if (state.exitCode !== void 0 && state.exitCode !== null) return void 0;
17421
+ if (state.isBackground === true || state.running === true) return state.commandId;
17422
+ };
17423
+ /** Mark a reply so the server knows a late result will follow and may park. */
17424
+ const withCompletionWatch = (result) => ({
17425
+ ...result,
17426
+ state: {
17427
+ ...result.state,
17428
+ completionWatch: true
17429
+ }
17430
+ });
17431
+ const defaultSleep = (ms, wake) => Promise.race([new Promise((resolve) => setTimeout(resolve, ms)), wake]);
17432
+ /**
17433
+ * Watch a command the device left running and deliver its final result.
17434
+ *
17435
+ * Observation is local (the device waits on its own process), so the wait costs
17436
+ * the server nothing. Delivery retries with backoff — sooner when the gateway
17437
+ * reconnects — until the gateway answers `delivered` or `rejected`, or the
17438
+ * result is older than `maxAgeMs` (the server has timed the call out by then).
17439
+ */
17440
+ const watchToolCallCompletion = async ({ getReporter, logger, maxAgeMs = DEFAULT_COMPLETION_MAX_AGE_MS, observe, operationId, sleep = defaultSleep, toolCallId }) => {
17441
+ const startedAt = Date.now();
17442
+ let result;
17443
+ for (;;) {
17444
+ let observed;
17445
+ try {
17446
+ observed = await observe();
17447
+ } catch (error) {
17448
+ const message = error instanceof Error ? error.message : String(error);
17449
+ observed = {
17450
+ done: true,
17451
+ result: {
17452
+ content: `Failed to observe the command: ${message}`,
17453
+ error: message,
17454
+ success: false
17455
+ }
17456
+ };
17457
+ }
17458
+ if (observed.done) {
17459
+ result = observed.result;
17460
+ break;
17461
+ }
17462
+ if (Date.now() - startedAt > maxAgeMs) return "expired";
17463
+ }
17464
+ let delay = INITIAL_RETRY_DELAY_MS;
17465
+ for (;;) {
17466
+ const reporter = getReporter();
17467
+ if (reporter) try {
17468
+ const ack = await reporter.reportToolCallCompletion({
17469
+ operationId,
17470
+ result,
17471
+ toolCallId
17472
+ });
17473
+ if (ack.status !== "retry") {
17474
+ logger?.info(`Completion for ${toolCallId} ${ack.status}`, ack.reason ?? "");
17475
+ return ack.status;
17476
+ }
17477
+ logger?.warn(`Completion for ${toolCallId} not taken yet`, ack.reason ?? "");
17478
+ } catch (error) {
17479
+ logger?.warn(`Completion for ${toolCallId} not sent`, error instanceof Error ? error.message : String(error));
17480
+ }
17481
+ if (Date.now() - startedAt > maxAgeMs) return "expired";
17482
+ let onConnected;
17483
+ const wake = new Promise((resolve) => {
17484
+ onConnected = resolve;
17485
+ reporter?.on("connected", resolve);
17486
+ });
17487
+ await sleep(delay, wake);
17488
+ if (onConnected) reporter?.off("connected", onConnected);
17489
+ delay = Math.min(delay * 2, MAX_RETRY_DELAY_MS);
17490
+ }
17491
+ };
17492
+
17311
17493
  //#endregion
17312
17494
  //#region ../../packages/const/src/agentDocument.ts
17313
17495
  const MARKDOWN_MIME_TYPES = ["text/markdown", "text/x-markdown"];
@@ -21614,7 +21796,7 @@ var require_command = /* @__PURE__ */ __commonJSMin$2(((exports) => {
21614
21796
  const childProcess$2 = __require("node:child_process");
21615
21797
  const path$16 = __require("node:path");
21616
21798
  const fs$17 = __require("node:fs");
21617
- const process$3 = __require("node:process");
21799
+ const process$2 = __require("node:process");
21618
21800
  const { Argument, humanReadableArgName } = require_argument();
21619
21801
  const { CommanderError } = require_error$1();
21620
21802
  const { Help, stripColor } = require_help();
@@ -21666,13 +21848,13 @@ var require_command = /* @__PURE__ */ __commonJSMin$2(((exports) => {
21666
21848
  this._showSuggestionAfterError = true;
21667
21849
  this._savedState = null;
21668
21850
  this._outputConfiguration = {
21669
- writeOut: (str) => process$3.stdout.write(str),
21670
- writeErr: (str) => process$3.stderr.write(str),
21851
+ writeOut: (str) => process$2.stdout.write(str),
21852
+ writeErr: (str) => process$2.stderr.write(str),
21671
21853
  outputError: (str, write) => write(str),
21672
- getOutHelpWidth: () => process$3.stdout.isTTY ? process$3.stdout.columns : void 0,
21673
- getErrHelpWidth: () => process$3.stderr.isTTY ? process$3.stderr.columns : void 0,
21674
- getOutHasColors: () => useColor() ?? (process$3.stdout.isTTY && process$3.stdout.hasColors?.()),
21675
- getErrHasColors: () => useColor() ?? (process$3.stderr.isTTY && process$3.stderr.hasColors?.()),
21854
+ getOutHelpWidth: () => process$2.stdout.isTTY ? process$2.stdout.columns : void 0,
21855
+ getErrHelpWidth: () => process$2.stderr.isTTY ? process$2.stderr.columns : void 0,
21856
+ getOutHasColors: () => useColor() ?? (process$2.stdout.isTTY && process$2.stdout.hasColors?.()),
21857
+ getErrHasColors: () => useColor() ?? (process$2.stderr.isTTY && process$2.stderr.hasColors?.()),
21676
21858
  stripColor: (str) => stripColor(str)
21677
21859
  };
21678
21860
  this._hidden = false;
@@ -22030,7 +22212,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
22030
22212
  */
22031
22213
  _exit(exitCode, code, message) {
22032
22214
  if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
22033
- process$3.exit(exitCode);
22215
+ process$2.exit(exitCode);
22034
22216
  }
22035
22217
  /**
22036
22218
  * Register callback `fn` for the command.
@@ -22369,11 +22551,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
22369
22551
  if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
22370
22552
  parseOptions = parseOptions || {};
22371
22553
  if (argv === void 0 && parseOptions.from === void 0) {
22372
- if (process$3.versions?.electron) parseOptions.from = "electron";
22373
- const execArgv = process$3.execArgv ?? [];
22554
+ if (process$2.versions?.electron) parseOptions.from = "electron";
22555
+ const execArgv = process$2.execArgv ?? [];
22374
22556
  if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
22375
22557
  }
22376
- if (argv === void 0) argv = process$3.argv;
22558
+ if (argv === void 0) argv = process$2.argv;
22377
22559
  this.rawArgs = argv.slice();
22378
22560
  let userArgs;
22379
22561
  switch (parseOptions.from) {
@@ -22383,7 +22565,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
22383
22565
  userArgs = argv.slice(2);
22384
22566
  break;
22385
22567
  case "electron":
22386
- if (process$3.defaultApp) {
22568
+ if (process$2.defaultApp) {
22387
22569
  this._scriptPath = argv[1];
22388
22570
  userArgs = argv.slice(2);
22389
22571
  } else userArgs = argv.slice(1);
@@ -22548,16 +22730,16 @@ Expecting one of '${allowedValues.join("', '")}'`);
22548
22730
  }
22549
22731
  launchWithNode = sourceExt.includes(path$16.extname(executableFile));
22550
22732
  let proc;
22551
- if (process$3.platform !== "win32") if (launchWithNode) {
22733
+ if (process$2.platform !== "win32") if (launchWithNode) {
22552
22734
  args.unshift(executableFile);
22553
- args = incrementNodeInspectorPort(process$3.execArgv).concat(args);
22554
- proc = childProcess$2.spawn(process$3.argv[0], args, { stdio: "inherit" });
22735
+ args = incrementNodeInspectorPort(process$2.execArgv).concat(args);
22736
+ proc = childProcess$2.spawn(process$2.argv[0], args, { stdio: "inherit" });
22555
22737
  } else proc = childProcess$2.spawn(executableFile, args, { stdio: "inherit" });
22556
22738
  else {
22557
22739
  this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
22558
22740
  args.unshift(executableFile);
22559
- args = incrementNodeInspectorPort(process$3.execArgv).concat(args);
22560
- proc = childProcess$2.spawn(process$3.execPath, args, { stdio: "inherit" });
22741
+ args = incrementNodeInspectorPort(process$2.execArgv).concat(args);
22742
+ proc = childProcess$2.spawn(process$2.execPath, args, { stdio: "inherit" });
22561
22743
  }
22562
22744
  if (!proc.killed) [
22563
22745
  "SIGUSR1",
@@ -22566,20 +22748,20 @@ Expecting one of '${allowedValues.join("', '")}'`);
22566
22748
  "SIGINT",
22567
22749
  "SIGHUP"
22568
22750
  ].forEach((signal) => {
22569
- process$3.on(signal, () => {
22751
+ process$2.on(signal, () => {
22570
22752
  if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
22571
22753
  });
22572
22754
  });
22573
22755
  const exitCallback = this._exitCallback;
22574
22756
  proc.on("close", (code) => {
22575
22757
  code = code ?? 1;
22576
- if (!exitCallback) process$3.exit(code);
22758
+ if (!exitCallback) process$2.exit(code);
22577
22759
  else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
22578
22760
  });
22579
22761
  proc.on("error", (err) => {
22580
22762
  if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
22581
22763
  else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
22582
- if (!exitCallback) process$3.exit(1);
22764
+ if (!exitCallback) process$2.exit(1);
22583
22765
  else {
22584
22766
  const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
22585
22767
  wrappedError.nestedError = err;
@@ -22988,13 +23170,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
22988
23170
  */
22989
23171
  _parseOptionsEnv() {
22990
23172
  this.options.forEach((option) => {
22991
- if (option.envVar && option.envVar in process$3.env) {
23173
+ if (option.envVar && option.envVar in process$2.env) {
22992
23174
  const optionKey = option.attributeName();
22993
23175
  if (this.getOptionValue(optionKey) === void 0 || [
22994
23176
  "default",
22995
23177
  "config",
22996
23178
  "env"
22997
- ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$3.env[option.envVar]);
23179
+ ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$2.env[option.envVar]);
22998
23180
  else this.emit(`optionEnv:${option.name()}`);
22999
23181
  }
23000
23182
  });
@@ -23411,7 +23593,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
23411
23593
  */
23412
23594
  help(contextOptions) {
23413
23595
  this.outputHelp(contextOptions);
23414
- let exitCode = Number(process$3.exitCode ?? 0);
23596
+ let exitCode = Number(process$2.exitCode ?? 0);
23415
23597
  if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
23416
23598
  this._exit(exitCode, "commander.help", "(outputHelp)");
23417
23599
  }
@@ -23501,8 +23683,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
23501
23683
  * @package
23502
23684
  */
23503
23685
  function useColor() {
23504
- if (process$3.env.NO_COLOR || process$3.env.FORCE_COLOR === "0" || process$3.env.FORCE_COLOR === "false") return false;
23505
- if (process$3.env.FORCE_COLOR || process$3.env.CLICOLOR_FORCE !== void 0) return true;
23686
+ if (process$2.env.NO_COLOR || process$2.env.FORCE_COLOR === "0" || process$2.env.FORCE_COLOR === "false") return false;
23687
+ if (process$2.env.FORCE_COLOR || process$2.env.CLICOLOR_FORCE !== void 0) return true;
23506
23688
  }
23507
23689
  exports.Command = Command;
23508
23690
  exports.useColor = useColor;
@@ -88758,6 +88940,25 @@ const SYSTEM_FILES_TO_IGNORE = [
88758
88940
  ".Trashes"
88759
88941
  ];
88760
88942
 
88943
+ //#endregion
88944
+ //#region ../../packages/file-loaders/src/fileParseBudget.ts
88945
+ var FileParseBudgetError, isFileParseBudgetError;
88946
+ var init_fileParseBudget = __esmMin((() => {
88947
+ FileParseBudgetError = class extends Error {
88948
+ actual;
88949
+ limit;
88950
+ reason;
88951
+ constructor(reason, limit, actual) {
88952
+ super(`File exceeds the parse budget (${reason}): ${actual} > ${limit}`);
88953
+ this.name = "FileParseBudgetError";
88954
+ this.reason = reason;
88955
+ this.limit = limit;
88956
+ this.actual = actual;
88957
+ }
88958
+ };
88959
+ isFileParseBudgetError = (error) => error instanceof FileParseBudgetError || error instanceof Error && error.name === "FileParseBudgetError";
88960
+ }));
88961
+
88761
88962
  //#endregion
88762
88963
  //#region ../../packages/utils/src/detectUtf16.ts
88763
88964
  var HEURISTIC_SAMPLE_BYTES, HEURISTIC_THRESHOLD, detectUtf16NoBom;
@@ -88782,10 +88983,284 @@ var init_detectUtf16 = __esmMin((() => {
88782
88983
  };
88783
88984
  }));
88784
88985
 
88986
+ //#endregion
88987
+ //#region ../../packages/utils/src/isBinaryContent.ts
88988
+ var NON_PRINTABLE_THRESHOLD, hasUtf8Bom, hasUtf16Bom, sniffBinaryBuffer, REPLACEMENT_CHAR, checkPrintableRatio;
88989
+ var init_isBinaryContent = __esmMin((() => {
88990
+ init_detectUtf16();
88991
+ NON_PRINTABLE_THRESHOLD = .3;
88992
+ hasUtf8Bom = (buf) => buf.length >= 3 && buf[0] === 239 && buf[1] === 187 && buf[2] === 191;
88993
+ hasUtf16Bom = (buf) => buf.length >= 2 && (buf[0] === 255 && buf[1] === 254 || buf[0] === 254 && buf[1] === 255);
88994
+ sniffBinaryBuffer = (buffer) => {
88995
+ if (buffer.length === 0) return { isBinary: false };
88996
+ if (hasUtf8Bom(buffer) || hasUtf16Bom(buffer)) return { isBinary: false };
88997
+ const utf16Variant = detectUtf16NoBom(buffer);
88998
+ if (utf16Variant) return checkPrintableRatio(new TextDecoder(utf16Variant, { fatal: false }).decode(buffer), buffer.length);
88999
+ if (buffer.includes(0)) return {
89000
+ isBinary: true,
89001
+ reason: "contains null byte"
89002
+ };
89003
+ return checkPrintableRatio(new TextDecoder("utf-8", { fatal: false }).decode(buffer), buffer.length);
89004
+ };
89005
+ REPLACEMENT_CHAR = "�";
89006
+ checkPrintableRatio = (text, sampledBytes) => {
89007
+ if (text.length === 0) return { isBinary: false };
89008
+ let suspect = 0;
89009
+ for (const ch of text) {
89010
+ if (ch === REPLACEMENT_CHAR) {
89011
+ suspect++;
89012
+ continue;
89013
+ }
89014
+ const code = ch.codePointAt(0);
89015
+ if (code < 32 && code !== 9 && code !== 10 && code !== 13) suspect++;
89016
+ }
89017
+ const ratio = suspect / text.length;
89018
+ if (ratio > NON_PRINTABLE_THRESHOLD) return {
89019
+ isBinary: true,
89020
+ reason: `${(ratio * 100).toFixed(1)}% non-printable chars in first ${sampledBytes} bytes`
89021
+ };
89022
+ return { isBinary: false };
89023
+ };
89024
+ }));
89025
+
89026
+ //#endregion
89027
+ //#region ../../packages/file-loaders/src/loaders/ipynb/index.ts
89028
+ var ipynb_exports = /* @__PURE__ */ __exportAll$2({
89029
+ IpynbLoader: () => IpynbLoader,
89030
+ convertIpynbToMarkdown: () => convertIpynbToMarkdown,
89031
+ scrubIpynbFallbackText: () => scrubIpynbFallbackText
89032
+ });
89033
+ var import_src$5, log$11, SCRIPT_TAG_RE, ANSI_RE, MIME_TOKEN, DATA_URI_RE, BASE64_RUN_RE, BASE64_SEPARATOR_RE, NON_BASE64_RE, BASE64_SCRUB_THRESHOLD, joinSource, cleanStreamText, STYLE_BOUNDARY, stripStyleTags, humanSize, humanChars, base64Bytes, scrubDataUris, base64Placeholder, scrubIpynbFallbackText, singleLine, fence, convertOutput, isNotebookCell, convertCell, convertIpynbToBlocks, convertIpynbToMarkdown, BinaryNotebookError, IpynbLoader;
89034
+ var init_ipynb = __esmMin((() => {
89035
+ init_isBinaryContent();
89036
+ import_src$5 = /* @__PURE__ */ __toESM$2(require_src());
89037
+ log$11 = (0, import_src$5.default)("file-loaders:ipynb");
89038
+ SCRIPT_TAG_RE = /<script[\t\n\f\r />]/i;
89039
+ ANSI_RE = /\u001B\[[\d:;?]*[\u0020-\u002F]*[\u0040-\u007E]|\u001B\][^\u0007\u001B\u009C]{0,256}(?:\u0007|\u001B\\)?|\u001B[\u0021-\u002F]{0,2}[\u0030-\u007E]|[\u001B\u0007\u009C]/g;
89040
+ MIME_TOKEN = "[^\\s()<>@,;:\\\\\"/\\[\\]?=]+";
89041
+ DATA_URI_RE = new RegExp(`data:(${MIME_TOKEN}/${MIME_TOKEN})?(?:;${MIME_TOKEN}=${MIME_TOKEN})*;base64,([\\d+/=A-Za-z]{256,})`, "gi");
89042
+ BASE64_RUN_RE = /[\d+/=A-Za-z]{32,}(?:(?:"[\s,]*"|\\n|\r?\n)+[\d+/=A-Za-z]{32,})*/g;
89043
+ BASE64_SEPARATOR_RE = /((?:"[\s,]*"|\\n|\r?\n)+)/;
89044
+ NON_BASE64_RE = /[^\d+/=A-Z]/gi;
89045
+ BASE64_SCRUB_THRESHOLD = 1024;
89046
+ joinSource = (source) => Array.isArray(source) ? source.filter((part) => typeof part === "string").join("") : typeof source === "string" ? source : "";
89047
+ cleanStreamText = (text) => text.replaceAll(ANSI_RE, "").replaceAll("\r\n", "\n").split("\n").map((line) => {
89048
+ return line.split("\r").filter((frame) => frame !== "").at(-1) ?? "";
89049
+ }).join("\n");
89050
+ STYLE_BOUNDARY = new Set([
89051
+ 9,
89052
+ 10,
89053
+ 12,
89054
+ 13,
89055
+ 32,
89056
+ 47,
89057
+ 62
89058
+ ]);
89059
+ stripStyleTags = (html) => {
89060
+ const openRe = /<style/gi;
89061
+ const closeRe = /<\/style[\t\n\f\r ]*>/gi;
89062
+ let result = "";
89063
+ let pos = 0;
89064
+ while (pos < html.length) {
89065
+ openRe.lastIndex = pos;
89066
+ const open = openRe.exec(html);
89067
+ if (open === null) {
89068
+ result += html.slice(pos);
89069
+ break;
89070
+ }
89071
+ if (!STYLE_BOUNDARY.has(html.charCodeAt(open.index + 6))) {
89072
+ result += html.slice(pos, open.index + 6);
89073
+ pos = open.index + 6;
89074
+ continue;
89075
+ }
89076
+ result += html.slice(pos, open.index);
89077
+ closeRe.lastIndex = open.index;
89078
+ const close = closeRe.exec(html);
89079
+ if (close === null) break;
89080
+ pos = close.index + close[0].length;
89081
+ }
89082
+ return result;
89083
+ };
89084
+ humanSize = (bytes) => bytes >= 1024 ? `${Math.round(bytes / 1024)} KB` : `${bytes} B`;
89085
+ humanChars = (chars) => chars >= 1024 ? `${Math.round(chars / 1024)}k chars` : `${chars} chars`;
89086
+ base64Bytes = (payload) => {
89087
+ const clean = payload.replaceAll(NON_BASE64_RE, "");
89088
+ const padding = Math.min(2, (clean.match(/=*$/) ?? [""])[0].length);
89089
+ return Math.floor(clean.length * 3 / 4) - padding;
89090
+ };
89091
+ scrubDataUris = (text) => text.replaceAll(DATA_URI_RE, (_match, mime, payload) => `data:${mime ?? "unknown"};base64,[${humanSize(base64Bytes(payload))} omitted]`);
89092
+ base64Placeholder = (payload) => `[base64 payload — ${humanSize(base64Bytes(payload))}, omitted]`;
89093
+ scrubIpynbFallbackText = (raw) => raw.replaceAll(BASE64_RUN_RE, (match) => {
89094
+ const parts = match.split(BASE64_SEPARATOR_RE);
89095
+ if (parts.length > 1) {
89096
+ const segments = parts.filter((_, index) => index % 2 === 0);
89097
+ const payload = segments.join("");
89098
+ if (segments.slice(0, -1).every((segment) => segment.length === 76) && payload.length >= BASE64_SCRUB_THRESHOLD) return base64Placeholder(payload);
89099
+ return parts.map((part, index) => index % 2 === 0 && part.length >= BASE64_SCRUB_THRESHOLD ? base64Placeholder(part) : part).join("");
89100
+ }
89101
+ if (match.length < BASE64_SCRUB_THRESHOLD) return match;
89102
+ return base64Placeholder(match);
89103
+ });
89104
+ singleLine = (text) => text.replaceAll(/[`\r\n]+/g, " ").trim();
89105
+ fence = (body, language = "") => {
89106
+ let longest = 0;
89107
+ for (const run of body.match(/`{3,}/g) ?? []) if (run.length > longest) longest = run.length;
89108
+ const ticks = "`".repeat(longest > 0 ? longest + 1 : 3);
89109
+ return [
89110
+ ticks + language,
89111
+ body,
89112
+ ticks
89113
+ ].join("\n");
89114
+ };
89115
+ convertOutput = (output) => {
89116
+ switch (output.output_type) {
89117
+ case "stream": {
89118
+ const body = cleanStreamText(joinSource(output.text));
89119
+ return body.trim() ? fence(body) : "";
89120
+ }
89121
+ case "error": {
89122
+ const traceback = cleanStreamText((Array.isArray(output.traceback) ? output.traceback : []).filter((line) => typeof line === "string").join("\n"));
89123
+ return [`**Error:** \`${output.ename ?? ""}: ${output.evalue ?? ""}\``, fence(traceback)].join("\n");
89124
+ }
89125
+ case "display_data":
89126
+ case "execute_result": {
89127
+ const data = output.data ?? {};
89128
+ if ("application/vnd.jupyter.widget-view+json" in data) return "`[interactive widget — omitted]`";
89129
+ const html = data["text/html"];
89130
+ if (html !== void 0) {
89131
+ const htmlText = joinSource(html);
89132
+ if (SCRIPT_TAG_RE.test(htmlText)) return `\`[interactive HTML output (script) — ${humanChars(htmlText.length)}, omitted]\``;
89133
+ return scrubDataUris(stripStyleTags(htmlText)).trim();
89134
+ }
89135
+ const svg = data["image/svg+xml"];
89136
+ if (svg !== void 0) {
89137
+ const svgText = joinSource(svg);
89138
+ if (SCRIPT_TAG_RE.test(svgText)) return `\`[svg output (script) — ${humanChars(svgText.length)}, omitted]\``;
89139
+ return scrubDataUris(svgText).trim();
89140
+ }
89141
+ for (const mime of Object.keys(data)) if (mime.startsWith("image/")) return `![${mime} output — ${humanSize(base64Bytes(joinSource(data[mime])))}, omitted]`;
89142
+ const markdown = data["text/markdown"];
89143
+ if (markdown !== void 0) return scrubDataUris(joinSource(markdown));
89144
+ for (const mime of Object.keys(data)) if (mime.startsWith("text/")) {
89145
+ const body = joinSource(data[mime]);
89146
+ return body.trim() ? fence(body) : "";
89147
+ }
89148
+ return `\`[${Object.keys(data).join(", ") || "unknown"} output — omitted]\``;
89149
+ }
89150
+ default: return "";
89151
+ }
89152
+ };
89153
+ isNotebookCell = (cell) => {
89154
+ if (!cell || typeof cell !== "object") return false;
89155
+ const { cell_type: cellType, source } = cell;
89156
+ if (typeof cellType !== "string") return false;
89157
+ return source === void 0 || typeof source === "string" || Array.isArray(source) && source.every((part) => typeof part === "string");
89158
+ };
89159
+ convertCell = (cell, language) => {
89160
+ const source = joinSource(cell.source);
89161
+ switch (cell.cell_type) {
89162
+ case "markdown": return scrubDataUris(source);
89163
+ case "raw": return fence(scrubDataUris(source));
89164
+ case "code": {
89165
+ const blocks = [`${`**In [${cell.execution_count ?? " "}]:**`}\n${fence(source, language)}`];
89166
+ const outputs = (cell.outputs ?? []).map(convertOutput).filter(Boolean);
89167
+ if (outputs.length > 0) blocks.push(`**Output:**\n${outputs.join("\n\n")}`);
89168
+ return blocks.join("\n\n");
89169
+ }
89170
+ default: return source.trim() ? fence(scrubDataUris(source)) : void 0;
89171
+ }
89172
+ };
89173
+ convertIpynbToBlocks = (raw) => {
89174
+ let notebook;
89175
+ try {
89176
+ notebook = JSON.parse(raw.replace(/^\uFEFF/, ""));
89177
+ } catch {
89178
+ return null;
89179
+ }
89180
+ if (!notebook || typeof notebook !== "object" || !Array.isArray(notebook.cells)) return null;
89181
+ if (!Number.isInteger(notebook.nbformat) || notebook.nbformat < 4) return null;
89182
+ if (!notebook.cells.every(isNotebookCell)) return null;
89183
+ try {
89184
+ const languageInfo = notebook.metadata?.language_info;
89185
+ const languageName = typeof languageInfo?.name === "string" ? languageInfo.name : void 0;
89186
+ const language = languageName?.match(/^[\w#+.-]+/)?.[0] ?? "python";
89187
+ const kernel = notebook.metadata?.kernelspec?.display_name ?? notebook.metadata?.kernelspec?.name;
89188
+ const headerBits = ["Jupyter notebook"];
89189
+ if (typeof kernel === "string" && kernel) headerBits.push(`kernel: ${singleLine(kernel)}`);
89190
+ if (languageName) headerBits.push(`language: ${singleLine(languageName)}${typeof languageInfo?.version === "string" && languageInfo.version ? ` ${singleLine(languageInfo.version)}` : ""}`);
89191
+ const blocks = [`> ${headerBits.join(" · ")}`];
89192
+ for (const cell of notebook.cells) {
89193
+ const block = convertCell(cell, language);
89194
+ if (block !== void 0 && block.trim()) blocks.push(block);
89195
+ }
89196
+ return blocks;
89197
+ } catch {
89198
+ return null;
89199
+ }
89200
+ };
89201
+ convertIpynbToMarkdown = (raw) => {
89202
+ const blocks = convertIpynbToBlocks(raw);
89203
+ return blocks === null ? null : blocks.join("\n\n");
89204
+ };
89205
+ BinaryNotebookError = class extends Error {};
89206
+ IpynbLoader = class {
89207
+ async loadPages(filePath) {
89208
+ log$11("Loading ipynb file:", filePath);
89209
+ try {
89210
+ const buffer = await readFile(filePath);
89211
+ const sniff = sniffBinaryBuffer(buffer.subarray(0, 8192));
89212
+ if (sniff.isBinary) {
89213
+ log$11("Rejecting binary content: %s", sniff.reason);
89214
+ throw new BinaryNotebookError(`Binary content in .ipynb file: ${sniff.reason}`);
89215
+ }
89216
+ const raw = buffer.toString("utf8").replace(/^\uFEFF/, "");
89217
+ const blocks = convertIpynbToBlocks(raw);
89218
+ if (blocks === null) {
89219
+ log$11("Not nbformat v4 JSON, falling back to scrubbed raw text");
89220
+ const fallback = scrubIpynbFallbackText(raw);
89221
+ const lines = fallback.split("\n");
89222
+ return [{
89223
+ charCount: fallback.length,
89224
+ lineCount: lines.length,
89225
+ metadata: {
89226
+ lineNumberEnd: lines.length,
89227
+ lineNumberStart: 1
89228
+ },
89229
+ pageContent: fallback
89230
+ }];
89231
+ }
89232
+ log$11("Converted notebook into %d blocks", blocks.length);
89233
+ return blocks.map((block, index) => ({
89234
+ charCount: block.length,
89235
+ lineCount: block.split("\n").length,
89236
+ metadata: {
89237
+ chunkIndex: index,
89238
+ totalChunks: blocks.length
89239
+ },
89240
+ pageContent: block
89241
+ }));
89242
+ } catch (e) {
89243
+ const error = e;
89244
+ if (error instanceof BinaryNotebookError) throw error;
89245
+ console.error(`Error loading ipynb file ${filePath}: ${error.message}`);
89246
+ return [{
89247
+ charCount: 0,
89248
+ lineCount: 0,
89249
+ metadata: { error: `Failed to load ipynb file: ${error.message}` },
89250
+ pageContent: ""
89251
+ }];
89252
+ }
89253
+ }
89254
+ async aggregateContent(pages) {
89255
+ return pages.map((page) => page.pageContent).join("\n\n");
89256
+ }
89257
+ };
89258
+ }));
89259
+
88785
89260
  //#endregion
88786
89261
  //#region ../../packages/file-loaders/src/loaders/text/index.ts
88787
89262
  init_detectUtf16();
88788
- const log$11 = (0, import_src$6.default)("file-loaders:text");
89263
+ const log$10 = (0, import_src$6.default)("file-loaders:text");
88789
89264
  /**
88790
89265
  * Read a text file with automatic encoding detection.
88791
89266
  * Detects UTF-8, UTF-16LE, and UTF-16BE via BOM, with a heuristic fallback
@@ -88794,20 +89269,20 @@ const log$11 = (0, import_src$6.default)("file-loaders:text");
88794
89269
  const readTextFile = async (filePath) => {
88795
89270
  const buffer = await readFile(filePath);
88796
89271
  if (buffer.length >= 2 && buffer[0] === 255 && buffer[1] === 254) {
88797
- log$11("Detected UTF-16LE BOM");
89272
+ log$10("Detected UTF-16LE BOM");
88798
89273
  return new TextDecoder("utf-16le").decode(buffer.subarray(2));
88799
89274
  }
88800
89275
  if (buffer.length >= 2 && buffer[0] === 254 && buffer[1] === 255) {
88801
- log$11("Detected UTF-16BE BOM");
89276
+ log$10("Detected UTF-16BE BOM");
88802
89277
  return new TextDecoder("utf-16be").decode(buffer.subarray(2));
88803
89278
  }
88804
89279
  if (buffer.length >= 3 && buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191) {
88805
- log$11("Detected UTF-8 BOM");
89280
+ log$10("Detected UTF-8 BOM");
88806
89281
  return buffer.subarray(3).toString("utf8");
88807
89282
  }
88808
89283
  const variant = detectUtf16NoBom(buffer);
88809
89284
  if (variant) {
88810
- log$11("Detected %s without BOM (heuristic)", variant);
89285
+ log$10("Detected %s without BOM (heuristic)", variant);
88811
89286
  return new TextDecoder(variant).decode(buffer);
88812
89287
  }
88813
89288
  return buffer.toString("utf8");
@@ -88817,13 +89292,13 @@ const readTextFile = async (filePath) => {
88817
89292
  */
88818
89293
  var TextLoader = class {
88819
89294
  async loadPages(filePath) {
88820
- log$11("Loading text file:", filePath);
89295
+ log$10("Loading text file:", filePath);
88821
89296
  try {
88822
89297
  const fileContent = await readTextFile(filePath);
88823
- log$11("Text file loaded successfully, size:", fileContent.length, "bytes");
89298
+ log$10("Text file loaded successfully, size:", fileContent.length, "bytes");
88824
89299
  const lineCount = fileContent.split("\n").length;
88825
89300
  const charCount = fileContent.length;
88826
- log$11("Text file stats:", {
89301
+ log$10("Text file stats:", {
88827
89302
  charCount,
88828
89303
  lineCount
88829
89304
  });
@@ -88836,11 +89311,11 @@ var TextLoader = class {
88836
89311
  },
88837
89312
  pageContent: fileContent
88838
89313
  };
88839
- log$11("Text page created successfully");
89314
+ log$10("Text page created successfully");
88840
89315
  return [page];
88841
89316
  } catch (e) {
88842
89317
  const error = e;
88843
- log$11("Error encountered while loading text file");
89318
+ log$10("Error encountered while loading text file");
88844
89319
  console.error(`Error loading text file ${filePath}: ${error.message}`);
88845
89320
  const errorPage = {
88846
89321
  charCount: 0,
@@ -88848,7 +89323,7 @@ var TextLoader = class {
88848
89323
  metadata: { error: `Failed to load text file: ${error.message}` },
88849
89324
  pageContent: ""
88850
89325
  };
88851
- log$11("Created error page for failed text file loading");
89326
+ log$10("Created error page for failed text file loading");
88852
89327
  return [errorPage];
88853
89328
  }
88854
89329
  }
@@ -88859,9 +89334,9 @@ var TextLoader = class {
88859
89334
  * @returns Aggregated content
88860
89335
  */
88861
89336
  async aggregateContent(pages) {
88862
- log$11("Aggregating content from", pages.length, "text pages");
89337
+ log$10("Aggregating content from", pages.length, "text pages");
88863
89338
  const result = pages.map((page) => page.pageContent).join("\n");
88864
- log$11("Content aggregated successfully, length:", result.length);
89339
+ log$10("Content aggregated successfully, length:", result.length);
88865
89340
  return result;
88866
89341
  }
88867
89342
  };
@@ -93352,14 +93827,14 @@ var require_word = /* @__PURE__ */ __commonJSMin$2(((exports, module) => {
93352
93827
  //#endregion
93353
93828
  //#region ../../packages/file-loaders/src/loaders/doc/index.ts
93354
93829
  var doc_exports = /* @__PURE__ */ __exportAll$2({ DocLoader: () => DocLoader });
93355
- var import_src$5, import_word, log$10, DocLoader;
93830
+ var import_src$4, import_word, log$9, DocLoader;
93356
93831
  var init_doc = __esmMin((() => {
93357
- import_src$5 = /* @__PURE__ */ __toESM$2(require_src());
93832
+ import_src$4 = /* @__PURE__ */ __toESM$2(require_src());
93358
93833
  import_word = /* @__PURE__ */ __toESM$2(require_word());
93359
- log$10 = (0, import_src$5.default)("file-loaders:doc");
93834
+ log$9 = (0, import_src$4.default)("file-loaders:doc");
93360
93835
  DocLoader = class {
93361
93836
  async loadPages(filePath) {
93362
- log$10("Loading DOC file:", filePath);
93837
+ log$9("Loading DOC file:", filePath);
93363
93838
  try {
93364
93839
  const extracted = await new import_word.default().extract(filePath);
93365
93840
  const pageContent = extracted && typeof extracted.getBody === "function" ? extracted.getBody() : extracted?.text ?? "";
@@ -93370,11 +93845,11 @@ var init_doc = __esmMin((() => {
93370
93845
  metadata: { pageNumber: 1 },
93371
93846
  pageContent
93372
93847
  };
93373
- log$10("DOC loading completed");
93848
+ log$9("DOC loading completed");
93374
93849
  return [page];
93375
93850
  } catch (e) {
93376
93851
  const error = e;
93377
- log$10("Error encountered while loading DOC file");
93852
+ log$9("Error encountered while loading DOC file");
93378
93853
  console.error(`Error loading DOC file ${filePath}: ${error.message}`);
93379
93854
  return [{
93380
93855
  charCount: 0,
@@ -93385,7 +93860,7 @@ var init_doc = __esmMin((() => {
93385
93860
  }
93386
93861
  }
93387
93862
  async aggregateContent(pages) {
93388
- log$10("Aggregating content from", pages.length, "DOC pages");
93863
+ log$9("Aggregating content from", pages.length, "DOC pages");
93389
93864
  return pages.map((p) => p.pageContent).join("\n\n");
93390
93865
  }
93391
93866
  };
@@ -117364,23 +117839,23 @@ var require_lib$2 = /* @__PURE__ */ __commonJSMin$2(((exports) => {
117364
117839
  //#endregion
117365
117840
  //#region ../../packages/file-loaders/src/loaders/docx/index.ts
117366
117841
  var docx_exports = /* @__PURE__ */ __exportAll$2({ DocxLoader: () => DocxLoader });
117367
- var import_src$4, import_lib$3, log$9, DocxLoader;
117842
+ var import_src$3, import_lib$3, log$8, DocxLoader;
117368
117843
  var init_docx = __esmMin((() => {
117369
- import_src$4 = /* @__PURE__ */ __toESM$2(require_src());
117844
+ import_src$3 = /* @__PURE__ */ __toESM$2(require_src());
117370
117845
  import_lib$3 = /* @__PURE__ */ __toESM$2(require_lib$2());
117371
- log$9 = (0, import_src$4.default)("file-loaders:docx");
117846
+ log$8 = (0, import_src$3.default)("file-loaders:docx");
117372
117847
  DocxLoader = class {
117373
117848
  async loadPages(filePath) {
117374
- log$9("Loading DOCX file:", filePath);
117849
+ log$8("Loading DOCX file:", filePath);
117375
117850
  try {
117376
117851
  const buffer = await fs$1.readFile(filePath);
117377
- log$9("File buffer read, size:", buffer.length);
117852
+ log$8("File buffer read, size:", buffer.length);
117378
117853
  const result = await import_lib$3.extractRawText({ buffer });
117379
117854
  const pageContent = result.value;
117380
- log$9("Text extracted, length:", pageContent.length);
117855
+ log$8("Text extracted, length:", pageContent.length);
117381
117856
  const lineCount = pageContent.split("\n").length;
117382
117857
  const charCount = pageContent.length;
117383
- log$9("DOCX document processed, lines:", lineCount, "chars:", charCount);
117858
+ log$8("DOCX document processed, lines:", lineCount, "chars:", charCount);
117384
117859
  const page = {
117385
117860
  charCount,
117386
117861
  lineCount,
@@ -117390,15 +117865,15 @@ var init_docx = __esmMin((() => {
117390
117865
  if (result.messages.length > 0) {
117391
117866
  const warnings = result.messages.filter((msg) => msg.type === "warning");
117392
117867
  if (warnings.length > 0) {
117393
- log$9("Extraction warnings:", warnings.length);
117394
- warnings.forEach((warning) => log$9("Warning:", warning.message));
117868
+ log$8("Extraction warnings:", warnings.length);
117869
+ warnings.forEach((warning) => log$8("Warning:", warning.message));
117395
117870
  }
117396
117871
  }
117397
- log$9("DOCX loading completed");
117872
+ log$8("DOCX loading completed");
117398
117873
  return [page];
117399
117874
  } catch (e) {
117400
117875
  const error = e;
117401
- log$9("Error encountered while loading DOCX file");
117876
+ log$8("Error encountered while loading DOCX file");
117402
117877
  console.error(`Error loading DOCX file ${filePath}: ${error.message}`);
117403
117878
  const errorPage = {
117404
117879
  charCount: 0,
@@ -117406,7 +117881,7 @@ var init_docx = __esmMin((() => {
117406
117881
  metadata: { error: `Failed to load DOCX file: ${error.message}` },
117407
117882
  pageContent: ""
117408
117883
  };
117409
- log$9("Created error page for failed DOCX loading");
117884
+ log$8("Created error page for failed DOCX loading");
117410
117885
  return [errorPage];
117411
117886
  }
117412
117887
  }
@@ -117417,9 +117892,9 @@ var init_docx = __esmMin((() => {
117417
117892
  * @returns Aggregated content as a string.
117418
117893
  */
117419
117894
  async aggregateContent(pages) {
117420
- log$9("Aggregating content from", pages.length, "DOCX pages");
117895
+ log$8("Aggregating content from", pages.length, "DOCX pages");
117421
117896
  const result = pages.map((page) => page.pageContent).join("\n\n");
117422
- log$9("DOCX content aggregated successfully, length:", result.length);
117897
+ log$8("DOCX content aggregated successfully, length:", result.length);
117423
117898
  return result;
117424
117899
  }
117425
117900
  };
@@ -140774,6 +141249,1245 @@ ${page.pageContent}
140774
141249
  };
140775
141250
  }));
140776
141251
 
141252
+ //#endregion
141253
+ //#region ../../packages/file-loaders/src/loaders/excel/sheetBounds.ts
141254
+ var MAX_SHEET_CELLS, isRealCell, clampSheetRefToData;
141255
+ var init_sheetBounds = __esmMin((() => {
141256
+ init_xlsx();
141257
+ init_fileParseBudget();
141258
+ MAX_SHEET_CELLS = 5e6;
141259
+ isRealCell = (cell) => !!cell && typeof cell === "object" && cell.t !== "z" && (cell.v !== void 0 && cell.v !== null ? true : cell.f !== void 0 || cell.w !== void 0);
141260
+ clampSheetRefToData = (worksheet, { maxCells = MAX_SHEET_CELLS } = {}) => {
141261
+ const ref = worksheet?.["!ref"];
141262
+ if (!worksheet || !ref) return;
141263
+ const range = utils.decode_range(ref);
141264
+ let lastRow = range.s.r;
141265
+ let lastCol = range.s.c;
141266
+ for (const key in worksheet) {
141267
+ if (key.charCodeAt(0) === 33) continue;
141268
+ if (!isRealCell(worksheet[key])) continue;
141269
+ const { c, r } = utils.decode_cell(key);
141270
+ if (r < range.s.r || r > range.e.r || c < range.s.c || c > range.e.c) continue;
141271
+ if (r > lastRow) lastRow = r;
141272
+ if (c > lastCol) lastCol = c;
141273
+ }
141274
+ const area = (lastRow - range.s.r + 1) * (lastCol - range.s.c + 1);
141275
+ if (area > maxCells) throw new FileParseBudgetError("sheet-cells", maxCells, area);
141276
+ worksheet["!ref"] = utils.encode_range({
141277
+ e: {
141278
+ c: lastCol,
141279
+ r: lastRow
141280
+ },
141281
+ s: range.s
141282
+ });
141283
+ };
141284
+ }));
141285
+
141286
+ //#endregion
141287
+ //#region node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/fd-slicer.js
141288
+ var require_fd_slicer = /* @__PURE__ */ __commonJSMin$2(((exports) => {
141289
+ var fs$8 = __require("fs");
141290
+ var util$3 = __require("util");
141291
+ var stream = __require("stream");
141292
+ var Readable = stream.Readable;
141293
+ var PassThrough = stream.PassThrough;
141294
+ var Pend = require_pend();
141295
+ var EventEmitter$2 = __require("events").EventEmitter;
141296
+ exports.BufferSlicer = BufferSlicer;
141297
+ exports.FdSlicer = FdSlicer;
141298
+ util$3.inherits(FdSlicer, EventEmitter$2);
141299
+ function FdSlicer(fd) {
141300
+ EventEmitter$2.call(this);
141301
+ this.fd = fd;
141302
+ this.pend = new Pend();
141303
+ this.pend.max = 1;
141304
+ this.refCount = 0;
141305
+ }
141306
+ FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
141307
+ var self = this;
141308
+ self.pend.go(function(cb) {
141309
+ fs$8.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer) {
141310
+ cb();
141311
+ callback(err, bytesRead, buffer);
141312
+ });
141313
+ });
141314
+ };
141315
+ FdSlicer.prototype.createReadStream = function(options) {
141316
+ return new ReadStream(this, options);
141317
+ };
141318
+ FdSlicer.prototype.ref = function() {
141319
+ this.refCount += 1;
141320
+ };
141321
+ FdSlicer.prototype.unref = function() {
141322
+ var self = this;
141323
+ self.refCount -= 1;
141324
+ if (self.refCount < 0) throw new Error("invalid unref");
141325
+ if (self.refCount > 0) return;
141326
+ fs$8.close(self.fd, onCloseDone);
141327
+ function onCloseDone(err) {
141328
+ if (err) self.emit("error", err);
141329
+ else self.emit("close");
141330
+ }
141331
+ };
141332
+ util$3.inherits(ReadStream, Readable);
141333
+ function ReadStream(context, options) {
141334
+ options = options || {};
141335
+ Readable.call(this, options);
141336
+ this.context = context;
141337
+ this.context.ref();
141338
+ this.start = options.start || 0;
141339
+ this.endOffset = options.end;
141340
+ this.pos = this.start;
141341
+ }
141342
+ ReadStream.prototype._read = function(n) {
141343
+ var self = this;
141344
+ var toRead = Math.min(self._readableState.highWaterMark, n);
141345
+ if (self.endOffset != null) toRead = Math.min(toRead, self.endOffset - self.pos);
141346
+ if (toRead <= 0) {
141347
+ self.push(null);
141348
+ this._cleanup();
141349
+ return;
141350
+ }
141351
+ self.context.pend.go(function(cb) {
141352
+ var buffer = Buffer.allocUnsafe(toRead);
141353
+ fs$8.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) {
141354
+ if (err) self.destroy(err);
141355
+ else if (bytesRead === 0) {
141356
+ self.push(null);
141357
+ self._cleanup();
141358
+ } else {
141359
+ self.pos += bytesRead;
141360
+ self.push(buffer.slice(0, bytesRead));
141361
+ }
141362
+ cb();
141363
+ });
141364
+ });
141365
+ };
141366
+ ReadStream.prototype._destroy = function(err, cb) {
141367
+ this._cleanup();
141368
+ cb(err);
141369
+ };
141370
+ ReadStream.prototype._cleanup = function() {
141371
+ if (this.context != null) {
141372
+ this.context.unref();
141373
+ this.context = null;
141374
+ }
141375
+ };
141376
+ util$3.inherits(BufferSlicer, EventEmitter$2);
141377
+ function BufferSlicer(buffer) {
141378
+ EventEmitter$2.call(this);
141379
+ this.refCount = 0;
141380
+ this.buffer = buffer;
141381
+ }
141382
+ BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) {
141383
+ if (!(0 <= offset && offset <= buffer.length)) throw new RangeError("offset outside buffer: 0 <= " + offset + " <= " + buffer.length);
141384
+ if (position < 0) throw new RangeError("position is negative: " + position);
141385
+ if (offset + length > buffer.length) length = buffer.length - offset;
141386
+ if (position + length > this.buffer.length) length = this.buffer.length - position;
141387
+ if (length <= 0) {
141388
+ setImmediate(function() {
141389
+ callback(null, 0);
141390
+ });
141391
+ return;
141392
+ }
141393
+ this.buffer.copy(buffer, offset, position, position + length);
141394
+ setImmediate(function() {
141395
+ callback(null, length);
141396
+ });
141397
+ };
141398
+ BufferSlicer.prototype.createReadStream = function(options) {
141399
+ options = options || {};
141400
+ var readStream = new PassThrough(options);
141401
+ readStream.start = options.start || 0;
141402
+ readStream.endOffset = options.end;
141403
+ readStream.pos = readStream.endOffset || this.buffer.length;
141404
+ var entireSlice = this.buffer.slice(readStream.start, readStream.pos);
141405
+ var maxChunkSize = 65536;
141406
+ var offset = 0;
141407
+ while (true) {
141408
+ var nextOffset = offset + maxChunkSize;
141409
+ if (nextOffset >= entireSlice.length) {
141410
+ if (offset < entireSlice.length) readStream.write(entireSlice.slice(offset, entireSlice.length));
141411
+ break;
141412
+ }
141413
+ readStream.write(entireSlice.slice(offset, nextOffset));
141414
+ offset = nextOffset;
141415
+ }
141416
+ readStream.end();
141417
+ return readStream;
141418
+ };
141419
+ BufferSlicer.prototype.ref = function() {
141420
+ this.refCount += 1;
141421
+ };
141422
+ BufferSlicer.prototype.unref = function() {
141423
+ this.refCount -= 1;
141424
+ if (this.refCount < 0) throw new Error("invalid unref");
141425
+ };
141426
+ }));
141427
+
141428
+ //#endregion
141429
+ //#region node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/crc32.js
141430
+ var require_crc32 = /* @__PURE__ */ __commonJSMin$2(((exports, module) => {
141431
+ const CRC_TABLE = new Int32Array([
141432
+ 0,
141433
+ 1996959894,
141434
+ 3993919788,
141435
+ 2567524794,
141436
+ 124634137,
141437
+ 1886057615,
141438
+ 3915621685,
141439
+ 2657392035,
141440
+ 249268274,
141441
+ 2044508324,
141442
+ 3772115230,
141443
+ 2547177864,
141444
+ 162941995,
141445
+ 2125561021,
141446
+ 3887607047,
141447
+ 2428444049,
141448
+ 498536548,
141449
+ 1789927666,
141450
+ 4089016648,
141451
+ 2227061214,
141452
+ 450548861,
141453
+ 1843258603,
141454
+ 4107580753,
141455
+ 2211677639,
141456
+ 325883990,
141457
+ 1684777152,
141458
+ 4251122042,
141459
+ 2321926636,
141460
+ 335633487,
141461
+ 1661365465,
141462
+ 4195302755,
141463
+ 2366115317,
141464
+ 997073096,
141465
+ 1281953886,
141466
+ 3579855332,
141467
+ 2724688242,
141468
+ 1006888145,
141469
+ 1258607687,
141470
+ 3524101629,
141471
+ 2768942443,
141472
+ 901097722,
141473
+ 1119000684,
141474
+ 3686517206,
141475
+ 2898065728,
141476
+ 853044451,
141477
+ 1172266101,
141478
+ 3705015759,
141479
+ 2882616665,
141480
+ 651767980,
141481
+ 1373503546,
141482
+ 3369554304,
141483
+ 3218104598,
141484
+ 565507253,
141485
+ 1454621731,
141486
+ 3485111705,
141487
+ 3099436303,
141488
+ 671266974,
141489
+ 1594198024,
141490
+ 3322730930,
141491
+ 2970347812,
141492
+ 795835527,
141493
+ 1483230225,
141494
+ 3244367275,
141495
+ 3060149565,
141496
+ 1994146192,
141497
+ 31158534,
141498
+ 2563907772,
141499
+ 4023717930,
141500
+ 1907459465,
141501
+ 112637215,
141502
+ 2680153253,
141503
+ 3904427059,
141504
+ 2013776290,
141505
+ 251722036,
141506
+ 2517215374,
141507
+ 3775830040,
141508
+ 2137656763,
141509
+ 141376813,
141510
+ 2439277719,
141511
+ 3865271297,
141512
+ 1802195444,
141513
+ 476864866,
141514
+ 2238001368,
141515
+ 4066508878,
141516
+ 1812370925,
141517
+ 453092731,
141518
+ 2181625025,
141519
+ 4111451223,
141520
+ 1706088902,
141521
+ 314042704,
141522
+ 2344532202,
141523
+ 4240017532,
141524
+ 1658658271,
141525
+ 366619977,
141526
+ 2362670323,
141527
+ 4224994405,
141528
+ 1303535960,
141529
+ 984961486,
141530
+ 2747007092,
141531
+ 3569037538,
141532
+ 1256170817,
141533
+ 1037604311,
141534
+ 2765210733,
141535
+ 3554079995,
141536
+ 1131014506,
141537
+ 879679996,
141538
+ 2909243462,
141539
+ 3663771856,
141540
+ 1141124467,
141541
+ 855842277,
141542
+ 2852801631,
141543
+ 3708648649,
141544
+ 1342533948,
141545
+ 654459306,
141546
+ 3188396048,
141547
+ 3373015174,
141548
+ 1466479909,
141549
+ 544179635,
141550
+ 3110523913,
141551
+ 3462522015,
141552
+ 1591671054,
141553
+ 702138776,
141554
+ 2966460450,
141555
+ 3352799412,
141556
+ 1504918807,
141557
+ 783551873,
141558
+ 3082640443,
141559
+ 3233442989,
141560
+ 3988292384,
141561
+ 2596254646,
141562
+ 62317068,
141563
+ 1957810842,
141564
+ 3939845945,
141565
+ 2647816111,
141566
+ 81470997,
141567
+ 1943803523,
141568
+ 3814918930,
141569
+ 2489596804,
141570
+ 225274430,
141571
+ 2053790376,
141572
+ 3826175755,
141573
+ 2466906013,
141574
+ 167816743,
141575
+ 2097651377,
141576
+ 4027552580,
141577
+ 2265490386,
141578
+ 503444072,
141579
+ 1762050814,
141580
+ 4150417245,
141581
+ 2154129355,
141582
+ 426522225,
141583
+ 1852507879,
141584
+ 4275313526,
141585
+ 2312317920,
141586
+ 282753626,
141587
+ 1742555852,
141588
+ 4189708143,
141589
+ 2394877945,
141590
+ 397917763,
141591
+ 1622183637,
141592
+ 3604390888,
141593
+ 2714866558,
141594
+ 953729732,
141595
+ 1340076626,
141596
+ 3518719985,
141597
+ 2797360999,
141598
+ 1068828381,
141599
+ 1219638859,
141600
+ 3624741850,
141601
+ 2936675148,
141602
+ 906185462,
141603
+ 1090812512,
141604
+ 3747672003,
141605
+ 2825379669,
141606
+ 829329135,
141607
+ 1181335161,
141608
+ 3412177804,
141609
+ 3160834842,
141610
+ 628085408,
141611
+ 1382605366,
141612
+ 3423369109,
141613
+ 3138078467,
141614
+ 570562233,
141615
+ 1426400815,
141616
+ 3317316542,
141617
+ 2998733608,
141618
+ 733239954,
141619
+ 1555261956,
141620
+ 3268935591,
141621
+ 3050360625,
141622
+ 752459403,
141623
+ 1541320221,
141624
+ 2607071920,
141625
+ 3965973030,
141626
+ 1969922972,
141627
+ 40735498,
141628
+ 2617837225,
141629
+ 3943577151,
141630
+ 1913087877,
141631
+ 83908371,
141632
+ 2512341634,
141633
+ 3803740692,
141634
+ 2075208622,
141635
+ 213261112,
141636
+ 2463272603,
141637
+ 3855990285,
141638
+ 2094854071,
141639
+ 198958881,
141640
+ 2262029012,
141641
+ 4057260610,
141642
+ 1759359992,
141643
+ 534414190,
141644
+ 2176718541,
141645
+ 4139329115,
141646
+ 1873836001,
141647
+ 414664567,
141648
+ 2282248934,
141649
+ 4279200368,
141650
+ 1711684554,
141651
+ 285281116,
141652
+ 2405801727,
141653
+ 4167216745,
141654
+ 1634467795,
141655
+ 376229701,
141656
+ 2685067896,
141657
+ 3608007406,
141658
+ 1308918612,
141659
+ 956543938,
141660
+ 2808555105,
141661
+ 3495958263,
141662
+ 1231636301,
141663
+ 1047427035,
141664
+ 2932959818,
141665
+ 3654703836,
141666
+ 1088359270,
141667
+ 936918e3,
141668
+ 2847714899,
141669
+ 3736837829,
141670
+ 1202900863,
141671
+ 817233897,
141672
+ 3183342108,
141673
+ 3401237130,
141674
+ 1404277552,
141675
+ 615818150,
141676
+ 3134207493,
141677
+ 3453421203,
141678
+ 1423857449,
141679
+ 601450431,
141680
+ 3009837614,
141681
+ 3294710456,
141682
+ 1567103746,
141683
+ 711928724,
141684
+ 3020668471,
141685
+ 3272380065,
141686
+ 1510334235,
141687
+ 755167117
141688
+ ]);
141689
+ function crc32(buf) {
141690
+ let crc = -1;
141691
+ for (let x of buf) crc = CRC_TABLE[(crc ^ x) & 255] ^ crc >>> 8;
141692
+ return (crc ^ -1) >>> 0;
141693
+ }
141694
+ module.exports = crc32;
141695
+ }));
141696
+
141697
+ //#endregion
141698
+ //#region node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/index.js
141699
+ var require_yauzl = /* @__PURE__ */ __commonJSMin$2(((exports) => {
141700
+ var fs$7 = __require("fs");
141701
+ var zlib$1 = __require("zlib");
141702
+ var fd_slicer = require_fd_slicer();
141703
+ var util$2 = __require("util");
141704
+ var EventEmitter$1 = __require("events").EventEmitter;
141705
+ var Transform$2 = __require("stream").Transform;
141706
+ var PassThrough$1 = __require("stream").PassThrough;
141707
+ var Writable$1 = __require("stream").Writable;
141708
+ const crc32 = typeof zlib$1.crc32 === "function" ? zlib$1.crc32 : require_crc32();
141709
+ exports.open = open;
141710
+ exports.fromBuffer = fromBuffer;
141711
+ function open(path, options, callback) {
141712
+ if (typeof options === "function") {
141713
+ callback = options;
141714
+ options = null;
141715
+ }
141716
+ if (options == null) options = {};
141717
+ if (options.autoClose == null) options.autoClose = true;
141718
+ if (options.lazyEntries == null) options.lazyEntries = false;
141719
+ if (options.decodeStrings == null) options.decodeStrings = true;
141720
+ if (options.validateEntrySizes == null) options.validateEntrySizes = true;
141721
+ if (options.strictFileNames == null) options.strictFileNames = false;
141722
+ if (callback == null) callback = defaultCallback;
141723
+ fs$7.open(path, "r", function(err, fd) {
141724
+ if (err) return callback(err);
141725
+ fromFd(fd, options, function(err, zipfile) {
141726
+ if (err) fs$7.close(fd, defaultCallback);
141727
+ callback(err, zipfile);
141728
+ });
141729
+ });
141730
+ }
141731
+ function fromFd(fd, options, callback) {
141732
+ if (typeof options === "function") {
141733
+ callback = options;
141734
+ options = null;
141735
+ }
141736
+ if (options == null) options = {};
141737
+ if (options.autoClose == null) options.autoClose = false;
141738
+ if (options.lazyEntries == null) options.lazyEntries = false;
141739
+ if (options.decodeStrings == null) options.decodeStrings = true;
141740
+ if (options.validateEntrySizes == null) options.validateEntrySizes = true;
141741
+ if (options.strictFileNames == null) options.strictFileNames = false;
141742
+ if (callback == null) callback = defaultCallback;
141743
+ fs$7.fstat(fd, function(err, stats) {
141744
+ if (err) return callback(err);
141745
+ fromRandomAccessReader(new fd_slicer.FdSlicer(fd), stats.size, options, callback);
141746
+ });
141747
+ }
141748
+ function fromBuffer(buffer, options, callback) {
141749
+ if (typeof options === "function") {
141750
+ callback = options;
141751
+ options = null;
141752
+ }
141753
+ if (options == null) options = {};
141754
+ options.autoClose = false;
141755
+ if (options.lazyEntries == null) options.lazyEntries = false;
141756
+ if (options.decodeStrings == null) options.decodeStrings = true;
141757
+ if (options.validateEntrySizes == null) options.validateEntrySizes = true;
141758
+ if (options.strictFileNames == null) options.strictFileNames = false;
141759
+ fromRandomAccessReader(new fd_slicer.BufferSlicer(buffer), buffer.length, options, callback);
141760
+ }
141761
+ function fromRandomAccessReader(reader, totalSize, options, callback) {
141762
+ if (typeof options === "function") {
141763
+ callback = options;
141764
+ options = null;
141765
+ }
141766
+ if (options == null) options = {};
141767
+ if (options.autoClose == null) options.autoClose = true;
141768
+ if (options.lazyEntries == null) options.lazyEntries = false;
141769
+ if (options.decodeStrings == null) options.decodeStrings = true;
141770
+ var decodeStrings = !!options.decodeStrings;
141771
+ if (options.validateEntrySizes == null) options.validateEntrySizes = true;
141772
+ if (options.strictFileNames == null) options.strictFileNames = false;
141773
+ if (callback == null) callback = defaultCallback;
141774
+ if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number");
141775
+ if (totalSize > Number.MAX_SAFE_INTEGER) throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");
141776
+ reader.ref();
141777
+ var eocdrWithoutCommentSize = 22;
141778
+ var zip64EocdlSize = 20;
141779
+ var bufferSize = Math.min(zip64EocdlSize + eocdrWithoutCommentSize + 65535, totalSize);
141780
+ var buffer = newBuffer(bufferSize);
141781
+ readAndAssertNoEof(reader, buffer, 0, bufferSize, totalSize - buffer.length, function(err) {
141782
+ if (err) return callback(err);
141783
+ for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) {
141784
+ if (buffer.readUInt32LE(i) !== 101010256) continue;
141785
+ var eocdrBuffer = buffer.subarray(i);
141786
+ var diskNumber = eocdrBuffer.readUInt16LE(4);
141787
+ var entryCount = eocdrBuffer.readUInt16LE(10);
141788
+ var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16);
141789
+ var commentLength = eocdrBuffer.readUInt16LE(20);
141790
+ var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize;
141791
+ if (commentLength !== expectedCommentLength) return callback(/* @__PURE__ */ new Error("Invalid comment length. Expected: " + expectedCommentLength + ". Found: " + commentLength + ". Are there extra bytes at the end of the file? Or is the end of central dir signature `PK☺☻` in the comment?"));
141792
+ var comment = decodeStrings ? decodeBuffer(eocdrBuffer.subarray(22), false) : eocdrBuffer.subarray(22);
141793
+ if (i - zip64EocdlSize >= 0 && buffer.readUInt32LE(i - zip64EocdlSize) === 117853008) {
141794
+ var zip64EocdrOffset = readUInt64LE(buffer.subarray(i - zip64EocdlSize, i - zip64EocdlSize + zip64EocdlSize), 8);
141795
+ var zip64EocdrBuffer = newBuffer(56);
141796
+ return readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err) {
141797
+ if (err) return callback(err);
141798
+ if (zip64EocdrBuffer.readUInt32LE(0) !== 101075792) return callback(/* @__PURE__ */ new Error("invalid zip64 end of central directory record signature"));
141799
+ diskNumber = zip64EocdrBuffer.readUInt32LE(16);
141800
+ if (diskNumber !== 0) return callback(/* @__PURE__ */ new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
141801
+ entryCount = readUInt64LE(zip64EocdrBuffer, 32);
141802
+ centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48);
141803
+ return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
141804
+ });
141805
+ }
141806
+ if (diskNumber !== 0) return callback(/* @__PURE__ */ new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
141807
+ return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
141808
+ }
141809
+ callback(/* @__PURE__ */ new Error("End of central directory record signature not found. Either not a zip file, or file is truncated."));
141810
+ });
141811
+ }
141812
+ util$2.inherits(ZipFile, EventEmitter$1);
141813
+ function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
141814
+ var self = this;
141815
+ EventEmitter$1.call(self);
141816
+ self.reader = reader;
141817
+ self.reader.on("error", function(err) {
141818
+ emitError(self, err);
141819
+ });
141820
+ self.reader.once("close", function() {
141821
+ self.emit("close");
141822
+ });
141823
+ self.readEntryCursor = centralDirectoryOffset;
141824
+ self.fileSize = fileSize;
141825
+ self.entryCount = entryCount;
141826
+ self.comment = comment;
141827
+ self.entriesRead = 0;
141828
+ self.autoClose = !!autoClose;
141829
+ self.lazyEntries = !!lazyEntries;
141830
+ self.decodeStrings = !!decodeStrings;
141831
+ self.validateEntrySizes = !!validateEntrySizes;
141832
+ self.strictFileNames = !!strictFileNames;
141833
+ self.isOpen = true;
141834
+ self.emittedError = false;
141835
+ self.hasEachEntryBeenCalled = false;
141836
+ if (!self.lazyEntries) self._readEntry();
141837
+ }
141838
+ ZipFile.prototype.close = function() {
141839
+ if (!this.isOpen) return;
141840
+ this.isOpen = false;
141841
+ this.reader.unref();
141842
+ };
141843
+ function emitErrorAndAutoClose(self, err) {
141844
+ if (self.autoClose) self.close();
141845
+ emitError(self, err);
141846
+ }
141847
+ function emitError(self, err) {
141848
+ if (self.emittedError) return;
141849
+ self.emittedError = true;
141850
+ self.emit("error", err);
141851
+ }
141852
+ ZipFile.prototype.readEntry = function() {
141853
+ if (!this.lazyEntries) throw new Error("readEntry() called without lazyEntries:true");
141854
+ this._readEntry();
141855
+ };
141856
+ ZipFile.prototype._readEntry = function() {
141857
+ var self = this;
141858
+ if (self.entryCount === self.entriesRead) {
141859
+ setImmediate(function() {
141860
+ if (self.autoClose) self.close();
141861
+ if (self.emittedError) return;
141862
+ self.emit("end");
141863
+ });
141864
+ return;
141865
+ }
141866
+ if (self.emittedError) return;
141867
+ var buffer = newBuffer(46);
141868
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
141869
+ if (err) return emitErrorAndAutoClose(self, err);
141870
+ if (self.emittedError) return;
141871
+ var entry = new Entry();
141872
+ var signature = buffer.readUInt32LE(0);
141873
+ if (signature !== 33639248) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("invalid central directory file header signature: 0x" + signature.toString(16)));
141874
+ entry.versionMadeBy = buffer.readUInt16LE(4);
141875
+ entry.versionNeededToExtract = buffer.readUInt16LE(6);
141876
+ entry.generalPurposeBitFlag = buffer.readUInt16LE(8);
141877
+ entry.compressionMethod = buffer.readUInt16LE(10);
141878
+ entry.lastModFileTime = buffer.readUInt16LE(12);
141879
+ entry.lastModFileDate = buffer.readUInt16LE(14);
141880
+ entry.crc32 = buffer.readUInt32LE(16);
141881
+ entry.compressedSize = buffer.readUInt32LE(20);
141882
+ entry.uncompressedSize = buffer.readUInt32LE(24);
141883
+ entry.fileNameLength = buffer.readUInt16LE(28);
141884
+ entry.extraFieldLength = buffer.readUInt16LE(30);
141885
+ entry.fileCommentLength = buffer.readUInt16LE(32);
141886
+ entry.internalFileAttributes = buffer.readUInt16LE(36);
141887
+ entry.externalFileAttributes = buffer.readUInt32LE(38);
141888
+ entry.relativeOffsetOfLocalHeader = buffer.readUInt32LE(42);
141889
+ if (entry.generalPurposeBitFlag & 64) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("strong encryption is not supported"));
141890
+ self.readEntryCursor += 46;
141891
+ buffer = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength);
141892
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
141893
+ if (err) return emitErrorAndAutoClose(self, err);
141894
+ if (self.emittedError) return;
141895
+ entry.fileNameRaw = buffer.subarray(0, entry.fileNameLength);
141896
+ var fileCommentStart = entry.fileNameLength + entry.extraFieldLength;
141897
+ entry.extraFieldRaw = buffer.subarray(entry.fileNameLength, fileCommentStart);
141898
+ entry.fileCommentRaw = buffer.subarray(fileCommentStart, fileCommentStart + entry.fileCommentLength);
141899
+ try {
141900
+ entry.extraFields = parseExtraFields(entry.extraFieldRaw);
141901
+ } catch (err) {
141902
+ return emitErrorAndAutoClose(self, err);
141903
+ }
141904
+ if (self.decodeStrings) {
141905
+ var isUtf8 = (entry.generalPurposeBitFlag & 2048) !== 0;
141906
+ entry.fileComment = decodeBuffer(entry.fileCommentRaw, isUtf8);
141907
+ entry.fileName = getFileNameLowLevel(entry.generalPurposeBitFlag, entry.fileNameRaw, entry.extraFields, self.strictFileNames);
141908
+ var errorMessage = validateFileName(entry.fileName);
141909
+ if (errorMessage != null) return emitErrorAndAutoClose(self, new Error(errorMessage));
141910
+ } else {
141911
+ entry.fileComment = entry.fileCommentRaw;
141912
+ entry.fileName = entry.fileNameRaw;
141913
+ }
141914
+ entry.comment = entry.fileComment;
141915
+ self.readEntryCursor += buffer.length;
141916
+ self.entriesRead += 1;
141917
+ for (var i = 0; i < entry.extraFields.length; i++) {
141918
+ var extraField = entry.extraFields[i];
141919
+ if (extraField.id !== 1) continue;
141920
+ var zip64EiefBuffer = extraField.data;
141921
+ var index = 0;
141922
+ if (entry.uncompressedSize === 4294967295) {
141923
+ if (index + 8 > zip64EiefBuffer.length) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("zip64 extended information extra field does not include uncompressed size"));
141924
+ entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index);
141925
+ index += 8;
141926
+ }
141927
+ if (entry.compressedSize === 4294967295) {
141928
+ if (index + 8 > zip64EiefBuffer.length) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("zip64 extended information extra field does not include compressed size"));
141929
+ entry.compressedSize = readUInt64LE(zip64EiefBuffer, index);
141930
+ index += 8;
141931
+ }
141932
+ if (entry.relativeOffsetOfLocalHeader === 4294967295) {
141933
+ if (index + 8 > zip64EiefBuffer.length) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("zip64 extended information extra field does not include relative header offset"));
141934
+ entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index);
141935
+ index += 8;
141936
+ }
141937
+ break;
141938
+ }
141939
+ if (self.validateEntrySizes && entry.compressionMethod === 0) {
141940
+ var expectedCompressedSize = entry.uncompressedSize;
141941
+ if (entry.isEncrypted()) expectedCompressedSize += 12;
141942
+ if (entry.compressedSize !== expectedCompressedSize) {
141943
+ var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize;
141944
+ return emitErrorAndAutoClose(self, new Error(msg));
141945
+ }
141946
+ }
141947
+ self.emit("entry", entry);
141948
+ if (!self.lazyEntries) self._readEntry();
141949
+ });
141950
+ });
141951
+ };
141952
+ ZipFile.prototype.eachEntry = function() {
141953
+ const self = this;
141954
+ if (!self.lazyEntries) throw new Error("eachEntry() requires lazyEntries: true");
141955
+ if (self.hasEachEntryBeenCalled) throw new Error("eachEntry() must only be called once per ZipFile");
141956
+ self.hasEachEntryBeenCalled = true;
141957
+ let pendingResolveReject = null;
141958
+ self.on("entry", onEntry);
141959
+ self.on("end", onEnd);
141960
+ self.on("error", onError);
141961
+ function cleanup() {
141962
+ self.removeListener("entry", onEntry);
141963
+ self.removeListener("end", onEnd);
141964
+ self.removeListener("error", onError);
141965
+ if (self.autoClose) self.close();
141966
+ }
141967
+ function onEntry(entry) {
141968
+ let { resolve } = pendingResolveReject;
141969
+ pendingResolveReject = null;
141970
+ resolve({ value: entry });
141971
+ }
141972
+ function onEnd() {
141973
+ let { resolve } = pendingResolveReject;
141974
+ pendingResolveReject = null;
141975
+ cleanup();
141976
+ resolve({ done: true });
141977
+ }
141978
+ function onError(err) {
141979
+ let { reject } = pendingResolveReject;
141980
+ pendingResolveReject = null;
141981
+ cleanup();
141982
+ reject(err);
141983
+ }
141984
+ return {
141985
+ [Symbol.asyncIterator]() {
141986
+ return this;
141987
+ },
141988
+ next() {
141989
+ const promise = new Promise((resolve, reject) => {
141990
+ if (pendingResolveReject != null) throw new Error("next() called before previous Promise was resolved.");
141991
+ pendingResolveReject = {
141992
+ resolve,
141993
+ reject
141994
+ };
141995
+ });
141996
+ self.readEntry();
141997
+ return promise;
141998
+ },
141999
+ return(value) {
142000
+ cleanup();
142001
+ return Promise.resolve({
142002
+ done: true,
142003
+ value
142004
+ });
142005
+ },
142006
+ throw(value) {
142007
+ cleanup();
142008
+ return Promise.reject(value);
142009
+ }
142010
+ };
142011
+ };
142012
+ ZipFile.prototype.openReadStream = function(entry, options, callback) {
142013
+ var self = this;
142014
+ var relativeStart = 0;
142015
+ var relativeEnd = entry.compressedSize;
142016
+ if (callback == null) {
142017
+ callback = options;
142018
+ options = null;
142019
+ }
142020
+ if (options == null) options = {};
142021
+ else {
142022
+ if (options.decodeFileData === false) {
142023
+ if (options.decrypt != null) throw new Error("cannot use options.decrypt when options.decodeFileData === false");
142024
+ if (options.decompress != null) throw new Error("cannot use options.decompress when options.decodeFileData === false");
142025
+ } else {
142026
+ if (options.decrypt != null) {
142027
+ if (!entry.isEncrypted()) throw new Error("options.decrypt can only be specified for encrypted entries. See also option decodeFileData.");
142028
+ if (options.decrypt !== false) throw new Error("invalid options.decrypt value: " + options.decrypt);
142029
+ if (entry.isCompressed()) {
142030
+ if (options.decompress !== false) throw new Error("entry is encrypted and compressed, and options.decompress !== false. See also option decodeFileData.");
142031
+ }
142032
+ }
142033
+ if (options.decompress != null) {
142034
+ if (!entry.isCompressed()) throw new Error("options.decompress can only be specified for compressed entries. See also option decodeFileData.");
142035
+ if (!(options.decompress === false || options.decompress === true)) throw new Error("invalid options.decompress value: " + options.decompress);
142036
+ decompress = options.decompress;
142037
+ }
142038
+ }
142039
+ if (options.start != null) {
142040
+ relativeStart = options.start;
142041
+ if (relativeStart < 0) throw new Error("options.start < 0");
142042
+ if (relativeStart > entry.compressedSize) throw new Error("options.start > entry.compressedSize");
142043
+ }
142044
+ if (options.end != null) {
142045
+ relativeEnd = options.end;
142046
+ if (relativeEnd < 0) throw new Error("options.end < 0");
142047
+ if (relativeEnd > entry.compressedSize) throw new Error("options.end > entry.compressedSize");
142048
+ if (relativeEnd < relativeStart) throw new Error("options.end < options.start");
142049
+ }
142050
+ }
142051
+ var rawMode = options.decodeFileData === false || (entry.compressionMethod === 0 || entry.compressionMethod === 8 && options.decompress === false) && (!entry.isEncrypted() || options.decrypt === false);
142052
+ if (options.start != null || options.end != null) {
142053
+ if (!rawMode) throw new Error("start/end range require options.decodeFileData === false for non-trivial encoded entries.");
142054
+ }
142055
+ if (!self.isOpen) return callback(/* @__PURE__ */ new Error("closed"));
142056
+ if (entry.isEncrypted() && !rawMode) {
142057
+ if (options.decrypt !== false) return callback(/* @__PURE__ */ new Error("entry is encrypted, and options.decodeFileData !== false"));
142058
+ }
142059
+ var decompress;
142060
+ if (rawMode) decompress = false;
142061
+ else if (entry.compressionMethod === 8) decompress = options.decodeFileData !== true;
142062
+ else return callback(/* @__PURE__ */ new Error("unsupported compression method: " + entry.compressionMethod));
142063
+ self.readLocalFileHeader(entry, { minimal: true }, function(err, localFileHeader) {
142064
+ if (err) return callback(err);
142065
+ self.openReadStreamLowLevel(localFileHeader.fileDataStart, entry.compressedSize, relativeStart, relativeEnd, decompress, entry.uncompressedSize, callback);
142066
+ });
142067
+ };
142068
+ ZipFile.prototype.openReadStreamLowLevel = function(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize, callback) {
142069
+ var self = this;
142070
+ fileDataStart + compressedSize;
142071
+ var readStream = self.reader.createReadStream({
142072
+ start: fileDataStart + relativeStart,
142073
+ end: fileDataStart + relativeEnd
142074
+ });
142075
+ var endpointStream = readStream;
142076
+ if (decompress) {
142077
+ var destroyed = false;
142078
+ var inflateFilter = zlib$1.createInflateRaw();
142079
+ readStream.on("error", function(err) {
142080
+ setImmediate(function() {
142081
+ if (!destroyed) inflateFilter.emit("error", err);
142082
+ });
142083
+ });
142084
+ readStream.pipe(inflateFilter);
142085
+ if (self.validateEntrySizes) {
142086
+ endpointStream = new AssertByteCountStream(uncompressedSize);
142087
+ inflateFilter.on("error", function(err) {
142088
+ setImmediate(function() {
142089
+ if (!destroyed) endpointStream.emit("error", err);
142090
+ });
142091
+ });
142092
+ inflateFilter.pipe(endpointStream);
142093
+ } else endpointStream = inflateFilter;
142094
+ installDestroyFn(endpointStream, function() {
142095
+ destroyed = true;
142096
+ if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream);
142097
+ readStream.unpipe(inflateFilter);
142098
+ readStream.destroy();
142099
+ });
142100
+ }
142101
+ callback(null, endpointStream);
142102
+ };
142103
+ ZipFile.prototype.readLocalFileHeader = function(entry, options, callback) {
142104
+ var self = this;
142105
+ if (callback == null) {
142106
+ callback = options;
142107
+ options = null;
142108
+ }
142109
+ if (options == null) options = {};
142110
+ self.reader.ref();
142111
+ var buffer = newBuffer(30);
142112
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader, function(err) {
142113
+ try {
142114
+ if (err) return callback(err);
142115
+ var signature = buffer.readUInt32LE(0);
142116
+ if (signature !== 67324752) return callback(/* @__PURE__ */ new Error("invalid local file header signature: 0x" + signature.toString(16)));
142117
+ var fileNameLength = buffer.readUInt16LE(26);
142118
+ var extraFieldLength = buffer.readUInt16LE(28);
142119
+ var fileDataStart = entry.relativeOffsetOfLocalHeader + 30 + fileNameLength + extraFieldLength;
142120
+ if (fileDataStart + entry.compressedSize > self.fileSize) return callback(/* @__PURE__ */ new Error("file data overflows file bounds: " + fileDataStart + " + " + entry.compressedSize + " > " + self.fileSize));
142121
+ if (options.minimal) return callback(null, { fileDataStart });
142122
+ var localFileHeader = new LocalFileHeader();
142123
+ localFileHeader.fileDataStart = fileDataStart;
142124
+ localFileHeader.versionNeededToExtract = buffer.readUInt16LE(4);
142125
+ localFileHeader.generalPurposeBitFlag = buffer.readUInt16LE(6);
142126
+ localFileHeader.compressionMethod = buffer.readUInt16LE(8);
142127
+ localFileHeader.lastModFileTime = buffer.readUInt16LE(10);
142128
+ localFileHeader.lastModFileDate = buffer.readUInt16LE(12);
142129
+ localFileHeader.crc32 = buffer.readUInt32LE(14);
142130
+ localFileHeader.compressedSize = buffer.readUInt32LE(18);
142131
+ localFileHeader.uncompressedSize = buffer.readUInt32LE(22);
142132
+ localFileHeader.fileNameLength = fileNameLength;
142133
+ localFileHeader.extraFieldLength = extraFieldLength;
142134
+ buffer = newBuffer(fileNameLength + extraFieldLength);
142135
+ self.reader.ref();
142136
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader + 30, function(err) {
142137
+ try {
142138
+ if (err) return callback(err);
142139
+ localFileHeader.fileName = buffer.subarray(0, fileNameLength);
142140
+ localFileHeader.extraField = buffer.subarray(fileNameLength);
142141
+ return callback(null, localFileHeader);
142142
+ } finally {
142143
+ self.reader.unref();
142144
+ }
142145
+ });
142146
+ } finally {
142147
+ self.reader.unref();
142148
+ }
142149
+ });
142150
+ };
142151
+ ZipFile.prototype.openReadStreamPromise = function(entry, options) {
142152
+ return new Promise((resolve, reject) => {
142153
+ this.openReadStream(entry, options, function(err, readStream) {
142154
+ if (err) return reject(err);
142155
+ resolve(readStream);
142156
+ });
142157
+ });
142158
+ };
142159
+ ZipFile.prototype.openReadStreamLowLevelPromise = function(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize) {
142160
+ return new Promise((resolve, reject) => {
142161
+ this.openReadStream(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize, function(err, readStream) {
142162
+ if (err) return reject(err);
142163
+ resolve(readStream);
142164
+ });
142165
+ });
142166
+ };
142167
+ ZipFile.prototype.readLocalFileHeaderPromise = function(entry, options) {
142168
+ return new Promise((resolve, reject) => {
142169
+ this.readLocalFileHeader(entry, options, function(err, localFileHeader) {
142170
+ if (err) return reject(err);
142171
+ resolve(localFileHeader);
142172
+ });
142173
+ });
142174
+ };
142175
+ function Entry() {}
142176
+ Entry.prototype.getLastModDate = function(options) {
142177
+ if (options == null) options = {};
142178
+ if (!options.forceDosFormat) for (var i = 0; i < this.extraFields.length; i++) {
142179
+ var extraField = this.extraFields[i];
142180
+ if (extraField.id === 21589) {
142181
+ var data = extraField.data;
142182
+ if (data.length < 5) continue;
142183
+ if (!(data[0] & 1)) continue;
142184
+ var posixTimestamp = data.readInt32LE(1);
142185
+ return /* @__PURE__ */ new Date(posixTimestamp * 1e3);
142186
+ } else if (extraField.id === 10) {
142187
+ var data = extraField.data;
142188
+ if (data.length !== 32) continue;
142189
+ if (data.readUInt16LE(4) !== 1) continue;
142190
+ if (data.readUInt16LE(6) !== 24) continue;
142191
+ var millisecondsSince1970 = (data.readUInt32LE(8) + 4294967296 * data.readInt32LE(12)) / 1e4 - 0xa9730b66800;
142192
+ return new Date(millisecondsSince1970);
142193
+ }
142194
+ }
142195
+ return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime, options.timezone);
142196
+ };
142197
+ Entry.prototype.canDecodeFileData = function() {
142198
+ return !this.isEncrypted() && (this.compressionMethod === 0 || this.compressionMethod === 8);
142199
+ };
142200
+ Entry.prototype.isEncrypted = function() {
142201
+ return (this.generalPurposeBitFlag & 1) !== 0;
142202
+ };
142203
+ Entry.prototype.isCompressed = function() {
142204
+ return this.compressionMethod === 8;
142205
+ };
142206
+ function LocalFileHeader() {}
142207
+ function dosDateTimeToDate(date, time, timezone) {
142208
+ var day = date & 31;
142209
+ var month = (date >> 5 & 15) - 1;
142210
+ var year = (date >> 9 & 127) + 1980;
142211
+ var millisecond = 0;
142212
+ var second = (time & 31) * 2;
142213
+ var minute = time >> 5 & 63;
142214
+ var hour = time >> 11 & 31;
142215
+ if (timezone == null || timezone === "local") return new Date(year, month, day, hour, minute, second, millisecond);
142216
+ else if (timezone === "UTC") return new Date(Date.UTC(year, month, day, hour, minute, second, millisecond));
142217
+ else throw new Error("unrecognized options.timezone: " + options.timezone);
142218
+ }
142219
+ function getFileNameLowLevel(generalPurposeBitFlag, fileNameBuffer, extraFields, strictFileNames) {
142220
+ var fileName = null;
142221
+ for (var i = 0; i < extraFields.length; i++) {
142222
+ var extraField = extraFields[i];
142223
+ if (extraField.id === 28789) {
142224
+ if (extraField.data.length < 6) continue;
142225
+ if (extraField.data.readUInt8(0) !== 1) continue;
142226
+ var oldNameCrc32 = extraField.data.readUInt32LE(1);
142227
+ if (crc32(fileNameBuffer) !== oldNameCrc32) continue;
142228
+ fileName = decodeBuffer(extraField.data.subarray(5), true);
142229
+ break;
142230
+ }
142231
+ }
142232
+ if (fileName == null) fileName = decodeBuffer(fileNameBuffer, (generalPurposeBitFlag & 2048) !== 0);
142233
+ if (!strictFileNames) fileName = fileName.replace(/\\/g, "/");
142234
+ return fileName;
142235
+ }
142236
+ function validateFileName(fileName) {
142237
+ if (fileName.indexOf("\\") !== -1) return "invalid characters in fileName: " + fileName;
142238
+ if (/^[a-zA-Z]:/.test(fileName) || /^\//.test(fileName)) return "absolute path: " + fileName;
142239
+ if (fileName.split("/").indexOf("..") !== -1) return "invalid relative path: " + fileName;
142240
+ return null;
142241
+ }
142242
+ function parseExtraFields(extraFieldBuffer) {
142243
+ var extraFields = [];
142244
+ var i = 0;
142245
+ while (i < extraFieldBuffer.length - 3) {
142246
+ var headerId = extraFieldBuffer.readUInt16LE(i + 0);
142247
+ var dataSize = extraFieldBuffer.readUInt16LE(i + 2);
142248
+ var dataStart = i + 4;
142249
+ var dataEnd = dataStart + dataSize;
142250
+ if (dataEnd > extraFieldBuffer.length) throw new Error("extra field length exceeds extra field buffer size");
142251
+ var dataBuffer = extraFieldBuffer.subarray(dataStart, dataEnd);
142252
+ extraFields.push({
142253
+ id: headerId,
142254
+ data: dataBuffer
142255
+ });
142256
+ i = dataEnd;
142257
+ }
142258
+ return extraFields;
142259
+ }
142260
+ function readAndAssertNoEof(reader, buffer, offset, length, position, callback) {
142261
+ if (length === 0) return setImmediate(function() {
142262
+ callback(null, newBuffer(0));
142263
+ });
142264
+ reader.read(buffer, offset, length, position, function(err, bytesRead) {
142265
+ if (err) return callback(err);
142266
+ if (bytesRead < length) return callback(/* @__PURE__ */ new Error("unexpected EOF"));
142267
+ callback();
142268
+ });
142269
+ }
142270
+ util$2.inherits(AssertByteCountStream, Transform$2);
142271
+ function AssertByteCountStream(byteCount) {
142272
+ Transform$2.call(this);
142273
+ this.actualByteCount = 0;
142274
+ this.expectedByteCount = byteCount;
142275
+ }
142276
+ AssertByteCountStream.prototype._transform = function(chunk, encoding, cb) {
142277
+ this.actualByteCount += chunk.length;
142278
+ if (this.actualByteCount > this.expectedByteCount) {
142279
+ var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount;
142280
+ return cb(new Error(msg));
142281
+ }
142282
+ cb(null, chunk);
142283
+ };
142284
+ AssertByteCountStream.prototype._flush = function(cb) {
142285
+ if (this.actualByteCount < this.expectedByteCount) {
142286
+ var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount;
142287
+ return cb(new Error(msg));
142288
+ }
142289
+ cb();
142290
+ };
142291
+ util$2.inherits(RandomAccessReader, EventEmitter$1);
142292
+ function RandomAccessReader() {
142293
+ EventEmitter$1.call(this);
142294
+ this.refCount = 0;
142295
+ }
142296
+ RandomAccessReader.prototype.ref = function() {
142297
+ this.refCount += 1;
142298
+ };
142299
+ RandomAccessReader.prototype.unref = function() {
142300
+ var self = this;
142301
+ self.refCount -= 1;
142302
+ if (self.refCount > 0) return;
142303
+ if (self.refCount < 0) throw new Error("invalid unref");
142304
+ self.close(onCloseDone);
142305
+ function onCloseDone(err) {
142306
+ if (err) return self.emit("error", err);
142307
+ self.emit("close");
142308
+ }
142309
+ };
142310
+ RandomAccessReader.prototype.createReadStream = function(options) {
142311
+ if (options == null) options = {};
142312
+ var start = options.start;
142313
+ var end = options.end;
142314
+ if (start === end) {
142315
+ var emptyStream = new PassThrough$1();
142316
+ setImmediate(function() {
142317
+ emptyStream.end();
142318
+ });
142319
+ return emptyStream;
142320
+ }
142321
+ var stream = this._readStreamForRange(start, end);
142322
+ var destroyed = false;
142323
+ var refUnrefFilter = new RefUnrefFilter(this);
142324
+ stream.on("error", function(err) {
142325
+ setImmediate(function() {
142326
+ if (!destroyed) refUnrefFilter.emit("error", err);
142327
+ });
142328
+ });
142329
+ installDestroyFn(refUnrefFilter, function() {
142330
+ stream.unpipe(refUnrefFilter);
142331
+ refUnrefFilter.unref();
142332
+ stream.destroy();
142333
+ });
142334
+ var byteCounter = new AssertByteCountStream(end - start);
142335
+ refUnrefFilter.on("error", function(err) {
142336
+ setImmediate(function() {
142337
+ if (!destroyed) byteCounter.emit("error", err);
142338
+ });
142339
+ });
142340
+ installDestroyFn(byteCounter, function() {
142341
+ destroyed = true;
142342
+ refUnrefFilter.unpipe(byteCounter);
142343
+ refUnrefFilter.destroy();
142344
+ });
142345
+ return stream.pipe(refUnrefFilter).pipe(byteCounter);
142346
+ };
142347
+ RandomAccessReader.prototype._readStreamForRange = function(start, end) {
142348
+ throw new Error("not implemented");
142349
+ };
142350
+ RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) {
142351
+ var readStream = this.createReadStream({
142352
+ start: position,
142353
+ end: position + length
142354
+ });
142355
+ var writeStream = new Writable$1();
142356
+ var written = 0;
142357
+ writeStream._write = function(chunk, encoding, cb) {
142358
+ chunk.copy(buffer, offset + written, 0, chunk.length);
142359
+ written += chunk.length;
142360
+ cb();
142361
+ };
142362
+ writeStream.on("finish", callback);
142363
+ readStream.on("error", function(error) {
142364
+ callback(error);
142365
+ });
142366
+ readStream.pipe(writeStream);
142367
+ };
142368
+ RandomAccessReader.prototype.close = function(callback) {
142369
+ setImmediate(callback);
142370
+ };
142371
+ util$2.inherits(RefUnrefFilter, PassThrough$1);
142372
+ function RefUnrefFilter(context) {
142373
+ PassThrough$1.call(this);
142374
+ this.context = context;
142375
+ this.context.ref();
142376
+ this.unreffedYet = false;
142377
+ }
142378
+ RefUnrefFilter.prototype._flush = function(cb) {
142379
+ this.unref();
142380
+ cb();
142381
+ };
142382
+ RefUnrefFilter.prototype.unref = function(cb) {
142383
+ if (this.unreffedYet) return;
142384
+ this.unreffedYet = true;
142385
+ this.context.unref();
142386
+ };
142387
+ var cp437 = "\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0";
142388
+ function decodeBuffer(buffer, isUtf8) {
142389
+ if (isUtf8) return buffer.toString("utf8");
142390
+ else {
142391
+ var result = "";
142392
+ for (var i = 0; i < buffer.length; i++) result += cp437[buffer[i]];
142393
+ return result;
142394
+ }
142395
+ }
142396
+ function readUInt64LE(buffer, offset) {
142397
+ var lower32 = buffer.readUInt32LE(offset);
142398
+ return buffer.readUInt32LE(offset + 4) * 4294967296 + lower32;
142399
+ }
142400
+ var newBuffer;
142401
+ if (typeof Buffer.allocUnsafe === "function") newBuffer = function(len) {
142402
+ return Buffer.allocUnsafe(len);
142403
+ };
142404
+ else newBuffer = function(len) {
142405
+ return new Buffer(len);
142406
+ };
142407
+ function installDestroyFn(stream, fn) {
142408
+ if (typeof stream.destroy === "function") stream._destroy = function(err, cb) {
142409
+ fn();
142410
+ if (cb != null) cb(err);
142411
+ };
142412
+ else stream.destroy = fn;
142413
+ }
142414
+ function defaultCallback(err) {
142415
+ if (err) throw err;
142416
+ }
142417
+ }));
142418
+
142419
+ //#endregion
142420
+ //#region ../../packages/file-loaders/src/loaders/excel/zipBudget.ts
142421
+ var import_yauzl$1, DEFAULT_XLSX_ZIP_LIMITS, WORKSHEET_PART, isZip, preflightXlsxZip;
142422
+ var init_zipBudget = __esmMin((() => {
142423
+ import_yauzl$1 = /* @__PURE__ */ __toESM$2(require_yauzl());
142424
+ init_fileParseBudget();
142425
+ DEFAULT_XLSX_ZIP_LIMITS = {
142426
+ maxEntries: 5e3,
142427
+ maxInputBytes: 64 * 1024 * 1024,
142428
+ maxTotalBytes: 512 * 1024 * 1024,
142429
+ maxWorksheetBytes: 256 * 1024 * 1024
142430
+ };
142431
+ WORKSHEET_PART = /(?:^|\/)worksheets\/[^/]+\.xml$/i;
142432
+ isZip = (data) => data.length >= 4 && data[0] === 80 && data[1] === 75;
142433
+ preflightXlsxZip = (input, limits = DEFAULT_XLSX_ZIP_LIMITS) => {
142434
+ if (!isZip(input)) return Promise.resolve();
142435
+ if (input.byteLength > limits.maxInputBytes) return Promise.reject(new FileParseBudgetError("zip-input", limits.maxInputBytes, input.byteLength));
142436
+ const buffer = Buffer.isBuffer(input) ? input : Buffer.from(input.buffer, input.byteOffset, input.byteLength);
142437
+ return new Promise((resolve, reject) => {
142438
+ import_yauzl$1.fromBuffer(buffer, { lazyEntries: true }, (err, zipfile) => {
142439
+ if (err || !zipfile) return reject(err || /* @__PURE__ */ new Error("Failed to open zip from buffer"));
142440
+ let settled = false;
142441
+ let active;
142442
+ const finish = (error) => {
142443
+ if (settled) return;
142444
+ settled = true;
142445
+ active?.destroy();
142446
+ active = void 0;
142447
+ zipfile.close();
142448
+ if (error) reject(error);
142449
+ else resolve();
142450
+ };
142451
+ if (zipfile.entryCount > limits.maxEntries) return finish(new FileParseBudgetError("zip-entries", limits.maxEntries, zipfile.entryCount));
142452
+ let declaredTotal = 0;
142453
+ let inflatedTotal = 0;
142454
+ const checkSizes = (entryBytes, total, isSheet) => {
142455
+ if (isSheet && entryBytes > limits.maxWorksheetBytes) return new FileParseBudgetError("sheet-xml", limits.maxWorksheetBytes, entryBytes);
142456
+ if (total > limits.maxTotalBytes) return new FileParseBudgetError("zip-expansion", limits.maxTotalBytes, total);
142457
+ };
142458
+ zipfile.on("entry", (entry) => {
142459
+ const isSheet = WORKSHEET_PART.test(entry.fileName);
142460
+ declaredTotal += entry.uncompressedSize;
142461
+ const declaredError = checkSizes(entry.uncompressedSize, declaredTotal, isSheet);
142462
+ if (declaredError) return finish(declaredError);
142463
+ if (entry.fileName.endsWith("/")) return zipfile.readEntry();
142464
+ zipfile.openReadStream(entry, (streamErr, stream) => {
142465
+ if (streamErr || !stream) return finish(streamErr || /* @__PURE__ */ new Error("Failed to open entry"));
142466
+ if (settled) return stream.destroy();
142467
+ active = stream;
142468
+ let entryBytes = 0;
142469
+ stream.on("data", (chunk) => {
142470
+ entryBytes += chunk.length;
142471
+ inflatedTotal += chunk.length;
142472
+ const actualError = checkSizes(entryBytes, inflatedTotal, isSheet);
142473
+ if (actualError) finish(actualError);
142474
+ });
142475
+ stream.on("error", finish);
142476
+ stream.on("end", () => {
142477
+ if (settled) return;
142478
+ active = void 0;
142479
+ zipfile.readEntry();
142480
+ });
142481
+ });
142482
+ });
142483
+ zipfile.on("end", () => finish());
142484
+ zipfile.on("error", finish);
142485
+ zipfile.readEntry();
142486
+ });
142487
+ });
142488
+ };
142489
+ }));
142490
+
140777
142491
  //#endregion
140778
142492
  //#region ../../packages/file-loaders/src/loaders/excel/index.ts
140779
142493
  var excel_exports = /* @__PURE__ */ __exportAll$2({ ExcelLoader: () => ExcelLoader });
@@ -140782,9 +142496,9 @@ var excel_exports = /* @__PURE__ */ __exportAll$2({ ExcelLoader: () => ExcelLoad
140782
142496
  * Handles empty sheets and escapes pipe characters.
140783
142497
  */
140784
142498
  function sheetToMarkdownTable(jsonData) {
140785
- log$8("Converting sheet data to Markdown table, rows:", jsonData?.length || 0);
142499
+ log$7("Converting sheet data to Markdown table, rows:", jsonData?.length || 0);
140786
142500
  if (!jsonData || jsonData.length === 0) {
140787
- log$8("Sheet is empty, returning placeholder message");
142501
+ log$7("Sheet is empty, returning placeholder message");
140788
142502
  return "*Sheet is empty or contains no data.*";
140789
142503
  }
140790
142504
  const toCell = (value) => value === null || value === void 0 ? "" : String(value).replaceAll("|", "\\|").trim();
@@ -140795,57 +142509,62 @@ function sheetToMarkdownTable(jsonData) {
140795
142509
  * workbook into 60+ MB of `| | |` text.
140796
142510
  */
140797
142511
  const headers = Object.keys(jsonData[0] || {}).filter((header) => !header.startsWith("__EMPTY") || jsonData.some((row) => toCell(row[header]) !== ""));
140798
- log$8("Sheet headers:", headers);
142512
+ log$7("Sheet headers:", headers);
140799
142513
  if (headers.length === 0) {
140800
- log$8("Sheet has no headers, returning placeholder message");
142514
+ log$7("Sheet has no headers, returning placeholder message");
140801
142515
  return "*Sheet has headers but no data.*";
140802
142516
  }
140803
142517
  const headerRow = `| ${headers.join(" | ")} |`;
140804
142518
  const separatorRow = `| ${headers.map(() => "---").join(" | ")} |`;
140805
- log$8("Building data rows for Markdown table");
142519
+ log$7("Building data rows for Markdown table");
140806
142520
  const result = `${headerRow}\n${separatorRow}\n${jsonData.map((row) => headers.map((header) => toCell(row[header]))).filter((cells) => cells.some((cell) => cell !== "")).map((cells) => `| ${cells.join(" | ")} |`).join("\n")}`;
140807
- log$8("Markdown table created, length:", result.length);
142521
+ log$7("Markdown table created, length:", result.length);
140808
142522
  return result;
140809
142523
  }
140810
- var import_src$3, log$8, ExcelLoader;
142524
+ var import_src$2, log$7, ExcelLoader;
140811
142525
  var init_excel = __esmMin((() => {
140812
- import_src$3 = /* @__PURE__ */ __toESM$2(require_src());
142526
+ import_src$2 = /* @__PURE__ */ __toESM$2(require_src());
140813
142527
  init_xlsx();
142528
+ init_fileParseBudget();
140814
142529
  init_prompt$1();
140815
- log$8 = (0, import_src$3.default)("file-loaders:excel");
142530
+ init_sheetBounds();
142531
+ init_zipBudget();
142532
+ log$7 = (0, import_src$2.default)("file-loaders:excel");
140816
142533
  ExcelLoader = class {
140817
142534
  async loadPages(filePath) {
140818
- log$8("Loading Excel file:", filePath);
142535
+ log$7("Loading Excel file:", filePath);
140819
142536
  const pages = [];
140820
142537
  try {
140821
- log$8("Reading Excel file as buffer");
142538
+ log$7("Reading Excel file as buffer");
140822
142539
  const dataBuffer = await readFile(filePath);
140823
- log$8("Excel file read successfully, size:", dataBuffer.length, "bytes");
140824
- log$8("Parsing Excel workbook");
142540
+ log$7("Excel file read successfully, size:", dataBuffer.length, "bytes");
142541
+ await preflightXlsxZip(dataBuffer);
142542
+ log$7("Parsing Excel workbook");
140825
142543
  const workbook = readSync$1(dataBuffer, { type: "buffer" });
140826
- log$8("Excel workbook parsed successfully, sheets:", workbook.SheetNames.length);
142544
+ log$7("Excel workbook parsed successfully, sheets:", workbook.SheetNames.length);
140827
142545
  for (const sheetName of workbook.SheetNames) {
140828
- log$8(`Processing sheet: ${sheetName}`);
142546
+ log$7(`Processing sheet: ${sheetName}`);
140829
142547
  const worksheet = workbook.Sheets[sheetName];
142548
+ clampSheetRefToData(worksheet);
140830
142549
  const jsonData = utils.sheet_to_json(worksheet, {
140831
142550
  defval: "",
140832
142551
  raw: false
140833
142552
  });
140834
- log$8(`Sheet ${sheetName} converted to JSON, rows:`, jsonData.length);
142553
+ log$7(`Sheet ${sheetName} converted to JSON, rows:`, jsonData.length);
140835
142554
  const tableMarkdown = sheetToMarkdownTable(jsonData);
140836
142555
  const lineCount = tableMarkdown.split("\n").length;
140837
142556
  const charCount = tableMarkdown.length;
140838
- log$8(`Sheet ${sheetName} converted to Markdown, lines: ${lineCount}, chars: ${charCount}`);
142557
+ log$7(`Sheet ${sheetName} converted to Markdown, lines: ${lineCount}, chars: ${charCount}`);
140839
142558
  pages.push({
140840
142559
  charCount,
140841
142560
  lineCount,
140842
142561
  metadata: { sheetName },
140843
142562
  pageContent: tableMarkdown.trim()
140844
142563
  });
140845
- log$8(`Added sheet ${sheetName} as page`);
142564
+ log$7(`Added sheet ${sheetName} as page`);
140846
142565
  }
140847
142566
  if (pages.length === 0) {
140848
- log$8("Excel file contains no sheets, creating empty page with error");
142567
+ log$7("Excel file contains no sheets, creating empty page with error");
140849
142568
  pages.push({
140850
142569
  charCount: 0,
140851
142570
  lineCount: 0,
@@ -140853,11 +142572,12 @@ var init_excel = __esmMin((() => {
140853
142572
  pageContent: ""
140854
142573
  });
140855
142574
  }
140856
- log$8("Excel loading completed, total pages:", pages.length);
142575
+ log$7("Excel loading completed, total pages:", pages.length);
140857
142576
  return pages;
140858
142577
  } catch (e) {
142578
+ if (isFileParseBudgetError(e)) throw e;
140859
142579
  const error = e;
140860
- log$8("Error encountered while loading Excel file");
142580
+ log$7("Error encountered while loading Excel file");
140861
142581
  console.error(`Error loading Excel file ${filePath}: ${error.message}`);
140862
142582
  const errorPage = {
140863
142583
  charCount: 0,
@@ -140865,7 +142585,7 @@ var init_excel = __esmMin((() => {
140865
142585
  metadata: { error: `Failed to load Excel file: ${error.message}` },
140866
142586
  pageContent: ""
140867
142587
  };
140868
- log$8("Created error page for failed Excel loading");
142588
+ log$7("Created error page for failed Excel loading");
140869
142589
  return [errorPage];
140870
142590
  }
140871
142591
  }
@@ -140876,288 +142596,14 @@ var init_excel = __esmMin((() => {
140876
142596
  * @returns Aggregated content as a string.
140877
142597
  */
140878
142598
  async aggregateContent(pages) {
140879
- log$8("Aggregating content from", pages.length, "Excel pages");
142599
+ log$7("Aggregating content from", pages.length, "Excel pages");
140880
142600
  const result = promptTemplate$1(pages);
140881
- log$8("Excel content aggregated successfully, length:", result.length);
142601
+ log$7("Excel content aggregated successfully, length:", result.length);
140882
142602
  return result;
140883
142603
  }
140884
142604
  };
140885
142605
  }));
140886
142606
 
140887
- //#endregion
140888
- //#region ../../packages/utils/src/isBinaryContent.ts
140889
- var NON_PRINTABLE_THRESHOLD, hasUtf8Bom, hasUtf16Bom, sniffBinaryBuffer, REPLACEMENT_CHAR, checkPrintableRatio;
140890
- var init_isBinaryContent = __esmMin((() => {
140891
- init_detectUtf16();
140892
- NON_PRINTABLE_THRESHOLD = .3;
140893
- hasUtf8Bom = (buf) => buf.length >= 3 && buf[0] === 239 && buf[1] === 187 && buf[2] === 191;
140894
- hasUtf16Bom = (buf) => buf.length >= 2 && (buf[0] === 255 && buf[1] === 254 || buf[0] === 254 && buf[1] === 255);
140895
- sniffBinaryBuffer = (buffer) => {
140896
- if (buffer.length === 0) return { isBinary: false };
140897
- if (hasUtf8Bom(buffer) || hasUtf16Bom(buffer)) return { isBinary: false };
140898
- const utf16Variant = detectUtf16NoBom(buffer);
140899
- if (utf16Variant) return checkPrintableRatio(new TextDecoder(utf16Variant, { fatal: false }).decode(buffer), buffer.length);
140900
- if (buffer.includes(0)) return {
140901
- isBinary: true,
140902
- reason: "contains null byte"
140903
- };
140904
- return checkPrintableRatio(new TextDecoder("utf-8", { fatal: false }).decode(buffer), buffer.length);
140905
- };
140906
- REPLACEMENT_CHAR = "�";
140907
- checkPrintableRatio = (text, sampledBytes) => {
140908
- if (text.length === 0) return { isBinary: false };
140909
- let suspect = 0;
140910
- for (const ch of text) {
140911
- if (ch === REPLACEMENT_CHAR) {
140912
- suspect++;
140913
- continue;
140914
- }
140915
- const code = ch.codePointAt(0);
140916
- if (code < 32 && code !== 9 && code !== 10 && code !== 13) suspect++;
140917
- }
140918
- const ratio = suspect / text.length;
140919
- if (ratio > NON_PRINTABLE_THRESHOLD) return {
140920
- isBinary: true,
140921
- reason: `${(ratio * 100).toFixed(1)}% non-printable chars in first ${sampledBytes} bytes`
140922
- };
140923
- return { isBinary: false };
140924
- };
140925
- }));
140926
-
140927
- //#endregion
140928
- //#region ../../packages/file-loaders/src/loaders/ipynb/index.ts
140929
- var ipynb_exports = /* @__PURE__ */ __exportAll$2({
140930
- IpynbLoader: () => IpynbLoader,
140931
- convertIpynbToMarkdown: () => convertIpynbToMarkdown,
140932
- scrubIpynbFallbackText: () => scrubIpynbFallbackText
140933
- });
140934
- var import_src$2, log$7, SCRIPT_TAG_RE, ANSI_RE, MIME_TOKEN, DATA_URI_RE, BASE64_RUN_RE, BASE64_SEPARATOR_RE, NON_BASE64_RE, BASE64_SCRUB_THRESHOLD, joinSource, cleanStreamText, STYLE_BOUNDARY, stripStyleTags, humanSize, humanChars, base64Bytes, scrubDataUris, base64Placeholder, scrubIpynbFallbackText, singleLine, fence, convertOutput, isNotebookCell, convertCell, convertIpynbToBlocks, convertIpynbToMarkdown, BinaryNotebookError, IpynbLoader;
140935
- var init_ipynb = __esmMin((() => {
140936
- init_isBinaryContent();
140937
- import_src$2 = /* @__PURE__ */ __toESM$2(require_src());
140938
- log$7 = (0, import_src$2.default)("file-loaders:ipynb");
140939
- SCRIPT_TAG_RE = /<script[\t\n\f\r />]/i;
140940
- ANSI_RE = /\u001B\[[\d:;?]*[\u0020-\u002F]*[\u0040-\u007E]|\u001B\][^\u0007\u001B\u009C]{0,256}(?:\u0007|\u001B\\)?|\u001B[\u0021-\u002F]{0,2}[\u0030-\u007E]|[\u001B\u0007\u009C]/g;
140941
- MIME_TOKEN = "[^\\s()<>@,;:\\\\\"/\\[\\]?=]+";
140942
- DATA_URI_RE = new RegExp(`data:(${MIME_TOKEN}/${MIME_TOKEN})?(?:;${MIME_TOKEN}=${MIME_TOKEN})*;base64,([\\d+/=A-Za-z]{256,})`, "gi");
140943
- BASE64_RUN_RE = /[\d+/=A-Za-z]{32,}(?:(?:"[\s,]*"|\\n|\r?\n)+[\d+/=A-Za-z]{32,})*/g;
140944
- BASE64_SEPARATOR_RE = /((?:"[\s,]*"|\\n|\r?\n)+)/;
140945
- NON_BASE64_RE = /[^\d+/=A-Z]/gi;
140946
- BASE64_SCRUB_THRESHOLD = 1024;
140947
- joinSource = (source) => Array.isArray(source) ? source.filter((part) => typeof part === "string").join("") : typeof source === "string" ? source : "";
140948
- cleanStreamText = (text) => text.replaceAll(ANSI_RE, "").replaceAll("\r\n", "\n").split("\n").map((line) => {
140949
- return line.split("\r").filter((frame) => frame !== "").at(-1) ?? "";
140950
- }).join("\n");
140951
- STYLE_BOUNDARY = new Set([
140952
- 9,
140953
- 10,
140954
- 12,
140955
- 13,
140956
- 32,
140957
- 47,
140958
- 62
140959
- ]);
140960
- stripStyleTags = (html) => {
140961
- const openRe = /<style/gi;
140962
- const closeRe = /<\/style[\t\n\f\r ]*>/gi;
140963
- let result = "";
140964
- let pos = 0;
140965
- while (pos < html.length) {
140966
- openRe.lastIndex = pos;
140967
- const open = openRe.exec(html);
140968
- if (open === null) {
140969
- result += html.slice(pos);
140970
- break;
140971
- }
140972
- if (!STYLE_BOUNDARY.has(html.charCodeAt(open.index + 6))) {
140973
- result += html.slice(pos, open.index + 6);
140974
- pos = open.index + 6;
140975
- continue;
140976
- }
140977
- result += html.slice(pos, open.index);
140978
- closeRe.lastIndex = open.index;
140979
- const close = closeRe.exec(html);
140980
- if (close === null) break;
140981
- pos = close.index + close[0].length;
140982
- }
140983
- return result;
140984
- };
140985
- humanSize = (bytes) => bytes >= 1024 ? `${Math.round(bytes / 1024)} KB` : `${bytes} B`;
140986
- humanChars = (chars) => chars >= 1024 ? `${Math.round(chars / 1024)}k chars` : `${chars} chars`;
140987
- base64Bytes = (payload) => {
140988
- const clean = payload.replaceAll(NON_BASE64_RE, "");
140989
- const padding = Math.min(2, (clean.match(/=*$/) ?? [""])[0].length);
140990
- return Math.floor(clean.length * 3 / 4) - padding;
140991
- };
140992
- scrubDataUris = (text) => text.replaceAll(DATA_URI_RE, (_match, mime, payload) => `data:${mime ?? "unknown"};base64,[${humanSize(base64Bytes(payload))} omitted]`);
140993
- base64Placeholder = (payload) => `[base64 payload — ${humanSize(base64Bytes(payload))}, omitted]`;
140994
- scrubIpynbFallbackText = (raw) => raw.replaceAll(BASE64_RUN_RE, (match) => {
140995
- const parts = match.split(BASE64_SEPARATOR_RE);
140996
- if (parts.length > 1) {
140997
- const segments = parts.filter((_, index) => index % 2 === 0);
140998
- const payload = segments.join("");
140999
- if (segments.slice(0, -1).every((segment) => segment.length === 76) && payload.length >= BASE64_SCRUB_THRESHOLD) return base64Placeholder(payload);
141000
- return parts.map((part, index) => index % 2 === 0 && part.length >= BASE64_SCRUB_THRESHOLD ? base64Placeholder(part) : part).join("");
141001
- }
141002
- if (match.length < BASE64_SCRUB_THRESHOLD) return match;
141003
- return base64Placeholder(match);
141004
- });
141005
- singleLine = (text) => text.replaceAll(/[`\r\n]+/g, " ").trim();
141006
- fence = (body, language = "") => {
141007
- let longest = 0;
141008
- for (const run of body.match(/`{3,}/g) ?? []) if (run.length > longest) longest = run.length;
141009
- const ticks = "`".repeat(longest > 0 ? longest + 1 : 3);
141010
- return [
141011
- ticks + language,
141012
- body,
141013
- ticks
141014
- ].join("\n");
141015
- };
141016
- convertOutput = (output) => {
141017
- switch (output.output_type) {
141018
- case "stream": {
141019
- const body = cleanStreamText(joinSource(output.text));
141020
- return body.trim() ? fence(body) : "";
141021
- }
141022
- case "error": {
141023
- const traceback = cleanStreamText((Array.isArray(output.traceback) ? output.traceback : []).filter((line) => typeof line === "string").join("\n"));
141024
- return [`**Error:** \`${output.ename ?? ""}: ${output.evalue ?? ""}\``, fence(traceback)].join("\n");
141025
- }
141026
- case "display_data":
141027
- case "execute_result": {
141028
- const data = output.data ?? {};
141029
- if ("application/vnd.jupyter.widget-view+json" in data) return "`[interactive widget — omitted]`";
141030
- const html = data["text/html"];
141031
- if (html !== void 0) {
141032
- const htmlText = joinSource(html);
141033
- if (SCRIPT_TAG_RE.test(htmlText)) return `\`[interactive HTML output (script) — ${humanChars(htmlText.length)}, omitted]\``;
141034
- return scrubDataUris(stripStyleTags(htmlText)).trim();
141035
- }
141036
- const svg = data["image/svg+xml"];
141037
- if (svg !== void 0) {
141038
- const svgText = joinSource(svg);
141039
- if (SCRIPT_TAG_RE.test(svgText)) return `\`[svg output (script) — ${humanChars(svgText.length)}, omitted]\``;
141040
- return scrubDataUris(svgText).trim();
141041
- }
141042
- for (const mime of Object.keys(data)) if (mime.startsWith("image/")) return `![${mime} output — ${humanSize(base64Bytes(joinSource(data[mime])))}, omitted]`;
141043
- const markdown = data["text/markdown"];
141044
- if (markdown !== void 0) return scrubDataUris(joinSource(markdown));
141045
- for (const mime of Object.keys(data)) if (mime.startsWith("text/")) {
141046
- const body = joinSource(data[mime]);
141047
- return body.trim() ? fence(body) : "";
141048
- }
141049
- return `\`[${Object.keys(data).join(", ") || "unknown"} output — omitted]\``;
141050
- }
141051
- default: return "";
141052
- }
141053
- };
141054
- isNotebookCell = (cell) => {
141055
- if (!cell || typeof cell !== "object") return false;
141056
- const { cell_type: cellType, source } = cell;
141057
- if (typeof cellType !== "string") return false;
141058
- return source === void 0 || typeof source === "string" || Array.isArray(source) && source.every((part) => typeof part === "string");
141059
- };
141060
- convertCell = (cell, language) => {
141061
- const source = joinSource(cell.source);
141062
- switch (cell.cell_type) {
141063
- case "markdown": return scrubDataUris(source);
141064
- case "raw": return fence(scrubDataUris(source));
141065
- case "code": {
141066
- const blocks = [`${`**In [${cell.execution_count ?? " "}]:**`}\n${fence(source, language)}`];
141067
- const outputs = (cell.outputs ?? []).map(convertOutput).filter(Boolean);
141068
- if (outputs.length > 0) blocks.push(`**Output:**\n${outputs.join("\n\n")}`);
141069
- return blocks.join("\n\n");
141070
- }
141071
- default: return source.trim() ? fence(scrubDataUris(source)) : void 0;
141072
- }
141073
- };
141074
- convertIpynbToBlocks = (raw) => {
141075
- let notebook;
141076
- try {
141077
- notebook = JSON.parse(raw.replace(/^\uFEFF/, ""));
141078
- } catch {
141079
- return null;
141080
- }
141081
- if (!notebook || typeof notebook !== "object" || !Array.isArray(notebook.cells)) return null;
141082
- if (!Number.isInteger(notebook.nbformat) || notebook.nbformat < 4) return null;
141083
- if (!notebook.cells.every(isNotebookCell)) return null;
141084
- try {
141085
- const languageInfo = notebook.metadata?.language_info;
141086
- const languageName = typeof languageInfo?.name === "string" ? languageInfo.name : void 0;
141087
- const language = languageName?.match(/^[\w#+.-]+/)?.[0] ?? "python";
141088
- const kernel = notebook.metadata?.kernelspec?.display_name ?? notebook.metadata?.kernelspec?.name;
141089
- const headerBits = ["Jupyter notebook"];
141090
- if (typeof kernel === "string" && kernel) headerBits.push(`kernel: ${singleLine(kernel)}`);
141091
- if (languageName) headerBits.push(`language: ${singleLine(languageName)}${typeof languageInfo?.version === "string" && languageInfo.version ? ` ${singleLine(languageInfo.version)}` : ""}`);
141092
- const blocks = [`> ${headerBits.join(" · ")}`];
141093
- for (const cell of notebook.cells) {
141094
- const block = convertCell(cell, language);
141095
- if (block !== void 0 && block.trim()) blocks.push(block);
141096
- }
141097
- return blocks;
141098
- } catch {
141099
- return null;
141100
- }
141101
- };
141102
- convertIpynbToMarkdown = (raw) => {
141103
- const blocks = convertIpynbToBlocks(raw);
141104
- return blocks === null ? null : blocks.join("\n\n");
141105
- };
141106
- BinaryNotebookError = class extends Error {};
141107
- IpynbLoader = class {
141108
- async loadPages(filePath) {
141109
- log$7("Loading ipynb file:", filePath);
141110
- try {
141111
- const buffer = await readFile(filePath);
141112
- const sniff = sniffBinaryBuffer(buffer.subarray(0, 8192));
141113
- if (sniff.isBinary) {
141114
- log$7("Rejecting binary content: %s", sniff.reason);
141115
- throw new BinaryNotebookError(`Binary content in .ipynb file: ${sniff.reason}`);
141116
- }
141117
- const raw = buffer.toString("utf8").replace(/^\uFEFF/, "");
141118
- const blocks = convertIpynbToBlocks(raw);
141119
- if (blocks === null) {
141120
- log$7("Not nbformat v4 JSON, falling back to scrubbed raw text");
141121
- const fallback = scrubIpynbFallbackText(raw);
141122
- const lines = fallback.split("\n");
141123
- return [{
141124
- charCount: fallback.length,
141125
- lineCount: lines.length,
141126
- metadata: {
141127
- lineNumberEnd: lines.length,
141128
- lineNumberStart: 1
141129
- },
141130
- pageContent: fallback
141131
- }];
141132
- }
141133
- log$7("Converted notebook into %d blocks", blocks.length);
141134
- return blocks.map((block, index) => ({
141135
- charCount: block.length,
141136
- lineCount: block.split("\n").length,
141137
- metadata: {
141138
- chunkIndex: index,
141139
- totalChunks: blocks.length
141140
- },
141141
- pageContent: block
141142
- }));
141143
- } catch (e) {
141144
- const error = e;
141145
- if (error instanceof BinaryNotebookError) throw error;
141146
- console.error(`Error loading ipynb file ${filePath}: ${error.message}`);
141147
- return [{
141148
- charCount: 0,
141149
- lineCount: 0,
141150
- metadata: { error: `Failed to load ipynb file: ${error.message}` },
141151
- pageContent: ""
141152
- }];
141153
- }
141154
- }
141155
- async aggregateContent(pages) {
141156
- return pages.map((page) => page.pageContent).join("\n\n");
141157
- }
141158
- };
141159
- }));
141160
-
141161
142607
  //#endregion
141162
142608
  //#region ../../packages/file-loaders/src/loaders/pdf/domMatrix.ts
141163
142609
  var IDENTITY, readInit, compose, DOMMatrixPolyfill, installDomMatrixPolyfill;
@@ -175232,7 +176678,7 @@ async function incrementalUpdate({ originalData, xrefInfo, changes, xref = null,
175232
176678
  for (const str of buffer) offset = writeString(str, offset, array);
175233
176679
  return array;
175234
176680
  }
175235
- var __webpack_modules__, __webpack_module_cache__, isNodeJS, FONT_IDENTITY_MATRIX, LINE_FACTOR, LINE_DESCENT_FACTOR, BASELINE_FACTOR, RenderingIntentFlag, AnnotationEditorPrefix, AnnotationEditorType, PermissionFlag, MeshFigureType, TextRenderingMode, ImageKind, AnnotationType, AnnotationReplyType, AnnotationFlag, AnnotationFieldFlag, AnnotationBorderStyleType, AnnotationActionEventType, DocumentActionEventType, PageActionEventType, VerbosityLevel, OPS, DrawOPS, PasswordResponses, verbosity, BaseException, PasswordException, UnknownErrorException, InvalidPDFException, ResponseException, FormatError, AbortException, FeatureTest, hexNumbers, Util, PDFStringTranslateTable, NormalizeRegex, NormalizationMap, AnnotationPrefix, CIRCULAR_REF, EOF, CmdCache, NameCache, RefCache, Name, Cmd, nonSerializable, Dict, Ref, RefSet, RefSetCache, BaseStream, PDF_VERSION_REGEXP, MAX_INT_32, MIN_INT_32, IDENTITY_MATRIX, RESOURCES_KEYS_OPERATOR_LIST, RESOURCES_KEYS_TEXT_CONTENT, MissingDataException, ParserEOFException, XRefEntryException, XRefParseException, ROMAN_NUMBER_MAP, XMLEntities, QCMS, wasm, cachedTextDecoder, cachedUint8ArrayMemory0, WASM_VECTOR_LEN, DataType, Intent, ColorSpace, AlternateCS, PatternCS, IndexedCS, DeviceGrayCS, DeviceRgbCS, DeviceRgbaCS, DeviceCmykCS, CalGrayCS, CalRGBCS, LabCS, IccColorSpace, CmykICCBasedCS, Stream$1, StringStream, NullStream, ChunkedStream, ChunkedStreamManager, MIN_IMAGE_DIM, MAX_IMAGE_DIM, MAX_ERROR, ImageResizer, emptyBuffer$1, DecodeStream, StreamsSequenceStream, ColorSpaceUtils, JpegError, DNLMarkerError, EOIMarkerError, dctZigZag, dctCos1, dctSin1, dctCos3, dctSin3, dctCos6, dctSin6, dctSqrt2, dctSqrt1d2, JpegImage, JpegStream, openjpeg, JpxError, JpxImage, InitialState, NullOptimizer, QueueOptimizer, OperatorList, MAX_NUM_SIZE, MAX_ENCODED_NUM_SIZE, BinaryCMapStream, BinaryCMapReader, Ascii85Stream, AsciiHexStream, ccittEOL, ccittEOF, twoDimPass, twoDimHoriz, twoDimVert0, twoDimVertR1, twoDimVertL1, twoDimVertR2, twoDimVertL2, twoDimVertR3, twoDimVertL3, twoDimTable, whiteTable1, whiteTable2, blackTable1, blackTable2, blackTable3, CCITTFaxDecoder, CCITTFaxStream, codeLenCodeMap, lengthDecode, distDecode, fixedLitCodeTab, fixedDistCodeTab, FlateStream, QeTable, ArithmeticDecoder, Jbig2Error, ContextCache, DecodingContext, SegmentTypes, CodingTemplates, RefinementTemplates, ReusedContexts, RefinementReusedContexts, RegionSegmentInformationFieldLength, SimpleSegmentVisitor, HuffmanLine, HuffmanTreeNode, HuffmanTable, standardTablesCache, Reader, Jbig2Image, Jbig2Stream, JpxStream, LZWStream, PredictorStream, RunLengthStream, MAX_LENGTH_TO_CACHE, Parser, specialChars, Lexer, Linearization, BUILT_IN_CMAPS, MAX_MAP_RANGE, CMap, IdentityCMap, CMapFactory, ExpertEncoding, MacExpertEncoding, MacRomanEncoding, StandardEncoding, WinAnsiEncoding, SymbolSetEncoding, ZapfDingbatsEncoding, getGlyphsUnicode, getDingbatsGlyphsUnicode, getSpecialPUASymbols, UnicodeRanges, SpecialCharRegExp, CategoryCache, SEAC_ANALYSIS_ENABLED, FontFlags, MacStandardGlyphOrdering, getVerticalPresentationForm, MAX_SIZE_TO_COMPILE, ISOAdobeCharset, ExpertCharset, ExpertSubsetCharset, MAX_SUBR_NESTING, CFFStandardStrings, NUM_STANDARD_CFF_STRINGS, CharstringValidationData, CharstringValidationData12, CFFParser, CFF, CFFHeader, CFFStrings, CFFIndex, CFFDict, CFFTopDictLayout, CFFTopDict, CFFPrivateDictLayout, CFFPrivateDict, CFFCharsetPredefinedTypes, CFFCharset, CFFEncoding, CFFFDSelect, CFFOffsetTracker, CFFCompiler, getStdFontMap, getFontNameToFileMap, getNonStdFontMap, getSerifFonts, getSymbolsFonts, getGlyphMapForStandardFonts, getSupplementalGlyphMapForArialBlack, getSupplementalGlyphMapForCalibri, ToUnicodeMap, IdentityToUnicodeMap, CFFFont, NOOP, Commands, CompiledFont, TrueTypeCompiled, Type2Compiled, FontRendererFactory, getMetrics, getFontBasicMetrics, ON_CURVE_POINT, X_SHORT_VECTOR, Y_SHORT_VECTOR, REPEAT_FLAG, X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR, Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR, OVERLAP_SIMPLE, ARG_1_AND_2_ARE_WORDS, ARGS_ARE_XY_VALUES, WE_HAVE_A_SCALE, MORE_COMPONENTS, WE_HAVE_AN_X_AND_Y_SCALE, WE_HAVE_A_TWO_BY_TWO, WE_HAVE_INSTRUCTIONS, GlyfTable, Glyph, GlyphHeader, Contour, SimpleGlyph, CompositeGlyph, OTF_HEADER_SIZE, OTF_TABLE_ENTRY_SIZE, OpenTypeFileBuilder, HINTING_ENABLED, COMMAND_MAP, Type1CharString, EEXEC_ENCRYPT_KEY, CHAR_STRS_ENCRYPT_KEY, Type1Parser, Type1Font, PRIVATE_USE_AREAS, PDF_GLYPH_SPACE_UNITS, EXPORT_DATA_PROPERTIES, EXPORT_DATA_EXTRA_PROPERTIES, fonts_Glyph, Font, ErrorFont, CssFontInfo, SystemFontInfo, FontInfo, PatternInfo, FontPathInfo, ShadingType, Pattern, BaseShading, RadialAxialShading, MeshStreamReader, bCache, MeshShading, DummyShading, CalibriBoldFactors, CalibriBoldMetrics, CalibriBoldItalicFactors, CalibriBoldItalicMetrics, CalibriItalicFactors, CalibriItalicMetrics, CalibriRegularFactors, CalibriRegularMetrics, HelveticaBoldFactors, HelveticaBoldMetrics, HelveticaBoldItalicFactors, HelveticaBoldItalicMetrics, HelveticaItalicFactors, HelveticaItalicMetrics, HelveticaRegularFactors, HelveticaRegularMetrics, LiberationSansBoldWidths, LiberationSansBoldMapping, LiberationSansBoldItalicWidths, LiberationSansBoldItalicMapping, LiberationSansItalicWidths, LiberationSansItalicMapping, LiberationSansRegularWidths, LiberationSansRegularMapping, MyriadProBoldFactors, MyriadProBoldMetrics, MyriadProBoldItalicFactors, MyriadProBoldItalicMetrics, MyriadProItalicFactors, MyriadProItalicMetrics, MyriadProRegularFactors, MyriadProRegularMetrics, SegoeuiBoldFactors, SegoeuiBoldMetrics, SegoeuiBoldItalicFactors, SegoeuiBoldItalicMetrics, SegoeuiItalicFactors, SegoeuiItalicMetrics, SegoeuiRegularFactors, SegoeuiRegularMetrics, getXFAFontMap, PostScriptParser, PostScriptTokenTypes, PostScriptToken, PostScriptLexer, BaseLocalCache, LocalImageCache, LocalColorSpaceCache, LocalFunctionCache, LocalGStateCache, LocalTilingPatternCache, RegionalImageCache, GlobalColorSpaceCache, GlobalImageCache, PDFFunctionFactory, PDFFunction, PostScriptStack, PostScriptEvaluator, AstNode, AstArgument, AstLiteral, AstBinaryOperation, AstMin, AstVariable, AstVariableDefinition, ExpressionBuilderVisitor, PostScriptCompiler, baseTypes, arabicTypes, chars, types, NORMAL, BOLD, ITALIC, BOLDITALIC, substitutionMap, fontAliases, SEED, MASK_HIGH, MASK_LOW, MurmurHash3_64, PDFImage, DefaultPartialEvaluatorOptions, PatternType, TEXT_CHUNK_BATCH_SIZE, deferred, TimeSlotManager, PartialEvaluator, TranslatedFont, StateManager, TextState, EvalState, EvaluatorPreprocessor, DefaultAppearanceEvaluator, AppearanceStreamEvaluator, FakeUnicodeFont, DateFormats, TimeFormats, NameOrNumberTree, NameTree, NumberTree, FileSpec, XMLParserErrorCode, XMLParserBase, SimpleDOMNode, SimpleXMLParser, MetadataParser, MAX_DEPTH, StructElementType, StructTreeRoot, StructElementNode, StructElement, StructTreePage, isRef, isValidExplicitDest, Catalog, ObjectLoader, $acceptWhitespace, $addHTML, $appendChild, $childrenToHTML, $clean, $cleanPage, $cleanup, $clone, $consumed, $content, $data, $dump, $extra, $finalize, $flushHTML, $getAttributeIt, $getAttributes, $getAvailableSpace, $getChildrenByClass, $getChildrenByName, $getChildrenByNameIt, $getDataValue, $getExtra, $getRealChildrenByNameIt, $getChildren, $getContainedChildren, $getNextPage, $getSubformParent, $getParent, $getTemplateRoot, $globalData, $hasSettableValue, $ids, $indexOf, $insertAt, $isCDATAXml, $isBindable, $isDataValue, $isDescendent, $isNsAgnostic, $isSplittable, $isThereMoreWidth, $isTransparent, $isUsable, $lastAttribute, $namespaceId, $nodeName, $nsAttributes, $onChild, $onChildCheck, $onText, $pushGlyphs, $popPara, $pushPara, $removeChild, $root, $resolvePrototypes, $searchNode, $setId, $setSetAttributes, $setValue, $tabIndex, $text, $toPages, $toHTML, $toString, $toStyle, $uid, $buildXFAObject, NamespaceIds, dimConverters, measurementPattern, HTMLResult, FontFinder, WIDTH_FACTOR, text_FontInfo, FontSelector, TextMeasure, namePattern, indexPattern, operators, shortcuts, somCache, _applyPrototype, _attributes, _attributeNames, _children, _cloneAttribute, _dataValue, _defaultValue, _filteredChildrenGenerator, _getPrototype, _getUnsetAttributes, _hasChildren, _max, _options, _parent, _resolvePrototypesHelper, _setAttributes, _validator, uid, NS_DATASETS, XFAObject, XFAObjectArray, XFAAttribute, XmlObject, ContentObject, OptionObject, StringObject, IntegerObject, Option01, Option10, converters, TEMPLATE_NS_ID, SVG_NS, MAX_ATTEMPTS_FOR_LRTB_LAYOUT, MAX_EMPTY_PAGES, DEFAULT_TAB_INDEX, HEADING_PATTERN, MIMES, IMAGES_HEADERS, AppearanceFilter, Arc, Area, Assist, Barcode, Bind, BindItems, Bookend, BooleanElement, Border, Break, BreakAfter, BreakBefore, Button, Calculate, Caption, Certificate, Certificates, CheckButton, ChoiceList, Color, Comb, Connect, ContentArea, Corner, DateElement, DateTime, DateTimeEdit, Decimal, DefaultUi, Desc, DigestMethod, DigestMethods, Draw, Edge, Encoding, Encodings, Encrypt, EncryptData, Encryption, EncryptionMethod, EncryptionMethods, Event$1, ExData, ExObject, ExclGroup, Execute, Extras, Field, Fill, Filter, Float, template_Font, Format, Handler, Hyphenation, Image$1, ImageEdit, Integer, Issuers, Items, Keep, KeyUsage, Line, Linear, LockDocument, Manifest, Margin, Mdp, Medium, Message, NumericEdit, Occur, Oid, Oids, Overflow, PageArea, PageSet, Para, PasswordEdit, template_Pattern, Picture, Proto, Radial, Reason, Reasons, Rectangle, RefElement, Script, SetProperty, SignData, Signature, Signing, Solid, Speak, Stipple, Subform, SubformSet, SubjectDN, SubjectDNs, Submit, Template, Text, TextEdit, Time, TimeStamp, ToolTip, Traversal, Traverse, Ui, Validate, Value, Variables, TemplateNamespace, bind_NS_DATASETS, Binder, DataHandler, CONFIG_NS_ID, Acrobat, Acrobat7, ADBE_JSConsole, ADBE_JSDebugger, AddSilentPrint, AddViewerPreferences, AdjustData, AdobeExtensionLevel, Agent$1, AlwaysEmbed, Amd, config_Area, Attributes, AutoSave, Base, BatchOutput, BehaviorOverride, Cache, Change, Common, Compress, CompressLogicalStructure, CompressObjectStream, Compression, Config, Conformance, ContentCopy, Copies, Creator, CurrentPage, Data, Debug, DefaultTypeface, Destination, DocumentAssembly, Driver, DuplexOption, DynamicRender, Embed, config_Encrypt, config_Encryption, EncryptionLevel, Enforce, Equate, EquateRange, Exclude, ExcludeNS, FlipLabel, config_FontInfo, FormFieldFilling, GroupParent, IfEmpty, IncludeXDPContent, IncrementalLoad, IncrementalMerge, Interactive, Jog, LabelPrinter, Layout, Level, Linearized, Locale, LocaleSet, Log, MapElement, MediumInfo, config_Message, Messaging, Mode, ModifyAnnots, MsgId, NameAttr, NeverEmbed, NumberOfCopies, OpenAction, Output, OutputBin, OutputXSL, Overprint, Packets, PageOffset, PageRange, Pagination, PaginationOverride, Part, Pcl, Pdf, Pdfa, Permissions, PickTrayByPDFSize, config_Picture, PlaintextMetadata, Presence, Present, Print, PrintHighQuality, PrintScaling, PrinterName, Producer, Ps, Range$1, Record, Relevant, Rename, RenderPolicy, RunScripts, config_Script, ScriptModel, Severity, SilentPrint, Staple, StartNode, StartPage, SubmitFormat, SubmitUrl, SubsetBelow, SuppressBanner, Tagged, config_Template, Threshold, To, TemplateCache, Trace, Transform$2, Type, Uri, config_Validate, ValidateApprovalSignatures, ValidationMessaging, Version, VersionControl, ViewerPreferences, WebClient, Whitespace, Window, Xdc, Xdp, Xsl, Zpl, ConfigNamespace, CONNECTION_SET_NS_ID, ConnectionSet, EffectiveInputPolicy, EffectiveOutputPolicy, Operation, RootElement, SoapAction, SoapAddress, connection_set_Uri, WsdlAddress, WsdlConnection, XmlConnection, XsdConnection, ConnectionSetNamespace, DATASETS_NS_ID, datasets_Data, Datasets, DatasetsNamespace, LOCALE_SET_NS_ID, CalendarSymbols, CurrencySymbol, CurrencySymbols, DatePattern, DatePatterns, DateTimeSymbols, Day, DayNames, Era, EraNames, locale_set_Locale, locale_set_LocaleSet, Meridiem, MeridiemNames, Month, MonthNames, NumberPattern, NumberPatterns, NumberSymbol, NumberSymbols, TimePattern, TimePatterns, TypeFace, TypeFaces, LocaleSetNamespace, SIGNATURE_NS_ID, signature_Signature, SignatureNamespace, STYLESHEET_NS_ID, Stylesheet, StylesheetNamespace, XDP_NS_ID, xdp_Xdp, XdpNamespace, XHTML_NS_ID, $richText, VALID_STYLES, StyleMapping, spacesRegExp, crlfRegExp, crlfForRichTextRegExp, NoWhites, XhtmlObject, A, B, Body, Br, Html, I, Li, Ol, P, Span, Sub, Sup, Ul, XhtmlNamespace, NamespaceSetUp, UnknownNamespace, Root, Empty, Builder, XFAParser, XFAFactory, AnnotationFactory, Annotation, AnnotationBorderStyle, MarkupAnnotation, WidgetAnnotation, TextWidgetAnnotation, ButtonWidgetAnnotation, ChoiceWidgetAnnotation, SignatureWidgetAnnotation, TextAnnotation, LinkAnnotation, PopupAnnotation, FreeTextAnnotation, LineAnnotation, SquareAnnotation, CircleAnnotation, PolylineAnnotation, PolygonAnnotation, CaretAnnotation, InkAnnotation, HighlightAnnotation, UnderlineAnnotation, SquigglyAnnotation, StrikeOutAnnotation, StampAnnotation, FileAttachmentAnnotation, PARAMS, DatasetXMLParser, DatasetReader, SingleIntersector, STEPS, Intersector, Word64, calculate_sha_other_PARAMS, calculate_sha256_PARAMS, chunkSize, DecryptStream, ARCFourCipher, NullCipher, AESBaseCipher, AES128Cipher, AES256Cipher, PDFBase, PDF17, PDF20, CipherTransform, CipherTransformFactory, XRef, LETTER_SIZE_MEDIABOX, Page, PDF_HEADER_SIGNATURE, STARTXREF_SIGNATURE, ENDOBJ_SIGNATURE, PDFDocument, BasePdfManager, LocalPdfManager, NetworkPdfManager, CallbackKind, StreamKind, MessageHandler, MAX_LEAVES_PER_PAGES_NODE, MAX_IN_NAME_TREE_NODE, PageData, DocumentData, XRefWrapper, PDFEditor, PDFWorkerStream, PDFWorkerStreamReader, PDFWorkerStreamRangeReader, WorkerTask, WorkerMessageHandler;
176681
+ var __webpack_modules__, __webpack_module_cache__, isNodeJS, FONT_IDENTITY_MATRIX, LINE_FACTOR, LINE_DESCENT_FACTOR, BASELINE_FACTOR, RenderingIntentFlag, AnnotationEditorPrefix, AnnotationEditorType, PermissionFlag, MeshFigureType, TextRenderingMode, ImageKind, AnnotationType, AnnotationReplyType, AnnotationFlag, AnnotationFieldFlag, AnnotationBorderStyleType, AnnotationActionEventType, DocumentActionEventType, PageActionEventType, VerbosityLevel, OPS, DrawOPS, PasswordResponses, verbosity, BaseException, PasswordException, UnknownErrorException, InvalidPDFException, ResponseException, FormatError, AbortException, FeatureTest, hexNumbers, Util, PDFStringTranslateTable, NormalizeRegex, NormalizationMap, AnnotationPrefix, CIRCULAR_REF, EOF, CmdCache, NameCache, RefCache, Name, Cmd, nonSerializable, Dict, Ref, RefSet, RefSetCache, BaseStream, PDF_VERSION_REGEXP, MAX_INT_32, MIN_INT_32, IDENTITY_MATRIX, RESOURCES_KEYS_OPERATOR_LIST, RESOURCES_KEYS_TEXT_CONTENT, MissingDataException, ParserEOFException, XRefEntryException, XRefParseException, ROMAN_NUMBER_MAP, XMLEntities, QCMS, wasm, cachedTextDecoder, cachedUint8ArrayMemory0, WASM_VECTOR_LEN, DataType, Intent, ColorSpace, AlternateCS, PatternCS, IndexedCS, DeviceGrayCS, DeviceRgbCS, DeviceRgbaCS, DeviceCmykCS, CalGrayCS, CalRGBCS, LabCS, IccColorSpace, CmykICCBasedCS, Stream$1, StringStream, NullStream, ChunkedStream, ChunkedStreamManager, MIN_IMAGE_DIM, MAX_IMAGE_DIM, MAX_ERROR, ImageResizer, emptyBuffer$1, DecodeStream, StreamsSequenceStream, ColorSpaceUtils, JpegError, DNLMarkerError, EOIMarkerError, dctZigZag, dctCos1, dctSin1, dctCos3, dctSin3, dctCos6, dctSin6, dctSqrt2, dctSqrt1d2, JpegImage, JpegStream, openjpeg, JpxError, JpxImage, InitialState, NullOptimizer, QueueOptimizer, OperatorList, MAX_NUM_SIZE, MAX_ENCODED_NUM_SIZE, BinaryCMapStream, BinaryCMapReader, Ascii85Stream, AsciiHexStream, ccittEOL, ccittEOF, twoDimPass, twoDimHoriz, twoDimVert0, twoDimVertR1, twoDimVertL1, twoDimVertR2, twoDimVertL2, twoDimVertR3, twoDimVertL3, twoDimTable, whiteTable1, whiteTable2, blackTable1, blackTable2, blackTable3, CCITTFaxDecoder, CCITTFaxStream, codeLenCodeMap, lengthDecode, distDecode, fixedLitCodeTab, fixedDistCodeTab, FlateStream, QeTable, ArithmeticDecoder, Jbig2Error, ContextCache, DecodingContext, SegmentTypes, CodingTemplates, RefinementTemplates, ReusedContexts, RefinementReusedContexts, RegionSegmentInformationFieldLength, SimpleSegmentVisitor, HuffmanLine, HuffmanTreeNode, HuffmanTable, standardTablesCache, Reader, Jbig2Image, Jbig2Stream, JpxStream, LZWStream, PredictorStream, RunLengthStream, MAX_LENGTH_TO_CACHE, Parser, specialChars, Lexer, Linearization, BUILT_IN_CMAPS, MAX_MAP_RANGE, CMap, IdentityCMap, CMapFactory, ExpertEncoding, MacExpertEncoding, MacRomanEncoding, StandardEncoding, WinAnsiEncoding, SymbolSetEncoding, ZapfDingbatsEncoding, getGlyphsUnicode, getDingbatsGlyphsUnicode, getSpecialPUASymbols, UnicodeRanges, SpecialCharRegExp, CategoryCache, SEAC_ANALYSIS_ENABLED, FontFlags, MacStandardGlyphOrdering, getVerticalPresentationForm, MAX_SIZE_TO_COMPILE, ISOAdobeCharset, ExpertCharset, ExpertSubsetCharset, MAX_SUBR_NESTING, CFFStandardStrings, NUM_STANDARD_CFF_STRINGS, CharstringValidationData, CharstringValidationData12, CFFParser, CFF, CFFHeader, CFFStrings, CFFIndex, CFFDict, CFFTopDictLayout, CFFTopDict, CFFPrivateDictLayout, CFFPrivateDict, CFFCharsetPredefinedTypes, CFFCharset, CFFEncoding, CFFFDSelect, CFFOffsetTracker, CFFCompiler, getStdFontMap, getFontNameToFileMap, getNonStdFontMap, getSerifFonts, getSymbolsFonts, getGlyphMapForStandardFonts, getSupplementalGlyphMapForArialBlack, getSupplementalGlyphMapForCalibri, ToUnicodeMap, IdentityToUnicodeMap, CFFFont, NOOP, Commands, CompiledFont, TrueTypeCompiled, Type2Compiled, FontRendererFactory, getMetrics, getFontBasicMetrics, ON_CURVE_POINT, X_SHORT_VECTOR, Y_SHORT_VECTOR, REPEAT_FLAG, X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR, Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR, OVERLAP_SIMPLE, ARG_1_AND_2_ARE_WORDS, ARGS_ARE_XY_VALUES, WE_HAVE_A_SCALE, MORE_COMPONENTS, WE_HAVE_AN_X_AND_Y_SCALE, WE_HAVE_A_TWO_BY_TWO, WE_HAVE_INSTRUCTIONS, GlyfTable, Glyph, GlyphHeader, Contour, SimpleGlyph, CompositeGlyph, OTF_HEADER_SIZE, OTF_TABLE_ENTRY_SIZE, OpenTypeFileBuilder, HINTING_ENABLED, COMMAND_MAP, Type1CharString, EEXEC_ENCRYPT_KEY, CHAR_STRS_ENCRYPT_KEY, Type1Parser, Type1Font, PRIVATE_USE_AREAS, PDF_GLYPH_SPACE_UNITS, EXPORT_DATA_PROPERTIES, EXPORT_DATA_EXTRA_PROPERTIES, fonts_Glyph, Font, ErrorFont, CssFontInfo, SystemFontInfo, FontInfo, PatternInfo, FontPathInfo, ShadingType, Pattern, BaseShading, RadialAxialShading, MeshStreamReader, bCache, MeshShading, DummyShading, CalibriBoldFactors, CalibriBoldMetrics, CalibriBoldItalicFactors, CalibriBoldItalicMetrics, CalibriItalicFactors, CalibriItalicMetrics, CalibriRegularFactors, CalibriRegularMetrics, HelveticaBoldFactors, HelveticaBoldMetrics, HelveticaBoldItalicFactors, HelveticaBoldItalicMetrics, HelveticaItalicFactors, HelveticaItalicMetrics, HelveticaRegularFactors, HelveticaRegularMetrics, LiberationSansBoldWidths, LiberationSansBoldMapping, LiberationSansBoldItalicWidths, LiberationSansBoldItalicMapping, LiberationSansItalicWidths, LiberationSansItalicMapping, LiberationSansRegularWidths, LiberationSansRegularMapping, MyriadProBoldFactors, MyriadProBoldMetrics, MyriadProBoldItalicFactors, MyriadProBoldItalicMetrics, MyriadProItalicFactors, MyriadProItalicMetrics, MyriadProRegularFactors, MyriadProRegularMetrics, SegoeuiBoldFactors, SegoeuiBoldMetrics, SegoeuiBoldItalicFactors, SegoeuiBoldItalicMetrics, SegoeuiItalicFactors, SegoeuiItalicMetrics, SegoeuiRegularFactors, SegoeuiRegularMetrics, getXFAFontMap, PostScriptParser, PostScriptTokenTypes, PostScriptToken, PostScriptLexer, BaseLocalCache, LocalImageCache, LocalColorSpaceCache, LocalFunctionCache, LocalGStateCache, LocalTilingPatternCache, RegionalImageCache, GlobalColorSpaceCache, GlobalImageCache, PDFFunctionFactory, PDFFunction, PostScriptStack, PostScriptEvaluator, AstNode, AstArgument, AstLiteral, AstBinaryOperation, AstMin, AstVariable, AstVariableDefinition, ExpressionBuilderVisitor, PostScriptCompiler, baseTypes, arabicTypes, chars, types, NORMAL, BOLD, ITALIC, BOLDITALIC, substitutionMap, fontAliases, SEED, MASK_HIGH, MASK_LOW, MurmurHash3_64, PDFImage, DefaultPartialEvaluatorOptions, PatternType, TEXT_CHUNK_BATCH_SIZE, deferred, TimeSlotManager, PartialEvaluator, TranslatedFont, StateManager, TextState, EvalState, EvaluatorPreprocessor, DefaultAppearanceEvaluator, AppearanceStreamEvaluator, FakeUnicodeFont, DateFormats, TimeFormats, NameOrNumberTree, NameTree, NumberTree, FileSpec, XMLParserErrorCode, XMLParserBase, SimpleDOMNode, SimpleXMLParser, MetadataParser, MAX_DEPTH, StructElementType, StructTreeRoot, StructElementNode, StructElement, StructTreePage, isRef, isValidExplicitDest, Catalog, ObjectLoader, $acceptWhitespace, $addHTML, $appendChild, $childrenToHTML, $clean, $cleanPage, $cleanup, $clone, $consumed, $content, $data, $dump, $extra, $finalize, $flushHTML, $getAttributeIt, $getAttributes, $getAvailableSpace, $getChildrenByClass, $getChildrenByName, $getChildrenByNameIt, $getDataValue, $getExtra, $getRealChildrenByNameIt, $getChildren, $getContainedChildren, $getNextPage, $getSubformParent, $getParent, $getTemplateRoot, $globalData, $hasSettableValue, $ids, $indexOf, $insertAt, $isCDATAXml, $isBindable, $isDataValue, $isDescendent, $isNsAgnostic, $isSplittable, $isThereMoreWidth, $isTransparent, $isUsable, $lastAttribute, $namespaceId, $nodeName, $nsAttributes, $onChild, $onChildCheck, $onText, $pushGlyphs, $popPara, $pushPara, $removeChild, $root, $resolvePrototypes, $searchNode, $setId, $setSetAttributes, $setValue, $tabIndex, $text, $toPages, $toHTML, $toString, $toStyle, $uid, $buildXFAObject, NamespaceIds, dimConverters, measurementPattern, HTMLResult, FontFinder, WIDTH_FACTOR, text_FontInfo, FontSelector, TextMeasure, namePattern, indexPattern, operators, shortcuts, somCache, _applyPrototype, _attributes, _attributeNames, _children, _cloneAttribute, _dataValue, _defaultValue, _filteredChildrenGenerator, _getPrototype, _getUnsetAttributes, _hasChildren, _max, _options, _parent, _resolvePrototypesHelper, _setAttributes, _validator, uid, NS_DATASETS, XFAObject, XFAObjectArray, XFAAttribute, XmlObject, ContentObject, OptionObject, StringObject, IntegerObject, Option01, Option10, converters, TEMPLATE_NS_ID, SVG_NS, MAX_ATTEMPTS_FOR_LRTB_LAYOUT, MAX_EMPTY_PAGES, DEFAULT_TAB_INDEX, HEADING_PATTERN, MIMES, IMAGES_HEADERS, AppearanceFilter, Arc, Area, Assist, Barcode, Bind, BindItems, Bookend, BooleanElement, Border, Break, BreakAfter, BreakBefore, Button, Calculate, Caption, Certificate, Certificates, CheckButton, ChoiceList, Color, Comb, Connect, ContentArea, Corner, DateElement, DateTime, DateTimeEdit, Decimal, DefaultUi, Desc, DigestMethod, DigestMethods, Draw, Edge, Encoding, Encodings, Encrypt, EncryptData, Encryption, EncryptionMethod, EncryptionMethods, Event$1, ExData, ExObject, ExclGroup, Execute, Extras, Field, Fill, Filter, Float, template_Font, Format, Handler, Hyphenation, Image$1, ImageEdit, Integer, Issuers, Items, Keep, KeyUsage, Line, Linear, LockDocument, Manifest, Margin, Mdp, Medium, Message, NumericEdit, Occur, Oid, Oids, Overflow, PageArea, PageSet, Para, PasswordEdit, template_Pattern, Picture, Proto, Radial, Reason, Reasons, Rectangle, RefElement, Script, SetProperty, SignData, Signature, Signing, Solid, Speak, Stipple, Subform, SubformSet, SubjectDN, SubjectDNs, Submit, Template, Text, TextEdit, Time, TimeStamp, ToolTip, Traversal, Traverse, Ui, Validate, Value, Variables, TemplateNamespace, bind_NS_DATASETS, Binder, DataHandler, CONFIG_NS_ID, Acrobat, Acrobat7, ADBE_JSConsole, ADBE_JSDebugger, AddSilentPrint, AddViewerPreferences, AdjustData, AdobeExtensionLevel, Agent$1, AlwaysEmbed, Amd, config_Area, Attributes, AutoSave, Base, BatchOutput, BehaviorOverride, Cache, Change, Common, Compress, CompressLogicalStructure, CompressObjectStream, Compression, Config, Conformance, ContentCopy, Copies, Creator, CurrentPage, Data, Debug, DefaultTypeface, Destination, DocumentAssembly, Driver, DuplexOption, DynamicRender, Embed, config_Encrypt, config_Encryption, EncryptionLevel, Enforce, Equate, EquateRange, Exclude, ExcludeNS, FlipLabel, config_FontInfo, FormFieldFilling, GroupParent, IfEmpty, IncludeXDPContent, IncrementalLoad, IncrementalMerge, Interactive, Jog, LabelPrinter, Layout, Level, Linearized, Locale, LocaleSet, Log, MapElement, MediumInfo, config_Message, Messaging, Mode, ModifyAnnots, MsgId, NameAttr, NeverEmbed, NumberOfCopies, OpenAction, Output, OutputBin, OutputXSL, Overprint, Packets, PageOffset, PageRange, Pagination, PaginationOverride, Part, Pcl, Pdf, Pdfa, Permissions, PickTrayByPDFSize, config_Picture, PlaintextMetadata, Presence, Present, Print, PrintHighQuality, PrintScaling, PrinterName, Producer, Ps, Range$1, Record, Relevant, Rename, RenderPolicy, RunScripts, config_Script, ScriptModel, Severity, SilentPrint, Staple, StartNode, StartPage, SubmitFormat, SubmitUrl, SubsetBelow, SuppressBanner, Tagged, config_Template, Threshold, To, TemplateCache, Trace, Transform$1, Type, Uri, config_Validate, ValidateApprovalSignatures, ValidationMessaging, Version, VersionControl, ViewerPreferences, WebClient, Whitespace, Window, Xdc, Xdp, Xsl, Zpl, ConfigNamespace, CONNECTION_SET_NS_ID, ConnectionSet, EffectiveInputPolicy, EffectiveOutputPolicy, Operation, RootElement, SoapAction, SoapAddress, connection_set_Uri, WsdlAddress, WsdlConnection, XmlConnection, XsdConnection, ConnectionSetNamespace, DATASETS_NS_ID, datasets_Data, Datasets, DatasetsNamespace, LOCALE_SET_NS_ID, CalendarSymbols, CurrencySymbol, CurrencySymbols, DatePattern, DatePatterns, DateTimeSymbols, Day, DayNames, Era, EraNames, locale_set_Locale, locale_set_LocaleSet, Meridiem, MeridiemNames, Month, MonthNames, NumberPattern, NumberPatterns, NumberSymbol, NumberSymbols, TimePattern, TimePatterns, TypeFace, TypeFaces, LocaleSetNamespace, SIGNATURE_NS_ID, signature_Signature, SignatureNamespace, STYLESHEET_NS_ID, Stylesheet, StylesheetNamespace, XDP_NS_ID, xdp_Xdp, XdpNamespace, XHTML_NS_ID, $richText, VALID_STYLES, StyleMapping, spacesRegExp, crlfRegExp, crlfForRichTextRegExp, NoWhites, XhtmlObject, A, B, Body, Br, Html, I, Li, Ol, P, Span, Sub, Sup, Ul, XhtmlNamespace, NamespaceSetUp, UnknownNamespace, Root, Empty, Builder, XFAParser, XFAFactory, AnnotationFactory, Annotation, AnnotationBorderStyle, MarkupAnnotation, WidgetAnnotation, TextWidgetAnnotation, ButtonWidgetAnnotation, ChoiceWidgetAnnotation, SignatureWidgetAnnotation, TextAnnotation, LinkAnnotation, PopupAnnotation, FreeTextAnnotation, LineAnnotation, SquareAnnotation, CircleAnnotation, PolylineAnnotation, PolygonAnnotation, CaretAnnotation, InkAnnotation, HighlightAnnotation, UnderlineAnnotation, SquigglyAnnotation, StrikeOutAnnotation, StampAnnotation, FileAttachmentAnnotation, PARAMS, DatasetXMLParser, DatasetReader, SingleIntersector, STEPS, Intersector, Word64, calculate_sha_other_PARAMS, calculate_sha256_PARAMS, chunkSize, DecryptStream, ARCFourCipher, NullCipher, AESBaseCipher, AES128Cipher, AES256Cipher, PDFBase, PDF17, PDF20, CipherTransform, CipherTransformFactory, XRef, LETTER_SIZE_MEDIABOX, Page, PDF_HEADER_SIGNATURE, STARTXREF_SIGNATURE, ENDOBJ_SIGNATURE, PDFDocument, BasePdfManager, LocalPdfManager, NetworkPdfManager, CallbackKind, StreamKind, MessageHandler, MAX_LEAVES_PER_PAGES_NODE, MAX_IN_NAME_TREE_NODE, PageData, DocumentData, XRefWrapper, PDFEditor, PDFWorkerStream, PDFWorkerStreamReader, PDFWorkerStreamRangeReader, WorkerTask, WorkerMessageHandler;
175236
176682
  var init_pdf_worker = __esmMin((() => {
175237
176683
  __webpack_modules__ = {
175238
176684
  34: ((module, __unused_webpack_exports, __webpack_require__) => {
@@ -238983,7 +240429,7 @@ var init_pdf_worker = __esmMin((() => {
238983
240429
  this.area = new XFAObjectArray();
238984
240430
  }
238985
240431
  };
238986
- Transform$2 = class extends XFAObject {
240432
+ Transform$1 = class extends XFAObject {
238987
240433
  constructor(attributes) {
238988
240434
  super(CONFIG_NS_ID, "transform", true);
238989
240435
  this.groupParent = null;
@@ -239519,7 +240965,7 @@ var init_pdf_worker = __esmMin((() => {
239519
240965
  return new Trace(attrs);
239520
240966
  }
239521
240967
  static transform(attrs) {
239522
- return new Transform$2(attrs);
240968
+ return new Transform$1(attrs);
239523
240969
  }
239524
240970
  static type(attrs) {
239525
240971
  return new Type(attrs);
@@ -260047,1139 +261493,6 @@ var require_concat_stream = /* @__PURE__ */ __commonJSMin$2(((exports, module) =
260047
261493
  }
260048
261494
  }));
260049
261495
 
260050
- //#endregion
260051
- //#region node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/fd-slicer.js
260052
- var require_fd_slicer = /* @__PURE__ */ __commonJSMin$2(((exports) => {
260053
- var fs$8 = __require("fs");
260054
- var util$3 = __require("util");
260055
- var stream = __require("stream");
260056
- var Readable = stream.Readable;
260057
- var PassThrough = stream.PassThrough;
260058
- var Pend = require_pend();
260059
- var EventEmitter$2 = __require("events").EventEmitter;
260060
- exports.BufferSlicer = BufferSlicer;
260061
- exports.FdSlicer = FdSlicer;
260062
- util$3.inherits(FdSlicer, EventEmitter$2);
260063
- function FdSlicer(fd) {
260064
- EventEmitter$2.call(this);
260065
- this.fd = fd;
260066
- this.pend = new Pend();
260067
- this.pend.max = 1;
260068
- this.refCount = 0;
260069
- }
260070
- FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
260071
- var self = this;
260072
- self.pend.go(function(cb) {
260073
- fs$8.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer) {
260074
- cb();
260075
- callback(err, bytesRead, buffer);
260076
- });
260077
- });
260078
- };
260079
- FdSlicer.prototype.createReadStream = function(options) {
260080
- return new ReadStream(this, options);
260081
- };
260082
- FdSlicer.prototype.ref = function() {
260083
- this.refCount += 1;
260084
- };
260085
- FdSlicer.prototype.unref = function() {
260086
- var self = this;
260087
- self.refCount -= 1;
260088
- if (self.refCount < 0) throw new Error("invalid unref");
260089
- if (self.refCount > 0) return;
260090
- fs$8.close(self.fd, onCloseDone);
260091
- function onCloseDone(err) {
260092
- if (err) self.emit("error", err);
260093
- else self.emit("close");
260094
- }
260095
- };
260096
- util$3.inherits(ReadStream, Readable);
260097
- function ReadStream(context, options) {
260098
- options = options || {};
260099
- Readable.call(this, options);
260100
- this.context = context;
260101
- this.context.ref();
260102
- this.start = options.start || 0;
260103
- this.endOffset = options.end;
260104
- this.pos = this.start;
260105
- }
260106
- ReadStream.prototype._read = function(n) {
260107
- var self = this;
260108
- var toRead = Math.min(self._readableState.highWaterMark, n);
260109
- if (self.endOffset != null) toRead = Math.min(toRead, self.endOffset - self.pos);
260110
- if (toRead <= 0) {
260111
- self.push(null);
260112
- this._cleanup();
260113
- return;
260114
- }
260115
- self.context.pend.go(function(cb) {
260116
- var buffer = Buffer.allocUnsafe(toRead);
260117
- fs$8.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) {
260118
- if (err) self.destroy(err);
260119
- else if (bytesRead === 0) {
260120
- self.push(null);
260121
- self._cleanup();
260122
- } else {
260123
- self.pos += bytesRead;
260124
- self.push(buffer.slice(0, bytesRead));
260125
- }
260126
- cb();
260127
- });
260128
- });
260129
- };
260130
- ReadStream.prototype._destroy = function(err, cb) {
260131
- this._cleanup();
260132
- cb(err);
260133
- };
260134
- ReadStream.prototype._cleanup = function() {
260135
- if (this.context != null) {
260136
- this.context.unref();
260137
- this.context = null;
260138
- }
260139
- };
260140
- util$3.inherits(BufferSlicer, EventEmitter$2);
260141
- function BufferSlicer(buffer) {
260142
- EventEmitter$2.call(this);
260143
- this.refCount = 0;
260144
- this.buffer = buffer;
260145
- }
260146
- BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) {
260147
- if (!(0 <= offset && offset <= buffer.length)) throw new RangeError("offset outside buffer: 0 <= " + offset + " <= " + buffer.length);
260148
- if (position < 0) throw new RangeError("position is negative: " + position);
260149
- if (offset + length > buffer.length) length = buffer.length - offset;
260150
- if (position + length > this.buffer.length) length = this.buffer.length - position;
260151
- if (length <= 0) {
260152
- setImmediate(function() {
260153
- callback(null, 0);
260154
- });
260155
- return;
260156
- }
260157
- this.buffer.copy(buffer, offset, position, position + length);
260158
- setImmediate(function() {
260159
- callback(null, length);
260160
- });
260161
- };
260162
- BufferSlicer.prototype.createReadStream = function(options) {
260163
- options = options || {};
260164
- var readStream = new PassThrough(options);
260165
- readStream.start = options.start || 0;
260166
- readStream.endOffset = options.end;
260167
- readStream.pos = readStream.endOffset || this.buffer.length;
260168
- var entireSlice = this.buffer.slice(readStream.start, readStream.pos);
260169
- var maxChunkSize = 65536;
260170
- var offset = 0;
260171
- while (true) {
260172
- var nextOffset = offset + maxChunkSize;
260173
- if (nextOffset >= entireSlice.length) {
260174
- if (offset < entireSlice.length) readStream.write(entireSlice.slice(offset, entireSlice.length));
260175
- break;
260176
- }
260177
- readStream.write(entireSlice.slice(offset, nextOffset));
260178
- offset = nextOffset;
260179
- }
260180
- readStream.end();
260181
- return readStream;
260182
- };
260183
- BufferSlicer.prototype.ref = function() {
260184
- this.refCount += 1;
260185
- };
260186
- BufferSlicer.prototype.unref = function() {
260187
- this.refCount -= 1;
260188
- if (this.refCount < 0) throw new Error("invalid unref");
260189
- };
260190
- }));
260191
-
260192
- //#endregion
260193
- //#region node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/crc32.js
260194
- var require_crc32 = /* @__PURE__ */ __commonJSMin$2(((exports, module) => {
260195
- const CRC_TABLE = new Int32Array([
260196
- 0,
260197
- 1996959894,
260198
- 3993919788,
260199
- 2567524794,
260200
- 124634137,
260201
- 1886057615,
260202
- 3915621685,
260203
- 2657392035,
260204
- 249268274,
260205
- 2044508324,
260206
- 3772115230,
260207
- 2547177864,
260208
- 162941995,
260209
- 2125561021,
260210
- 3887607047,
260211
- 2428444049,
260212
- 498536548,
260213
- 1789927666,
260214
- 4089016648,
260215
- 2227061214,
260216
- 450548861,
260217
- 1843258603,
260218
- 4107580753,
260219
- 2211677639,
260220
- 325883990,
260221
- 1684777152,
260222
- 4251122042,
260223
- 2321926636,
260224
- 335633487,
260225
- 1661365465,
260226
- 4195302755,
260227
- 2366115317,
260228
- 997073096,
260229
- 1281953886,
260230
- 3579855332,
260231
- 2724688242,
260232
- 1006888145,
260233
- 1258607687,
260234
- 3524101629,
260235
- 2768942443,
260236
- 901097722,
260237
- 1119000684,
260238
- 3686517206,
260239
- 2898065728,
260240
- 853044451,
260241
- 1172266101,
260242
- 3705015759,
260243
- 2882616665,
260244
- 651767980,
260245
- 1373503546,
260246
- 3369554304,
260247
- 3218104598,
260248
- 565507253,
260249
- 1454621731,
260250
- 3485111705,
260251
- 3099436303,
260252
- 671266974,
260253
- 1594198024,
260254
- 3322730930,
260255
- 2970347812,
260256
- 795835527,
260257
- 1483230225,
260258
- 3244367275,
260259
- 3060149565,
260260
- 1994146192,
260261
- 31158534,
260262
- 2563907772,
260263
- 4023717930,
260264
- 1907459465,
260265
- 112637215,
260266
- 2680153253,
260267
- 3904427059,
260268
- 2013776290,
260269
- 251722036,
260270
- 2517215374,
260271
- 3775830040,
260272
- 2137656763,
260273
- 141376813,
260274
- 2439277719,
260275
- 3865271297,
260276
- 1802195444,
260277
- 476864866,
260278
- 2238001368,
260279
- 4066508878,
260280
- 1812370925,
260281
- 453092731,
260282
- 2181625025,
260283
- 4111451223,
260284
- 1706088902,
260285
- 314042704,
260286
- 2344532202,
260287
- 4240017532,
260288
- 1658658271,
260289
- 366619977,
260290
- 2362670323,
260291
- 4224994405,
260292
- 1303535960,
260293
- 984961486,
260294
- 2747007092,
260295
- 3569037538,
260296
- 1256170817,
260297
- 1037604311,
260298
- 2765210733,
260299
- 3554079995,
260300
- 1131014506,
260301
- 879679996,
260302
- 2909243462,
260303
- 3663771856,
260304
- 1141124467,
260305
- 855842277,
260306
- 2852801631,
260307
- 3708648649,
260308
- 1342533948,
260309
- 654459306,
260310
- 3188396048,
260311
- 3373015174,
260312
- 1466479909,
260313
- 544179635,
260314
- 3110523913,
260315
- 3462522015,
260316
- 1591671054,
260317
- 702138776,
260318
- 2966460450,
260319
- 3352799412,
260320
- 1504918807,
260321
- 783551873,
260322
- 3082640443,
260323
- 3233442989,
260324
- 3988292384,
260325
- 2596254646,
260326
- 62317068,
260327
- 1957810842,
260328
- 3939845945,
260329
- 2647816111,
260330
- 81470997,
260331
- 1943803523,
260332
- 3814918930,
260333
- 2489596804,
260334
- 225274430,
260335
- 2053790376,
260336
- 3826175755,
260337
- 2466906013,
260338
- 167816743,
260339
- 2097651377,
260340
- 4027552580,
260341
- 2265490386,
260342
- 503444072,
260343
- 1762050814,
260344
- 4150417245,
260345
- 2154129355,
260346
- 426522225,
260347
- 1852507879,
260348
- 4275313526,
260349
- 2312317920,
260350
- 282753626,
260351
- 1742555852,
260352
- 4189708143,
260353
- 2394877945,
260354
- 397917763,
260355
- 1622183637,
260356
- 3604390888,
260357
- 2714866558,
260358
- 953729732,
260359
- 1340076626,
260360
- 3518719985,
260361
- 2797360999,
260362
- 1068828381,
260363
- 1219638859,
260364
- 3624741850,
260365
- 2936675148,
260366
- 906185462,
260367
- 1090812512,
260368
- 3747672003,
260369
- 2825379669,
260370
- 829329135,
260371
- 1181335161,
260372
- 3412177804,
260373
- 3160834842,
260374
- 628085408,
260375
- 1382605366,
260376
- 3423369109,
260377
- 3138078467,
260378
- 570562233,
260379
- 1426400815,
260380
- 3317316542,
260381
- 2998733608,
260382
- 733239954,
260383
- 1555261956,
260384
- 3268935591,
260385
- 3050360625,
260386
- 752459403,
260387
- 1541320221,
260388
- 2607071920,
260389
- 3965973030,
260390
- 1969922972,
260391
- 40735498,
260392
- 2617837225,
260393
- 3943577151,
260394
- 1913087877,
260395
- 83908371,
260396
- 2512341634,
260397
- 3803740692,
260398
- 2075208622,
260399
- 213261112,
260400
- 2463272603,
260401
- 3855990285,
260402
- 2094854071,
260403
- 198958881,
260404
- 2262029012,
260405
- 4057260610,
260406
- 1759359992,
260407
- 534414190,
260408
- 2176718541,
260409
- 4139329115,
260410
- 1873836001,
260411
- 414664567,
260412
- 2282248934,
260413
- 4279200368,
260414
- 1711684554,
260415
- 285281116,
260416
- 2405801727,
260417
- 4167216745,
260418
- 1634467795,
260419
- 376229701,
260420
- 2685067896,
260421
- 3608007406,
260422
- 1308918612,
260423
- 956543938,
260424
- 2808555105,
260425
- 3495958263,
260426
- 1231636301,
260427
- 1047427035,
260428
- 2932959818,
260429
- 3654703836,
260430
- 1088359270,
260431
- 936918e3,
260432
- 2847714899,
260433
- 3736837829,
260434
- 1202900863,
260435
- 817233897,
260436
- 3183342108,
260437
- 3401237130,
260438
- 1404277552,
260439
- 615818150,
260440
- 3134207493,
260441
- 3453421203,
260442
- 1423857449,
260443
- 601450431,
260444
- 3009837614,
260445
- 3294710456,
260446
- 1567103746,
260447
- 711928724,
260448
- 3020668471,
260449
- 3272380065,
260450
- 1510334235,
260451
- 755167117
260452
- ]);
260453
- function crc32(buf) {
260454
- let crc = -1;
260455
- for (let x of buf) crc = CRC_TABLE[(crc ^ x) & 255] ^ crc >>> 8;
260456
- return (crc ^ -1) >>> 0;
260457
- }
260458
- module.exports = crc32;
260459
- }));
260460
-
260461
- //#endregion
260462
- //#region node_modules/.pnpm/yauzl@3.4.0/node_modules/yauzl/index.js
260463
- var require_yauzl = /* @__PURE__ */ __commonJSMin$2(((exports) => {
260464
- var fs$7 = __require("fs");
260465
- var zlib$1 = __require("zlib");
260466
- var fd_slicer = require_fd_slicer();
260467
- var util$2 = __require("util");
260468
- var EventEmitter$1 = __require("events").EventEmitter;
260469
- var Transform$1 = __require("stream").Transform;
260470
- var PassThrough$1 = __require("stream").PassThrough;
260471
- var Writable$1 = __require("stream").Writable;
260472
- const crc32 = typeof zlib$1.crc32 === "function" ? zlib$1.crc32 : require_crc32();
260473
- exports.open = open;
260474
- exports.fromBuffer = fromBuffer;
260475
- function open(path, options, callback) {
260476
- if (typeof options === "function") {
260477
- callback = options;
260478
- options = null;
260479
- }
260480
- if (options == null) options = {};
260481
- if (options.autoClose == null) options.autoClose = true;
260482
- if (options.lazyEntries == null) options.lazyEntries = false;
260483
- if (options.decodeStrings == null) options.decodeStrings = true;
260484
- if (options.validateEntrySizes == null) options.validateEntrySizes = true;
260485
- if (options.strictFileNames == null) options.strictFileNames = false;
260486
- if (callback == null) callback = defaultCallback;
260487
- fs$7.open(path, "r", function(err, fd) {
260488
- if (err) return callback(err);
260489
- fromFd(fd, options, function(err, zipfile) {
260490
- if (err) fs$7.close(fd, defaultCallback);
260491
- callback(err, zipfile);
260492
- });
260493
- });
260494
- }
260495
- function fromFd(fd, options, callback) {
260496
- if (typeof options === "function") {
260497
- callback = options;
260498
- options = null;
260499
- }
260500
- if (options == null) options = {};
260501
- if (options.autoClose == null) options.autoClose = false;
260502
- if (options.lazyEntries == null) options.lazyEntries = false;
260503
- if (options.decodeStrings == null) options.decodeStrings = true;
260504
- if (options.validateEntrySizes == null) options.validateEntrySizes = true;
260505
- if (options.strictFileNames == null) options.strictFileNames = false;
260506
- if (callback == null) callback = defaultCallback;
260507
- fs$7.fstat(fd, function(err, stats) {
260508
- if (err) return callback(err);
260509
- fromRandomAccessReader(new fd_slicer.FdSlicer(fd), stats.size, options, callback);
260510
- });
260511
- }
260512
- function fromBuffer(buffer, options, callback) {
260513
- if (typeof options === "function") {
260514
- callback = options;
260515
- options = null;
260516
- }
260517
- if (options == null) options = {};
260518
- options.autoClose = false;
260519
- if (options.lazyEntries == null) options.lazyEntries = false;
260520
- if (options.decodeStrings == null) options.decodeStrings = true;
260521
- if (options.validateEntrySizes == null) options.validateEntrySizes = true;
260522
- if (options.strictFileNames == null) options.strictFileNames = false;
260523
- fromRandomAccessReader(new fd_slicer.BufferSlicer(buffer), buffer.length, options, callback);
260524
- }
260525
- function fromRandomAccessReader(reader, totalSize, options, callback) {
260526
- if (typeof options === "function") {
260527
- callback = options;
260528
- options = null;
260529
- }
260530
- if (options == null) options = {};
260531
- if (options.autoClose == null) options.autoClose = true;
260532
- if (options.lazyEntries == null) options.lazyEntries = false;
260533
- if (options.decodeStrings == null) options.decodeStrings = true;
260534
- var decodeStrings = !!options.decodeStrings;
260535
- if (options.validateEntrySizes == null) options.validateEntrySizes = true;
260536
- if (options.strictFileNames == null) options.strictFileNames = false;
260537
- if (callback == null) callback = defaultCallback;
260538
- if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number");
260539
- if (totalSize > Number.MAX_SAFE_INTEGER) throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");
260540
- reader.ref();
260541
- var eocdrWithoutCommentSize = 22;
260542
- var zip64EocdlSize = 20;
260543
- var bufferSize = Math.min(zip64EocdlSize + eocdrWithoutCommentSize + 65535, totalSize);
260544
- var buffer = newBuffer(bufferSize);
260545
- readAndAssertNoEof(reader, buffer, 0, bufferSize, totalSize - buffer.length, function(err) {
260546
- if (err) return callback(err);
260547
- for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) {
260548
- if (buffer.readUInt32LE(i) !== 101010256) continue;
260549
- var eocdrBuffer = buffer.subarray(i);
260550
- var diskNumber = eocdrBuffer.readUInt16LE(4);
260551
- var entryCount = eocdrBuffer.readUInt16LE(10);
260552
- var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16);
260553
- var commentLength = eocdrBuffer.readUInt16LE(20);
260554
- var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize;
260555
- if (commentLength !== expectedCommentLength) return callback(/* @__PURE__ */ new Error("Invalid comment length. Expected: " + expectedCommentLength + ". Found: " + commentLength + ". Are there extra bytes at the end of the file? Or is the end of central dir signature `PK☺☻` in the comment?"));
260556
- var comment = decodeStrings ? decodeBuffer(eocdrBuffer.subarray(22), false) : eocdrBuffer.subarray(22);
260557
- if (i - zip64EocdlSize >= 0 && buffer.readUInt32LE(i - zip64EocdlSize) === 117853008) {
260558
- var zip64EocdrOffset = readUInt64LE(buffer.subarray(i - zip64EocdlSize, i - zip64EocdlSize + zip64EocdlSize), 8);
260559
- var zip64EocdrBuffer = newBuffer(56);
260560
- return readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err) {
260561
- if (err) return callback(err);
260562
- if (zip64EocdrBuffer.readUInt32LE(0) !== 101075792) return callback(/* @__PURE__ */ new Error("invalid zip64 end of central directory record signature"));
260563
- diskNumber = zip64EocdrBuffer.readUInt32LE(16);
260564
- if (diskNumber !== 0) return callback(/* @__PURE__ */ new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
260565
- entryCount = readUInt64LE(zip64EocdrBuffer, 32);
260566
- centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48);
260567
- return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
260568
- });
260569
- }
260570
- if (diskNumber !== 0) return callback(/* @__PURE__ */ new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
260571
- return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
260572
- }
260573
- callback(/* @__PURE__ */ new Error("End of central directory record signature not found. Either not a zip file, or file is truncated."));
260574
- });
260575
- }
260576
- util$2.inherits(ZipFile, EventEmitter$1);
260577
- function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
260578
- var self = this;
260579
- EventEmitter$1.call(self);
260580
- self.reader = reader;
260581
- self.reader.on("error", function(err) {
260582
- emitError(self, err);
260583
- });
260584
- self.reader.once("close", function() {
260585
- self.emit("close");
260586
- });
260587
- self.readEntryCursor = centralDirectoryOffset;
260588
- self.fileSize = fileSize;
260589
- self.entryCount = entryCount;
260590
- self.comment = comment;
260591
- self.entriesRead = 0;
260592
- self.autoClose = !!autoClose;
260593
- self.lazyEntries = !!lazyEntries;
260594
- self.decodeStrings = !!decodeStrings;
260595
- self.validateEntrySizes = !!validateEntrySizes;
260596
- self.strictFileNames = !!strictFileNames;
260597
- self.isOpen = true;
260598
- self.emittedError = false;
260599
- self.hasEachEntryBeenCalled = false;
260600
- if (!self.lazyEntries) self._readEntry();
260601
- }
260602
- ZipFile.prototype.close = function() {
260603
- if (!this.isOpen) return;
260604
- this.isOpen = false;
260605
- this.reader.unref();
260606
- };
260607
- function emitErrorAndAutoClose(self, err) {
260608
- if (self.autoClose) self.close();
260609
- emitError(self, err);
260610
- }
260611
- function emitError(self, err) {
260612
- if (self.emittedError) return;
260613
- self.emittedError = true;
260614
- self.emit("error", err);
260615
- }
260616
- ZipFile.prototype.readEntry = function() {
260617
- if (!this.lazyEntries) throw new Error("readEntry() called without lazyEntries:true");
260618
- this._readEntry();
260619
- };
260620
- ZipFile.prototype._readEntry = function() {
260621
- var self = this;
260622
- if (self.entryCount === self.entriesRead) {
260623
- setImmediate(function() {
260624
- if (self.autoClose) self.close();
260625
- if (self.emittedError) return;
260626
- self.emit("end");
260627
- });
260628
- return;
260629
- }
260630
- if (self.emittedError) return;
260631
- var buffer = newBuffer(46);
260632
- readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
260633
- if (err) return emitErrorAndAutoClose(self, err);
260634
- if (self.emittedError) return;
260635
- var entry = new Entry();
260636
- var signature = buffer.readUInt32LE(0);
260637
- if (signature !== 33639248) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("invalid central directory file header signature: 0x" + signature.toString(16)));
260638
- entry.versionMadeBy = buffer.readUInt16LE(4);
260639
- entry.versionNeededToExtract = buffer.readUInt16LE(6);
260640
- entry.generalPurposeBitFlag = buffer.readUInt16LE(8);
260641
- entry.compressionMethod = buffer.readUInt16LE(10);
260642
- entry.lastModFileTime = buffer.readUInt16LE(12);
260643
- entry.lastModFileDate = buffer.readUInt16LE(14);
260644
- entry.crc32 = buffer.readUInt32LE(16);
260645
- entry.compressedSize = buffer.readUInt32LE(20);
260646
- entry.uncompressedSize = buffer.readUInt32LE(24);
260647
- entry.fileNameLength = buffer.readUInt16LE(28);
260648
- entry.extraFieldLength = buffer.readUInt16LE(30);
260649
- entry.fileCommentLength = buffer.readUInt16LE(32);
260650
- entry.internalFileAttributes = buffer.readUInt16LE(36);
260651
- entry.externalFileAttributes = buffer.readUInt32LE(38);
260652
- entry.relativeOffsetOfLocalHeader = buffer.readUInt32LE(42);
260653
- if (entry.generalPurposeBitFlag & 64) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("strong encryption is not supported"));
260654
- self.readEntryCursor += 46;
260655
- buffer = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength);
260656
- readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
260657
- if (err) return emitErrorAndAutoClose(self, err);
260658
- if (self.emittedError) return;
260659
- entry.fileNameRaw = buffer.subarray(0, entry.fileNameLength);
260660
- var fileCommentStart = entry.fileNameLength + entry.extraFieldLength;
260661
- entry.extraFieldRaw = buffer.subarray(entry.fileNameLength, fileCommentStart);
260662
- entry.fileCommentRaw = buffer.subarray(fileCommentStart, fileCommentStart + entry.fileCommentLength);
260663
- try {
260664
- entry.extraFields = parseExtraFields(entry.extraFieldRaw);
260665
- } catch (err) {
260666
- return emitErrorAndAutoClose(self, err);
260667
- }
260668
- if (self.decodeStrings) {
260669
- var isUtf8 = (entry.generalPurposeBitFlag & 2048) !== 0;
260670
- entry.fileComment = decodeBuffer(entry.fileCommentRaw, isUtf8);
260671
- entry.fileName = getFileNameLowLevel(entry.generalPurposeBitFlag, entry.fileNameRaw, entry.extraFields, self.strictFileNames);
260672
- var errorMessage = validateFileName(entry.fileName);
260673
- if (errorMessage != null) return emitErrorAndAutoClose(self, new Error(errorMessage));
260674
- } else {
260675
- entry.fileComment = entry.fileCommentRaw;
260676
- entry.fileName = entry.fileNameRaw;
260677
- }
260678
- entry.comment = entry.fileComment;
260679
- self.readEntryCursor += buffer.length;
260680
- self.entriesRead += 1;
260681
- for (var i = 0; i < entry.extraFields.length; i++) {
260682
- var extraField = entry.extraFields[i];
260683
- if (extraField.id !== 1) continue;
260684
- var zip64EiefBuffer = extraField.data;
260685
- var index = 0;
260686
- if (entry.uncompressedSize === 4294967295) {
260687
- if (index + 8 > zip64EiefBuffer.length) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("zip64 extended information extra field does not include uncompressed size"));
260688
- entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index);
260689
- index += 8;
260690
- }
260691
- if (entry.compressedSize === 4294967295) {
260692
- if (index + 8 > zip64EiefBuffer.length) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("zip64 extended information extra field does not include compressed size"));
260693
- entry.compressedSize = readUInt64LE(zip64EiefBuffer, index);
260694
- index += 8;
260695
- }
260696
- if (entry.relativeOffsetOfLocalHeader === 4294967295) {
260697
- if (index + 8 > zip64EiefBuffer.length) return emitErrorAndAutoClose(self, /* @__PURE__ */ new Error("zip64 extended information extra field does not include relative header offset"));
260698
- entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index);
260699
- index += 8;
260700
- }
260701
- break;
260702
- }
260703
- if (self.validateEntrySizes && entry.compressionMethod === 0) {
260704
- var expectedCompressedSize = entry.uncompressedSize;
260705
- if (entry.isEncrypted()) expectedCompressedSize += 12;
260706
- if (entry.compressedSize !== expectedCompressedSize) {
260707
- var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize;
260708
- return emitErrorAndAutoClose(self, new Error(msg));
260709
- }
260710
- }
260711
- self.emit("entry", entry);
260712
- if (!self.lazyEntries) self._readEntry();
260713
- });
260714
- });
260715
- };
260716
- ZipFile.prototype.eachEntry = function() {
260717
- const self = this;
260718
- if (!self.lazyEntries) throw new Error("eachEntry() requires lazyEntries: true");
260719
- if (self.hasEachEntryBeenCalled) throw new Error("eachEntry() must only be called once per ZipFile");
260720
- self.hasEachEntryBeenCalled = true;
260721
- let pendingResolveReject = null;
260722
- self.on("entry", onEntry);
260723
- self.on("end", onEnd);
260724
- self.on("error", onError);
260725
- function cleanup() {
260726
- self.removeListener("entry", onEntry);
260727
- self.removeListener("end", onEnd);
260728
- self.removeListener("error", onError);
260729
- if (self.autoClose) self.close();
260730
- }
260731
- function onEntry(entry) {
260732
- let { resolve } = pendingResolveReject;
260733
- pendingResolveReject = null;
260734
- resolve({ value: entry });
260735
- }
260736
- function onEnd() {
260737
- let { resolve } = pendingResolveReject;
260738
- pendingResolveReject = null;
260739
- cleanup();
260740
- resolve({ done: true });
260741
- }
260742
- function onError(err) {
260743
- let { reject } = pendingResolveReject;
260744
- pendingResolveReject = null;
260745
- cleanup();
260746
- reject(err);
260747
- }
260748
- return {
260749
- [Symbol.asyncIterator]() {
260750
- return this;
260751
- },
260752
- next() {
260753
- const promise = new Promise((resolve, reject) => {
260754
- if (pendingResolveReject != null) throw new Error("next() called before previous Promise was resolved.");
260755
- pendingResolveReject = {
260756
- resolve,
260757
- reject
260758
- };
260759
- });
260760
- self.readEntry();
260761
- return promise;
260762
- },
260763
- return(value) {
260764
- cleanup();
260765
- return Promise.resolve({
260766
- done: true,
260767
- value
260768
- });
260769
- },
260770
- throw(value) {
260771
- cleanup();
260772
- return Promise.reject(value);
260773
- }
260774
- };
260775
- };
260776
- ZipFile.prototype.openReadStream = function(entry, options, callback) {
260777
- var self = this;
260778
- var relativeStart = 0;
260779
- var relativeEnd = entry.compressedSize;
260780
- if (callback == null) {
260781
- callback = options;
260782
- options = null;
260783
- }
260784
- if (options == null) options = {};
260785
- else {
260786
- if (options.decodeFileData === false) {
260787
- if (options.decrypt != null) throw new Error("cannot use options.decrypt when options.decodeFileData === false");
260788
- if (options.decompress != null) throw new Error("cannot use options.decompress when options.decodeFileData === false");
260789
- } else {
260790
- if (options.decrypt != null) {
260791
- if (!entry.isEncrypted()) throw new Error("options.decrypt can only be specified for encrypted entries. See also option decodeFileData.");
260792
- if (options.decrypt !== false) throw new Error("invalid options.decrypt value: " + options.decrypt);
260793
- if (entry.isCompressed()) {
260794
- if (options.decompress !== false) throw new Error("entry is encrypted and compressed, and options.decompress !== false. See also option decodeFileData.");
260795
- }
260796
- }
260797
- if (options.decompress != null) {
260798
- if (!entry.isCompressed()) throw new Error("options.decompress can only be specified for compressed entries. See also option decodeFileData.");
260799
- if (!(options.decompress === false || options.decompress === true)) throw new Error("invalid options.decompress value: " + options.decompress);
260800
- decompress = options.decompress;
260801
- }
260802
- }
260803
- if (options.start != null) {
260804
- relativeStart = options.start;
260805
- if (relativeStart < 0) throw new Error("options.start < 0");
260806
- if (relativeStart > entry.compressedSize) throw new Error("options.start > entry.compressedSize");
260807
- }
260808
- if (options.end != null) {
260809
- relativeEnd = options.end;
260810
- if (relativeEnd < 0) throw new Error("options.end < 0");
260811
- if (relativeEnd > entry.compressedSize) throw new Error("options.end > entry.compressedSize");
260812
- if (relativeEnd < relativeStart) throw new Error("options.end < options.start");
260813
- }
260814
- }
260815
- var rawMode = options.decodeFileData === false || (entry.compressionMethod === 0 || entry.compressionMethod === 8 && options.decompress === false) && (!entry.isEncrypted() || options.decrypt === false);
260816
- if (options.start != null || options.end != null) {
260817
- if (!rawMode) throw new Error("start/end range require options.decodeFileData === false for non-trivial encoded entries.");
260818
- }
260819
- if (!self.isOpen) return callback(/* @__PURE__ */ new Error("closed"));
260820
- if (entry.isEncrypted() && !rawMode) {
260821
- if (options.decrypt !== false) return callback(/* @__PURE__ */ new Error("entry is encrypted, and options.decodeFileData !== false"));
260822
- }
260823
- var decompress;
260824
- if (rawMode) decompress = false;
260825
- else if (entry.compressionMethod === 8) decompress = options.decodeFileData !== true;
260826
- else return callback(/* @__PURE__ */ new Error("unsupported compression method: " + entry.compressionMethod));
260827
- self.readLocalFileHeader(entry, { minimal: true }, function(err, localFileHeader) {
260828
- if (err) return callback(err);
260829
- self.openReadStreamLowLevel(localFileHeader.fileDataStart, entry.compressedSize, relativeStart, relativeEnd, decompress, entry.uncompressedSize, callback);
260830
- });
260831
- };
260832
- ZipFile.prototype.openReadStreamLowLevel = function(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize, callback) {
260833
- var self = this;
260834
- fileDataStart + compressedSize;
260835
- var readStream = self.reader.createReadStream({
260836
- start: fileDataStart + relativeStart,
260837
- end: fileDataStart + relativeEnd
260838
- });
260839
- var endpointStream = readStream;
260840
- if (decompress) {
260841
- var destroyed = false;
260842
- var inflateFilter = zlib$1.createInflateRaw();
260843
- readStream.on("error", function(err) {
260844
- setImmediate(function() {
260845
- if (!destroyed) inflateFilter.emit("error", err);
260846
- });
260847
- });
260848
- readStream.pipe(inflateFilter);
260849
- if (self.validateEntrySizes) {
260850
- endpointStream = new AssertByteCountStream(uncompressedSize);
260851
- inflateFilter.on("error", function(err) {
260852
- setImmediate(function() {
260853
- if (!destroyed) endpointStream.emit("error", err);
260854
- });
260855
- });
260856
- inflateFilter.pipe(endpointStream);
260857
- } else endpointStream = inflateFilter;
260858
- installDestroyFn(endpointStream, function() {
260859
- destroyed = true;
260860
- if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream);
260861
- readStream.unpipe(inflateFilter);
260862
- readStream.destroy();
260863
- });
260864
- }
260865
- callback(null, endpointStream);
260866
- };
260867
- ZipFile.prototype.readLocalFileHeader = function(entry, options, callback) {
260868
- var self = this;
260869
- if (callback == null) {
260870
- callback = options;
260871
- options = null;
260872
- }
260873
- if (options == null) options = {};
260874
- self.reader.ref();
260875
- var buffer = newBuffer(30);
260876
- readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader, function(err) {
260877
- try {
260878
- if (err) return callback(err);
260879
- var signature = buffer.readUInt32LE(0);
260880
- if (signature !== 67324752) return callback(/* @__PURE__ */ new Error("invalid local file header signature: 0x" + signature.toString(16)));
260881
- var fileNameLength = buffer.readUInt16LE(26);
260882
- var extraFieldLength = buffer.readUInt16LE(28);
260883
- var fileDataStart = entry.relativeOffsetOfLocalHeader + 30 + fileNameLength + extraFieldLength;
260884
- if (fileDataStart + entry.compressedSize > self.fileSize) return callback(/* @__PURE__ */ new Error("file data overflows file bounds: " + fileDataStart + " + " + entry.compressedSize + " > " + self.fileSize));
260885
- if (options.minimal) return callback(null, { fileDataStart });
260886
- var localFileHeader = new LocalFileHeader();
260887
- localFileHeader.fileDataStart = fileDataStart;
260888
- localFileHeader.versionNeededToExtract = buffer.readUInt16LE(4);
260889
- localFileHeader.generalPurposeBitFlag = buffer.readUInt16LE(6);
260890
- localFileHeader.compressionMethod = buffer.readUInt16LE(8);
260891
- localFileHeader.lastModFileTime = buffer.readUInt16LE(10);
260892
- localFileHeader.lastModFileDate = buffer.readUInt16LE(12);
260893
- localFileHeader.crc32 = buffer.readUInt32LE(14);
260894
- localFileHeader.compressedSize = buffer.readUInt32LE(18);
260895
- localFileHeader.uncompressedSize = buffer.readUInt32LE(22);
260896
- localFileHeader.fileNameLength = fileNameLength;
260897
- localFileHeader.extraFieldLength = extraFieldLength;
260898
- buffer = newBuffer(fileNameLength + extraFieldLength);
260899
- self.reader.ref();
260900
- readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader + 30, function(err) {
260901
- try {
260902
- if (err) return callback(err);
260903
- localFileHeader.fileName = buffer.subarray(0, fileNameLength);
260904
- localFileHeader.extraField = buffer.subarray(fileNameLength);
260905
- return callback(null, localFileHeader);
260906
- } finally {
260907
- self.reader.unref();
260908
- }
260909
- });
260910
- } finally {
260911
- self.reader.unref();
260912
- }
260913
- });
260914
- };
260915
- ZipFile.prototype.openReadStreamPromise = function(entry, options) {
260916
- return new Promise((resolve, reject) => {
260917
- this.openReadStream(entry, options, function(err, readStream) {
260918
- if (err) return reject(err);
260919
- resolve(readStream);
260920
- });
260921
- });
260922
- };
260923
- ZipFile.prototype.openReadStreamLowLevelPromise = function(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize) {
260924
- return new Promise((resolve, reject) => {
260925
- this.openReadStream(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize, function(err, readStream) {
260926
- if (err) return reject(err);
260927
- resolve(readStream);
260928
- });
260929
- });
260930
- };
260931
- ZipFile.prototype.readLocalFileHeaderPromise = function(entry, options) {
260932
- return new Promise((resolve, reject) => {
260933
- this.readLocalFileHeader(entry, options, function(err, localFileHeader) {
260934
- if (err) return reject(err);
260935
- resolve(localFileHeader);
260936
- });
260937
- });
260938
- };
260939
- function Entry() {}
260940
- Entry.prototype.getLastModDate = function(options) {
260941
- if (options == null) options = {};
260942
- if (!options.forceDosFormat) for (var i = 0; i < this.extraFields.length; i++) {
260943
- var extraField = this.extraFields[i];
260944
- if (extraField.id === 21589) {
260945
- var data = extraField.data;
260946
- if (data.length < 5) continue;
260947
- if (!(data[0] & 1)) continue;
260948
- var posixTimestamp = data.readInt32LE(1);
260949
- return /* @__PURE__ */ new Date(posixTimestamp * 1e3);
260950
- } else if (extraField.id === 10) {
260951
- var data = extraField.data;
260952
- if (data.length !== 32) continue;
260953
- if (data.readUInt16LE(4) !== 1) continue;
260954
- if (data.readUInt16LE(6) !== 24) continue;
260955
- var millisecondsSince1970 = (data.readUInt32LE(8) + 4294967296 * data.readInt32LE(12)) / 1e4 - 0xa9730b66800;
260956
- return new Date(millisecondsSince1970);
260957
- }
260958
- }
260959
- return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime, options.timezone);
260960
- };
260961
- Entry.prototype.canDecodeFileData = function() {
260962
- return !this.isEncrypted() && (this.compressionMethod === 0 || this.compressionMethod === 8);
260963
- };
260964
- Entry.prototype.isEncrypted = function() {
260965
- return (this.generalPurposeBitFlag & 1) !== 0;
260966
- };
260967
- Entry.prototype.isCompressed = function() {
260968
- return this.compressionMethod === 8;
260969
- };
260970
- function LocalFileHeader() {}
260971
- function dosDateTimeToDate(date, time, timezone) {
260972
- var day = date & 31;
260973
- var month = (date >> 5 & 15) - 1;
260974
- var year = (date >> 9 & 127) + 1980;
260975
- var millisecond = 0;
260976
- var second = (time & 31) * 2;
260977
- var minute = time >> 5 & 63;
260978
- var hour = time >> 11 & 31;
260979
- if (timezone == null || timezone === "local") return new Date(year, month, day, hour, minute, second, millisecond);
260980
- else if (timezone === "UTC") return new Date(Date.UTC(year, month, day, hour, minute, second, millisecond));
260981
- else throw new Error("unrecognized options.timezone: " + options.timezone);
260982
- }
260983
- function getFileNameLowLevel(generalPurposeBitFlag, fileNameBuffer, extraFields, strictFileNames) {
260984
- var fileName = null;
260985
- for (var i = 0; i < extraFields.length; i++) {
260986
- var extraField = extraFields[i];
260987
- if (extraField.id === 28789) {
260988
- if (extraField.data.length < 6) continue;
260989
- if (extraField.data.readUInt8(0) !== 1) continue;
260990
- var oldNameCrc32 = extraField.data.readUInt32LE(1);
260991
- if (crc32(fileNameBuffer) !== oldNameCrc32) continue;
260992
- fileName = decodeBuffer(extraField.data.subarray(5), true);
260993
- break;
260994
- }
260995
- }
260996
- if (fileName == null) fileName = decodeBuffer(fileNameBuffer, (generalPurposeBitFlag & 2048) !== 0);
260997
- if (!strictFileNames) fileName = fileName.replace(/\\/g, "/");
260998
- return fileName;
260999
- }
261000
- function validateFileName(fileName) {
261001
- if (fileName.indexOf("\\") !== -1) return "invalid characters in fileName: " + fileName;
261002
- if (/^[a-zA-Z]:/.test(fileName) || /^\//.test(fileName)) return "absolute path: " + fileName;
261003
- if (fileName.split("/").indexOf("..") !== -1) return "invalid relative path: " + fileName;
261004
- return null;
261005
- }
261006
- function parseExtraFields(extraFieldBuffer) {
261007
- var extraFields = [];
261008
- var i = 0;
261009
- while (i < extraFieldBuffer.length - 3) {
261010
- var headerId = extraFieldBuffer.readUInt16LE(i + 0);
261011
- var dataSize = extraFieldBuffer.readUInt16LE(i + 2);
261012
- var dataStart = i + 4;
261013
- var dataEnd = dataStart + dataSize;
261014
- if (dataEnd > extraFieldBuffer.length) throw new Error("extra field length exceeds extra field buffer size");
261015
- var dataBuffer = extraFieldBuffer.subarray(dataStart, dataEnd);
261016
- extraFields.push({
261017
- id: headerId,
261018
- data: dataBuffer
261019
- });
261020
- i = dataEnd;
261021
- }
261022
- return extraFields;
261023
- }
261024
- function readAndAssertNoEof(reader, buffer, offset, length, position, callback) {
261025
- if (length === 0) return setImmediate(function() {
261026
- callback(null, newBuffer(0));
261027
- });
261028
- reader.read(buffer, offset, length, position, function(err, bytesRead) {
261029
- if (err) return callback(err);
261030
- if (bytesRead < length) return callback(/* @__PURE__ */ new Error("unexpected EOF"));
261031
- callback();
261032
- });
261033
- }
261034
- util$2.inherits(AssertByteCountStream, Transform$1);
261035
- function AssertByteCountStream(byteCount) {
261036
- Transform$1.call(this);
261037
- this.actualByteCount = 0;
261038
- this.expectedByteCount = byteCount;
261039
- }
261040
- AssertByteCountStream.prototype._transform = function(chunk, encoding, cb) {
261041
- this.actualByteCount += chunk.length;
261042
- if (this.actualByteCount > this.expectedByteCount) {
261043
- var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount;
261044
- return cb(new Error(msg));
261045
- }
261046
- cb(null, chunk);
261047
- };
261048
- AssertByteCountStream.prototype._flush = function(cb) {
261049
- if (this.actualByteCount < this.expectedByteCount) {
261050
- var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount;
261051
- return cb(new Error(msg));
261052
- }
261053
- cb();
261054
- };
261055
- util$2.inherits(RandomAccessReader, EventEmitter$1);
261056
- function RandomAccessReader() {
261057
- EventEmitter$1.call(this);
261058
- this.refCount = 0;
261059
- }
261060
- RandomAccessReader.prototype.ref = function() {
261061
- this.refCount += 1;
261062
- };
261063
- RandomAccessReader.prototype.unref = function() {
261064
- var self = this;
261065
- self.refCount -= 1;
261066
- if (self.refCount > 0) return;
261067
- if (self.refCount < 0) throw new Error("invalid unref");
261068
- self.close(onCloseDone);
261069
- function onCloseDone(err) {
261070
- if (err) return self.emit("error", err);
261071
- self.emit("close");
261072
- }
261073
- };
261074
- RandomAccessReader.prototype.createReadStream = function(options) {
261075
- if (options == null) options = {};
261076
- var start = options.start;
261077
- var end = options.end;
261078
- if (start === end) {
261079
- var emptyStream = new PassThrough$1();
261080
- setImmediate(function() {
261081
- emptyStream.end();
261082
- });
261083
- return emptyStream;
261084
- }
261085
- var stream = this._readStreamForRange(start, end);
261086
- var destroyed = false;
261087
- var refUnrefFilter = new RefUnrefFilter(this);
261088
- stream.on("error", function(err) {
261089
- setImmediate(function() {
261090
- if (!destroyed) refUnrefFilter.emit("error", err);
261091
- });
261092
- });
261093
- installDestroyFn(refUnrefFilter, function() {
261094
- stream.unpipe(refUnrefFilter);
261095
- refUnrefFilter.unref();
261096
- stream.destroy();
261097
- });
261098
- var byteCounter = new AssertByteCountStream(end - start);
261099
- refUnrefFilter.on("error", function(err) {
261100
- setImmediate(function() {
261101
- if (!destroyed) byteCounter.emit("error", err);
261102
- });
261103
- });
261104
- installDestroyFn(byteCounter, function() {
261105
- destroyed = true;
261106
- refUnrefFilter.unpipe(byteCounter);
261107
- refUnrefFilter.destroy();
261108
- });
261109
- return stream.pipe(refUnrefFilter).pipe(byteCounter);
261110
- };
261111
- RandomAccessReader.prototype._readStreamForRange = function(start, end) {
261112
- throw new Error("not implemented");
261113
- };
261114
- RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) {
261115
- var readStream = this.createReadStream({
261116
- start: position,
261117
- end: position + length
261118
- });
261119
- var writeStream = new Writable$1();
261120
- var written = 0;
261121
- writeStream._write = function(chunk, encoding, cb) {
261122
- chunk.copy(buffer, offset + written, 0, chunk.length);
261123
- written += chunk.length;
261124
- cb();
261125
- };
261126
- writeStream.on("finish", callback);
261127
- readStream.on("error", function(error) {
261128
- callback(error);
261129
- });
261130
- readStream.pipe(writeStream);
261131
- };
261132
- RandomAccessReader.prototype.close = function(callback) {
261133
- setImmediate(callback);
261134
- };
261135
- util$2.inherits(RefUnrefFilter, PassThrough$1);
261136
- function RefUnrefFilter(context) {
261137
- PassThrough$1.call(this);
261138
- this.context = context;
261139
- this.context.ref();
261140
- this.unreffedYet = false;
261141
- }
261142
- RefUnrefFilter.prototype._flush = function(cb) {
261143
- this.unref();
261144
- cb();
261145
- };
261146
- RefUnrefFilter.prototype.unref = function(cb) {
261147
- if (this.unreffedYet) return;
261148
- this.unreffedYet = true;
261149
- this.context.unref();
261150
- };
261151
- var cp437 = "\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0";
261152
- function decodeBuffer(buffer, isUtf8) {
261153
- if (isUtf8) return buffer.toString("utf8");
261154
- else {
261155
- var result = "";
261156
- for (var i = 0; i < buffer.length; i++) result += cp437[buffer[i]];
261157
- return result;
261158
- }
261159
- }
261160
- function readUInt64LE(buffer, offset) {
261161
- var lower32 = buffer.readUInt32LE(offset);
261162
- return buffer.readUInt32LE(offset + 4) * 4294967296 + lower32;
261163
- }
261164
- var newBuffer;
261165
- if (typeof Buffer.allocUnsafe === "function") newBuffer = function(len) {
261166
- return Buffer.allocUnsafe(len);
261167
- };
261168
- else newBuffer = function(len) {
261169
- return new Buffer(len);
261170
- };
261171
- function installDestroyFn(stream, fn) {
261172
- if (typeof stream.destroy === "function") stream._destroy = function(err, cb) {
261173
- fn();
261174
- if (cb != null) cb(err);
261175
- };
261176
- else stream.destroy = fn;
261177
- }
261178
- function defaultCallback(err) {
261179
- if (err) throw err;
261180
- }
261181
- }));
261182
-
261183
261496
  //#endregion
261184
261497
  //#region ../../packages/file-loaders/src/utils/parser-utils.ts
261185
261498
  /** Extract specific files from either a ZIP file buffer or file path based on a filter function.
@@ -261545,6 +261858,7 @@ function isReadableFileType(fileType) {
261545
261858
 
261546
261859
  //#endregion
261547
261860
  //#region ../../packages/file-loaders/src/loadFile.ts
261861
+ init_fileParseBudget();
261548
261862
  const log$4 = (0, import_src$6.default)("file-loaders:loadFile");
261549
261863
  var UnsupportedFileTypeError = class extends Error {
261550
261864
  fileType;
@@ -261678,6 +261992,7 @@ const loadFile = async (filePath, fileMetadata) => {
261678
261992
  }
261679
261993
  } else log$4("Loader does not support attachDocumentMetadata.");
261680
261994
  } catch (loadErr) {
261995
+ if (isFileParseBudgetError(loadErr)) throw loadErr;
261681
261996
  const error = loadErr;
261682
261997
  console.error(`Error loading pages for ${filePath} using ${LoaderClass.name}: ${error.message}`);
261683
261998
  loaderError = `Loader execution failed: ${error.message}`;
@@ -330535,7 +330850,7 @@ var stdio_exports = /* @__PURE__ */ __exportAll$2({
330535
330850
  function getDefaultEnvironment() {
330536
330851
  const env = {};
330537
330852
  for (const key of DEFAULT_INHERITED_ENV_VARS) {
330538
- const value = process$1.env[key];
330853
+ const value = _w.env[key];
330539
330854
  if (value === void 0) continue;
330540
330855
  if (value.startsWith("()")) continue;
330541
330856
  env[key] = value;
@@ -330546,7 +330861,7 @@ var import_cross_spawn$1, DEFAULT_INHERITED_ENV_VARS, StdioClientTransport;
330546
330861
  var init_stdio = __esmMin((() => {
330547
330862
  init_src_CeKsbNLO();
330548
330863
  import_cross_spawn$1 = /* @__PURE__ */ __toESM$2(require_cross_spawn(), 1);
330549
- DEFAULT_INHERITED_ENV_VARS = process$1.platform === "win32" ? [
330864
+ DEFAULT_INHERITED_ENV_VARS = _w.platform === "win32" ? [
330550
330865
  "APPDATA",
330551
330866
  "COMSPEC",
330552
330867
  "HOMEDRIVE",
@@ -330603,7 +330918,7 @@ var init_stdio = __esmMin((() => {
330603
330918
  this._serverParams.stderr ?? "inherit"
330604
330919
  ],
330605
330920
  shell: false,
330606
- windowsHide: process$1.platform === "win32",
330921
+ windowsHide: _w.platform === "win32",
330607
330922
  cwd: this._serverParams.cwd
330608
330923
  });
330609
330924
  this._process.on("error", (error) => {
@@ -333637,9 +333952,9 @@ const getSubprocessResult = ({ stdout }) => {
333637
333952
  //#region node_modules/.pnpm/execa@9.6.1/node_modules/execa/lib/utils/standard-stream.js
333638
333953
  const isStandardStream = (stream) => STANDARD_STREAMS.includes(stream);
333639
333954
  const STANDARD_STREAMS = [
333640
- process$1.stdin,
333641
- process$1.stdout,
333642
- process$1.stderr
333955
+ _w.stdin,
333956
+ _w.stdout,
333957
+ _w.stderr
333643
333958
  ];
333644
333959
  const STANDARD_STREAMS_ALIASES = [
333645
333960
  "stdin",
@@ -333764,9 +334079,9 @@ const NO_ESCAPE_REGEXP = /^[\w./-]+$/;
333764
334079
  //#endregion
333765
334080
  //#region node_modules/.pnpm/is-unicode-supported@2.1.0/node_modules/is-unicode-supported/index.js
333766
334081
  function isUnicodeSupported() {
333767
- const { env } = process$1;
334082
+ const { env } = _w;
333768
334083
  const { TERM, TERM_PROGRAM } = env;
333769
- if (process$1.platform !== "win32") return TERM !== "linux";
334084
+ if (_w.platform !== "win32") return TERM !== "linux";
333770
334085
  return Boolean(env.WT_SESSION) || Boolean(env.TERMINUS_SUBLIME) || env.ConEmuTask === "{cmd::Cmder}" || TERM_PROGRAM === "Terminus-Sublime" || TERM_PROGRAM === "vscode" || TERM === "xterm-256color" || TERM === "alacritty" || TERM === "rxvt-unicode" || TERM === "rxvt-unicode-256color" || env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
333771
334086
  }
333772
334087
 
@@ -334301,7 +334616,7 @@ function traversePathUp(startPath) {
334301
334616
 
334302
334617
  //#endregion
334303
334618
  //#region node_modules/.pnpm/npm-run-path@6.0.0/node_modules/npm-run-path/index.js
334304
- const npmRunPath = ({ cwd = process$1.cwd(), path: pathOption = process$1.env[pathKey()], preferLocal = true, execPath = process$1.execPath, addExecPath = true } = {}) => {
334619
+ const npmRunPath = ({ cwd = _w.cwd(), path: pathOption = _w.env[pathKey()], preferLocal = true, execPath = _w.execPath, addExecPath = true } = {}) => {
334305
334620
  const cwdPath = path.resolve(toPath(cwd));
334306
334621
  const result = [];
334307
334622
  const pathParts = pathOption.split(path.delimiter);
@@ -334319,7 +334634,7 @@ const applyExecPath = (result, pathParts, execPath, cwdPath) => {
334319
334634
  const pathPart = path.resolve(cwdPath, toPath(execPath), "..");
334320
334635
  if (!pathParts.includes(pathPart)) result.push(pathPart);
334321
334636
  };
334322
- const npmRunPathEnv = ({ env = process$1.env, ...options } = {}) => {
334637
+ const npmRunPathEnv = ({ env = _w.env, ...options } = {}) => {
334323
334638
  env = { ...env };
334324
334639
  const pathName = pathKey({ env });
334325
334640
  options.path = env[pathName];
@@ -335454,7 +335769,7 @@ const normalizeCwd = (cwd = getDefaultCwd()) => {
335454
335769
  };
335455
335770
  const getDefaultCwd = () => {
335456
335771
  try {
335457
- return process$1.cwd();
335772
+ return _w.cwd();
335458
335773
  } catch (error) {
335459
335774
  error.message = `The current directory does not exist.\n${error.message}`;
335460
335775
  throw error;
@@ -335490,7 +335805,7 @@ const normalizeOptions = (filePath, rawArguments, rawOptions) => {
335490
335805
  options.killSignal = normalizeKillSignal(options.killSignal);
335491
335806
  options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);
335492
335807
  options.lines = options.lines.map((lines, fdNumber) => lines && !BINARY_ENCODINGS.has(options.encoding) && options.buffer[fdNumber]);
335493
- if (process$1.platform === "win32" && path.basename(file, ".exe") === "cmd") commandArguments.unshift("/q");
335808
+ if (_w.platform === "win32" && path.basename(file, ".exe") === "cmd") commandArguments.unshift("/q");
335494
335809
  return {
335495
335810
  file,
335496
335811
  commandArguments,
@@ -335517,7 +335832,7 @@ const addDefaultOptions = ({ extendEnv = true, preferLocal = false, cwd, localDi
335517
335832
  });
335518
335833
  const getEnv = ({ env: envOption, extendEnv, preferLocal, node, localDirectory, nodePath }) => {
335519
335834
  const env = extendEnv ? {
335520
- ...process$1.env,
335835
+ ..._w.env,
335521
335836
  ...envOption
335522
335837
  } : envOption;
335523
335838
  if (preferLocal || node) return npmRunPathEnv({
@@ -336519,12 +336834,12 @@ const guessStreamDirection = {
336519
336834
  }
336520
336835
  };
336521
336836
  const getStandardStreamDirection = (value) => {
336522
- if ([0, process$1.stdin].includes(value)) return "input";
336837
+ if ([0, _w.stdin].includes(value)) return "input";
336523
336838
  if ([
336524
336839
  1,
336525
336840
  2,
336526
- process$1.stdout,
336527
- process$1.stderr
336841
+ _w.stdout,
336842
+ _w.stderr
336528
336843
  ].includes(value)) return "output";
336529
336844
  };
336530
336845
  const DEFAULT_DIRECTION = "output";
@@ -337588,9 +337903,9 @@ const addIpcMethods = (subprocess, { ipc }) => {
337588
337903
  Object.assign(subprocess, getIpcMethods(subprocess, false, ipc));
337589
337904
  };
337590
337905
  const getIpcExport = () => {
337591
- const anyProcess = process$1;
337906
+ const anyProcess = _w;
337592
337907
  const isSubprocess = true;
337593
- const ipc = process$1.channel !== void 0;
337908
+ const ipc = _w.channel !== void 0;
337594
337909
  return {
337595
337910
  ...getIpcMethods(anyProcess, isSubprocess, ipc),
337596
337911
  getCancelSignal: getCancelSignal$1.bind(void 0, {
@@ -338067,7 +338382,7 @@ var SignalExitFallback = class extends SignalExitBase {
338067
338382
  };
338068
338383
  var SignalExit = class extends SignalExitBase {
338069
338384
  /* c8 ignore start */
338070
- #hupSig = process$2.platform === "win32" ? "SIGINT" : "SIGHUP";
338385
+ #hupSig = process$1.platform === "win32" ? "SIGINT" : "SIGHUP";
338071
338386
  /* c8 ignore stop */
338072
338387
  #emitter = new Emitter();
338073
338388
  #process;
@@ -338162,8 +338477,8 @@ var SignalExit = class extends SignalExitBase {
338162
338477
  } else return og.call(this.#process, ev, ...args);
338163
338478
  }
338164
338479
  };
338165
- const process$2 = globalThis.process;
338166
- const { onExit, load: load$1, unload } = signalExitWrap(processOk(process$2) ? new SignalExit(process$2) : new SignalExitFallback());
338480
+ const process$1 = globalThis.process;
338481
+ const { onExit, load: load$1, unload } = signalExitWrap(processOk(process$1) ? new SignalExit(process$1) : new SignalExitFallback());
338167
338482
 
338168
338483
  //#endregion
338169
338484
  //#region node_modules/.pnpm/execa@9.6.1/node_modules/execa/lib/terminate/cleanup.js
@@ -552543,6 +552858,7 @@ var ComputerRuntime = class {
552543
552858
  isBackground: args.background || false,
552544
552859
  output: r.output,
552545
552860
  outputFiles,
552861
+ running: r.running,
552546
552862
  sandboxed: r.sandboxed,
552547
552863
  stderr: r.stderr,
552548
552864
  stdout: r.stdout,
@@ -553661,6 +553977,52 @@ async function executeToolCall(apiName, argsStr, timeout, auth) {
553661
553977
  }
553662
553978
  }
553663
553979
 
553980
+ //#endregion
553981
+ //#region src/commands/connect/completionWatch.ts
553982
+ /** The longest single local wait for a watched command (the shell's own cap). */
553983
+ const COMPLETION_OBSERVATION_TIMEOUT_MS = 6e5;
553984
+ /**
553985
+ * The reply for a finished tool call. When the server asked for a late result
553986
+ * and the command is still running, the reply says this device keeps watching
553987
+ * (`state.completionWatch`) and the final `getCommandOutput` answer is reported
553988
+ * once the process exits — the server parks the run instead of the model
553989
+ * polling.
553990
+ *
553991
+ * The watch runs outside `maintenance.run` on purpose: a command can run for
553992
+ * hours, and a CLI restart must not wait on it. A restart loses the watch; the
553993
+ * server's own deadline then closes the call.
553994
+ */
553995
+ const prepareCompletionReply = (request, result, { getReporter, getToolAuth, logger }) => {
553996
+ const shellId = resolveWatchableShell(request, result);
553997
+ if (!shellId || !request.operationId || !request.completion) return result;
553998
+ watchToolCallCompletion({
553999
+ getReporter,
554000
+ logger,
554001
+ observe: async () => {
554002
+ const output = await executeToolCall("getCommandOutput", JSON.stringify({
554003
+ shell_id: shellId,
554004
+ timeout: COMPLETION_OBSERVATION_TIMEOUT_MS
554005
+ }), COMPLETION_OBSERVATION_TIMEOUT_MS, getToolAuth());
554006
+ const running = output.state?.running === true;
554007
+ const final = {
554008
+ content: output.content,
554009
+ success: output.success
554010
+ };
554011
+ if (output.error !== void 0) final.error = output.error;
554012
+ if (output.state !== void 0) final.state = output.state;
554013
+ return {
554014
+ done: output.success === false || !running,
554015
+ result: final
554016
+ };
554017
+ },
554018
+ operationId: request.operationId,
554019
+ toolCallId: request.completion.toolCallId
554020
+ }).catch((err) => {
554021
+ logger.error(`Completion watch for ${shellId} failed: ${err instanceof Error ? err.message : err}`);
554022
+ });
554023
+ return withCompletionWatch(result);
554024
+ };
554025
+
553664
554026
  //#endregion
553665
554027
  //#region src/commands/connect/handlers.ts
553666
554028
  /**
@@ -553732,15 +554094,24 @@ function bindGatewayClientHandlers(client, ctx, connectionWorkspaceId) {
553732
554094
  const executionTimeMs = Math.round(performance.now() - startedAt);
553733
554095
  if (isDaemonChild) appendLog(`[RESULT] ${result.success ? "OK" : "FAIL"} ${executionTimeMs}ms${operationId ? ` op=${operationId}` : ""} (${requestId})`);
553734
554096
  else log$13.toolResult(requestId, result.success, result.content, operationId);
554097
+ const reply = prepareCompletionReply(request, {
554098
+ content: result.content,
554099
+ error: result.error,
554100
+ executionTimeMs,
554101
+ state: result.state,
554102
+ success: result.success
554103
+ }, {
554104
+ getReporter: () => client,
554105
+ getToolAuth,
554106
+ logger: {
554107
+ error: (...args) => error(args.join(" ")),
554108
+ info: (...args) => isDaemonChild ? appendLog(`[COMPLETION] ${args.join(" ")}`) : info(args.join(" ")),
554109
+ warn: (...args) => error(args.join(" "))
554110
+ }
554111
+ });
553735
554112
  client.sendToolCallResponse({
553736
554113
  requestId,
553737
- result: {
553738
- content: result.content,
553739
- error: result.error,
553740
- executionTimeMs,
553741
- state: result.state,
553742
- success: result.success
553743
- }
554114
+ result: reply
553744
554115
  });
553745
554116
  });
553746
554117
  client.on("rpc_request", async (request) => {
@@ -554814,14 +555185,16 @@ function registerConnectorCommand(program) {
554814
555185
  truncate$2(c.name || "", 30),
554815
555186
  c.sourceType || "",
554816
555187
  c.status === "connected" ? import_picocolors.default.green(c.status) : c.status || "",
554817
- String(c.toolCount)
555188
+ String(c.toolCount),
555189
+ String(c.links?.length ?? 0)
554818
555190
  ]), [
554819
555191
  "ID",
554820
555192
  "IDENTIFIER",
554821
555193
  "NAME",
554822
555194
  "SOURCE",
554823
555195
  "STATUS",
554824
- "TOOLS"
555196
+ "TOOLS",
555197
+ "ACCOUNTS"
554825
555198
  ]);
554826
555199
  });
554827
555200
  connector.command("add").description("Add a custom MCP connector and sync its tools").option("--url <url>", "MCP server URL (streamable HTTP / SSE)").option("--name <name>", "Display name (defaults to the identifier)").option("--identifier <id>", "Connector identifier (derived from --name or --url if omitted)").option("--auth <type>", "Auth type: none, bearer or oauth2").option("--token <token>", "Bearer token (with --auth bearer)").option("--header <key:value>", "Custom request header (repeatable)", collect$1, []).option("--stdio-cmd <command>", "stdio MCP server command").option("--stdio-arg <arg>", "stdio MCP server argument (repeatable)", collect$1, []).option("--force", "Overwrite an existing connector with the same identifier").option("--json [fields]", "Output JSON, optionally specify fields (comma-separated)").action(async (options) => {