@cmmd-center/forge 0.13.137 → 0.13.138

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/bin.cjs CHANGED
@@ -12,7 +12,7 @@ const require_Cache = require("./Cache-D-JaJz5Q.cjs");
12
12
  const require_SqlError = require("./SqlError-BqOsoG0V.cjs");
13
13
  const require_Mime = require("./Mime-Bilnh8zE.cjs");
14
14
  const require_esm = require("./esm-BZhXwX5p.cjs");
15
- const require_runtimeControlAuthority = require("./runtimeControlAuthority-DCitZFTk.cjs");
15
+ const require_runtimeControlAuthority = require("./runtimeControlAuthority-D380Wxs0.cjs");
16
16
  const require_PTY = require("./PTY-C8ypptmz.cjs");
17
17
  const require_settle = require("./settle-B6Rn65UV.cjs");
18
18
  let node_child_process = require("node:child_process");
@@ -66431,7 +66431,7 @@ function normalizeNumberish(value) {
66431
66431
  }
66432
66432
  //#endregion
66433
66433
  //#region package.json
66434
- var version$1 = "0.13.137";
66434
+ var version$1 = "0.13.138";
66435
66435
  //#endregion
66436
66436
  //#region src/sentry.ts
66437
66437
  const SERVER_APP_NAME = "forge-server";
@@ -292019,6 +292019,51 @@ async function maybeRefreshRuntimeProvisioningGrant(input) {
292019
292019
  return "refreshed";
292020
292020
  }
292021
292021
  //#endregion
292022
+ //#region src/runtimeAuth/SidekickHeartbeatAuthorityInstaller.ts
292023
+ const SIDEKICK_HEARTBEAT_OWNER_ID = "runtime-heartbeat";
292024
+ function verifySidekickHeartbeatTicket(ticket, identity) {
292025
+ const claims = require_runtimeControlAuthority.verifyCmmdRuntimeTicket(ticket.token, identity);
292026
+ if (claims === null || claims.scope.length !== 1 || claims.scope[0] !== "sidekick" || claims.machineId !== identity.machineId || claims.credentialEpoch !== identity.credentialEpoch || Date.parse(ticket.expiresAt) !== claims.expiresAtSeconds * 1e3) return null;
292027
+ return claims;
292028
+ }
292029
+ /**
292030
+ * Verifies and installs a `sidekickAuthority` ticket the runtime control
292031
+ * heartbeat delivered (CMMD#5945, forge#3594) into the SAME
292032
+ * `runtimeBrokerAuthority` cache `resolveWorkSessionSidekickRuntimeGrant`
292033
+ * (`cmmdWorkSessionCapabilityBroker.ts`) reads for the Work Session
292034
+ * capability broker. Without this, that cache holds only the original kick
292035
+ * ticket's `sidekick` scope, which expires 15 minutes into a turn with
292036
+ * nothing to replace it — any re-mint of the delegated Sidekick-tool
292037
+ * capability past that point fails closed with `CMMD_AUTH_REQUIRED`. The
292038
+ * 30-second heartbeat tick calling this re-installs a fresh one long before
292039
+ * that TTL is ever in danger.
292040
+ *
292041
+ * Uses the synthetic session id `cmmd-runtime:<runtimeId>:<userId>` — the
292042
+ * SAME one `PipelineProviderAuthorityInstaller` installs `provider`
292043
+ * authority under for automation runs. `readRuntimeBrokerAuthorityForRuntime`
292044
+ * scans every session for a runtime regardless of which one recorded it, so
292045
+ * sharing the id costs nothing and keeps one fewer synthetic session alive
292046
+ * per runtime.
292047
+ *
292048
+ * Never throws: a malformed or wrongly-scoped ticket is a bug on CMMD's side
292049
+ * or a corrupted response in flight, not a reason to crash the heartbeat
292050
+ * loop that is this runtime's own path back to a healthy state. Returns
292051
+ * whether anything was actually installed, purely for logging/tests — the
292052
+ * heartbeat loop that calls this must never let a `false` here interrupt the
292053
+ * heartbeat itself.
292054
+ */
292055
+ function installSidekickHeartbeatAuthority(input) {
292056
+ if (input.ticket === null) return false;
292057
+ const claims = verifySidekickHeartbeatTicket(input.ticket, input.identity);
292058
+ if (claims === null) return false;
292059
+ return recordRuntimeBrokerAuthority({
292060
+ sessionId: AuthSessionId.make(`cmmd-runtime:${input.identity.runtimeId}:${input.identity.userId}`),
292061
+ ownerId: SIDEKICK_HEARTBEAT_OWNER_ID,
292062
+ token: input.ticket.token,
292063
+ claims
292064
+ }).installed;
292065
+ }
292066
+ //#endregion
292022
292067
  //#region src/runtimeDrain/RuntimeDrainReporter.ts
292023
292068
  const HEARTBEAT_INTERVAL = require_Schema$1.seconds(30);
292024
292069
  const HEARTBEAT_TICK_TIMEOUT = require_Schema$1.seconds(60);
@@ -292035,6 +292080,30 @@ function runtimeHeartbeatConfig(config) {
292035
292080
  credentialEpoch
292036
292081
  };
292037
292082
  }
292083
+ /**
292084
+ * The full exact-machine identity `installSidekickHeartbeatAuthority` needs
292085
+ * to verify a delivered `sidekickAuthority` ticket — a superset of
292086
+ * `runtimeHeartbeatConfig` (which the heartbeat request itself needs) with
292087
+ * org, user and the verification public key added, the same fields
292088
+ * `PipelineProviderAuthorityInstaller.ts`'s `resolveExactRuntimeIdentity`
292089
+ * requires for the `provider` scope. Null on any missing field: a runtime
292090
+ * without a complete exact identity gets no `sidekick` re-delivery, exactly
292091
+ * as it gets no control heartbeat at all from `runtimeHeartbeatConfig`.
292092
+ */
292093
+ function sidekickHeartbeatIdentityConfig(config) {
292094
+ const heartbeatConfig = runtimeHeartbeatConfig(config);
292095
+ if (!heartbeatConfig) return null;
292096
+ const orgId = config.forgeCmmdRuntimeOrgId?.trim();
292097
+ const userId = config.forgeCmmdRuntimeUserId?.trim();
292098
+ const publicKeyPem = config.forgeCmmdRuntimePublicKey?.trim();
292099
+ if (!orgId || !userId || !publicKeyPem) return null;
292100
+ return {
292101
+ ...heartbeatConfig,
292102
+ orgId,
292103
+ userId,
292104
+ publicKeyPem
292105
+ };
292106
+ }
292038
292107
  function runtimeGrantRefreshConfig(config) {
292039
292108
  if (config.forgeCmmdRuntimeMode !== true) return null;
292040
292109
  const runtimeId = config.forgeCmmdRuntimeId?.trim();
@@ -292088,12 +292157,21 @@ const makeRuntimeDrainReporter = require_Schema$1.gen(function* () {
292088
292157
  const spriteTaskHoldReactor = yield* SpriteTaskHoldReactor;
292089
292158
  const reportSemaphore = yield* require_Path.make$5(1);
292090
292159
  let heartbeatSilent = false;
292091
- const applyControlPlaneState = (runtime) => drainState.applyControlPlaneState({
292092
- draining: runtime.draining,
292093
- drainReason: runtime.drainReason,
292094
- drainTargetImageRef: runtime.drainTargetImageRef,
292095
- drainTargetImageVersion: runtime.drainTargetImageVersion,
292096
- drainForceRequired: runtime.drainForceRequired
292160
+ const applyControlPlaneState = (runtime) => require_Schema$1.gen(function* () {
292161
+ yield* drainState.applyControlPlaneState({
292162
+ draining: runtime.draining,
292163
+ drainReason: runtime.drainReason,
292164
+ drainTargetImageRef: runtime.drainTargetImageRef,
292165
+ drainTargetImageVersion: runtime.drainTargetImageVersion,
292166
+ drainForceRequired: runtime.drainForceRequired
292167
+ });
292168
+ const sidekickIdentity = sidekickHeartbeatIdentityConfig(serverConfig);
292169
+ if (sidekickIdentity) yield* require_Schema$1.sync(() => {
292170
+ installSidekickHeartbeatAuthority({
292171
+ identity: sidekickIdentity,
292172
+ ticket: runtime.sidekickAuthority
292173
+ });
292174
+ });
292097
292175
  });
292098
292176
  const refreshProvisioningGrantIfNeeded = require_Schema$1.gen(function* () {
292099
292177
  const grantConfig = runtimeGrantRefreshConfig(serverConfig);
@@ -300696,7 +300774,7 @@ function resolveBuildCommitFromEnv(env) {
300696
300774
  * environment descriptor down instead of reporting an honest "unknown".
300697
300775
  */
300698
300776
  function readBakedBuildCommit() {
300699
- return "bcd01e1ae34a37fd182605061608b45892800be2";
300777
+ return "f3819c0511ca941efd0516f5de0ac518febcb0f2";
300700
300778
  }
300701
300779
  async function resolveServerBuildCommit(input) {
300702
300780
  if (isFullCommitSha(input.baked)) return input.baked;
package/dist/bin.mjs CHANGED
@@ -11,7 +11,7 @@ import { a as make$51, i as keys, n as getOption, o as makeWith$1, r as invalida
11
11
  import { S as layer$9, _ as defaultEscape, a as DeadlockError, b as makeCompiler$1, c as SqlError, d as UnknownError, g as custom, h as make$52, i as ConstraintError, l as SqlSyntaxError, m as SqlClient, n as AuthorizationError, o as LockTimeoutError, r as ConnectionError, s as SerializationError, t as AuthenticationError, u as StatementTimeoutError, v as defaultTransforms, y as fragment } from "./SqlError-BBR7DPrQ.mjs";
12
12
  import { r as wrapper_default, t as Mime_default } from "./Mime-Dq9IoNiV.mjs";
13
13
  import { a as diag, c as SpanKind$1, d as TraceFlags, f as ROOT_CONTEXT, i as propagation, l as isSpanContextValid, m as DiagLogLevel, n as init_esm$1, o as context$1, p as createContextKey, r as trace, s as SpanStatusCode, t as esm_exports$1 } from "./esm-wLIF-u3N.mjs";
14
- import { a as verifyCmmdAuthRuntimeTicket, c as verifyCmmdRuntimeTicket, d as runtimeGrantToken, f as setRuntimeGrantToken, i as sendRuntimeControlHeartbeat, l as verifyCmmdRuntimeTicketRefreshProof, n as bootstrapRuntimeControlAuthorityFromNarrowGrant, o as verifyCmmdClaudeReadinessTicket, p as createReadOnceFileTokenAccessor, r as readRuntimeControlAuthority, s as verifyCmmdClaudeUsageTicket, t as bootstrapRuntimeControlAuthority, u as verifyCmmdScopedRuntimePayload } from "./runtimeControlAuthority-DpRIoWqP.mjs";
14
+ import { a as verifyCmmdAuthRuntimeTicket, c as verifyCmmdRuntimeTicket, d as runtimeGrantToken, f as setRuntimeGrantToken, i as sendRuntimeControlHeartbeat, l as verifyCmmdRuntimeTicketRefreshProof, n as bootstrapRuntimeControlAuthorityFromNarrowGrant, o as verifyCmmdClaudeReadinessTicket, p as createReadOnceFileTokenAccessor, r as readRuntimeControlAuthority, s as verifyCmmdClaudeUsageTicket, t as bootstrapRuntimeControlAuthority, u as verifyCmmdScopedRuntimePayload } from "./runtimeControlAuthority-BtHvsEIc.mjs";
15
15
  import { n as PtySpawnError, t as PtyAdapter } from "./PTY-BRT13Y8S.mjs";
16
16
  import { t as settleValueWithin } from "./settle-BJcmpbvq.mjs";
17
17
  import { createRequire } from "node:module";
@@ -66139,7 +66139,7 @@ function normalizeNumberish(value) {
66139
66139
  }
66140
66140
  //#endregion
66141
66141
  //#region package.json
66142
- var version$1 = "0.13.137";
66142
+ var version$1 = "0.13.138";
66143
66143
  //#endregion
66144
66144
  //#region src/sentry.ts
66145
66145
  const SERVER_APP_NAME = "forge-server";
@@ -291502,6 +291502,51 @@ async function maybeRefreshRuntimeProvisioningGrant(input) {
291502
291502
  return "refreshed";
291503
291503
  }
291504
291504
  //#endregion
291505
+ //#region src/runtimeAuth/SidekickHeartbeatAuthorityInstaller.ts
291506
+ const SIDEKICK_HEARTBEAT_OWNER_ID = "runtime-heartbeat";
291507
+ function verifySidekickHeartbeatTicket(ticket, identity) {
291508
+ const claims = verifyCmmdRuntimeTicket(ticket.token, identity);
291509
+ if (claims === null || claims.scope.length !== 1 || claims.scope[0] !== "sidekick" || claims.machineId !== identity.machineId || claims.credentialEpoch !== identity.credentialEpoch || Date.parse(ticket.expiresAt) !== claims.expiresAtSeconds * 1e3) return null;
291510
+ return claims;
291511
+ }
291512
+ /**
291513
+ * Verifies and installs a `sidekickAuthority` ticket the runtime control
291514
+ * heartbeat delivered (CMMD#5945, forge#3594) into the SAME
291515
+ * `runtimeBrokerAuthority` cache `resolveWorkSessionSidekickRuntimeGrant`
291516
+ * (`cmmdWorkSessionCapabilityBroker.ts`) reads for the Work Session
291517
+ * capability broker. Without this, that cache holds only the original kick
291518
+ * ticket's `sidekick` scope, which expires 15 minutes into a turn with
291519
+ * nothing to replace it — any re-mint of the delegated Sidekick-tool
291520
+ * capability past that point fails closed with `CMMD_AUTH_REQUIRED`. The
291521
+ * 30-second heartbeat tick calling this re-installs a fresh one long before
291522
+ * that TTL is ever in danger.
291523
+ *
291524
+ * Uses the synthetic session id `cmmd-runtime:<runtimeId>:<userId>` — the
291525
+ * SAME one `PipelineProviderAuthorityInstaller` installs `provider`
291526
+ * authority under for automation runs. `readRuntimeBrokerAuthorityForRuntime`
291527
+ * scans every session for a runtime regardless of which one recorded it, so
291528
+ * sharing the id costs nothing and keeps one fewer synthetic session alive
291529
+ * per runtime.
291530
+ *
291531
+ * Never throws: a malformed or wrongly-scoped ticket is a bug on CMMD's side
291532
+ * or a corrupted response in flight, not a reason to crash the heartbeat
291533
+ * loop that is this runtime's own path back to a healthy state. Returns
291534
+ * whether anything was actually installed, purely for logging/tests — the
291535
+ * heartbeat loop that calls this must never let a `false` here interrupt the
291536
+ * heartbeat itself.
291537
+ */
291538
+ function installSidekickHeartbeatAuthority(input) {
291539
+ if (input.ticket === null) return false;
291540
+ const claims = verifySidekickHeartbeatTicket(input.ticket, input.identity);
291541
+ if (claims === null) return false;
291542
+ return recordRuntimeBrokerAuthority({
291543
+ sessionId: AuthSessionId.make(`cmmd-runtime:${input.identity.runtimeId}:${input.identity.userId}`),
291544
+ ownerId: SIDEKICK_HEARTBEAT_OWNER_ID,
291545
+ token: input.ticket.token,
291546
+ claims
291547
+ }).installed;
291548
+ }
291549
+ //#endregion
291505
291550
  //#region src/runtimeDrain/RuntimeDrainReporter.ts
291506
291551
  const HEARTBEAT_INTERVAL = seconds(30);
291507
291552
  const HEARTBEAT_TICK_TIMEOUT = seconds(60);
@@ -291518,6 +291563,30 @@ function runtimeHeartbeatConfig(config) {
291518
291563
  credentialEpoch
291519
291564
  };
291520
291565
  }
291566
+ /**
291567
+ * The full exact-machine identity `installSidekickHeartbeatAuthority` needs
291568
+ * to verify a delivered `sidekickAuthority` ticket — a superset of
291569
+ * `runtimeHeartbeatConfig` (which the heartbeat request itself needs) with
291570
+ * org, user and the verification public key added, the same fields
291571
+ * `PipelineProviderAuthorityInstaller.ts`'s `resolveExactRuntimeIdentity`
291572
+ * requires for the `provider` scope. Null on any missing field: a runtime
291573
+ * without a complete exact identity gets no `sidekick` re-delivery, exactly
291574
+ * as it gets no control heartbeat at all from `runtimeHeartbeatConfig`.
291575
+ */
291576
+ function sidekickHeartbeatIdentityConfig(config) {
291577
+ const heartbeatConfig = runtimeHeartbeatConfig(config);
291578
+ if (!heartbeatConfig) return null;
291579
+ const orgId = config.forgeCmmdRuntimeOrgId?.trim();
291580
+ const userId = config.forgeCmmdRuntimeUserId?.trim();
291581
+ const publicKeyPem = config.forgeCmmdRuntimePublicKey?.trim();
291582
+ if (!orgId || !userId || !publicKeyPem) return null;
291583
+ return {
291584
+ ...heartbeatConfig,
291585
+ orgId,
291586
+ userId,
291587
+ publicKeyPem
291588
+ };
291589
+ }
291521
291590
  function runtimeGrantRefreshConfig(config) {
291522
291591
  if (config.forgeCmmdRuntimeMode !== true) return null;
291523
291592
  const runtimeId = config.forgeCmmdRuntimeId?.trim();
@@ -291571,12 +291640,21 @@ const makeRuntimeDrainReporter = gen(function* () {
291571
291640
  const spriteTaskHoldReactor = yield* SpriteTaskHoldReactor;
291572
291641
  const reportSemaphore = yield* make$43(1);
291573
291642
  let heartbeatSilent = false;
291574
- const applyControlPlaneState = (runtime) => drainState.applyControlPlaneState({
291575
- draining: runtime.draining,
291576
- drainReason: runtime.drainReason,
291577
- drainTargetImageRef: runtime.drainTargetImageRef,
291578
- drainTargetImageVersion: runtime.drainTargetImageVersion,
291579
- drainForceRequired: runtime.drainForceRequired
291643
+ const applyControlPlaneState = (runtime) => gen(function* () {
291644
+ yield* drainState.applyControlPlaneState({
291645
+ draining: runtime.draining,
291646
+ drainReason: runtime.drainReason,
291647
+ drainTargetImageRef: runtime.drainTargetImageRef,
291648
+ drainTargetImageVersion: runtime.drainTargetImageVersion,
291649
+ drainForceRequired: runtime.drainForceRequired
291650
+ });
291651
+ const sidekickIdentity = sidekickHeartbeatIdentityConfig(serverConfig);
291652
+ if (sidekickIdentity) yield* sync$1(() => {
291653
+ installSidekickHeartbeatAuthority({
291654
+ identity: sidekickIdentity,
291655
+ ticket: runtime.sidekickAuthority
291656
+ });
291657
+ });
291580
291658
  });
291581
291659
  const refreshProvisioningGrantIfNeeded = gen(function* () {
291582
291660
  const grantConfig = runtimeGrantRefreshConfig(serverConfig);
@@ -300140,7 +300218,7 @@ function resolveBuildCommitFromEnv(env) {
300140
300218
  * environment descriptor down instead of reporting an honest "unknown".
300141
300219
  */
300142
300220
  function readBakedBuildCommit() {
300143
- return "bcd01e1ae34a37fd182605061608b45892800be2";
300221
+ return "f3819c0511ca941efd0516f5de0ac518febcb0f2";
300144
300222
  }
300145
300223
  async function resolveServerBuildCommit(input) {
300146
300224
  if (isFullCommitSha(input.baked)) return input.baked;
@@ -1,4 +1,4 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Ha as t,Mi as n,Ua as r,Wa as i}from"./Stream-mUTFnSY9.js";import{Kr as a,Lr as o,Ls as s,Nn as c,Qn as l,Tn as u,Vn as d,Wn as f,Yo as p,c as m,d as h,fn as g,kn as _,m as v,ns as y,o as b,pi as x,qn as S,qt as C,s as w,t as T,ts as E,u as D,zn as O}from"./WorkerPoolContext-wx5NJQK1.js";import{a as k,c as A,i as j,l as M,n as N,o as P,r as F,s as I,t as L}from"./Virtualizer-CFIPzyOA.js";import{H as R,Hn as z,Wn as ee,j as B}from"./cmmdForgeRuntimeListResource-KXJO7nN7.js";import{On as V,at as H,ot as U}from"./src-e9jwz4Nc.js";import"./cmmdAuthRedirect-Cpw3QgrC.js";import{t as W}from"./utils-MX9zGa4a.js";import{t as G}from"./chevron-left-1XbEOuXj.js";import{t as K}from"./chevron-right-DAF000Jz.js";import{a as q,c as te,d as ne,h as re,i as ie,l as ae,m as oe,n as se,o as J,p as ce,r as le,s as ue,t as de,u as fe}from"./DiffPanel.logic-B0YyP6X_.js";import{n as pe,t as Y}from"./toggle-group-BRN0oZh2.js";var X=e(i(),1),me=typeof window>`u`?X.useEffect:X.useLayoutEffect;function he({fileDiff:e,options:t,editorOptions:n,lineAnnotations:r,selectedLines:i,prerenderedHTML:a,metrics:o,hasGutterRenderUtility:s,hasCustomHeader:c,disableWorkerPool:l,edit:u}){let d=N(),f=i!==void 0,p=(0,X.useContext)(T),h=w(),g=(0,X.useRef)(null),_=m(n=>{if(n!=null){if(g.current!=null)throw Error(`useFileDiffInstance: An instance should not already exist when a node is created`);d==null?g.current=new ne(Z({controlledSelection:f,hasCustomHeader:c,hasGutterRenderUtility:s,options:t}),l?void 0:p,!0):g.current=new fe(Z({controlledSelection:f,hasCustomHeader:c,hasGutterRenderUtility:s,options:t}),d,o,l?void 0:p,!0),g.current.hydrate({fileDiff:e,fileContainer:n,lineAnnotations:r,prerenderedHTML:a})}else{if(g.current==null)throw Error(`useFileDiffInstance: A FileDiff instance should exist when unmounting`);g.current.cleanUp(),g.current=null}});return me(()=>{let{current:n}=g;if(n==null)return;let a=Z({controlledSelection:f,hasCustomHeader:c,hasGutterRenderUtility:s,options:t}),o=a!==void 0&&!C(n.options,a);n.setOptions(a),n.render({forceRender:o,fileDiff:e,lineAnnotations:r}),i!==void 0&&n.setSelectedLines(i)}),me(()=>{if(u&&g.current!=null){if(h===void 0)throw Error(`FileDiff: EditContext is not attached`);let e=h(n??{});if(e==null)throw Error(`FileDiff: EditProvider.createEditor must return an editor instance`);try{return e.edit(g.current)}catch(t){throw e.cleanUp(),t}}},[u]),{ref:_,getHoveredLine:(0,X.useCallback)(()=>g.current?.getHoveredLine(),[])}}function Z({options:e,controlledSelection:t,hasCustomHeader:n,hasGutterRenderUtility:r}){return t||r||n?{...e,controlledSelection:t,renderCustomHeader:n?b:e?.renderCustomHeader,renderGutterUtility:r?b:e?.renderGutterUtility}:e}var Q=r();function ge({fileDiff:e,options:t,editorOptions:n,metrics:r,lineAnnotations:i,selectedLines:a,className:o,style:s,prerenderedHTML:c,renderAnnotation:l,renderCustomHeader:u,renderHeaderPrefix:d,renderHeaderFilenameSuffix:f,renderHeaderMetadata:p,renderGutterUtility:m,disableWorkerPool:h=!1,edit:_=!1}){let{ref:v,getHoveredLine:y}=he({fileDiff:e,options:t,editorOptions:n,metrics:r,lineAnnotations:i,selectedLines:a,prerenderedHTML:c,hasGutterRenderUtility:m!=null,hasCustomHeader:u!=null,disableWorkerPool:h,edit:_});return(0,Q.jsx)(g,{ref:v,className:o,style:s,children:F(ae({fileDiff:e,renderCustomHeader:u,renderHeaderPrefix:d,renderHeaderFilenameSuffix:f,renderHeaderMetadata:p,renderAnnotation:l,renderGutterUtility:m,lineAnnotations:i,getHoveredLine:y}),c)})}var $=t();function _e(e){return e.fromTurnCount===0?V(H)({threadId:e.threadId,toTurnCount:e.toTurnCount}).pipe(n(e=>({kind:`fullThreadDiff`,input:e}))):V(U)({threadId:e.threadId,fromTurnCount:e.fromTurnCount,toTurnCount:e.toTurnCount}).pipe(n(e=>({kind:`turnDiff`,input:e})))}function ve(e){return e instanceof Error?e.message:typeof e==`string`?e:``}function ye(e){let t=ve(e).trim();if(t.length===0)return`Failed to load checkpoint diff.`;let n=t.toLowerCase();if(n.includes(`not a git repository`))return`Turn diffs are unavailable because this project is not a git repository.`;if(n.includes(`checkpoint unavailable for thread`)||n.includes(`checkpoint invariant violation`)){let e=t.indexOf(`:`);if(e>=0){let n=t.slice(e+1).trim();if(n.length>0)return n}}return t}function be(e){let t=ve(e).toLowerCase();return t.includes(`exceeds current turn count`)||t.includes(`checkpoint is unavailable for turn`)||t.includes(`filesystem checkpoint is unavailable`)}function xe(e){let t=_e(e);return E({queryKey:p.checkpointDiff(e),queryFn:async({signal:n})=>{if(!e.environmentId||!e.threadId||t._tag===`None`)throw Error(`Checkpoint diff is unavailable.`);let r=l(e.environmentId);try{return t.value.kind===`fullThreadDiff`?await r.orchestration.getFullThreadDiff(t.value.input,{signal:n}):await r.orchestration.getTurnDiff(t.value.input,{signal:n})}catch(e){throw Error(ye(e),{cause:e})}},enabled:(e.enabled??!0)&&!!e.environmentId&&!!e.threadId&&t._tag===`Some`,staleTime:1/0,retry:(e,t)=>be(t)?e<12:e<3,retryDelay:(e,t)=>be(t)?Math.min(5e3,250*2**(e-1)):Math.min(1e3,100*2**(e-1))})}function Se(e){if(!(!e.canScrollLeft&&!e.canScrollRight))return{maskImage:`linear-gradient(to right, ${e.canScrollLeft?`transparent 24px, black 72px`:`black`}, ${e.canScrollRight?`black calc(100% - 72px), transparent calc(100% - 24px)`:`black`})`}}function Ce(e){return e instanceof Error?e.message:e?`Failed to load checkpoint diff.`:null}function we(e){return{environmentId:e.environmentId??null,threadId:e.threadId,fromTurnCount:e.range?.fromTurnCount??null,toTurnCount:e.range?.toTurnCount??null,cacheScope:e.selectedTurnId?`turn:${e.selectedTurnId}`:e.conversationCacheScope,enabled:e.enabled}}function Te(){let e=(0,$.c)(8),t=(0,X.useRef)(null),[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)(!1),o;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(o=()=>{let e=t.current;if(!e){r(!1),a(!1);return}let n=ue({scrollLeft:e.scrollLeft,scrollWidth:e.scrollWidth,clientWidth:e.clientWidth});r(n.canScrollLeft),a(n.canScrollRight)},e[0]=o):o=e[0];let s=o,c;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(c=e=>{t.current?.scrollBy({left:e,behavior:`smooth`})},e[1]=c):c=e[1];let l=c,u;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(u=e=>{let n=t.current;n&&te({scrollWidth:n.scrollWidth,clientWidth:n.clientWidth,deltaX:e.deltaX,deltaY:e.deltaY})&&(e.preventDefault(),n.scrollBy({left:e.deltaY,behavior:`auto`}))},e[2]=u):u=e[2];let d=u,f,p;e[3]===Symbol.for(`react.memo_cache_sentinel`)?(f=()=>{let e=t.current;if(!e)return;let n=window.requestAnimationFrame(s),r=()=>s();e.addEventListener(`scroll`,r,{passive:!0});let i=new ResizeObserver(()=>s());return i.observe(e),()=>{window.cancelAnimationFrame(n),e.removeEventListener(`scroll`,r),i.disconnect()}},p=[s],e[3]=f,e[4]=p):(f=e[3],p=e[4]),(0,X.useEffect)(f,p);let m;return e[5]!==n||e[6]!==i?(m={ref:t,canScrollLeft:n,canScrollRight:i,scrollBy:l,onWheel:d,remeasure:s},e[5]=n,e[6]=i,e[7]=m):m=e[7],m}function Ee(e,t){let n=(0,$.c)(5),r;n[0]===e.current?r=n[1]:(r=()=>{(e.current?.querySelector(`[data-turn-chip-selected='true']`))?.scrollIntoView({block:`nearest`,inline:`nearest`,behavior:`smooth`})},n[0]=e.current,n[1]=r);let i;n[2]!==e||n[3]!==t?(i=[e,t],n[2]=e,n[3]=t,n[4]=i):i=n[4],(0,X.useEffect)(r,i)}var De=`
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Ha as t,Mi as n,Ua as r,Wa as i}from"./Stream-mUTFnSY9.js";import{Kr as a,Lr as o,Ls as s,Nn as c,Qn as l,Tn as u,Vn as d,Wn as f,Yo as p,c as m,d as h,fn as g,kn as _,m as v,ns as y,o as b,pi as x,qn as S,qt as C,s as w,t as T,ts as E,u as D,zn as O}from"./WorkerPoolContext-TpWU8uqG.js";import{a as k,c as A,i as j,l as M,n as N,o as P,r as F,s as I,t as L}from"./Virtualizer-BmzUFtvU.js";import{H as R,Hn as z,Wn as ee,j as B}from"./cmmdForgeRuntimeListResource-BNkVBIli.js";import{On as V,at as H,ot as U}from"./src-e9jwz4Nc.js";import"./cmmdAuthRedirect-Cpw3QgrC.js";import{t as W}from"./utils-MX9zGa4a.js";import{t as G}from"./chevron-left-1XbEOuXj.js";import{t as K}from"./chevron-right-DAF000Jz.js";import{a as q,c as te,d as ne,h as re,i as ie,l as ae,m as oe,n as se,o as J,p as ce,r as le,s as ue,t as de,u as fe}from"./DiffPanel.logic-Bzk6loSH.js";import{n as pe,t as Y}from"./toggle-group-BRN0oZh2.js";var X=e(i(),1),me=typeof window>`u`?X.useEffect:X.useLayoutEffect;function he({fileDiff:e,options:t,editorOptions:n,lineAnnotations:r,selectedLines:i,prerenderedHTML:a,metrics:o,hasGutterRenderUtility:s,hasCustomHeader:c,disableWorkerPool:l,edit:u}){let d=N(),f=i!==void 0,p=(0,X.useContext)(T),h=w(),g=(0,X.useRef)(null),_=m(n=>{if(n!=null){if(g.current!=null)throw Error(`useFileDiffInstance: An instance should not already exist when a node is created`);d==null?g.current=new ne(Z({controlledSelection:f,hasCustomHeader:c,hasGutterRenderUtility:s,options:t}),l?void 0:p,!0):g.current=new fe(Z({controlledSelection:f,hasCustomHeader:c,hasGutterRenderUtility:s,options:t}),d,o,l?void 0:p,!0),g.current.hydrate({fileDiff:e,fileContainer:n,lineAnnotations:r,prerenderedHTML:a})}else{if(g.current==null)throw Error(`useFileDiffInstance: A FileDiff instance should exist when unmounting`);g.current.cleanUp(),g.current=null}});return me(()=>{let{current:n}=g;if(n==null)return;let a=Z({controlledSelection:f,hasCustomHeader:c,hasGutterRenderUtility:s,options:t}),o=a!==void 0&&!C(n.options,a);n.setOptions(a),n.render({forceRender:o,fileDiff:e,lineAnnotations:r}),i!==void 0&&n.setSelectedLines(i)}),me(()=>{if(u&&g.current!=null){if(h===void 0)throw Error(`FileDiff: EditContext is not attached`);let e=h(n??{});if(e==null)throw Error(`FileDiff: EditProvider.createEditor must return an editor instance`);try{return e.edit(g.current)}catch(t){throw e.cleanUp(),t}}},[u]),{ref:_,getHoveredLine:(0,X.useCallback)(()=>g.current?.getHoveredLine(),[])}}function Z({options:e,controlledSelection:t,hasCustomHeader:n,hasGutterRenderUtility:r}){return t||r||n?{...e,controlledSelection:t,renderCustomHeader:n?b:e?.renderCustomHeader,renderGutterUtility:r?b:e?.renderGutterUtility}:e}var Q=r();function ge({fileDiff:e,options:t,editorOptions:n,metrics:r,lineAnnotations:i,selectedLines:a,className:o,style:s,prerenderedHTML:c,renderAnnotation:l,renderCustomHeader:u,renderHeaderPrefix:d,renderHeaderFilenameSuffix:f,renderHeaderMetadata:p,renderGutterUtility:m,disableWorkerPool:h=!1,edit:_=!1}){let{ref:v,getHoveredLine:y}=he({fileDiff:e,options:t,editorOptions:n,metrics:r,lineAnnotations:i,selectedLines:a,prerenderedHTML:c,hasGutterRenderUtility:m!=null,hasCustomHeader:u!=null,disableWorkerPool:h,edit:_});return(0,Q.jsx)(g,{ref:v,className:o,style:s,children:F(ae({fileDiff:e,renderCustomHeader:u,renderHeaderPrefix:d,renderHeaderFilenameSuffix:f,renderHeaderMetadata:p,renderAnnotation:l,renderGutterUtility:m,lineAnnotations:i,getHoveredLine:y}),c)})}var $=t();function _e(e){return e.fromTurnCount===0?V(H)({threadId:e.threadId,toTurnCount:e.toTurnCount}).pipe(n(e=>({kind:`fullThreadDiff`,input:e}))):V(U)({threadId:e.threadId,fromTurnCount:e.fromTurnCount,toTurnCount:e.toTurnCount}).pipe(n(e=>({kind:`turnDiff`,input:e})))}function ve(e){return e instanceof Error?e.message:typeof e==`string`?e:``}function ye(e){let t=ve(e).trim();if(t.length===0)return`Failed to load checkpoint diff.`;let n=t.toLowerCase();if(n.includes(`not a git repository`))return`Turn diffs are unavailable because this project is not a git repository.`;if(n.includes(`checkpoint unavailable for thread`)||n.includes(`checkpoint invariant violation`)){let e=t.indexOf(`:`);if(e>=0){let n=t.slice(e+1).trim();if(n.length>0)return n}}return t}function be(e){let t=ve(e).toLowerCase();return t.includes(`exceeds current turn count`)||t.includes(`checkpoint is unavailable for turn`)||t.includes(`filesystem checkpoint is unavailable`)}function xe(e){let t=_e(e);return E({queryKey:p.checkpointDiff(e),queryFn:async({signal:n})=>{if(!e.environmentId||!e.threadId||t._tag===`None`)throw Error(`Checkpoint diff is unavailable.`);let r=l(e.environmentId);try{return t.value.kind===`fullThreadDiff`?await r.orchestration.getFullThreadDiff(t.value.input,{signal:n}):await r.orchestration.getTurnDiff(t.value.input,{signal:n})}catch(e){throw Error(ye(e),{cause:e})}},enabled:(e.enabled??!0)&&!!e.environmentId&&!!e.threadId&&t._tag===`Some`,staleTime:1/0,retry:(e,t)=>be(t)?e<12:e<3,retryDelay:(e,t)=>be(t)?Math.min(5e3,250*2**(e-1)):Math.min(1e3,100*2**(e-1))})}function Se(e){if(!(!e.canScrollLeft&&!e.canScrollRight))return{maskImage:`linear-gradient(to right, ${e.canScrollLeft?`transparent 24px, black 72px`:`black`}, ${e.canScrollRight?`black calc(100% - 72px), transparent calc(100% - 24px)`:`black`})`}}function Ce(e){return e instanceof Error?e.message:e?`Failed to load checkpoint diff.`:null}function we(e){return{environmentId:e.environmentId??null,threadId:e.threadId,fromTurnCount:e.range?.fromTurnCount??null,toTurnCount:e.range?.toTurnCount??null,cacheScope:e.selectedTurnId?`turn:${e.selectedTurnId}`:e.conversationCacheScope,enabled:e.enabled}}function Te(){let e=(0,$.c)(8),t=(0,X.useRef)(null),[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)(!1),o;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(o=()=>{let e=t.current;if(!e){r(!1),a(!1);return}let n=ue({scrollLeft:e.scrollLeft,scrollWidth:e.scrollWidth,clientWidth:e.clientWidth});r(n.canScrollLeft),a(n.canScrollRight)},e[0]=o):o=e[0];let s=o,c;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(c=e=>{t.current?.scrollBy({left:e,behavior:`smooth`})},e[1]=c):c=e[1];let l=c,u;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(u=e=>{let n=t.current;n&&te({scrollWidth:n.scrollWidth,clientWidth:n.clientWidth,deltaX:e.deltaX,deltaY:e.deltaY})&&(e.preventDefault(),n.scrollBy({left:e.deltaY,behavior:`auto`}))},e[2]=u):u=e[2];let d=u,f,p;e[3]===Symbol.for(`react.memo_cache_sentinel`)?(f=()=>{let e=t.current;if(!e)return;let n=window.requestAnimationFrame(s),r=()=>s();e.addEventListener(`scroll`,r,{passive:!0});let i=new ResizeObserver(()=>s());return i.observe(e),()=>{window.cancelAnimationFrame(n),e.removeEventListener(`scroll`,r),i.disconnect()}},p=[s],e[3]=f,e[4]=p):(f=e[3],p=e[4]),(0,X.useEffect)(f,p);let m;return e[5]!==n||e[6]!==i?(m={ref:t,canScrollLeft:n,canScrollRight:i,scrollBy:l,onWheel:d,remeasure:s},e[5]=n,e[6]=i,e[7]=m):m=e[7],m}function Ee(e,t){let n=(0,$.c)(5),r;n[0]===e.current?r=n[1]:(r=()=>{(e.current?.querySelector(`[data-turn-chip-selected='true']`))?.scrollIntoView({block:`nearest`,inline:`nearest`,behavior:`smooth`})},n[0]=e.current,n[1]=r);let i;n[2]!==e||n[3]!==t?(i=[e,t],n[2]=e,n[3]=t,n[4]=i):i=n[4],(0,X.useEffect)(r,i)}var De=`
2
2
  [data-diffs-header],
3
3
  [data-diff],
4
4
  [data-file],
@@ -61,4 +61,4 @@ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Ha as t,Mi as n,Ua as
61
61
  text-decoration-color: currentColor;
62
62
  }
63
63
  `;function Oe(e){let t=(0,$.c)(44),{mode:n}=e,r=n===void 0?`inline`:n,{resolvedTheme:i}=c(),o=a(),[s,l]=(0,X.useState)(`stacked`),[d,f]=(0,X.useState)(o.diffWordWrap),p=(0,X.useRef)(null),m=(0,X.useRef)(!1),g=Te(),{activeCwd:v,activeThread:y,bodyState:b,diffOpen:x,inferredCheckpointTurnCountByTurnId:C,orderedTurnDiffSummaries:w,renderableFiles:T,renderablePatch:E,selectedFilePath:D,selectedTurn:k,selectedTurnId:A}=Le(i),j,M;t[0]!==x||t[1]!==o.diffWordWrap?(j=()=>{x&&!m.current&&f(o.diffWordWrap),m.current=x},M=[x,o.diffWordWrap],t[0]=x,t[1]=o.diffWordWrap,t[2]=j,t[3]=M):(j=t[2],M=t[3]),(0,X.useEffect)(j,M);let N;t[4]===D?N=t[5]:(N=()=>{!D||!p.current||Array.from(p.current.querySelectorAll(`[data-diff-file-path]`)).find(e=>e.dataset.diffFilePath===D)?.scrollIntoView({block:`nearest`})},t[4]=D,t[5]=N);let P;t[6]!==T||t[7]!==D?(P=[D,T],t[6]=T,t[7]=D,t[8]=P):P=t[8],(0,X.useEffect)(N,P);let F;t[9]===v?F=t[10]:(F=e=>{let t=O();if(!t)return;let n=v?u(e,v):e;_(t,n).catch(ke)},t[9]=v,t[10]=F);let I=F,L;t[11]===y?L=t[12]:(L=e=>{y&&S.getState().openDiff(ee(z(y.environmentId,y.id)),e)},t[11]=y,t[12]=L);let R=L,B;t[13]===y?B=t[14]:(B=()=>{y&&S.getState().openDiff(ee(z(y.environmentId,y.id)))},t[13]=y,t[14]=B);let V=B,H;t[15]===g.remeasure?H=t[16]:(H=()=>{let e=window.requestAnimationFrame(g.remeasure);return()=>window.cancelAnimationFrame(e)},t[15]=g.remeasure,t[16]=H);let U;t[17]!==w||t[18]!==A||t[19]!==g.remeasure?(U=[w,A,g.remeasure],t[17]=w,t[18]=A,t[19]=g.remeasure,t[20]=U):U=t[20],(0,X.useEffect)(H,U),Ee(g.ref,k?.turnId??A);let W;t[21]!==s||t[22]!==d||t[23]!==C||t[24]!==w||t[25]!==R||t[26]!==V||t[27]!==k||t[28]!==A||t[29]!==o||t[30]!==g?(W=(0,Q.jsx)(Ae,{diffRenderMode:s,diffWordWrap:d,inferredCheckpointTurnCountByTurnId:C,orderedTurnDiffSummaries:w,selectTurn:R,selectWholeConversation:V,selectedTurn:k,selectedTurnId:A,setDiffRenderMode:l,setDiffWordWrap:f,settings:o,turnStrip:g}),t[21]=s,t[22]=d,t[23]=C,t[24]=w,t[25]=R,t[26]=V,t[27]=k,t[28]=A,t[29]=o,t[30]=g,t[31]=W):W=t[31];let G=W,K;t[32]!==b||t[33]!==s||t[34]!==d||t[35]!==I||t[36]!==T||t[37]!==E||t[38]!==i?(K=(0,Q.jsx)(je,{bodyState:b,diffRenderMode:s,diffWordWrap:d,openDiffFileInEditor:I,patchViewportRef:p,renderableFiles:T,renderablePatch:E,resolvedTheme:i}),t[32]=b,t[33]=s,t[34]=d,t[35]=I,t[36]=T,t[37]=E,t[38]=i,t[39]=K):K=t[39];let q;return t[40]!==G||t[41]!==r||t[42]!==K?(q=(0,Q.jsx)(h,{mode:r,header:G,children:K}),t[40]=G,t[41]=r,t[42]=K,t[43]=q):q=t[43],q}function ke(e){console.warn(`Failed to open diff file in editor.`,e)}function Ae(e){let t=(0,$.c)(59),{diffRenderMode:n,diffWordWrap:r,inferredCheckpointTurnCountByTurnId:i,orderedTurnDiffSummaries:a,selectTurn:o,selectWholeConversation:s,selectedTurn:c,selectedTurnId:l,setDiffRenderMode:u,setDiffWordWrap:d,settings:f,turnStrip:p}=e,m,h;t[0]===p?(m=t[1],h=t[2]):(m=(0,Q.jsx)(Be,{direction:`left`,strip:p}),h=(0,Q.jsx)(Be,{direction:`right`,strip:p}),t[0]=p,t[1]=m,t[2]=h);let g=p.ref,_;t[3]!==p.canScrollLeft||t[4]!==p.canScrollRight?(_=Se({canScrollLeft:p.canScrollLeft,canScrollRight:p.canScrollRight}),t[3]=p.canScrollLeft,t[4]=p.canScrollRight,t[5]=_):_=t[5];let v=p.onWheel,y=l===null,b=l===null?`border-border bg-accent text-accent-foreground`:`border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80`,x;t[6]===b?x=t[7]:(x=W(`rounded-md border px-2 py-1 text-left transition-colors`,b),t[6]=b,t[7]=x);let S;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(S=(0,Q.jsx)(`div`,{className:`text-[10px] leading-tight font-medium`,children:`All turns`}),t[8]=S):S=t[8];let C;t[9]===x?C=t[10]:(C=(0,Q.jsx)(`div`,{className:x,children:S}),t[9]=x,t[10]=C);let w;t[11]!==s||t[12]!==C||t[13]!==y?(w=(0,Q.jsx)(`button`,{type:`button`,className:`shrink-0 rounded-md`,onClick:s,"data-turn-chip-selected":y,children:C}),t[11]=s,t[12]=C,t[13]=y,t[14]=w):w=t[14];let T;if(t[15]!==i||t[16]!==a||t[17]!==o||t[18]!==c?.turnId||t[19]!==f){let e;t[21]!==i||t[22]!==o||t[23]!==c?.turnId||t[24]!==f?(e=e=>(0,Q.jsx)(Ve,{summary:e,selected:e.turnId===c?.turnId,turnCount:e.checkpointTurnCount??i[e.turnId],timestampFormat:f.timestampFormat,onSelect:o},e.turnId),t[21]=i,t[22]=o,t[23]=c?.turnId,t[24]=f,t[25]=e):e=t[25],T=a.map(e),t[15]=i,t[16]=a,t[17]=o,t[18]=c?.turnId,t[19]=f,t[20]=T}else T=t[20];let E;t[26]!==w||t[27]!==T||t[28]!==_||t[29]!==p.onWheel||t[30]!==p.ref?(E=(0,Q.jsxs)(`div`,{ref:g,className:`turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5`,style:_,onWheel:v,children:[w,T]}),t[26]=w,t[27]=T,t[28]=_,t[29]=p.onWheel,t[30]=p.ref,t[31]=E):E=t[31];let D;t[32]!==m||t[33]!==E||t[34]!==h?(D=(0,Q.jsxs)(`div`,{className:`relative min-w-0 flex-1 [-webkit-app-region:no-drag]`,children:[m,h,E]}),t[32]=m,t[33]=E,t[34]=h,t[35]=D):D=t[35];let O;t[36]===n?O=t[37]:(O=[n],t[36]=n,t[37]=O);let k;t[38]===u?k=t[39]:(k=e=>{let t=e[0];(t===`stacked`||t===`split`)&&u(t)},t[38]=u,t[39]=k);let A;t[40]===Symbol.for(`react.memo_cache_sentinel`)?(A=(0,Q.jsx)(Y,{"aria-label":`Stacked diff view`,value:`stacked`,children:(0,Q.jsx)(oe,{className:`size-3`})}),t[40]=A):A=t[40];let j;t[41]===Symbol.for(`react.memo_cache_sentinel`)?(j=(0,Q.jsx)(Y,{"aria-label":`Split diff view`,value:`split`,children:(0,Q.jsx)(re,{className:`size-3`})}),t[41]=j):j=t[41];let M;t[42]!==O||t[43]!==k?(M=(0,Q.jsxs)(pe,{className:`shrink-0`,variant:`outline`,size:`xs`,value:O,onValueChange:k,children:[A,j]}),t[42]=O,t[43]=k,t[44]=M):M=t[44];let N=r?`Disable diff line wrapping`:`Enable diff line wrapping`,P=r?`Disable line wrapping`:`Enable line wrapping`,F;t[45]===d?F=t[46]:(F=e=>{d(!!e)},t[45]=d,t[46]=F);let I;t[47]===Symbol.for(`react.memo_cache_sentinel`)?(I=(0,Q.jsx)(ce,{className:`size-3`}),t[47]=I):I=t[47];let L;t[48]!==r||t[49]!==N||t[50]!==P||t[51]!==F?(L=(0,Q.jsx)(Y,{"aria-label":N,title:P,variant:`outline`,size:`xs`,pressed:r,onPressedChange:F,children:I}),t[48]=r,t[49]=N,t[50]=P,t[51]=F,t[52]=L):L=t[52];let R;t[53]!==M||t[54]!==L?(R=(0,Q.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]`,children:[M,L]}),t[53]=M,t[54]=L,t[55]=R):R=t[55];let z;return t[56]!==D||t[57]!==R?(z=(0,Q.jsxs)(Q.Fragment,{children:[D,R]}),t[56]=D,t[57]=R,t[58]=z):z=t[58],z}function je(e){let t=(0,$.c)(18),{bodyState:n,diffRenderMode:r,diffWordWrap:i,openDiffFileInEditor:a,patchViewportRef:o,renderableFiles:s,renderablePatch:c,resolvedTheme:l}=e;if(n.kind===`no-thread`){let e;return t[0]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,Q.jsx)(Ne,{children:`Select a thread to inspect turn diffs.`}),t[0]=e):e=t[0],e}if(n.kind===`not-git-repo`){let e;return t[1]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,Q.jsx)(Ne,{children:`Turn diffs are unavailable because this project is not a git repository.`}),t[1]=e):e=t[1],e}if(n.kind===`no-completed-turns`){let e;return t[2]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,Q.jsx)(Ne,{children:`No completed turns yet.`}),t[2]=e):e=t[2],e}let u;t[3]!==n.error||t[4]!==c?(u=n.error&&!c&&(0,Q.jsx)(`div`,{className:`px-3`,children:(0,Q.jsx)(`p`,{className:`mb-2 text-[11px] text-destructive-foreground`,children:n.error})}),t[3]=n.error,t[4]=c,t[5]=u):u=t[5];let d;t[6]!==n||t[7]!==r||t[8]!==i||t[9]!==a||t[10]!==s||t[11]!==c||t[12]!==l?(d=c?c.kind===`files`?(0,Q.jsx)(L,{className:`diff-render-surface h-full min-h-0 overflow-auto px-2 pb-2`,config:{overscrollSize:600,intersectionObserverMargin:1200},children:s.map(e=>{let t=J(e),n=`${de(e)}:${l}`;return(0,Q.jsx)(`div`,{"data-diff-file-path":t,className:`diff-render-file mb-2 rounded-md first:mt-2 last:mb-0`,onClickCapture:e=>{(e.nativeEvent.composedPath?.()??[]).some(Me)&&a(t)},children:(0,Q.jsx)(ge,{fileDiff:e,options:{diffStyle:r===`split`?`split`:`unified`,lineDiffType:`none`,overflow:i?`wrap`:`scroll`,theme:v(l),themeType:l,unsafeCSS:De}})},n)})}):(0,Q.jsx)(`div`,{className:`h-full overflow-auto p-2`,children:(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`p`,{className:`text-[11px] text-muted-foreground/75`,children:c.reason}),(0,Q.jsx)(`pre`,{className:W(`max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90`,i?`overflow-auto whitespace-pre-wrap wrap-break-word`:`overflow-auto`),children:c.text})]})}):(0,Q.jsx)(Re,{bodyState:n}),t[6]=n,t[7]=r,t[8]=i,t[9]=a,t[10]=s,t[11]=c,t[12]=l,t[13]=d):d=t[13];let f;return t[14]!==o||t[15]!==u||t[16]!==d?(f=(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsxs)(`div`,{ref:o,className:`diff-panel-viewport min-h-0 min-w-0 flex-1 overflow-hidden`,children:[u,d]})}),t[14]=o,t[15]=u,t[16]=d,t[17]=f):f=t[17],f}function Me(e){return e instanceof Element&&e.hasAttribute(`data-title`)}function Ne(e){let t=(0,$.c)(2),{children:n}=e,r;return t[0]===n?r=t[1]:(r=(0,Q.jsx)(`div`,{className:`flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70`,children:n}),t[0]=n,t[1]=r),r}function Pe(){let e=(0,$.c)(19),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t={strict:!1,select:Ie},e[0]=t):t=e[0];let n=s(t),r;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(r={strict:!1,select:Fe},e[1]=r):r=e[1];let i=M(r),a=i.rightPanel===`diff`,c=n?.threadId??null,l,u;e[2]===n?u=e[3]:(u=o(n),e[2]=n,e[3]=u),l=u;let f=R(l),p=He(f),m=f?.worktreePath,h=p?.cwd,g;e[4]!==m||e[5]!==h?(g=P({threadWorktreePath:m,projectCwd:h}),e[4]=m,e[5]=h,e[6]=g):g=e[6];let _=g,v=f?.environmentId??null,y=_??null,b;e[7]!==v||e[8]!==y?(b={environmentId:v,cwd:y},e[7]=v,e[8]=y,e[9]=b):b=e[9];let x=d(b),S;e[10]===x.data?S=e[11]:(S=I(x.data),e[10]=x.data,e[11]=S);let C=S,w;return e[12]!==_||e[13]!==f||e[14]!==c||e[15]!==a||e[16]!==i||e[17]!==C?(w={activeThread:f,activeThreadId:c,activeCwd:_,isGitRepo:C,diffSearch:i,diffOpen:a},e[12]=_,e[13]=f,e[14]=c,e[15]=a,e[16]=i,e[17]=C,e[18]=w):w=e[18],w}function Fe(e){return k(e)}function Ie(e){return x(e)}function Le(e){let{activeThread:t,activeThreadId:n,activeCwd:r,isGitRepo:i,diffSearch:a,diffOpen:o}=Pe(),{turnDiffSummaries:s,inferredCheckpointTurnCountByTurnId:c}=j(t),l=a.diffTurnId??null,u=l===null?null:a.diffFilePath??null,{activeCheckpointRange:d,conversationCacheScope:f,orderedTurnDiffSummaries:p,selectedTurn:m}=(0,X.useMemo)(()=>q({summaries:s,inferredCheckpointTurnCountByTurnId:c,selectedTurnId:l}),[c,l,s]),h=y(xe(we({environmentId:t?.environmentId,threadId:n,range:d,selectedTurnId:m?.turnId,conversationCacheScope:f,enabled:i}))),g=h.isLoading,_=Ce(h.error),v=h.data?.diff,b=typeof v==`string`&&v.trim().length===0,{emptyDiffMessage:x}=(0,X.useMemo)(()=>ie(m),[m]),S=(0,X.useMemo)(()=>se(v,`diff-panel:${e}`),[e,v]),C=(0,X.useMemo)(()=>Ue(S),[S]);return{activeCwd:r,activeThread:t,bodyState:le({hasActiveThread:!!t,isGitRepo:i,turnSummaryCount:p.length,checkpointDiffError:_,hasRenderablePatch:!!S,isLoadingCheckpointDiff:g,hasNoNetChanges:b,emptyDiffMessage:x}),diffOpen:o,inferredCheckpointTurnCountByTurnId:c,orderedTurnDiffSummaries:p,renderableFiles:C,renderablePatch:S,selectedFilePath:u,selectedTurn:m,selectedTurnId:l}}function Re(e){let t=(0,$.c)(4),{bodyState:n}=e;if(n.kind===`loading`){let e;return t[0]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,Q.jsx)(D,{label:`Loading checkpoint diff...`}),t[0]=e):e=t[0],e}let r;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,Q.jsx)(A,{className:`size-7 text-muted-foreground/25`}),t[1]=r):r=t[1];let i=n.kind===`empty`?n.message:`No diff is available for this range.`,a;return t[2]===i?a=t[3]:(a=(0,Q.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-2 px-5 py-2 text-center`,children:[r,(0,Q.jsx)(`p`,{className:`text-xs text-muted-foreground/70`,children:i})]}),t[2]=i,t[3]=a),a}var ze=180;function Be(e){let t=(0,$.c)(14),{direction:n,strip:r}=e,i=n===`left`,a=i?r.canScrollLeft:r.canScrollRight,o=i?G:K,s=i?`left-0`:`right-0`,c=a?`border-border/70 hover:border-border hover:text-foreground`:`cursor-not-allowed border-border/40 text-muted-foreground/40`,l;t[0]!==s||t[1]!==c?(l=W(`absolute top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors`,s,c),t[0]=s,t[1]=c,t[2]=l):l=t[2];let u;t[3]!==i||t[4]!==r?(u=()=>r.scrollBy(i?-180:ze),t[3]=i,t[4]=r,t[5]=u):u=t[5];let d=!a,f=`Scroll turn list ${n}`,p;t[6]===o?p=t[7]:(p=(0,Q.jsx)(o,{className:`size-3.5`}),t[6]=o,t[7]=p);let m;return t[8]!==l||t[9]!==u||t[10]!==d||t[11]!==f||t[12]!==p?(m=(0,Q.jsx)(`button`,{type:`button`,className:l,onClick:u,disabled:d,"aria-label":f,children:p}),t[8]=l,t[9]=u,t[10]=d,t[11]=f,t[12]=p,t[13]=m):m=t[13],m}function Ve(e){let t=(0,$.c)(23),{summary:n,selected:r,turnCount:i,timestampFormat:a,onSelect:o}=e,s;t[0]!==o||t[1]!==n.turnId?(s=()=>o(n.turnId),t[0]=o,t[1]=n.turnId,t[2]=s):s=t[2];let c=n.turnId,l=r?`border-border bg-accent text-accent-foreground`:`border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80`,u;t[3]===l?u=t[4]:(u=W(`rounded-md border px-2 py-1 text-left transition-colors`,l),t[3]=l,t[4]=u);let d=i??`?`,p;t[5]===d?p=t[6]:(p=(0,Q.jsxs)(`span`,{className:`text-[10px] leading-tight font-medium`,children:[`Turn `,d]}),t[5]=d,t[6]=p);let m;t[7]!==n.completedAt||t[8]!==a?(m=f(n.completedAt,a),t[7]=n.completedAt,t[8]=a,t[9]=m):m=t[9];let h;t[10]===m?h=t[11]:(h=(0,Q.jsx)(`span`,{className:`text-[9px] leading-tight opacity-70`,children:m}),t[10]=m,t[11]=h);let g;t[12]!==p||t[13]!==h?(g=(0,Q.jsxs)(`div`,{className:`flex items-center gap-1`,children:[p,h]}),t[12]=p,t[13]=h,t[14]=g):g=t[14];let _;t[15]!==u||t[16]!==g?(_=(0,Q.jsx)(`div`,{className:u,children:g}),t[15]=u,t[16]=g,t[17]=_):_=t[17];let v;return t[18]!==r||t[19]!==n.turnId||t[20]!==s||t[21]!==_?(v=(0,Q.jsx)(`button`,{type:`button`,className:`shrink-0 rounded-md`,onClick:s,title:c,"data-turn-chip-selected":r,children:_}),t[18]=r,t[19]=n.turnId,t[20]=s,t[21]=_,t[22]=v):v=t[22],v}function He(e){let t=(0,$.c)(3),n=e?.environmentId,r=e?.projectId,i;return t[0]!==n||t[1]!==r?(i=e=>n&&r?B(e,{environmentId:n,projectId:r}):void 0,t[0]=n,t[1]=r,t[2]=i):i=t[2],R(i)}function Ue(e){return!e||e.kind!==`files`?[]:e.files.toSorted((e,t)=>J(e).localeCompare(J(t),void 0,{numeric:!0,sensitivity:`base`}))}export{Oe as default};
64
- //# sourceMappingURL=DiffPanel-B9TB-BHO.js.map
64
+ //# sourceMappingURL=DiffPanel-CtAr4l_R.js.map
@@ -1,4 +1,4 @@
1
- import{Ua as e}from"./Stream-mUTFnSY9.js";import{$ as t,A as n,B as r,Bt as i,C as a,D as o,E as s,F as c,Ft as l,G as u,H as d,Ht as f,I as p,It as m,J as h,Jt as g,K as _,L as v,Lt as y,M as b,N as x,O as S,P as C,Pt as w,Q as T,Qt as E,R as D,Rt as O,S as k,T as A,U as j,Ut as M,V as N,Vt as P,W as F,Wt as I,X as ee,Xt as te,Yt as ne,Z as re,Zt as ie,_ as L,_n as ae,_t as oe,a as se,an as ce,at as le,b as R,bn as ue,bt as de,cn as z,ct as fe,et as pe,f as me,g as he,gn as ge,gt as _e,h as B,hn as ve,ht as ye,i as be,it as V,j as xe,k as Se,ln as Ce,lt as we,mn as Te,nn as Ee,on as De,ot as Oe,pn as ke,pt as Ae,q as je,qt as Me,st as Ne,tn as Pe,tt as Fe,ut as Ie,v as H,vn as Le,vt as Re,w as U,x as ze,xn as Be,xt as W,y as Ve,yn as He,yt as Ue,z as We,zt as Ge}from"./WorkerPoolContext-wx5NJQK1.js";import{dn as Ke}from"./CompositeItem-DTyKsv13.js";var qe=Ke(`columns-2`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M12 3v18`,key:`108xh3`}]]),Je=Ke(`rows-3`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M21 9H3`,key:`1338ky`}],[`path`,{d:`M21 15H3`,key:`9uk58r`}]]),Ye=Ke(`text-wrap`,[[`path`,{d:`m16 16-3 3 3 3`,key:`117b85`}],[`path`,{d:`M3 12h14.5a1 1 0 0 1 0 7H13`,key:`18xa6z`}],[`path`,{d:`M3 19h6`,key:`1ygdsz`}],[`path`,{d:`M3 5h18`,key:`1u36vt`}]]),Xe=new TextEncoder,Ze=new TextDecoder(`utf-8`,{ignoreBOM:!0}),Qe=/[\uD800-\uDFFF]/,$e=1024,G=new Uint8Array($e);function et(){G.length!==$e&&(G=new Uint8Array($e))}function K(e){if(e.length===0)return e;if(Qe.test(e))return JSON.parse(JSON.stringify(e));let t=e.length*3;G.length<t&&(G=new Uint8Array(t));let{written:n}=Xe.encodeInto(e,G);return Ze.decode(G.subarray(0,n))}var tt=4096,nt=.5;function rt(e){for(let t of e.hunks){for(let n=0;n<t.hunkContent.length;n++){let r=t.hunkContent[n];if(r.type!==`change`)continue;let i=at(e,r);i!=null&&(t.hunkContent.splice(n,1,...i),n+=i.length-1)}it(t,e)}}function it(e,t){let{hunkContent:n}=e;for(let e=1;e<n.length;e++){let r=n[e],i=n[e-1];if(r.type!==`change`||r.additions>0&&r.deletions>0||i.type!==`context`)continue;let a=r.additions>0,o=a?t.additionLines:t.deletionLines,s=a?r.additionLineIndex:r.deletionLineIndex,c=a?r.additions:r.deletions,l=o[s]??``;if(l.trim()!==``)continue;let u=!0;for(let e=1;e<c;e++)if(o[s+e]!==l){u=!1;break}if(!u)continue;let d=0;for(;d<i.lines&&t.additionLines[i.additionLineIndex+i.lines-1-d]===l;)d++;if(d===0||e===1&&d===i.lines)continue;r.additionLineIndex-=d,r.deletionLineIndex-=d;let f=r.additionLineIndex+r.additions,p=r.deletionLineIndex+r.deletions,m=n[e+1];m?.type===`context`?(m.lines+=d,m.additionLineIndex=f,m.deletionLineIndex=p):n.splice(e+1,0,{type:`context`,lines:d,additionLineIndex:f,deletionLineIndex:p}),i.lines-=d,i.lines===0&&(n.splice(e-1,1),e--)}}function at(e,t){let{deletions:n,additions:r,deletionLineIndex:i,additionLineIndex:a}=t,o=Math.min(n,r),s=Math.abs(r-n);if(o===0||s===0||o*(s+1)>tt)return null;let c=[];for(let t=0;t<n;t++)c.push(st(e.deletionLines[i+t]??``));let l=[];for(let t=0;t<r;t++)l.push(st(e.additionLines[a+t]??``));let u=r>n,d=0,f=-1;for(let e=0;e<=s;e++){let t=0;for(let n=0;n<o;n++)t+=ct(c[n+(u?0:e)],l[n+(u?e:0)]);e===0?f=t+o*nt:t>f&&(f=t,d=e)}if(d===0)return null;let p=[],m=(e,t,n,r)=>{(e>0||t>0)&&p.push({type:`change`,deletions:e,additions:t,deletionLineIndex:n,additionLineIndex:r})};return u?(m(0,d,i,a),m(o,o,i,a+d),m(0,r-o-d,i+o,a+d+o)):(m(d,0,i,a),m(o,o,i+d,a),m(n-o-d,0,i+d+o,a+o)),p}var ot=/\s+/g;function st(e){return e.replace(ot,``)}function ct(e,t){if(e===t)return 1;let n=Math.max(e.length,t.length),r=Math.min(e.length,t.length);if(r===0)return 0;let i=0;for(;i<r&&e[i]===t[i];)i++;let a=0;for(;a<r-i&&e[e.length-1-a]===t[t.length-1-a];)a++;return(i+a)/n}function lt(e,t,n){try{return ut(e,t,n)}finally{et()}}function ut(e,t,n=!1){let r=Ot(e),i=r?_t(e):vt(e),a,o=[];for(let e of i){if(r&&!ge.test(e)){if(a==null)a=K(e);else if(n)throw Error(`parsePatchContent: unknown file blob`);else console.error(`parsePatchContent: unknown file blob:`,e);continue}if(!r&&!yt(e)){if(a==null)a=K(e);else if(n)throw Error(`parsePatchContent: unknown file blob`);else console.error(`parsePatchContent: unknown file blob:`,e);continue}let i=ft(e,{cacheKey:t==null?void 0:`${t}-${o.length}`,isGitDiff:r,throwOnError:n});i!=null&&o.push(i)}return{patchMetadata:a,files:o}}function dt(e,t){try{return ft(e,t)}finally{et()}}function ft(e,{cacheKey:t,isGitDiff:n=ge.test(e),oldFile:r,newFile:i,throwOnError:a=!1}={}){let o=0,s=kt(e,`@@ `),c,l=r==null||i==null,u=0,d=0;for(let e of s){let s=gt(e),p=s[0];if(p==null){if(a)throw Error(`parsePatchContent: invalid hunk`);console.error(`parsePatchContent: invalid hunk`,e);continue}let m=Tt(p),h=0,g=0;if(m==null||c==null){if(c!=null){if(a)throw Error(`parsePatchContent: Invalid hunk`);console.error(`parsePatchContent: Invalid hunk`,e);continue}c={name:``,type:`change`,hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:l,additionLines:!l&&r!=null&&i!=null?ht(i.contents):[],deletionLines:!l&&r!=null&&i!=null?ht(r.contents):[],cacheKey:jt(t)},c.additionLines.length===1&&i?.contents===``&&(c.additionLines.length=0),c.deletionLines.length===1&&r?.contents===``&&(c.deletionLines.length=0);for(let e of s){if(e.startsWith(`diff --git`)){let t=e.trim().match(E),n=t?.[1]??t?.[2],r=t?.[3]??t?.[4];if(n==null||r==null){if(a)throw Error(`parsePatchContent: invalid git diff header`);console.error(`parsePatchContent: invalid git diff header`,e);continue}c.name=K(r.trim()),n!==r&&(c.prevName=K(n.trim()));continue}let t=e.startsWith(`---`)||e.startsWith(`+++`)?e.match(n?ve:Te):null;if(t!=null){let[,e,n]=t;if(e===`---`&&n!==`/dev/null`){let e=K(n.trim());c.prevName=e,c.name=e}else e===`+++`&&n!==`/dev/null`&&(c.name=K(n.trim()))}else if(n){if(e.startsWith(`new mode `)&&(c.mode=K(e.slice(8).trim())),e.startsWith(`old mode `)&&(c.prevMode=K(e.slice(8).trim())),e.startsWith(`new file mode`)&&(c.type=`new`,c.mode=K(e.slice(13).trim())),e.startsWith(`deleted file mode`)&&(c.type=`deleted`,c.mode=K(e.slice(17).trim())),e.startsWith(`similarity index`)&&(e.startsWith(`similarity index 100%`)?c.type=`rename-pure`:c.type=`rename-changed`),e.startsWith(`index `)){let[,t,n,r]=e.trim().match(ue)??[];t!=null&&(c.prevObjectId=K(t)),n!=null&&(c.newObjectId=K(n)),r!=null&&(c.mode=K(r))}e.startsWith(`rename from `)&&(c.prevName=K(e.slice(12).trim())),e.startsWith(`rename to `)&&(c.name=K(e.slice(10).trim()))}}continue}let _,v;for(;s.length>0&&(s[s.length-1]===`
1
+ import{Ua as e}from"./Stream-mUTFnSY9.js";import{$ as t,A as n,B as r,Bt as i,C as a,D as o,E as s,F as c,Ft as l,G as u,H as d,Ht as f,I as p,It as m,J as h,Jt as g,K as _,L as v,Lt as y,M as b,N as x,O as S,P as C,Pt as w,Q as T,Qt as E,R as D,Rt as O,S as k,T as A,U as j,Ut as M,V as N,Vt as P,W as F,Wt as I,X as ee,Xt as te,Yt as ne,Z as re,Zt as ie,_ as L,_n as ae,_t as oe,a as se,an as ce,at as le,b as R,bn as ue,bt as de,cn as z,ct as fe,et as pe,f as me,g as he,gn as ge,gt as _e,h as B,hn as ve,ht as ye,i as be,it as V,j as xe,k as Se,ln as Ce,lt as we,mn as Te,nn as Ee,on as De,ot as Oe,pn as ke,pt as Ae,q as je,qt as Me,st as Ne,tn as Pe,tt as Fe,ut as Ie,v as H,vn as Le,vt as Re,w as U,x as ze,xn as Be,xt as W,y as Ve,yn as He,yt as Ue,z as We,zt as Ge}from"./WorkerPoolContext-TpWU8uqG.js";import{dn as Ke}from"./CompositeItem-DTyKsv13.js";var qe=Ke(`columns-2`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M12 3v18`,key:`108xh3`}]]),Je=Ke(`rows-3`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M21 9H3`,key:`1338ky`}],[`path`,{d:`M21 15H3`,key:`9uk58r`}]]),Ye=Ke(`text-wrap`,[[`path`,{d:`m16 16-3 3 3 3`,key:`117b85`}],[`path`,{d:`M3 12h14.5a1 1 0 0 1 0 7H13`,key:`18xa6z`}],[`path`,{d:`M3 19h6`,key:`1ygdsz`}],[`path`,{d:`M3 5h18`,key:`1u36vt`}]]),Xe=new TextEncoder,Ze=new TextDecoder(`utf-8`,{ignoreBOM:!0}),Qe=/[\uD800-\uDFFF]/,$e=1024,G=new Uint8Array($e);function et(){G.length!==$e&&(G=new Uint8Array($e))}function K(e){if(e.length===0)return e;if(Qe.test(e))return JSON.parse(JSON.stringify(e));let t=e.length*3;G.length<t&&(G=new Uint8Array(t));let{written:n}=Xe.encodeInto(e,G);return Ze.decode(G.subarray(0,n))}var tt=4096,nt=.5;function rt(e){for(let t of e.hunks){for(let n=0;n<t.hunkContent.length;n++){let r=t.hunkContent[n];if(r.type!==`change`)continue;let i=at(e,r);i!=null&&(t.hunkContent.splice(n,1,...i),n+=i.length-1)}it(t,e)}}function it(e,t){let{hunkContent:n}=e;for(let e=1;e<n.length;e++){let r=n[e],i=n[e-1];if(r.type!==`change`||r.additions>0&&r.deletions>0||i.type!==`context`)continue;let a=r.additions>0,o=a?t.additionLines:t.deletionLines,s=a?r.additionLineIndex:r.deletionLineIndex,c=a?r.additions:r.deletions,l=o[s]??``;if(l.trim()!==``)continue;let u=!0;for(let e=1;e<c;e++)if(o[s+e]!==l){u=!1;break}if(!u)continue;let d=0;for(;d<i.lines&&t.additionLines[i.additionLineIndex+i.lines-1-d]===l;)d++;if(d===0||e===1&&d===i.lines)continue;r.additionLineIndex-=d,r.deletionLineIndex-=d;let f=r.additionLineIndex+r.additions,p=r.deletionLineIndex+r.deletions,m=n[e+1];m?.type===`context`?(m.lines+=d,m.additionLineIndex=f,m.deletionLineIndex=p):n.splice(e+1,0,{type:`context`,lines:d,additionLineIndex:f,deletionLineIndex:p}),i.lines-=d,i.lines===0&&(n.splice(e-1,1),e--)}}function at(e,t){let{deletions:n,additions:r,deletionLineIndex:i,additionLineIndex:a}=t,o=Math.min(n,r),s=Math.abs(r-n);if(o===0||s===0||o*(s+1)>tt)return null;let c=[];for(let t=0;t<n;t++)c.push(st(e.deletionLines[i+t]??``));let l=[];for(let t=0;t<r;t++)l.push(st(e.additionLines[a+t]??``));let u=r>n,d=0,f=-1;for(let e=0;e<=s;e++){let t=0;for(let n=0;n<o;n++)t+=ct(c[n+(u?0:e)],l[n+(u?e:0)]);e===0?f=t+o*nt:t>f&&(f=t,d=e)}if(d===0)return null;let p=[],m=(e,t,n,r)=>{(e>0||t>0)&&p.push({type:`change`,deletions:e,additions:t,deletionLineIndex:n,additionLineIndex:r})};return u?(m(0,d,i,a),m(o,o,i,a+d),m(0,r-o-d,i+o,a+d+o)):(m(d,0,i,a),m(o,o,i+d,a),m(n-o-d,0,i+d+o,a+o)),p}var ot=/\s+/g;function st(e){return e.replace(ot,``)}function ct(e,t){if(e===t)return 1;let n=Math.max(e.length,t.length),r=Math.min(e.length,t.length);if(r===0)return 0;let i=0;for(;i<r&&e[i]===t[i];)i++;let a=0;for(;a<r-i&&e[e.length-1-a]===t[t.length-1-a];)a++;return(i+a)/n}function lt(e,t,n){try{return ut(e,t,n)}finally{et()}}function ut(e,t,n=!1){let r=Ot(e),i=r?_t(e):vt(e),a,o=[];for(let e of i){if(r&&!ge.test(e)){if(a==null)a=K(e);else if(n)throw Error(`parsePatchContent: unknown file blob`);else console.error(`parsePatchContent: unknown file blob:`,e);continue}if(!r&&!yt(e)){if(a==null)a=K(e);else if(n)throw Error(`parsePatchContent: unknown file blob`);else console.error(`parsePatchContent: unknown file blob:`,e);continue}let i=ft(e,{cacheKey:t==null?void 0:`${t}-${o.length}`,isGitDiff:r,throwOnError:n});i!=null&&o.push(i)}return{patchMetadata:a,files:o}}function dt(e,t){try{return ft(e,t)}finally{et()}}function ft(e,{cacheKey:t,isGitDiff:n=ge.test(e),oldFile:r,newFile:i,throwOnError:a=!1}={}){let o=0,s=kt(e,`@@ `),c,l=r==null||i==null,u=0,d=0;for(let e of s){let s=gt(e),p=s[0];if(p==null){if(a)throw Error(`parsePatchContent: invalid hunk`);console.error(`parsePatchContent: invalid hunk`,e);continue}let m=Tt(p),h=0,g=0;if(m==null||c==null){if(c!=null){if(a)throw Error(`parsePatchContent: Invalid hunk`);console.error(`parsePatchContent: Invalid hunk`,e);continue}c={name:``,type:`change`,hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:l,additionLines:!l&&r!=null&&i!=null?ht(i.contents):[],deletionLines:!l&&r!=null&&i!=null?ht(r.contents):[],cacheKey:jt(t)},c.additionLines.length===1&&i?.contents===``&&(c.additionLines.length=0),c.deletionLines.length===1&&r?.contents===``&&(c.deletionLines.length=0);for(let e of s){if(e.startsWith(`diff --git`)){let t=e.trim().match(E),n=t?.[1]??t?.[2],r=t?.[3]??t?.[4];if(n==null||r==null){if(a)throw Error(`parsePatchContent: invalid git diff header`);console.error(`parsePatchContent: invalid git diff header`,e);continue}c.name=K(r.trim()),n!==r&&(c.prevName=K(n.trim()));continue}let t=e.startsWith(`---`)||e.startsWith(`+++`)?e.match(n?ve:Te):null;if(t!=null){let[,e,n]=t;if(e===`---`&&n!==`/dev/null`){let e=K(n.trim());c.prevName=e,c.name=e}else e===`+++`&&n!==`/dev/null`&&(c.name=K(n.trim()))}else if(n){if(e.startsWith(`new mode `)&&(c.mode=K(e.slice(8).trim())),e.startsWith(`old mode `)&&(c.prevMode=K(e.slice(8).trim())),e.startsWith(`new file mode`)&&(c.type=`new`,c.mode=K(e.slice(13).trim())),e.startsWith(`deleted file mode`)&&(c.type=`deleted`,c.mode=K(e.slice(17).trim())),e.startsWith(`similarity index`)&&(e.startsWith(`similarity index 100%`)?c.type=`rename-pure`:c.type=`rename-changed`),e.startsWith(`index `)){let[,t,n,r]=e.trim().match(ue)??[];t!=null&&(c.prevObjectId=K(t)),n!=null&&(c.newObjectId=K(n)),r!=null&&(c.mode=K(r))}e.startsWith(`rename from `)&&(c.prevName=K(e.slice(12).trim())),e.startsWith(`rename to `)&&(c.name=K(e.slice(10).trim()))}}continue}let _,v;for(;s.length>0&&(s[s.length-1]===`
2
2
  `||s[s.length-1]===`\r`||s[s.length-1]===`\r
3
3
  `||s[s.length-1]===``);)s.pop();let{additionStart:y,deletionStart:b}=m;u=l?u:b-1,d=l?d:y-1;let x={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:m.additionCount,additionStart:y,additionLines:h,deletionCount:m.deletionCount,deletionStart:b,deletionLines:g,deletionLineIndex:u,additionLineIndex:d,hunkContent:[],hunkContext:jt(m.hunkContext),hunkSpecs:K(p),noEOFCRAdditions:!1,noEOFCRDeletions:!1},S=0,C=0;for(let e=1;e<s.length;e++){let t=s[e];if(S>=x.additionCount&&C>=x.deletionCount&&!t.startsWith(`\\`)){if(a&&Ct(t)&&!wt(t))throw Error(`parsePatchContent: hunk has more lines than expected`);break}let n=t[0];if(n!==`+`&&n!==`-`&&n!==` `&&n!==`\\`){if(a)throw Error(`parsePatchContent: invalid hunk line`);console.error(`parseLineType: Invalid firstChar: "${n}", full line: "${t}"`),console.error(`processFile: invalid rawLine:`,t);continue}let r=Mt(n);if(r===`addition`){if(a&&S>=x.additionCount)throw Error(`parsePatchContent: hunk has too many addition lines`);let e=Nt(t);(_==null||_.type!==`change`)&&(_=Pt(`change`,u,d),x.hunkContent.push(_)),d++,S++,l&&c.additionLines.push(e),_.additions++,h++,v=`addition`}else if(r===`deletion`){if(a&&C>=x.deletionCount)throw Error(`parsePatchContent: hunk has too many deletion lines`);let e=Nt(t);(_==null||_.type!==`change`)&&(_=Pt(`change`,u,d),x.hunkContent.push(_)),u++,C++,l&&c.deletionLines.push(e),_.deletions++,g++,v=`deletion`}else if(r===`context`){if(a&&(C>=x.deletionCount||S>=x.additionCount))throw Error(`parsePatchContent: hunk has too many context lines`);let e=Nt(t);(_==null||_.type!==`context`)&&(_=Pt(`context`,u,d),x.hunkContent.push(_)),d++,u++,S++,C++,l&&(c.deletionLines.push(e),c.additionLines.push(e)),_.lines++,v=`context`}else if(r===`metadata`&&_!=null){if(_.type===`context`?(x.noEOFCRAdditions=!0,x.noEOFCRDeletions=!0):v===`deletion`?x.noEOFCRDeletions=!0:v===`addition`&&(x.noEOFCRAdditions=!0),l&&(v===`addition`||v===`context`)){let e=c.additionLines.length-1;e>=0&&(c.additionLines[e]=I(c.additionLines[e]))}if(l&&(v===`deletion`||v===`context`)){let e=c.deletionLines.length-1;e>=0&&(c.deletionLines[e]=I(c.deletionLines[e]))}}}if(a&&(S!==x.additionCount||C!==x.deletionCount))throw Error(`parsePatchContent: hunk line count mismatch`);x.additionLines=h,x.deletionLines=g,x.collapsedBefore=Math.max(M(x.additionStart,x.additionCount)-o,0),c.hunks.push(x),o=f(x.additionStart,x.additionCount);for(let e of x.hunkContent)e.type===`context`?(x.splitLineCount+=e.lines,x.unifiedLineCount+=e.lines):(x.splitLineCount+=Math.max(e.additions,e.deletions),x.unifiedLineCount+=e.deletions+e.additions);x.splitLineStart=c.splitLineCount+x.collapsedBefore,x.unifiedLineStart=c.unifiedLineCount+x.collapsedBefore,c.splitLineCount+=x.collapsedBefore+x.splitLineCount,c.unifiedLineCount+=x.collapsedBefore+x.unifiedLineCount}if(c!=null){if(a&&l&&!n&&c.hunks.length===0)throw Error(`parsePatchContent: unified file has no hunks`);if(c.hunks.length>0&&!l&&c.additionLines.length>0&&c.deletionLines.length>0){let e=c.hunks[c.hunks.length-1],t=f(e.additionStart,e.additionCount),n=c.additionLines.length,r=Math.max(n-t,0);c.splitLineCount+=r,c.unifiedLineCount+=r}return n||(c.prevName!=null&&c.name!==c.prevName?c.hunks.length>0?c.type=`rename-changed`:c.type=`rename-pure`:(r==null||r.contents===``)&&i!=null&&i.contents!==``?c.type=`new`:r!=null&&r.contents!==``&&(i==null||i.contents===``)&&(c.type=`deleted`)),c.type!==`rename-pure`&&c.type!==`rename-changed`&&(c.prevName=void 0),rt(c),c}}function pt(e,t,n=!1){let r=[],i=mt(e)?e.split(Pe):[e];for(let e of i)try{r.push(lt(e,t==null?void 0:`${t}-${r.length}`,n))}catch(e){if(n)throw e;console.error(e)}return r}function mt(e){return e.startsWith(`From `)||e.includes(`
4
4
  From `)}function ht(e){let t=gt(e);for(let e=0;e<t.length;e++)t[e]=K(t[e]);return t}function gt(e){if(e.length===0)return[``];let t=[],n=0;for(;;){let r=e.indexOf(`
@@ -18,4 +18,4 @@ diff --git`)}function kt(e,t){if(e.length===0)return[``];let n=`\n${t}`,r=e.star
18
18
  `))return`
19
19
  `;if(t.endsWith(`\r`))return`\r`}return`
20
20
  `}function sr(e,t){return Math.max(e.additionLines.length,e.deletionLines.length)>t}function cr(e,t){return e.isPartial&&t&&(e.type===`change`||e.type===`rename-changed`)}function lr(e,t){return e.lineNumber===t.lineNumber&&e.side===t.side&&e.metadata===t.metadata}function ur(e,t){return e.slotName===t.slotName&&e.hunkIndex===t.hunkIndex&&e.lines===t.lines&&e.lineCountKnown===t.lineCountKnown&&e.type===t.type&&e.expandable?.chunked===t.expandable?.chunked&&e.expandable?.up===t.expandable?.up&&e.expandable?.down===t.expandable?.down}async function dr(e,t=300){let n;try{await Promise.race([e(),new Promise(e=>{n=setTimeout(e,t)})])}finally{n!=null&&clearTimeout(n)}}function fr({oldFile:e,newFile:t},n){if(e!==void 0||t!==void 0){if(e===void 0||t===void 0)throw Error(`${n}: Pass null for an intentionally missing oldFile or newFile side`);if(e===null){if(t===null)throw Error(`${n}: You must pass oldFile, newFile, or both`);return{oldFile:e,newFile:t}}return{oldFile:e,newFile:t}}}function pr(e){return{theme:e?.theme,disableLineNumbers:e?.disableLineNumbers,overflow:e?.overflow,collapsed:e?.collapsed,disableFileHeader:e?.disableFileHeader,disableVirtualizationBuffers:e?.disableVirtualizationBuffers,stickyHeader:e?.stickyHeader,preferredHighlighter:e?.preferredHighlighter,useCSSClasses:e?.useCSSClasses,useTokenTransformer:c(e),tokenizeMaxLineLength:e?.tokenizeMaxLineLength,tokenizeMaxLength:e?.tokenizeMaxLength,diffStyle:e?.diffStyle,diffIndicators:e?.diffIndicators,disableBackground:e?.disableBackground,hunkSeparators:typeof e?.hunkSeparators==`function`?`custom`:e?.hunkSeparators,expandUnchanged:e?.expandUnchanged,loadDiffFiles:e?.loadDiffFiles,collapsedContextThreshold:e?.collapsedContextThreshold,lineDiffType:e?.lineDiffType,maxLineDiffLength:e?.maxLineDiffLength,expansionLineCount:e?.expansionLineCount,headerRenderMode:e?.renderCustomHeader==null?`default`:`custom`}}function mr(e){return e.isPartial&&(e.type===`change`||e.type===`rename-changed`||e.type===`rename-pure`)}var hr=-1,gr=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file-diff:${++hr}`;type=`file-diff`;fileContainer;spriteSVG;pre;codeUnified;codeDeletions;codeAdditions;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;headerElement;headerPrefix;headerFilenameSuffix;headerMetadata;headerCustom;separatorCache=new Map;errorWrapper;placeHolder;hunksRenderer;resizeManager;scrollSyncManager;interactionManager;annotationCache=new Map;lineAnnotations=[];managersDirty=!1;deletionFile;additionFile;fileDiff;renderRange;pendingFiles;appliedPreAttributes;lastRenderedHeaderHTML;cachedHeaderHTML;lastRowCount;mounted=!1;enabled=!0;editor;refreshViewTimeout;lineStateRefreshPending=!1;deferredSelectedLines;deferredEditorActiveLine;constructor(e={theme:z},t,n=!1){this.options=e,this.workerManager=t,this.isContainerManaged=n,this.hunksRenderer=this.createHunksRenderer(e),this.resizeManager=new Re,this.scrollSyncManager=new Jt,this.interactionManager=new Ue(`diff`,de(e,typeof e.hunkSeparators==`function`||(e.hunkSeparators??`line-info`)===`line-info`||e.hunkSeparators===`line-info-basic`?this.handleExpandHunk:void 0,this.getLineIndex)),this.workerManager?.subscribeToThemeChanges(this),this.enabled=!0}handleHighlightRender=()=>{this.rerender()};getHunksRendererOptions(e){return pr(e)}createHunksRenderer(e){return new Kn(this.getHunksRendererOptions(e),this.handleHighlightRender,this.workerManager)}getLineIndex=(e,t=`additions`)=>{let n=this.fileDiffCache;if(n==null)return;let r=n.hunks.at(-1),i,a;hunkIterator:for(let o of n.hunks){let n=t===`deletions`?o.deletionStart:o.additionStart,s=t===`deletions`?o.deletionCount:o.additionCount,c=M(n,s)+1,l=o.splitLineStart,u=o.unifiedLineStart;if(e<c){let t=c-e;i=Math.max(u-t,0),a=Math.max(l-t,0);break hunkIterator}if(e>=c+s){if(o===r){let t=e-(c+s);i=u+o.unifiedLineCount+t,a=l+o.splitLineCount+t;break hunkIterator}continue}for(let n of o.hunkContent)if(n.type===`context`)if(e<c+n.lines){let t=e-c;a=l+t,i=u+t;break hunkIterator}else c+=n.lines,l+=n.lines,u+=n.lines;else{let r=t===`deletions`?n.deletions:n.additions;if(e<c+r){let r=e-c;i=u+(t===`additions`?n.deletions:0)+r,a=l+r;break hunkIterator}c+=r,l+=Math.max(n.deletions,n.additions),u+=n.deletions+n.additions}break hunkIterator}if(i!=null&&a!=null)return[i,a]};setOptions(e){e!=null&&(this.options=e,this.cachedHeaderHTML=void 0,this.hunksRenderer.setOptions(this.getHunksRendererOptions(e)),this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(de(this.options,typeof this.options.hunkSeparators==`function`||(this.options.hunkSeparators??`line-info`)===`line-info`||this.options.hunkSeparators===`line-info-basic`?this.handleExpandHunk:void 0,this.getLineIndex))}mergeOptions(e){this.options={...this.options,...e}}setThemeType(e){(this.options.themeType??`system`)!==e&&(this.mergeOptions({themeType:e}),this.applyCachedThemeState(e))}applyCachedThemeState(e){if(typeof this.options.theme==`string`||this.fileContainer==null||this.appliedThemeCSS==null)return!1;let t=this.appliedThemeCSS.baseThemeType??e;return this.appliedThemeCSS.themeType!==t&&(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,e,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!g(this.appliedThemeCSS.theme,this.options.theme??z)}getHoveredLine=()=>this.interactionManager.getHoveredLine();setLineAnnotations(e){this.lineAnnotations=e}canPartiallyRender(e,t,n){return!(e||t||n||typeof this.options.hunkSeparators==`function`)}setSelectedLines(e,t){this.lineStateRefreshPending?this.deferredSelectedLines=[e,t]:this.interactionManager.setSelection(e,t)}setEditorActiveLine(e,t){this.lineStateRefreshPending?this.deferredEditorActiveLine=[e,t]:this.interactionManager.setEditorActiveLine(e,{lineNumberOnly:t?.lineNumberOnly,side:t?.side??`additions`})}flushDeferredLineState(){let{deferredEditorActiveLine:e,deferredSelectedLines:t}=this;this.lineStateRefreshPending=!1,this.deferredEditorActiveLine=void 0,this.deferredSelectedLines=void 0,e!=null&&this.setEditorActiveLine(...e),t!=null&&this.interactionManager.setSelection(...t)}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}let{diffStyle:e=`split`,overflow:t=`scroll`}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,{disableAnnotations:t===`wrap`,columnVariables:this.shouldApplyColumnVariables(t)?`apply`:`measure`}),t===`scroll`&&e===`split`?this.scrollSyncManager.setup(this.pre,this.codeDeletions,this.codeAdditions):this.scrollSyncManager.cleanUp(),this.managersDirty=!1}shouldApplyColumnVariables(e){return typeof this.options.hunkSeparators==`function`||e===`scroll`&&(this.lineAnnotations.length>0||this.pre?.hasAttribute(`data-has-merge-conflict`)===!0)}getCodeScrollLeft(){return Math.max(this.codeUnified?.scrollLeft??0,this.codeDeletions?.scrollLeft??0,this.codeAdditions?.scrollLeft??0)}setCodeScrollLeft(e){this.codeUnified!=null&&(this.codeUnified.scrollLeft=e),this.codeAdditions!=null&&(this.codeAdditions.scrollLeft=e),this.codeDeletions!=null&&(this.codeDeletions.scrollLeft=e)}__getEffectiveCodeOptions(){return{...this.options,...this.hunksRenderer.getEffectiveCodeOptions()}}cleanUp(e=!1){te(this.handleEditSessionRender),this.emitPostRender(!0),this.editor?.cleanUp(e),this.editor=void 0,this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.scrollSyncManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.pendingFiles=void 0,this.isContainerManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,e||(this.lineAnnotations=[]),this.clearAuxiliaryNodes(),this.annotationCache.clear(),this.pre=void 0,this.codeUnified=void 0,this.codeDeletions=void 0,this.codeAdditions=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.placeHolder?.remove(),this.placeHolder=void 0,this.lastRenderedHeaderHTML=void 0,e||(this.cachedHeaderHTML=void 0),this.errorWrapper?.remove(),this.errorWrapper=void 0,this.spriteSVG=void 0,this.lastRowCount=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,e?this.hunksRenderer.recycle():(this.hunksRenderer.cleanUp(),this.workerManager=void 0,this.fileDiff=void 0,this.deletionFile=void 0,this.additionFile=void 0),this.refreshViewTimeout!=null&&(clearTimeout(this.refreshViewTimeout),this.refreshViewTimeout=void 0),this.lineStateRefreshPending=!1,this.deferredEditorActiveLine=void 0,this.deferredSelectedLines=void 0,this.enabled=!1}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate({fileContainer:e,prerenderedHTML:t,preventEmit:n=!1,lineAnnotations:r,fileDiff:i,...a}){if(!this.enabled)throw Error(`FileDiff.hydrate: attempting to call hydrate after cleaned up`);if(this.fileContainer!=null)throw Error(`FileDiff.hydrate: hydrate can only be called before the instance has rendered or hydrated`);let o=fr(a,`FileDiff.hydrate`),s=o?.oldFile,c=o?.newFile;this.hydrateElements(e,t),br(this.pre,vr({fileDiff:i,oldFile:s,newFile:c}),this.options.collapsed)||xr(this.headerElement,yr({fileDiff:i,oldFile:s,newFile:c}),this.options.disableFileHeader)?this.render({...a,fileContainer:e,lineAnnotations:r,fileDiff:i,preventEmit:!0}):this.hydrationSetup({fileDiff:i,lineAnnotations:r,...o}),n||this.emitPostRender()}hydrateElements(e,t){this.fileContainer!==e&&this.emitPostRender(!0),D(e,t);for(let t of e.shadowRoot?.children??[]){if(t instanceof SVGElement){this.spriteSVG=t;continue}if(t instanceof HTMLElement){if(t instanceof HTMLPreElement){this.pre=t;for(let e of t.children)!(e instanceof HTMLElement)||e.tagName.toLowerCase()!==`code`||(`deletions`in e.dataset&&(this.codeDeletions=e),`additions`in e.dataset&&(this.codeAdditions=e),`unified`in e.dataset&&(this.codeUnified=e));continue}if(`diffsHeader`in t.dataset){this.headerElement=t;continue}if(t instanceof HTMLStyleElement&&t.hasAttribute(`data-theme-css`)){this.themeCSSStyle=t;continue}if(t instanceof HTMLStyleElement&&t.hasAttribute(`data-unsafe-css`)){this.unsafeCSSStyle=t,this.appliedUnsafeCSS=t.textContent;continue}}}this.pre!=null&&(this.syncCodeNodesFromPre(this.pre),this.pre.removeAttribute(`data-dehydrated`)),this.fileContainer=e,this.hydrateMeasuredScrollbar()}hydrationSetup({fileDiff:e,oldFile:t,newFile:n,lineAnnotations:r}){this.lineAnnotations=r??this.lineAnnotations,this.additionFile=n,this.deletionFile=t,this.fileDiff=e??(t!==void 0&&n!==void 0?q(t,n,this.options.parseDiffOptions):void 0),this.pre!=null&&(this.syncInteractionOptions(),this.hunksRenderer.hydrate(this.fileDiff),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}rerender(){!this.enabled||this.fileDiff==null&&this.additionFile==null&&this.deletionFile==null||this.render({forceRender:!0,renderRange:this.renderRange})}onThemeChange(){this.hunksRenderer.clearRenderCache(),this.rerender()}handleExpandHunk=(e,t,n)=>{this.expandHunk(e,t,n)};expandHunk=(e,t,n)=>{this.hunksRenderer.expandHunk(e,t,n),this.loadFilesIfNecessary(),this.rerender()};loadFilesIfNecessary(){let{fileDiff:e,options:{loadDiffFiles:t}}=this;e==null||t==null||!mr(e)||this.pendingFiles?.fileDiff===e||(this.pendingFiles={fileDiff:e,promise:this.loadFilesForDiff(e,t)})}async loadFilesForDiff(e,t){try{let n=await t(e);if(!this.enabled||this.fileDiff!==e)return;await this.handleFilesLoaded(e,n)}catch(e){if(this.options.disableErrorHandling===!0)throw e;console.error(e)}finally{this.pendingFiles?.fileDiff===e&&(this.pendingFiles=void 0)}}async handleFilesLoaded(e,t){this.fileDiff!==e||!e.isPartial||(zt(`merge`,e,t),this.setHydratedState(t),await dr(()=>this.primeHighlightCache(e)),!(!this.enabled||this.fileDiff!==e)&&this.rerender())}setHydratedState(e){this.deletionFile=e.oldFile,this.additionFile=e.newFile,this.workerManager?.cleanUpTasks(this.hunksRenderer),this.hunksRenderer.clearRenderCache()}render({fileDiff:e,deferManagers:t=!1,forceRender:n=!1,preventEmit:r=!1,lineAnnotations:i,fileContainer:a,containerWrapper:o,renderRange:s,...c}){let l=fr(c,`FileDiff.render`),u=l?.oldFile,d=l?.newFile;if(!this.enabled)throw Error(`FileDiff.render: attempting to call render after cleaned up`);e!=null&&e.cacheKey===void 0&&(e.cacheKey=e.prevName==null?e.name:e.prevName+`:`+e.name),this.editor?.__postponeBgTokenizeToNextFrame();let{collapsed:f=!1,themeType:p=`system`,expandUnchanged:m=!1}=this.options,h=f?void 0:s,g=this.hasThemeChanged(),_=l!=null,v=_&&(!_r(u,this.deletionFile)||!_r(d,this.additionFile)),y=e!=null&&e!==this.fileDiff,b=i!=null&&(i.length>0||this.lineAnnotations.length>0)&&i!==this.lineAnnotations;if(!f&&Ie(h,this.renderRange)&&!n&&!b&&!g&&(e!=null&&e===this.fileDiff||e==null&&!v))return this.applyCachedThemeState(p);let x;e==null&&_&&(v||this.fileDiff==null)&&(x=q(l.oldFile,l.newFile,this.options.parseDiffOptions));let{renderRange:S}=this;if(this.renderRange=h,_?(this.deletionFile=u,this.additionFile=d):e!=null&&(this.deletionFile=void 0,this.additionFile=void 0),e==null?x!=null&&(y=!0,this.fileDiff=x):this.fileDiff=e,y&&(this.cachedHeaderHTML=void 0),i!=null&&this.setLineAnnotations(i),this.fileDiff==null)return!1;this.fileDiff.editSessionDirty===!0&&this.shouldSelfHealEditSession()&&(An(this.fileDiff,this.options.parseDiffOptions),this.hunksRenderer.refreshHighlightedResult()),m&&this.loadFilesIfNecessary(),this.hunksRenderer.setOptions(this.getHunksRendererOptions(this.options)),this.syncInteractionOptions(),this.hunksRenderer.setLineAnnotations(this.lineAnnotations);let{disableErrorHandling:C=!1,disableFileHeader:w=!1}=this.options;if(w&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),a=this.getOrCreateFileContainer(a,o),this.applyCachedThemeState(p),f){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{let e=this.hunksRenderer.renderDiff(this.fileDiff,ke);e!=null&&this.applyThemeState(a,e.themeStyles,p,e.baseThemeType),e?.headerElement!=null&&this.applyHeaderToDOM(e.headerElement,a),this.renderSeparators([]),this.injectUnsafeCSS()}catch(e){if(C)throw e;console.error(e),e instanceof Error&&this.applyErrorToDOM(e,a)}return r||this.emitPostRender(),!0}try{let e=this.getOrCreatePreNode(a);if(!(this.canPartiallyRender(n,b,v||y||g)&&this.applyPartialRender({previousRenderRange:S,renderRange:h}))){let t=this.hunksRenderer.renderDiff(this.fileDiff,h);if(t==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(a,t.themeStyles,p,t.baseThemeType),t.headerElement!=null&&this.applyHeaderToDOM(t.headerElement,a),t.additionsContentAST!=null||t.deletionsContentAST!=null||t.unifiedContentAST!=null?this.applyHunksToDOM(e,t):this.pre!=null&&(this.pre.remove(),this.pre=void 0),this.renderSeparators(t.hunkData)}this.applyBuffers(e,h),this.injectUnsafeCSS(),this.renderAnnotations(),this.renderGutterUtility(),this.managersDirty=!0,t||this.flushManagers(),this.editor!=null&&this.syncRenderViewToEditor()}catch(e){if(C)throw e;console.error(e),e instanceof Error&&this.applyErrorToDOM(e,a)}return r||this.emitPostRender(),!0}emitPostRender(e=!1){let{fileContainer:t,options:{onPostRender:n}}=this;if(e){if(!this.mounted||(this.mounted=!1,t==null))return;this.options.onPostRender?.(t,this,`unmount`);return}if(t==null)return;let r=this.mounted?`update`:`mount`;this.mounted=!0,n?.(t,this,r)}get fileDiffCache(){return this.hunksRenderer.diffCache??this.fileDiff}syncRenderViewToEditor(){let e=this.editor,t=this.fileContainer,n=this.fileDiffCache,r=this.lineAnnotations,i=this.computeEditorRenderRange(this.renderRange);e!=null&&t!=null&&n!=null&&!n.isPartial&&this.hunksRenderer.initializeHighlighter().then(a=>{!this.enabled||this.editor!==e||this.fileContainer!==t||this.fileDiffCache!==n||e.__syncRenderView(a,t,n,r,i)})}computeEditorRenderRange(e){let t=this.fileDiffCache;if(e==null||t==null||en(e))return e;let{diffStyle:n=`split`,expandUnchanged:r=!1,collapsedContextThreshold:i=1}=this.options,a,o;return L({diff:t,diffStyle:n,startingLine:e.startingLine,totalLines:e.totalLines,expandedHunks:r?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:i,callback:({additionLine:e})=>{e!=null&&(a??=e.lineNumber,o=e.lineNumber)}}),a==null||o==null?{...e,startingLine:0,totalLines:0}:{...e,startingLine:a-1,totalLines:o-a+1}}attachEditor(e){if(this.type!==`file-diff`)throw Error(`FileDiff.attachEditor: cannot attach an editor to a "${this.type}" diff`);return this.editor?.cleanUp(),this.editor=e,this.hunksRenderer.beginEditSession(),this.fileDiff?.isPartial===!0&&this.loadFilesIfNecessary(),this.hunksRenderer.editorRenderReady()?this.syncRenderViewToEditor():this.rerender(),e=>{this.editor=void 0,e!==!0&&this.finishEditSession()}}finishEditSession(){this.hunksRenderer.endEditSession(),this.completeEditSession()}completeEditSession(){let e=this.fileDiffCache;if(e==null||e.editSessionDirty!==!0)return!1;let{collapsedContextThreshold:t=1}=this.options,n=On(e,this.hunksRenderer.getExpandedHunksMap(),t);return An(e,this.options.parseDiffOptions),this.hunksRenderer.setExpandedHunksMap(kn(e,n)),this.hunksRenderer.refreshHighlightedResult(),this.escalateEditSessionRender(),!0}applyDocumentChange(e,t){this.hunksRenderer.applyDocumentChange(e);let n=this.hunksRenderer.diffCache;if(n!=null){let e=this.fileDiff?.cacheKey;e!=null&&n.cacheKey==null&&(n.cacheKey=e),this.fileDiff=n}t!==void 0&&t!==this.lineAnnotations&&(this.setLineAnnotations(t),this.hunksRenderer.setLineAnnotations(this.lineAnnotations),this.renderAnnotations()),this.rerender(),this.interactionManager.setSelectionDirty()}updateRenderCache(e,t,n={}){let{shouldRefreshDiffsView:r,lineCountChangeInFlight:i}=n;if(this.hunksRenderer.updateRenderCache(e,t,i)){this.refreshViewTimeout!=null&&(clearTimeout(this.refreshViewTimeout),this.refreshViewTimeout=void 0),this.lineStateRefreshPending=!0,this.escalateEditSessionRender();return}r===!0&&(this.refreshViewTimeout!=null&&clearTimeout(this.refreshViewTimeout),this.lineStateRefreshPending=!0,this.refreshViewTimeout=setTimeout(()=>{this.refreshViewTimeout=void 0,this.options.diffStyle===`split`?this.refreshSplitDiffView():this.refreshUnifiedDiffView(),this.flushDeferredLineState()},150))}isLineRenderable(e){let t=this.fileDiffCache;if(t==null)return!0;let{expandUnchanged:n=!1,collapsedContextThreshold:r=1}=this.options;return s({fileDiff:t,lineNumber:e,expandedHunks:n?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:r})}getNearestRenderableLine(e,t){let n=this.fileDiffCache;if(n==null)return e;let{expandUnchanged:r=!1,collapsedContextThreshold:i=1}=this.options;return ze({fileDiff:n,lineNumber:e,direction:t,expandedHunks:r?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:i})}revealLine(e){let t=this.fileDiffCache,{expandUnchanged:n=!1,collapsedContextThreshold:r=1,expansionLineCount:i=100}=this.options;if(t==null||t.isPartial||n)return!1;let o=this.hunksRenderer.getExpandedHunksMap();for(let[n,a]of t.hunks.entries()){let[s,c]=Ve(a);if(e<s){let c=H({isPartial:t.isPartial,rangeSize:a.collapsedBefore,expandedHunks:o,hunkIndex:n,collapsedContextThreshold:r}),l=s-c.rangeSize;if(c.renderAll||e<l+c.fromStart||e>=s-c.fromEnd)return!1;let u=e-(l+c.fromStart)+1,d=s-c.fromEnd-e;return u<=d?this.expandHunk(n,`up`,u+i):this.expandHunk(n,`down`,d+i),!0}if(e<c)return!1}let s=a({fileDiff:t,hunkIndex:t.hunks.length-1,expandedHunks:o,collapsedContextThreshold:r,errorPrefix:`FileDiff.revealLine`});if(s==null||s.renderAll)return!1;let c=t.hunks[t.hunks.length-1],[,l]=Ve(c);return e<l+s.fromStart||e>=l+s.rangeSize?!1:(this.expandHunk(t.hunks.length,`up`,e-(l+s.fromStart)+1+i),!0)}shouldSelfHealEditSession(){return this.editor==null}escalateEditSessionRender(){ie(this.handleEditSessionRender)}handleEditSessionRender=()=>{this.rerender(),this.flushDeferredLineState()};removeRenderedCode(){this.resizeManager.cleanUp(),this.scrollSyncManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.codeUnified?.remove(),this.codeUnified=void 0,this.codeDeletions?.remove(),this.codeDeletions=void 0,this.codeAdditions?.remove(),this.codeAdditions=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(let{element:e}of this.separatorCache.values())e.remove();this.separatorCache.clear();for(let{element:e}of this.annotationCache.values())e.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}renderPlaceholder(e){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){let e=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:`open`});this.placeHolder=document.createElement(`div`),this.placeHolder.dataset.placeholder=``,e.appendChild(this.placeHolder)}return this.placeHolder.style.setProperty(`height`,`${e}px`),!0}async primeHighlightCache(e=this.fileDiff){let{workerManager:t}=this;if(e==null||t==null||!t.isWorkingPool()||e.cacheKey==null||B(e))return;let n=this.options.tokenizeMaxLength??1e5;Math.max(e.additionLines.length,e.deletionLines.length)>n||await t.primeDiffHighlightCache(e).catch(e=>{console.error(e)})}cleanChildNodes(){this.resizeManager.cleanUp(),this.scrollSyncManager.cleanUp(),this.interactionManager.cleanUp(),this.clearAuxiliaryNodes(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.codeAdditions?.remove(),this.codeDeletions?.remove(),this.codeUnified?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.codeAdditions=void 0,this.codeDeletions=void 0,this.codeUnified=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderSeparators(e){let{hunkSeparators:t}=this.options;if(this.isContainerManaged||this.fileContainer==null||typeof t!=`function`){for(let{element:e}of this.separatorCache.values())e.remove();this.separatorCache.clear();return}let n=new Map(this.separatorCache);for(let r of e){let e=r.slotName,i=this.separatorCache.get(e);if(i==null||!ur(r,i.hunkData)){i?.element.remove();let n=document.createElement(`div`);n.style.display=`contents`,n.slot=r.slotName;let a=t(r,this);a!=null&&n.appendChild(a),this.fileContainer.appendChild(n),i={element:n,hunkData:r},this.separatorCache.set(e,i)}n.delete(e)}for(let[e,{element:t}]of n.entries())this.separatorCache.delete(e),t.remove()}renderAnnotations(){if(this.isContainerManaged||this.fileContainer==null){for(let{element:e}of this.annotationCache.values())e.remove();this.annotationCache.clear();return}let e=new Map(this.annotationCache),{renderAnnotation:t}=this.options;if(t!=null&&this.lineAnnotations.length>0)for(let[n,r]of this.lineAnnotations.entries()){let i=`${n}-${V(r)}`,a=this.annotationCache.get(i);if(a==null||!lr(r,a.annotation)){a?.element.remove();let e=t(r);if(e==null)continue;a={element:_(V(r)),annotation:r},a.element.appendChild(e),this.fileContainer.appendChild(a.element),this.annotationCache.set(i,a)}e.delete(i)}for(let[t,{element:n}]of e.entries())this.annotationCache.delete(t),n.remove()}renderGutterUtility(){let{renderGutterUtility:e}=this.options;if(this.fileContainer==null||e==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}let t=e(this.interactionManager.getHoveredLine);if(t!=null&&this.gutterUtilityContent!=null)return;if(t==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}let n=u();n.appendChild(t),this.fileContainer.appendChild(n),this.gutterUtilityContent=n}getOrCreateFileContainer(e,t){let{fileContainer:n}=this,r=e??n??document.createElement(`diffs-container`),i=n!==r;return n!=null&&i&&this.editor?.__captureFocusForDOMReplacement(),i&&this.emitPostRender(!0),this.fileContainer=r,n!=null&&i&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),t!=null&&this.fileContainer.parentNode!==t&&t.appendChild(this.fileContainer),i&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(e){let{shadowRoot:t}=e;if(t!=null)for(let e of t.children)e instanceof SVGElement?this.spriteSVG??=e:p(e)&&e.hasAttribute(`data-theme-css`)?(this.themeCSSStyle??=e,this.hasAdoptedThemeCSS=!0):p(e)&&e.hasAttribute(`data-unsafe-css`)&&(this.unsafeCSSStyle??=e,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(e){let t=e.shadowRoot??e.attachShadow({mode:`open`});if(this.spriteSVG==null){let e=document.createElement(`div`);e.innerHTML=h;let t=e.firstChild;t instanceof SVGElement&&(this.spriteSVG=t)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==t&&t.appendChild(this.spriteSVG)}getOrCreatePreNode(e){let t=e.shadowRoot??e.attachShadow({mode:`open`});return this.pre==null?(this.pre=document.createElement(`pre`),this.appliedPreAttributes=void 0,this.codeUnified=void 0,this.codeDeletions=void 0,this.codeAdditions=void 0,t.appendChild(this.pre)):this.pre.parentNode!==t&&(this.editor?.__captureFocusForDOMReplacement(),t.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodesFromPre(e){this.codeUnified=void 0,this.codeDeletions=void 0,this.codeAdditions=void 0;for(let t of Array.from(e.children))t instanceof HTMLElement&&(t.hasAttribute(`data-unified`)?this.codeUnified=t:t.hasAttribute(`data-deletions`)?this.codeDeletions=t:t.hasAttribute(`data-additions`)&&(this.codeAdditions=t))}applyHeaderToDOM(e,t){this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;let{fileDiff:n}=this,r=this.cachedHeaderHTML??W(e);if(this.cachedHeaderHTML=r,r!==this.lastRenderedHeaderHTML){let e=document.createElement(`div`);e.innerHTML=r;let n=e.firstElementChild;if(!(n instanceof HTMLElement))return;this.headerElement==null?t.shadowRoot?.prepend(n):t.shadowRoot?.replaceChild(n,this.headerElement),this.headerElement=n,this.lastRenderedHeaderHTML=r}if(this.isContainerManaged||n==null)return;let{renderCustomHeader:i,renderHeaderPrefix:a,renderHeaderFilenameSuffix:o,renderHeaderMetadata:s}=this.options;if(i!=null){let e=i(n)??void 0;this.headerCustom=this.upsertHeaderSlotElement(t,this.headerCustom,Ee,e),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0;return}let c=a?.(n)??void 0,l=o?.(n)??void 0,u=s?.(n)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(t,this.headerPrefix,He,c),this.headerFilenameSuffix=this.upsertHeaderSlotElement(t,this.headerFilenameSuffix,ae,l),this.headerMetadata=this.upsertHeaderSlotElement(t,this.headerMetadata,Le,u),this.headerCustom?.remove(),this.headerCustom=void 0}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(e,t,n,r){if(r==null){t?.remove();return}let i=t??this.createHeaderSlotElement(n);return t??e.appendChild(i),this.replaceHeaderSlotContent(i,r),i}replaceHeaderSlotContent(e,t){e.replaceChildren(),t instanceof Element?e.appendChild(t):e.innerText=`${t}`}createHeaderSlotElement(e){let t=document.createElement(`div`);return t.slot=e,t}injectUnsafeCSS(){let{unsafeCSS:e}=this.options,t=this.fileContainer?.shadowRoot;if(t!=null){if(e==null||e===``){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}(this.unsafeCSSStyle?.parentNode!==t||this.appliedUnsafeCSS!==e)&&(this.unsafeCSSStyle??=F(),this.unsafeCSSStyle.parentNode!==t&&t.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=d(e),this.appliedUnsafeCSS=e)}}applyThemeState(e,t,n,r){let i=e.shadowRoot??e.attachShadow({mode:`open`}),a=r??n,o=this.options.theme??z,s=typeof o==`string`?o:{...o},c=j(i);if(this.themeCSSStyle?.parentNode===i&&this.appliedThemeCSS?.themeStyles===t&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===c){this.appliedThemeCSS.theme=s;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===i){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme:s,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:c};return}this.themeCSSStyle=x({shadowRoot:i,currentNode:this.themeCSSStyle,themeCSS:N(t,a,c)}),this.appliedThemeCSS=this.themeCSSStyle==null?void 0:{theme:s,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:c}}hydrateMeasuredScrollbar(){let e=this.fileContainer?.shadowRoot;e!=null&&this.themeCSSStyle!=null&&(this.themeCSSStyle.textContent=r(this.themeCSSStyle.textContent??``,j(e)))}shouldGuardRebuildScroll(){return this.editor!=null&&b()}applyHunksToDOM(e,t){this.shouldGuardRebuildScroll()?C(e,()=>this.replaceCodeColumns(e,t)):this.replaceCodeColumns(e,t)}applyCodeColumnsInPlace(e,t,n){let r=this.getColumnPair(e);if(r==null)return!1;let i=Q(t[0]),a=Q(t[1]);return i==null||a==null?!1:(r.gutter.innerHTML=W(i),r.content.innerHTML=W(a),n!==this.lastRowCount&&(r.gutter.style.setProperty(`grid-row`,`span ${n}`),r.content.style.setProperty(`grid-row`,`span ${n}`)),!0)}replaceCodeColumns(e,t){let{overflow:n=`scroll`}=this.options,r=(this.options.hunkSeparators??`line-info`)===`line-info`,i=n===`wrap`?t.rowCount:void 0;this.cleanupErrorWrapper(),this.applyPreNodeAttributes(e,t);let a=!1,o=[],s=this.hunksRenderer.renderCodeAST(`unified`,t),c=this.hunksRenderer.renderCodeAST(`deletions`,t),l=this.hunksRenderer.renderCodeAST(`additions`,t);this.editor?.__captureFocusForDOMReplacement(),s==null?c!=null||l!=null?(c==null?(this.codeDeletions?.remove(),this.codeDeletions=void 0):(a=this.codeDeletions==null||this.codeUnified!=null,this.codeUnified?.remove(),this.codeUnified=void 0,this.codeDeletions=We({code:this.codeDeletions,columnType:`deletions`,rowSpan:i,containerSize:r}),this.applyCodeColumnsInPlace(this.codeDeletions,c,t.rowCount)||(this.codeDeletions.innerHTML=this.hunksRenderer.renderPartialHTML(c)),o.push(this.codeDeletions)),l==null?(this.codeAdditions?.remove(),this.codeAdditions=void 0):(a=a||this.codeAdditions==null||this.codeUnified!=null,this.codeUnified?.remove(),this.codeUnified=void 0,this.codeAdditions=We({code:this.codeAdditions,columnType:`additions`,rowSpan:i,containerSize:r}),this.applyCodeColumnsInPlace(this.codeAdditions,l,t.rowCount)||(this.codeAdditions.innerHTML=this.hunksRenderer.renderPartialHTML(l)),o.push(this.codeAdditions))):(this.codeUnified?.remove(),this.codeUnified=void 0,this.codeDeletions?.remove(),this.codeDeletions=void 0,this.codeAdditions?.remove(),this.codeAdditions=void 0):(a=this.codeUnified==null||this.codeAdditions!=null||this.codeDeletions!=null,this.codeDeletions?.remove(),this.codeDeletions=void 0,this.codeAdditions?.remove(),this.codeAdditions=void 0,this.codeUnified=We({code:this.codeUnified,columnType:`unified`,rowSpan:i,containerSize:r}),this.applyCodeColumnsInPlace(this.codeUnified,s,t.rowCount)||(this.codeUnified.innerHTML=this.hunksRenderer.renderPartialHTML(s)),o.push(this.codeUnified)),o.length===0?e.textContent=``:a&&e.replaceChildren(...o),this.lastRowCount=t.rowCount}applyPartialRender({previousRenderRange:e,renderRange:t}){let{pre:n,codeUnified:r,codeAdditions:i,codeDeletions:a,options:{diffStyle:o=`split`}}=this;if(n==null||e==null||t==null||!Number.isFinite(e.totalLines)||!Number.isFinite(t.totalLines)||this.lastRowCount==null)return!1;let s=this.getCodeColumns(o,r,a,i);if(s==null)return!1;let c=e.startingLine,l=t.startingLine,u=c+e.totalLines,d=l+t.totalLines,f=Math.max(c,l),p=Math.min(u,d);if(p<=f)return!1;let m=Math.max(0,f-c),h=Math.max(0,u-p),g=this.trimColumns({columns:s,trimStart:m,trimEnd:h,previousStart:c,overlapStart:f,overlapEnd:p,diffStyle:o});if(g<0)throw Error(`FileDiff.applyPartialRender: failed to trim to overlap`);if(this.lastRowCount<g)throw Error(`FileDiff.applyPartialRender: trimmed beyond DOM row count`);let _=this.lastRowCount-g,v=(e,t)=>{if(!(t<=0||this.fileDiff==null))return this.hunksRenderer.renderDiff(this.fileDiff,{startingLine:e,totalLines:t,bufferBefore:0,bufferAfter:0})},y=v(l,Math.max(f-l,0));if(y==null&&l<f)return!1;let b=v(p,Math.max(d-p,0));if(b==null&&d>p)return!1;let x=(e,t)=>{if(e!=null){if(o===`unified`&&!Array.isArray(s))this.insertPartialHTML(o,s,e,t);else if(o===`split`&&Array.isArray(s))this.insertPartialHTML(o,s,e,t);else throw Error(`FileDiff.applyPartialRender.applyChunk: invalid chunk application`);_+=e.rowCount}};return this.cleanupErrorWrapper(),x(y,`afterbegin`),x(b,`beforeend`),this.lastRowCount!==_&&(this.applyRowSpan(o,s,_),this.lastRowCount=_),!0}insertPartialHTML(e,t,n,r){if(e===`unified`&&!Array.isArray(t)){let e=this.hunksRenderer.renderCodeAST(`unified`,n);this.renderPartialColumn(t,e,r)}else if(e===`split`&&Array.isArray(t)){let e=this.hunksRenderer.renderCodeAST(`deletions`,n),i=this.hunksRenderer.renderCodeAST(`additions`,n);this.renderPartialColumn(t[0],e,r),this.renderPartialColumn(t[1],i,r)}else throw Error(`FileDiff.insertPartialHTML: Invalid argument composition`)}refreshSplitDiffView(){if(this.options.diffStyle!==`split`)return;let e=this.hunksRenderer.renderDiff(this.fileDiff,this.renderRange);if(e==null)return;let t=this.getCodeColumns(`split`,this.codeUnified,this.codeDeletions,this.codeAdditions);if(!Array.isArray(t))return;let n=(t,n)=>{if(n==null)return;let r=this.hunksRenderer.renderCodeAST(t,e),i=Q(r?.[0]),a=Q(r?.[1]);for(let[e,t]of[[n.gutter,i],[n.content,a]])if(t!=null&&e.childElementCount===t.length)for(let n=0;n<t.length;n++){let r=e.children[n],i=t[n].properties[`data-line-type`];i!=null&&r.dataset.lineType!==i&&(r.dataset.lineType=i)}};n(`deletions`,t[0]),n(`additions`,t[1])}refreshUnifiedDiffView(){if(this.options.diffStyle!==`unified`)return;let e=this.hunksRenderer.renderDiff(this.fileDiff,this.renderRange);if(e==null)return;let t=this.getCodeColumns(`unified`,this.codeUnified,this.codeDeletions,this.codeAdditions);if(t==null||Array.isArray(t))return;let n=this.hunksRenderer.renderCodeAST(`unified`,e),r=Q(n?.[0]),i=Q(n?.[1]),a=()=>{for(let[e,n]of[[t.gutter,r],[t.content,i]])n!=null&&(e.innerHTML=W(n));e.rowCount!==this.lastRowCount&&(this.applyRowSpan(`unified`,t,e.rowCount),this.lastRowCount=e.rowCount)};this.shouldGuardRebuildScroll()?C(this.pre,a):a(),this.renderSeparators(e.hunkData),this.managersDirty=!0,this.flushManagers(),this.syncRenderViewToEditor()}renderPartialColumn(e,t,n){if(e==null||t==null)return;let r=Q(t[0]),i=Q(t[1]);if(r==null||i==null)throw Error(`FileDiff.insertPartialHTML: Unexpected AST structure`);let a=i.at(0);n===`beforeend`&&a?.type===`element`&&typeof a.properties[`data-buffer-size`]==`number`&&this.mergeBuffersIfNecessary(a.properties[`data-buffer-size`],e.content.children[e.content.children.length-1],e.gutter.children[e.gutter.children.length-1],r,i,!0);let o=i.at(-1);n===`afterbegin`&&o?.type===`element`&&typeof o.properties[`data-buffer-size`]==`number`&&this.mergeBuffersIfNecessary(o.properties[`data-buffer-size`],e.content.children[0],e.gutter.children[0],r,i,!1),e.gutter.insertAdjacentHTML(n,this.hunksRenderer.renderPartialHTML(r)),e.content.insertAdjacentHTML(n,this.hunksRenderer.renderPartialHTML(i))}mergeBuffersIfNecessary(e,t,n,r,i,a){if(!(t instanceof HTMLElement)||!(n instanceof HTMLElement))return;let o=this.getBufferSize(t.dataset);o!=null&&(a?(r.shift(),i.shift()):(r.pop(),i.pop()),this.updateBufferSize(t,o+e),this.updateBufferSize(n,o+e))}applyRowSpan(e,t,n){let r=e=>{e!=null&&(e.gutter.style.setProperty(`grid-row`,`span ${n}`),e.content.style.setProperty(`grid-row`,`span ${n}`))};if(e===`unified`&&!Array.isArray(t))r(t);else if(e===`split`&&Array.isArray(t))r(t[0]),r(t[1]);else throw Error(`dun fuuuuked up`)}trimColumnRows(e,t,n){let r=0,i=0,a=0,o=!1,s=n>=0;if(e==null)return 0;let c=Array.from(e.content.children),l=Array.from(e.gutter.children);if(c.length!==l.length)throw Error(`FileDiff.trimColumnRows: columns do not match`);for(;a<c.length&&!(t<=0&&!s&&!o);){let e=l[a],u=c[a];if(a++,!(e instanceof HTMLElement)||!(u instanceof HTMLElement))throw console.error({gutterElement:e,contentElement:u}),Error(`FileDiff.trimColumnRows: invalid row elements`);if(o&&(o=!1,e.dataset.gutterBuffer===`annotation`&&`lineAnnotation`in u.dataset||e.dataset.gutterBuffer===`metadata`&&`noNewline`in u.dataset)){e.remove(),u.remove(),i++;continue}if(`lineIndex`in e.dataset&&`lineIndex`in u.dataset){(t>0||s&&r>=n)&&(e.remove(),u.remove(),t>0&&(t--,t===0&&(o=!0)),i++),r++;continue}if(`separator`in e.dataset&&`separator`in u.dataset){(t>0||s&&r>=n)&&(e.remove(),u.remove(),i++);continue}if(e.dataset.gutterBuffer===`annotation`&&`lineAnnotation`in u.dataset){(t>0||s&&r>=n)&&(e.remove(),u.remove(),i++);continue}if(e.dataset.gutterBuffer===`metadata`&&`noNewline`in u.dataset){(t>0||s&&r>=n)&&(e.remove(),u.remove(),i++);continue}if(e.dataset.gutterBuffer===`buffer`&&`contentBuffer`in u.dataset){let a=this.getBufferSize(u.dataset);if(a==null)throw Error(`FileDiff.trimColumnRows: invalid element`);if(t>0){let n=Math.min(t,a),r=a-n;r>0?(this.updateBufferSize(e,r),this.updateBufferSize(u,r),i+=n):(e.remove(),u.remove(),i+=a),t-=n,t===0&&r===0&&(o=!0)}else if(s){let t=r,o=r+a-1;if(n<=t)e.remove(),u.remove(),i+=a;else if(n<=o){let t=o-n+1,r=a-t;this.updateBufferSize(e,r),this.updateBufferSize(u,r),i+=t}}r+=a;continue}throw console.error({gutterElement:e,contentElement:u}),Error(`FileDiff.trimColumnRows: unknown row elements`)}return i}trimColumns({columns:e,diffStyle:t,overlapEnd:n,overlapStart:r,previousStart:i,trimEnd:a,trimStart:o}){let s=Math.max(0,r-i),c=n-i;if(c<0)throw Error(`FileDiff.trimColumns: overlap ends before previous`);let l=o>0,u=a>0;if(!l&&!u)return 0;let d=l?s:0,f=u?c:-1;if(t===`unified`&&!Array.isArray(e))return this.trimColumnRows(e,d,f);if(t===`split`&&Array.isArray(e)){let t=this.trimColumnRows(e[0],d,f),n=this.trimColumnRows(e[1],d,f);if(e[0]!=null&&e[1]!=null&&t!==n)throw Error(`FileDiff.trimColumns: split columns out of sync`);return e[0]==null?n:t}throw console.error({diffStyle:t,columns:e}),Error(`FileDiff.trimColumns: Invalid columns for diffType`)}getBufferSize(e){let t=Number.parseInt(e?.bufferSize??``,10);return Number.isNaN(t)?void 0:t}updateBufferSize(e,t){e.dataset.bufferSize=`${t}`,e.style.setProperty(`grid-row`,`span ${t}`),e.style.setProperty(`min-height`,`calc(${t} * 1lh)`)}getColumnPair(e){if(e==null)return;let t=e.children[0],n=e.children[1];if(!(!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||t.dataset.gutter==null||n.dataset.content==null))return{gutter:t,content:n}}getCodeColumns(e,t,n,r){if(e===`unified`)return this.getColumnPair(t);{let e=this.getColumnPair(n),t=this.getColumnPair(r);return e!=null||t!=null?[e,t]:void 0}}updateBuffers(e){this.pre!=null&&this.applyBuffers(this.pre,e)}applyBuffers(e,t){if(t==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}t.bufferBefore>0?(this.bufferBefore??(this.bufferBefore=document.createElement(`div`),this.bufferBefore.dataset.virtualizerBuffer=`before`,e.before(this.bufferBefore)),this.bufferBefore.style.setProperty(`height`,`${t.bufferBefore}px`),this.bufferBefore.style.setProperty(`contain`,`strict`)):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),t.bufferAfter>0?(this.bufferAfter??(this.bufferAfter=document.createElement(`div`),this.bufferAfter.dataset.virtualizerBuffer=`after`,e.after(this.bufferAfter)),this.bufferAfter.style.setProperty(`height`,`${t.bufferAfter}px`),this.bufferAfter.style.setProperty(`contain`,`strict`)):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyPreNodeAttributes(e,{additionsContentAST:t,deletionsContentAST:n,totalLines:r},i){let{diffIndicators:a=`bars`,disableBackground:o=!1,disableLineNumbers:s=!1,overflow:c=`scroll`,diffStyle:l=`split`}=this.options,u={type:`diff`,diffIndicators:a,disableBackground:o,disableLineNumbers:s,overflow:c,split:l!==`unified`&&t!=null&&n!=null,totalLines:r,customProperties:i};je(u,this.appliedPreAttributes)||(v(e,u),this.appliedPreAttributes=u)}applyErrorToDOM(e,t){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;let n=t.shadowRoot??t.attachShadow({mode:`open`});this.errorWrapper??=document.createElement(`div`),this.errorWrapper.dataset.errorWrapper=``,this.errorWrapper.textContent=``,n.appendChild(this.errorWrapper);let r=document.createElement(`div`);r.dataset.errorMessage=``,r.innerText=e.message,this.errorWrapper.appendChild(r);let i=document.createElement(`pre`);i.dataset.errorStack=``,i.innerText=e.stack??`No Error Stack`,this.errorWrapper.appendChild(i)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function _r(e,t){return e==null||t==null?e==null&&t==null:i(e,t)}function vr({fileDiff:e,oldFile:t,newFile:n}){return e!=null&&e.hunks.length>0||t!=null||n!=null}function yr({fileDiff:e,oldFile:t,newFile:n}){return e!=null||t!=null||n!=null}function br(e,t,n=!1){return!n&&e==null&&t}function xr(e,t,n=!1){return e==null&&t&&!n}function Q(e){if(e!=null&&e.type===`element`)return e.children??[]}function Sr({fileDiff:e,metrics:t,disableFileHeader:r,hunkSeparators:i,expandUnchanged:o,expandedHunks:s,collapsedContextThreshold:c,canHydratePartialDiff:l}){let u=n(t,r),d=u,f=o?!0:s,p=e.hunks.length-1;for(let n=0;n<e.hunks.length;n++){let r=e.hunks[n];if(r==null)throw Error(`computeEstimatedDiffHeights: invalid hunk index`);let o=H({isPartial:e.isPartial,rangeSize:r.collapsedBefore,expandedHunks:f,hunkIndex:n,collapsedContextThreshold:c}),s=(o.fromStart+o.fromEnd)*t.lineHeight;if(u+=s,d+=s,o.collapsedLines>0){let e=R({type:i,metrics:t,hunkIndex:n,hunkSpecs:r.hunkSpecs})?.totalHeight??0;u+=e,d+=e}u+=r.splitLineCount*t.lineHeight,d+=r.unifiedLineCount*t.lineHeight;let m=Cr(r);u+=m.split*t.lineHeight,d+=m.unified*t.lineHeight;let h=n===p?a({fileDiff:e,hunkIndex:n,expandedHunks:f,collapsedContextThreshold:c,errorPrefix:`computeEstimatedDiffHeights`}):void 0;if(h!=null){let e=(h.fromStart+h.fromEnd)*t.lineHeight;if(u+=e,d+=e,h.collapsedLines>0){let e=U({type:i,metrics:t})?.totalHeight??0;u+=e,d+=e}}else if(n===p&&e.isPartial&&l){let e=U({type:i,metrics:t})?.totalHeight??0;u+=e,d+=e}}if(e.hunks.length>0){let e=xe(t);u+=e,d+=e}return{splitHeight:u,unifiedHeight:d}}function Cr(e){if(!e.noEOFCRAdditions&&!e.noEOFCRDeletions)return{split:0,unified:0};let t=e.hunkContent.at(-1);if(t==null)return{split:0,unified:0};if(t.type===`context`){let e=+(t.lines>0);return{split:e,unified:e}}return wr(e,t)}function wr(e,t){let n=(t.deletions>0&&e.noEOFCRDeletions?1:0)+(t.additions>0&&e.noEOFCRAdditions?1:0),r=t.deletions>0&&e.noEOFCRDeletions,i=t.additions>0&&e.noEOFCRAdditions;return{split:r||i?1:0,unified:n}}var Tr=3e3,Er=-1,Dr=class extends gr{__id=`little-virtualized-file-diff:${++Er}`;top;height=0;metrics;cache={heightDeltas:new Map,measuredHeightDeltaTotal:0,estimatedSplitHeight:void 0,estimatedUnifiedHeight:void 0,checkpoints:[],totalLines:0,fileAnnotationHeight:0};isVisible=!1;isSetup=!1;virtualizer;layoutDirty=!0;forceRenderOverride;currentCollapsed;currentExpandUnchanged;pendingHydratedDiff;pendingExpansions;constructor(e,t,n,r,i=!1){super(e,r,i),this.virtualizer=t,this.metrics=Se(n)}setMetrics(e,t=!1){let n=Se(e);!t&&ne(this.metrics,n)||(this.metrics=n,this.resetLayoutCache({includeEstimatedHeights:!0}))}setLineAnnotations(e){this.syncLineAnnotations(e)&&this.resetLayoutCache({includeEstimatedHeights:!1})}syncLineAnnotations(e){return e==null||e===this.lineAnnotations||e.length===0&&this.lineAnnotations.length===0?!1:(super.setLineAnnotations(e),!0)}setFileAnnotationHeight(e){let t=this.cache.fileAnnotationHeight;return e!==t&&(this.cache.fileAnnotationHeight=e,this.cache.measuredHeightDeltaTotal+=e-t,!0)}hasFileAnnotations(e=this.fileDiff){return e==null||!pe(this.lineAnnotations)?!1:this.lineAnnotations.some(t=>t.lineNumber===0?e.type===`new`?t.side===`additions`:e.type!==`deleted`||t.side===`deletions`:!1)}getLineHeight(e,t=!1){return this.getEstimatedLineHeight(t)+(this.cache.heightDeltas.get(e)??0)}getEstimatedLineHeight(e=!1){let t=e?2:1;return this.metrics.lineHeight*t}setOptions(e){if(this.isAdvancedMode())throw Error(`VirtualizedFileDiff.setOptions cannot be used inside CodeView. Update CodeView options instead.`);if(e==null)return;let{options:t}=this,n=!Me(t,e),r=n&&Fr(t,e);super.setOptions(e),r&&this.resetLayoutCache({forceSimpleRecompute:!0,includeEstimatedHeights:Ir(t,e)}),n&&(this.forceRenderOverride=!0),n&&this.isSimpleMode()&&this.virtualizer.instanceChanged(this,r)}setThemeType(e){if(this.isAdvancedMode())throw Error(`VirtualizedFileDiff.setThemeType cannot be used inside CodeView. Update CodeView options instead.`);super.setThemeType(e)}resetLayoutCache({forceSimpleRecompute:e=!1,includeEstimatedHeights:t=!1,resetRenderRange:n=!0}={}){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heightDeltas.size>0&&this.cache.heightDeltas.clear(),this.cache.measuredHeightDeltaTotal!==0&&(this.cache.measuredHeightDeltaTotal=0),this.invalidateDerivedLayoutCache(t,n),e&&this.isSimpleMode()&&this.computeApproximateSize()}invalidateDerivedLayoutCache(e,t=!0){this.layoutDirty=!0,this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.cache.totalLines!==0&&(this.cache.totalLines=0),e&&(this.cache.estimatedSplitHeight=void 0,this.cache.estimatedUnifiedHeight=void 0),this.renderRange!=null&&t&&(this.renderRange=void 0)}reconcileHeights(){let e=!1,{overflow:t=`scroll`}=this.options;if(this.fileContainer==null||this.fileDiff==null)return this.height!==0&&(e=!0),this.height=0,e;if(this.top=this.getVirtualizedTop(),t===`scroll`&&this.lineAnnotations.length===0&&!this.isResizeDebuggingEnabled())return e;let n=this.getDiffStyle(),r=n===`split`?[this.codeDeletions,this.codeAdditions]:[this.codeUnified],i=this.hasFileAnnotations(this.fileDiff);if(this.renderRange!=null&&i&&Fe(this.renderRange)){let t=Or(r)??0;this.setFileAnnotationHeight(t)&&(e=!0)}else!i&&this.setFileAnnotationHeight(0)&&(e=!0);for(let t of r){if(t==null)continue;let r=t.children[1];if(r instanceof HTMLElement)for(let t of r.children){if(!(t instanceof HTMLElement))continue;let r=t.dataset.lineIndex;if(r==null)continue;let i=Br(r,n),a=t.getBoundingClientRect().height,o=!1;t.nextElementSibling instanceof HTMLElement&&(`lineAnnotation`in t.nextElementSibling.dataset||`noNewline`in t.nextElementSibling.dataset)&&(`noNewline`in t.nextElementSibling.dataset&&(o=!0),a+=t.nextElementSibling.getBoundingClientRect().height);let s=this.getEstimatedLineHeight(o),c=this.cache.heightDeltas.get(i)??0,l=a-s;l!==c&&(e=!0,this.cache.measuredHeightDeltaTotal+=l-c,l===0?this.cache.heightDeltas.delete(i):this.cache.heightDeltas.set(i,l))}}return(e||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),e}onRender=e=>this.fileContainer!=null&&(e&&(this.top=this.getVirtualizedTop()),this.render());flushManagers(){super.flushManagers(),this.lineStateRefreshPending&&this.flushDeferredLineState()}prepareCodeViewItem(e,t,n,r){let i=!S(this.fileDiff,e),a=this.syncLineAnnotations(r),o=n?.resetDiffLayoutCache===!0||i||a,s=i||n?.resetDiffLayoutCache===!0&&n.includeEstimatedDiffHeights;n?.metrics!=null&&(this.metrics=Se(n.metrics),o=!0,s=!0);let{collapsed:c=!1,expandUnchanged:l=!1}=this.options;return this.currentCollapsed!==c&&(this.currentCollapsed=c,o=!0),this.currentExpandUnchanged!==l&&(this.currentExpandUnchanged=l,o=!0,s=!0),o&&this.resetLayoutCache({includeEstimatedHeights:s}),this.fileDiff=e,this.top=t,this.computeApproximateSize(),this.height}getLinePosition(e,t=`additions`){if(this.fileDiff==null||e<1)return;let r=this.getLineIndex(e,t);if(r==null)return;let{disableFileHeader:i=!1,expandUnchanged:a=!1,collapsed:o=!1,collapsedContextThreshold:s=1}=this.options,c=this.getDiffStyle(),l=this.getHunkSeparatorType(),u=c===`split`?r[1]:r[0];this.approximateLayoutCheckpoints();let d=n(this.metrics,i),f=this.getLayoutCheckpointBeforeLineIndex(u),p=f?.top??d+this.cache.fileAnnotationHeight;if(o)return{top:d,height:0};let m;return L({diff:this.fileDiff,diffStyle:c,startingLine:f?.renderedLineIndex??0,expandedHunks:a?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:s,callback:({hunkIndex:e,hunk:t,collapsedBefore:n,collapsedAfter:r,deletionLine:i,additionLine:a})=>{let o=c===`split`?a?.splitLineIndex??i?.splitLineIndex:a?.unifiedLineIndex??i?.unifiedLineIndex;if(o==null)throw Error(`VirtualizedFileDiff.getLinePosition: missing line index data`);if(n>0){let r=R({type:l,metrics:this.metrics,hunkIndex:e,hunkSpecs:t?.hunkSpecs});if(r!=null){if(p+=r.gapBefore,u>=o-n&&u<o)return m={top:p,height:r.height},!0;p+=r.height+r.gapAfter}}let s=this.getLineHeight(o,(a?.noEOFCR??!1)||(i?.noEOFCR??!1));if(o===u)return m={top:p,height:s},!0;if(p+=s,r>0){let e=U({type:l,metrics:this.metrics});if(e!=null){if(u>o&&u<=o+r)return m={top:p+e.gapBefore,height:e.height},!0;p+=e.totalHeight}}return!1}}),m}getEditorViewport(){return this.virtualizer.type===`simple`?this.virtualizer.getRoot():this.virtualizer.getContainerElement()}getNumericScrollAnchor(e){if(this.fileDiff==null)return;let{disableFileHeader:t=!1,expandUnchanged:r=!1,collapsed:i=!1,collapsedContextThreshold:a=1}=this.options;if(i)return;let o=this.getDiffStyle(),s=this.getHunkSeparatorType();this.approximateLayoutCheckpoints();let c=this.getLayoutCheckpointBeforeTop(e),l=c?.top??n(this.metrics,t)+this.cache.fileAnnotationHeight,u;return L({diff:this.fileDiff,diffStyle:o,startingLine:c?.renderedLineIndex??0,expandedHunks:r?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:a,callback:({hunkIndex:t,hunk:n,collapsedBefore:r,collapsedAfter:i,deletionLine:a,additionLine:c})=>{let d=o===`split`?c?.splitLineIndex??a?.splitLineIndex:c?.unifiedLineIndex??a?.unifiedLineIndex;if(d==null)throw Error(`VirtualizedFileDiff.getNumericScrollAnchor: missing line index data`);if(r>0){let e=R({type:s,metrics:this.metrics,hunkIndex:t,hunkSpecs:n?.hunkSpecs});e!=null&&(l+=e.totalHeight)}if(l>=e&&(a==null?c!=null&&(u={lineNumber:c.lineNumber,side:`additions`,top:l}):u={lineNumber:a.lineNumber,side:`deletions`,top:l},u!=null))return!0;let f=this.getLineHeight(d,(c?.noEOFCR??!1)||(a?.noEOFCR??!1));if(l+=f,i>0){let e=U({type:s,metrics:this.metrics});e!=null&&(l+=e.totalHeight)}return!1}}),u}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(e){if(this.top==null||this.fileDiff==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};let t=e==null?this.renderRange:this.computeRenderRangeFromWindow(this.fileDiff,this.top,e);if(t==null)return;let{bufferBefore:n,bufferAfter:r,totalLines:i}=t,a=0;if(i===0){let t=e??this.virtualizer.getWindowSpecs();this.top<t.top&&(a=r)}return{topOffset:this.top+n+a,height:this.height-(n+r)}}cleanUp(e=!1){this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),e||(this.resetLayoutCache({includeEstimatedHeights:!0}),this.pendingExpansions=void 0,this.pendingHydratedDiff=void 0),this.isSetup=!1,super.cleanUp(e)}expandHunk=(e,t,n)=>{this.fileDiff!=null&&(this.isAdvancedMode()?(this.pendingExpansions??=[],this.pendingExpansions.push({hunkIndex:e,direction:t,expansionLineCountOverride:n})):(this.hunksRenderer.expandHunk(e,t,n),this.resetLayoutCache({includeEstimatedHeights:!0}),this.computeApproximateSize()),this.loadFilesIfNecessary(),this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0))};async handleFilesLoaded(e,t){if(!(this.fileDiff!==e||!e.isPartial)){if(this.isAdvancedMode()){let n=zt(`clone`,e,t);if(await dr(()=>this.primeHighlightCache(n)),!this.enabled||this.fileDiff!==e)return;this.pendingHydratedDiff={expectedDiff:e,nextDiff:n,files:t}}else{if(zt(`merge`,e,t),this.setHydratedState(t),await dr(()=>this.primeHighlightCache(e)),!this.enabled||this.fileDiff!==e)return;this.resetLayoutCache({includeEstimatedHeights:!0}),this.computeApproximateSize()}this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0)}}consumeCodeViewLayoutChanges(e){let t=!1,n,{pendingExpansions:r,pendingHydratedDiff:i}=this;if(r!=null){this.pendingExpansions=void 0;for(let e of r)this.hunksRenderer.expandHunk(e.hunkIndex,e.direction,e.expansionLineCountOverride),t=!0}return i!=null&&(this.pendingHydratedDiff=void 0,i.expectedDiff===e&&(this.setHydratedState(i.files),n=i.nextDiff)),n==null?t&&(this.forceRenderOverride=!0,this.invalidateDerivedLayoutCache(!0)):(this.forceRenderOverride=!0,this.resetLayoutCache({includeEstimatedHeights:!0})),n}loadFilesIfNecessary(){if(this.pendingHydratedDiff!=null){if(this.pendingHydratedDiff.expectedDiff===this.fileDiff)return;this.pendingHydratedDiff=void 0}super.loadFilesIfNecessary()}isLineRenderable(e){if(super.isLineRenderable(e))return!0;let{pendingExpansions:t}=this,n=this.fileDiffCache;if(t==null||t.length===0||n==null)return!1;let{expansionLineCount:r=100,collapsedContextThreshold:i=1}=this.options,a=new Map(this.hunksRenderer.getExpandedHunksMap());for(let e of t){let t={...a.get(e.hunkIndex)??{fromStart:0,fromEnd:0}},n=e.expansionLineCountOverride??r;(e.direction===`up`||e.direction===`both`)&&(t.fromStart+=n),(e.direction===`down`||e.direction===`both`)&&(t.fromEnd+=n),a.set(e.hunkIndex,t)}return s({fileDiff:n,lineNumber:e,expandedHunks:a,collapsedContextThreshold:i})}invalidateEditSessionLayout(){this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache({forceSimpleRecompute:this.isSimpleMode(),includeEstimatedHeights:!0,resetRenderRange:!1}),this.isSimpleMode()||this.computeApproximateSize(!0),this.getSimpleVirtualizer()?.requestHeightReconcile(this)}escalateEditSessionRender(){this.invalidateEditSessionLayout(),!(!this.enabled||this.fileDiff==null)&&(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0))}shouldSelfHealEditSession(){return!this.isAdvancedMode()&&super.shouldSelfHealEditSession()}setVisibility(e){this.isAdvancedMode()||this.fileContainer==null||(this.renderRange=void 0,e&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!e&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){!this.enabled||this.fileDiff==null&&this.additionFile==null&&this.deletionFile==null||(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!1))}applyDocumentChange(e,t,n=!1){let{renderRange:r}=this;if(this.getAdvancedVirtualizer()?.capturePendingLayoutAnchor(),super.applyDocumentChange(e,t),this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache({forceSimpleRecompute:this.isSimpleMode(),includeEstimatedHeights:!0,resetRenderRange:!1}),!this.isSimpleMode())this.computeApproximateSize(!0);else if(n&&r!==void 0&&this.fileDiff!==void 0){let e=this.virtualizer.getWindowSpecs(),t=this.computeRenderRangeFromWindow(this.fileDiff,this.top??0,e);t.bufferAfter!==r.bufferAfter&&this.updateBuffers(t)}this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0)}computeApproximateSize(e=!1,t=this.fileDiff){let r=this.isResizeDebuggingEnabled();if(!e&&!this.layoutDirty&&!r)return;let i=this.height===0;if(this.height=0,this.cache.checkpoints=[],this.cache.totalLines=0,t==null){this.layoutDirty=!1;return}let{disableFileHeader:a=!1,collapsed:o=!1}=this.options,s=n(this.metrics,a);if(this.height+=s,o){this.layoutDirty=!1;return}this.height=this.getActiveEstimatedHeight(t)+this.cache.measuredHeightDeltaTotal,r&&!i&&this.validateComputedHeight(t),this.layoutDirty=!1}getActiveEstimatedHeight(e=this.fileDiff){this.ensureEstimatedDiffHeights(e);let t=this.getDiffStyle()===`split`?this.cache.estimatedSplitHeight:this.cache.estimatedUnifiedHeight;if(t==null)throw Error(`VirtualizedFileDiff.getActiveEstimatedHeight: missing estimated height`);return t}ensureEstimatedDiffHeights(e=this.fileDiff){if(e==null){this.cache.estimatedSplitHeight=void 0,this.cache.estimatedUnifiedHeight=void 0;return}if(this.cache.estimatedSplitHeight!=null&&this.cache.estimatedUnifiedHeight!=null)return;let{disableFileHeader:t=!1,expandUnchanged:n=!1,collapsedContextThreshold:r=1}=this.options,{splitHeight:i,unifiedHeight:a}=Sr({fileDiff:e,metrics:this.metrics,disableFileHeader:t,hunkSeparators:this.getHunkSeparatorType(),expandUnchanged:n,expandedHunks:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:r,canHydratePartialDiff:Lr(e,this.options.loadDiffFiles!=null)});this.cache.estimatedSplitHeight=i,this.cache.estimatedUnifiedHeight=a}validateComputedHeight(e=this.fileDiff){if(this.fileContainer==null||e==null)return;let t=this.fileContainer.getBoundingClientRect();t.height===this.height?console.log(`VirtualizedFileDiff.computeApproximateSize: computed height IS CORRECT`):console.log(`VirtualizedFileDiff.computeApproximateSize: computed height doesnt match`,{name:e.name,elementHeight:t.height,computedHeight:this.height})}render({fileContainer:e,fileDiff:t,forceRender:n=!1,lineAnnotations:r,...i}={}){let a=fr(i,`VirtualizedFileDiff.render`),o=a!=null,s=a?.oldFile,c=a?.newFile,l=o&&(!zr(s,this.deletionFile)||!zr(c,this.additionFile)),u=t??this.fileDiff;t==null&&o&&(l||this.fileDiff==null)&&(u=q(a.oldFile,a.newFile,this.options.parseDiffOptions));let{forceRenderOverride:d,isSetup:f}=this;this.forceRenderOverride=void 0;let p=this.syncLineAnnotations(r);p&&this.resetLayoutCache({includeEstimatedHeights:!1});let m=t!=null&&t!==this.fileDiff,h=u!=null&&!S(this.fileDiff,u),g=m||l;if(h&&this.resetLayoutCache({includeEstimatedHeights:!0}),e=this.getOrCreateFileContainer(e),u==null)return console.error(`VirtualizedFileDiff.render: attempting to virtually render when we dont have the correct data`),!1;if(f)this.top??=this.getVirtualizedTop(),h&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.computeApproximateSize(!1,u));else{this.computeApproximateSize(!1,u);let t=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(t==null)throw Error(`VirtualizedFileDiff.render: simple virtualizer is not available`);t.connect(e,this),this.isVisible=t.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode()&&(!g||!f))return this.fileDiff=u,a!=null&&(this.deletionFile=s,this.additionFile=c),h&&(this.cachedHeaderHTML=void 0),this.renderPlaceholder(this.height);let _=this.virtualizer.getWindowSpecs(),v=this.top??0,y=this.computeRenderRangeFromWindow(u,v,_),b=super.render({fileDiff:u,fileContainer:e,renderRange:y,lineAnnotations:r,forceRender:(d??n)||p||h,...a,...i});return this.isSimpleMode()&&b&&this.getSimpleVirtualizer()?.requestHeightReconcile(this),b}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}shouldGuardRebuildScroll(){return!1}isSimpleMode(){return this.virtualizer.type===`simple`}isAdvancedMode(){return this.virtualizer.type===`advanced`}getVirtualizedTop(){return this.virtualizer.type===`advanced`?this.virtualizer.getLocalTopForInstance(this):this.fileContainer==null?0:this.virtualizer.getOffsetInScrollContainer(this.fileContainer)}getSimpleVirtualizer(){return this.virtualizer.type===`simple`?this.virtualizer:void 0}getAdvancedVirtualizer(){return this.virtualizer.type===`advanced`?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}getDiffStyle(){return this.options.diffStyle??`split`}getHunkSeparatorType(){return Rr(this.options.hunkSeparators)}approximateLayoutCheckpoints(e=this.fileDiff){if(!this.layoutDirty&&this.cache.checkpoints.length>0||e==null||e.hunks.length===0||this.options.collapsed===!0)return;let{disableFileHeader:t=!1,expandUnchanged:r=!1,collapsedContextThreshold:i=1}=this.options,o=e.hunks.length-1,s=Lr(e,this.options.loadDiffFiles!=null),c=this.getDiffStyle(),l=this.getHunkSeparatorType(),u=r?!0:this.hunksRenderer.getExpandedHunksMap(),d=kr(this.cache.heightDeltas),f=n(this.metrics,t)+this.cache.fileAnnotationHeight,p=0,m=({rowCount:e,startLineIndex:t,preSeparatorHeight:n=0,postSeparatorHeight:r=0,metadataOffsets:i=[]})=>{if(e<=0)return;let a=p,o=p+e,s=Mr(a);for(;s<o;){let e=s-a,r=f+(e>0?n:0)+e*this.metrics.lineHeight+Nr(i,e)*this.metrics.lineHeight+Ar(d,t,t+e);this.cache.checkpoints.push({renderedLineIndex:s,lineIndex:t+e,top:r}),s+=Tr}f+=n+e*this.metrics.lineHeight+i.length*this.metrics.lineHeight+Ar(d,t,t+e)+r,p=o};for(let t=0;t<e.hunks.length;t++){let n=e.hunks[t];if(n==null)throw Error(`VirtualizedFileDiff.approximateLayoutCheckpoints: invalid hunk index`);let r=H({isPartial:e.isPartial,rangeSize:n.collapsedBefore,expandedHunks:u,hunkIndex:t,collapsedContextThreshold:i}),d=r.collapsedLines>0?R({type:l,metrics:this.metrics,hunkIndex:t,hunkSpecs:n.hunkSpecs})?.totalHeight??0:0;m({rowCount:r.fromStart,startLineIndex:(c===`split`?n.splitLineStart:n.unifiedLineStart)-r.rangeSize});let f=d;m({rowCount:r.fromEnd,startLineIndex:(c===`split`?n.splitLineStart:n.unifiedLineStart)-r.fromEnd,preSeparatorHeight:f}),r.fromEnd>0&&(f=0);let p=t===o?a({fileDiff:e,hunkIndex:t,expandedHunks:u,collapsedContextThreshold:i,errorPrefix:`VirtualizedFileDiff`}):void 0,h=p!=null&&p.collapsedLines>0||t===o&&s?U({type:l,metrics:this.metrics})?.totalHeight??0:0,g=p==null?0:p.fromStart+p.fromEnd,_=c===`split`?n.splitLineCount:n.unifiedLineCount,v=c===`split`?n.splitLineStart:n.unifiedLineStart;m({rowCount:_,startLineIndex:v,preSeparatorHeight:f,postSeparatorHeight:g===0?h:0,metadataOffsets:Pr({diffStyle:c,hunk:n,rowCount:_})}),p!=null&&g>0&&m({rowCount:g,startLineIndex:v+_,postSeparatorHeight:h})}this.cache.totalLines=p}getLayoutCheckpointBeforeLineIndex(e){if(e<=0||this.cache.checkpoints.length===0)return;let t=0,n=this.cache.checkpoints.length-1,r;for(;t<=n;){let i=t+n>>1,a=this.cache.checkpoints[i];if(a==null)throw Error(`VirtualizedFileDiff: invalid checkpoint index`);a.lineIndex<=e?(r=a,t=i+1):n=i-1}return r}getLayoutCheckpointBeforeTop(e,t){let n=0,r=this.cache.checkpoints.length-1,i=-1;for(;n<=r;){let t=n+r>>1,a=this.cache.checkpoints[t];if(a==null)throw Error(`VirtualizedFileDiff: invalid checkpoint index`);a.top<=e?(i=t,n=t+1):r=t-1}if(t==null)return i>=0?this.cache.checkpoints[i]:void 0;for(let e=i;e>=0;e--){let n=this.cache.checkpoints[e];if(n==null)throw Error(`VirtualizedFileDiff: invalid checkpoint index`);if(n.renderedLineIndex%t===0)return n}}getExpandedLineCount(e,t){let n=0;if(e.isPartial){for(let r of e.hunks)n+=t===`split`?r.splitLineCount:r.unifiedLineCount;return n}let{expandUnchanged:r=!1,collapsedContextThreshold:i=1}=this.options,o=r?!0:this.hunksRenderer.getExpandedHunksMap();for(let[r,a]of e.hunks.entries()){let s=t===`split`?a.splitLineCount:a.unifiedLineCount;n+=s;let c=Math.max(a.collapsedBefore,0),{fromStart:l,fromEnd:u,renderAll:d}=H({isPartial:e.isPartial,rangeSize:c,expandedHunks:o,hunkIndex:r,collapsedContextThreshold:i});c>0&&(n+=d?c:l+u)}let s=a({fileDiff:e,hunkIndex:e.hunks.length-1,expandedHunks:o,collapsedContextThreshold:i,errorPrefix:`VirtualizedFileDiff`});return s!=null&&(n+=s.fromStart+s.fromEnd),n}getLayoutLineCount(e,t){let n=this.getExpandedLineCount(e,t),r=t===`split`?e.splitLineCount:e.unifiedLineCount;return Math.max(n,r,e.additionLines.length,e.deletionLines.length,this.cache.totalLines)}computeRenderRangeFromWindow(e,t,{top:r,bottom:i}){let{disableFileHeader:a=!1,expandUnchanged:o=!1,collapsedContextThreshold:s=1}=this.options,{hunkLineCount:c,lineHeight:l}=this.metrics,u=this.getDiffStyle(),d=this.getHunkSeparatorType(),f=Lr(e,this.options.loadDiffFiles!=null),p=this.height,m=this.getLayoutLineCount(e,u),h=n(this.metrics,a),g=e.hunks.length>0?xe(this.metrics):0,{fileAnnotationHeight:_}=this.cache,v=h+_,y=Math.max(0,p-h-_-g),b=this.hasFileAnnotations(e),x=t+h,S=_>0&&b&&x<i&&x+_>r;if(t<r-p||t>i)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:p-h-g};if(m<=c||e.hunks.length===0)return{startingLine:0,totalLines:c,bufferBefore:0,bufferAfter:0};this.approximateLayoutCheckpoints(e),m=this.getLayoutLineCount(e,u);let C=Math.ceil(Math.max(i-r,0)/l),w=Math.ceil(C/c)*c+c,T=w/c,E=T,D=[],O=(r+i)/2,k=this.getLayoutCheckpointBeforeTop(Math.max(0,r-t-w*l*2),c),A=t+(k?.top??v),j=k?.renderedLineIndex??0,M,N,P;if(L({diff:e,diffStyle:u,startingLine:k?.renderedLineIndex??0,expandedHunks:o?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:s,callback:({hunkIndex:n,hunk:a,collapsedBefore:o,collapsedAfter:s,deletionLine:l,additionLine:p})=>{let m=p==null?l.splitLineIndex:p.splitLineIndex,h=p==null?l.unifiedLineIndex:p.unifiedLineIndex,g=(p?.noEOFCR??!1)||(l?.noEOFCR??!1),_=n===e.hunks.length-1&&a!=null&&(u===`split`?m===a.splitLineStart+a.splitLineCount-1:h===a.unifiedLineStart+a.unifiedLineCount-1),y=(o>0?R({type:d,metrics:this.metrics,hunkIndex:n,hunkSpecs:a?.hunkSpecs}):void 0)?.totalHeight??0;A+=y;let b=j%c===0,x=Math.floor(j/c);if(b&&(D[x]=A-(t+v+y),P!=null)){if(P<=0)return!0;P--}let S=this.getLineHeight(u===`split`?m:h,g);if(A>r-S&&A<i&&(M??=x),N==null&&A+S>O&&(N=x),P==null&&A>=i&&b&&(P=E),j++,A+=S,s>0||_&&f){let e=U({type:d,metrics:this.metrics});e!=null&&(A<i&&A+e.totalHeight>r&&(M??=x),N==null&&A+e.totalHeight>O&&(N=x),A+=e.totalHeight)}return!1}}),M==null)if(S)M=0,N=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:p-h-g};N??=M;let F=Math.round(N-T/2),I=Math.max(0,Math.ceil(m/c)-T),ee=Math.max(0,Math.min(F,I)),te=ee*c,ne=F<0?w+F*c:w,re=D[ee]??0,ie=te===0?0:_+re,ae=ee+ne/c,oe=ae<D.length?y-D[ae]:y-(A-t-v);return{startingLine:te,totalLines:ne,bufferBefore:ie,bufferAfter:Math.max(0,oe)}}};function Or(e){let t;for(let n of e){if(n==null)continue;let e=n.children[1];if(e instanceof HTMLElement)for(let n of e.children)n instanceof HTMLElement&&n.dataset.lineAnnotation===T&&(t=Math.max(t??0,n.getBoundingClientRect().height))}return t}function kr(e){let t=Array.from(e).sort((e,t)=>e[0]-t[0]),n=[],r=[0],i=0;for(let[e,a]of t)n.push(e),i+=a,r.push(i);return{lineIndexes:n,prefixTotals:r}}function Ar({lineIndexes:e,prefixTotals:t},n,r){if(n>=r||e.length===0)return 0;let i=jr(e,n);return(t[jr(e,r)]??0)-(t[i]??0)}function jr(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>1,a=e[i];if(a==null)throw Error(`VirtualizedFileDiff: invalid prefix index`);a<t?n=i+1:r=i}return n}function Mr(e){return Math.ceil(e/Tr)*Tr}function Nr(e,t){let n=0;for(let r of e)r<t&&n++;return n}function Pr({diffStyle:e,hunk:t,rowCount:n}){if(n<=0||!t.noEOFCRAdditions&&!t.noEOFCRDeletions)return[];let r=t.hunkContent.at(-1);if(r==null)return[];if(r.type===`context`)return[n-1];let i=Math.max(r.deletions,r.additions),a=r.deletions+r.additions;if(e===`split`)return i>0&&(t.noEOFCRAdditions||t.noEOFCRDeletions)?[n-1]:[];let o=[],s=n-a;return r.deletions>0&&t.noEOFCRDeletions&&o.push(s+r.deletions-1),r.additions>0&&t.noEOFCRAdditions&&o.push(n-1),o}function Fr(e,t){return(e.diffStyle??`split`)!==(t.diffStyle??`split`)||(e.overflow??`scroll`)!==(t.overflow??`scroll`)||(e.collapsed??!1)!==(t.collapsed??!1)||(e.disableLineNumbers??!1)!==(t.disableLineNumbers??!1)||(e.disableFileHeader??!1)!==(t.disableFileHeader??!1)||(e.diffIndicators??`bars`)!==(t.diffIndicators??`bars`)||(e.hunkSeparators??`line-info`)!==(t.hunkSeparators??`line-info`)||!!e.loadDiffFiles!=!!t.loadDiffFiles||(e.expandUnchanged??!1)!==(t.expandUnchanged??!1)||(e.collapsedContextThreshold??1)!==(t.collapsedContextThreshold??1)||e.unsafeCSS!==t.unsafeCSS}function Ir(e,t){return(e.disableFileHeader??!1)!==(t.disableFileHeader??!1)||(e.hunkSeparators??`line-info`)!==(t.hunkSeparators??`line-info`)||!!e.loadDiffFiles!=!!t.loadDiffFiles||(e.expandUnchanged??!1)!==(t.expandUnchanged??!1)||(e.collapsedContextThreshold??1)!==(t.collapsedContextThreshold??1)}function Lr(e,t){return e.isPartial&&t&&(e.type===`change`||e.type===`rename-changed`)}function Rr(e){return typeof e==`function`?`custom`:e??`line-info`}function zr(e,t){return e==null||t==null?e==null&&t==null:i(e,t)}function Br(e,t){let[n,r]=e.split(`,`).map(Number);return t===`split`?r:n}function Vr({hunkIndex:e,lineIndex:t,conflictIndex:n}){return`merge-conflict-action-${e}-${t}-${n}`}function Hr(e,t){let n=t.hunks[e.hunkIndex];if(n!=null)return{hunkIndex:e.hunkIndex,lineIndex:Ur(n,e.startContentIndex)}}function Ur(e,t){let n=e.unifiedLineStart;for(let r=0;r<t;r++){let t=e.hunkContent[r];n+=t.type===`context`?t.lines:t.deletions+t.additions}return n}var $=e();function Wr({fileDiff:e,actions:t,renderCustomHeader:n,renderHeaderPrefix:r,renderHeaderFilenameSuffix:i,renderHeaderMetadata:a,renderAnnotation:o,renderGutterUtility:s,renderMergeConflictUtility:c,lineAnnotations:l,getHoveredLine:u,getInstance:d}){let f=n?.(e),p=r?.(e),m=i?.(e),h=a?.(e);return(0,$.jsxs)($.Fragment,{children:[f==null?(0,$.jsxs)($.Fragment,{children:[p!=null&&(0,$.jsx)(`div`,{slot:`header-prefix`,children:p}),m!=null&&(0,$.jsx)(`div`,{slot:`header-filename-suffix`,children:m}),h!=null&&(0,$.jsx)(`div`,{slot:`header-metadata`,children:h})]}):(0,$.jsx)(`div`,{slot:Ee,children:f}),o!=null&&l?.map((e,t)=>(0,$.jsx)(`div`,{slot:V(e),children:o(e)},t)),t!=null&&c!=null&&d!=null&&t.map(t=>{if(t==null)return;let n=Gr(t,e);return(0,$.jsx)(`div`,{slot:n,style:se,children:c(t,d)},n)}),s!=null&&(0,$.jsx)(`div`,{slot:`gutter-utility-slot`,style:be,children:s(u)})]})}function Gr(e,t){let n=Hr(e,t);return n==null?void 0:Vr({hunkIndex:n.hunkIndex,lineIndex:n.lineIndex,conflictIndex:e.conflictIndex})}function Kr(e,t=`diff-panel`){if(!e)return null;let n=e.trim();if(n.length===0)return null;try{let e=pt(n,me(n,t)).flatMap(e=>e.files);return e.length>0?{kind:`files`,files:e}:{kind:`raw`,text:n,reason:`Unsupported diff format. Showing raw patch.`}}catch{return{kind:`raw`,text:n,reason:`Failed to parse patch. Showing raw patch.`}}}function qr(e){let t=e.name??e.prevName??``;return t.startsWith(`a/`)||t.startsWith(`b/`)?t.slice(2):t}function Jr(e){return e.cacheKey??`${e.prevName??`none`}:${e.name}`}function Yr(e,t){return[...e].toSorted((e,n)=>{let r=e.checkpointTurnCount??t[e.turnId]??0,i=n.checkpointTurnCount??t[n.turnId]??0;return r===i?n.completedAt.localeCompare(e.completedAt):i-r})}function Xr(e){let t=Yr(e.summaries,e.inferredCheckpointTurnCountByTurnId),n=e.selectedTurnId===null?void 0:t.find(t=>t.turnId===e.selectedTurnId)??t[0],r=n&&(n.checkpointTurnCount??e.inferredCheckpointTurnCountByTurnId[n.turnId]),i=typeof r==`number`?{fromTurnCount:Math.max(0,r-1),toTurnCount:r}:null,a=t.map(t=>t.checkpointTurnCount??e.inferredCheckpointTurnCountByTurnId[t.turnId]).filter(e=>typeof e==`number`),o=a.length>0?Math.max(...a):void 0,s=typeof o==`number`&&o>0?o:void 0,c=!n&&typeof s==`number`?{fromTurnCount:0,toTurnCount:s}:null,l=n||t.length===0?null:`conversation:${t.map(e=>e.turnId).join(`,`)}`;return{orderedTurnDiffSummaries:t,selectedTurn:n,selectedCheckpointTurnCount:r,selectedCheckpointRange:i,conversationCheckpointTurnCount:s,conversationCheckpointRange:c,activeCheckpointRange:n?i:c,conversationCacheScope:l}}function Zr(e){return{emptyDiffMessage:e?`No net changes were captured for this turn.`:`No full-thread patch is available for these checkpoint summaries. Select a turn or a changed file to inspect captured changes.`}}function Qr(e){let t=e.edgeThreshold??4,n=Math.max(0,e.scrollWidth-e.clientWidth);return{canScrollLeft:e.scrollLeft>t,canScrollRight:e.scrollLeft<n-t}}function $r(e){return e.scrollWidth<=e.clientWidth+1?!1:Math.abs(e.deltaY)>Math.abs(e.deltaX)}function ei(e){return e.hasActiveThread?e.isGitRepo?e.turnSummaryCount===0?{kind:`no-completed-turns`}:e.hasRenderablePatch?{kind:`renderable`,error:e.checkpointDiffError}:e.isLoadingCheckpointDiff?{kind:`loading`,error:e.checkpointDiffError}:{kind:`empty`,error:e.checkpointDiffError,message:e.hasNoNetChanges?e.emptyDiffMessage:`No diff is available for this range.`}:{kind:`not-git-repo`}:{kind:`no-thread`}}export{Xr as a,$r as c,gr as d,An as f,qe as h,Zr as i,Wr as l,Je as m,Kr as n,qr as o,Ye as p,ei as r,Qr as s,Jr as t,Dr as u};
21
- //# sourceMappingURL=DiffPanel.logic-B0YyP6X_.js.map
21
+ //# sourceMappingURL=DiffPanel.logic-Bzk6loSH.js.map