@davmash/bygone 0.8.13 → 0.8.16
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/CHANGELOG.md +16 -0
- package/README.md +2 -2
- package/cli/commandSpec.js +12 -2
- package/cli/completions.js +1 -1
- package/cli/present.js +42 -1
- package/cli/tour.js +13 -2
- package/cli/tourHistory.js +90 -0
- package/completions/_bygone +2 -1
- package/completions/bygone +1 -1
- package/completions/bygone.fish +1 -0
- package/docs/change-tour-format.md +46 -6
- package/docs/explore.md +36 -10
- package/docs/present.md +9 -1
- package/docs/product-surface.md +18 -14
- package/docs/releasing.md +25 -29
- package/media/diff.worker.js +3 -3
- package/media/webview.css +1 -1
- package/media/webview.js +173 -173
- package/out/changeTour.js +953 -410
- package/out/gitComparison.js +354 -0
- package/out/standalone-main.js +7678 -2124
- package/out/tourCoverage.js +992 -402
- package/package.json +1 -1
- package/schemas/change-tour-source.schema.json +58 -3
- package/skills/pr-tour-guide/SKILL.md +16 -7
- package/standalone/index.html +5 -0
- package/web/index.html +14 -0
- package/web/presenter.css +101 -0
- package/web/web-host.js +5 -5
package/web/web-host.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";(()=>{function
|
|
2
|
-
`));var
|
|
1
|
+
"use strict";(()=>{function ee(){}ee.prototype={diff:function(t,n){var i,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},a=o.callback;typeof o=="function"&&(a=o,o={}),this.options=o;var l=this;function d(L){return a?(setTimeout(function(){a(void 0,L)},0),!0):L}t=this.castInput(t),n=this.castInput(n),t=this.removeEmpty(this.tokenize(t)),n=this.removeEmpty(this.tokenize(n));var p=n.length,m=t.length,f=1,s=p+m;o.maxEditLength&&(s=Math.min(s,o.maxEditLength));var x=(i=o.timeout)!==null&&i!==void 0?i:1/0,T=Date.now()+x,A=[{oldPos:-1,lastComponent:void 0}],I=this.extractCommon(A[0],n,t,0);if(A[0].oldPos+1>=m&&I+1>=p)return d([{value:this.join(n),count:n.length}]);var y=-1/0,E=1/0;function k(){for(var L=Math.max(y,-f);L<=Math.min(E,f);L+=2){var F=void 0,U=A[L-1],J=A[L+1];U&&(A[L-1]=void 0);var ne=!1;if(J){var Ie=J.oldPos-L;ne=J&&0<=Ie&&Ie<p}var ve=U&&U.oldPos+1<m;if(!ne&&!ve){A[L]=void 0;continue}if(!ve||ne&&U.oldPos+1<J.oldPos?F=l.addToPath(J,!0,void 0,0):F=l.addToPath(U,void 0,!0,1),I=l.extractCommon(F,n,t,L),F.oldPos+1>=m&&I+1>=p)return d(jn(l,F.lastComponent,n,t,l.useLongestToken));A[L]=F,F.oldPos+1>=m&&(E=Math.min(E,L-1)),I+1>=p&&(y=Math.max(y,L+1))}f++}if(a)(function L(){setTimeout(function(){if(f>s||Date.now()>T)return a();k()||L()},0)})();else for(;f<=s&&Date.now()<=T;){var N=k();if(N)return N}},addToPath:function(t,n,i,o){var a=t.lastComponent;return a&&a.added===n&&a.removed===i?{oldPos:t.oldPos+o,lastComponent:{count:a.count+1,added:n,removed:i,previousComponent:a.previousComponent}}:{oldPos:t.oldPos+o,lastComponent:{count:1,added:n,removed:i,previousComponent:a}}},extractCommon:function(t,n,i,o){for(var a=n.length,l=i.length,d=t.oldPos,p=d-o,m=0;p+1<a&&d+1<l&&this.equals(n[p+1],i[d+1]);)p++,d++,m++;return m&&(t.lastComponent={count:m,previousComponent:t.lastComponent}),t.oldPos=d,p},equals:function(t,n){return this.options.comparator?this.options.comparator(t,n):t===n||this.options.ignoreCase&&t.toLowerCase()===n.toLowerCase()},removeEmpty:function(t){for(var n=[],i=0;i<t.length;i++)t[i]&&n.push(t[i]);return n},castInput:function(t){return t},tokenize:function(t){return t.split("")},join:function(t){return t.join("")}};function jn(e,t,n,i,o){for(var a=[],l;t;)a.push(t),l=t.previousComponent,delete t.previousComponent,t=l;a.reverse();for(var d=0,p=a.length,m=0,f=0;d<p;d++){var s=a[d];if(s.removed){if(s.value=e.join(i.slice(f,f+s.count)),f+=s.count,d&&a[d-1].added){var T=a[d-1];a[d-1]=a[d],a[d]=T}}else{if(!s.added&&o){var x=n.slice(m,m+s.count);x=x.map(function(I,y){var E=i[f+y];return E.length>I.length?E:I}),s.value=e.join(x)}else s.value=e.join(n.slice(m,m+s.count));m+=s.count,s.added||(f+=s.count)}}var A=a[p-1];return p>1&&typeof A.value=="string"&&(A.added||A.removed)&&e.equals("",A.value)&&(a[p-2].value+=A.value,a.pop()),a}var Vn=new ee;function At(e,t,n){return Vn.diff(e,t,n)}var Nt=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Lt=/\S/,et=new ee;et.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!Lt.test(e)&&!Lt.test(t)};et.tokenize=function(e){for(var t=e.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),n=0;n<t.length-1;n++)!t[n+1]&&t[n+2]&&Nt.test(t[n])&&Nt.test(t[n+2])&&(t[n]+=t[n+2],t.splice(n+1,2),n--);return t};function Rt(e,t,n){return et.diff(e,t,n)}var Mt=new ee;Mt.tokenize=function(e){this.options.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
2
|
+
`));var t=[],n=e.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var i=0;i<n.length;i++){var o=n[i];i%2&&!this.options.newlineIsToken?t[t.length-1]+=o:(this.options.ignoreWhitespace&&(o=o.trim()),t.push(o))}return t};var Kn=new ee;Kn.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var Zn=new ee;Zn.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function Le(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Le=function(t){return typeof t}:Le=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Le(e)}var Xn=Object.prototype.toString,me=new ee;me.useLongestToken=!0;me.tokenize=Mt.tokenize;me.castInput=function(e){var t=this.options,n=t.undefinedReplacement,i=t.stringifyReplacer,o=i===void 0?function(a,l){return typeof l>"u"?n:l}:i;return typeof e=="string"?e:JSON.stringify(Qe(e,null,null,o),o," ")};me.equals=function(e,t){return ee.prototype.equals.call(me,e.replace(/,([\r\n])/g,"$1"),t.replace(/,([\r\n])/g,"$1"))};function Qe(e,t,n,i,o){t=t||[],n=n||[],i&&(e=i(o,e));var a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];var l;if(Xn.call(e)==="[object Array]"){for(t.push(e),l=new Array(e.length),n.push(l),a=0;a<e.length;a+=1)l[a]=Qe(e[a],t,n,i,o);return t.pop(),n.pop(),l}if(e&&e.toJSON&&(e=e.toJSON()),Le(e)==="object"&&e!==null){t.push(e),l={},n.push(l);var d=[],p;for(p in e)e.hasOwnProperty(p)&&d.push(p);for(d.sort(),a=0;a<d.length;a+=1)p=d[a],l[p]=Qe(e[p],t,n,i,p);t.pop(),n.pop()}else l=e;return l}var Ae=new ee;Ae.tokenize=function(e){return e.slice()};Ae.join=Ae.removeEmpty=function(e){return e};function Ft(e,t,n){return Ae.diff(e,t,n)}var Jn=500,Qn=100,_t=Qt("BYGONE_MAX_INLINE_HIGHLIGHT_LINE_LENGTH",Jn),er=Qt("BYGONE_DIFF_TIMEOUT_MS",Qn);function ae(e,t,n={}){let i=Ot(e),o=Ot(t);if(e===t)return nr(i);let a=tr(i,o),l=Ft(a.left,a.right,{timeout:n.timeoutMs??er});if(!l)return rr(i,o);let d=l.map(I=>({...I,value:I.value.map(y=>a.lines[y])})),p=[],m=[],f=[],s=[],x=1,T=1;for(let I=0;I<d.length;I++){let y=d[I],E=y.removed?y.value:[],k=y.added?y.value:[];if(!y.added&&!y.removed){for(let N of y.value)m.push(X("context",N,x)),f.push(X("context",N,T)),p.push(se(Z("context",N,x++),Z("context",N,T++)));continue}if(y.removed&&I+1<d.length&&d[I+1].added){let N=d[I+1],L=ir(E,N.value,x,T,p,m,f,s);x=L.left,T=L.right,I++;continue}if(y.removed){let N=m.length,L=f.length;for(let F of E)m.push(X("removed",F,x)),p.push(se(Z("removed",F,x++),ue()));s.push(Oe("delete",N,m.length,L,f.length));continue}if(y.added){let N=m.length,L=f.length;for(let F of k)f.push(X("added",F,T)),p.push(se(ue(),Z("added",F,T++)));s.push(Oe("insert",N,m.length,L,f.length))}}let A=p.some(I=>I.left.kind!=="context"||I.right.kind!=="context");return{rows:p,leftLines:m,rightLines:f,blocks:s,hasChanges:A,quality:"exact"}}function tr(e,t){let n=new Map,i=[],o=a=>{let l=n.get(a);if(l!==void 0)return l;let d=i.length;return n.set(a,d),i.push(a),d};return{left:e.map(o),right:t.map(o),lines:i}}function nr(e){return{rows:e.map((t,n)=>se(Z("context",t,n+1),Z("context",t,n+1))),leftLines:e.map((t,n)=>X("context",t,n+1)),rightLines:e.map((t,n)=>X("context",t,n+1)),blocks:[],hasChanges:!1,quality:"exact"}}function rr(e,t){let n=e.map((l,d)=>X("removed",l,d+1)),i=t.map((l,d)=>X("added",l,d+1)),o=[...e.map((l,d)=>se(Z("removed",l,d+1),ue())),...t.map((l,d)=>se(ue(),Z("added",l,d+1)))],a="replace";return e.length===0?a="insert":t.length===0&&(a="delete"),{rows:o,leftLines:n,rightLines:i,blocks:o.length===0?[]:[Oe(a,0,e.length,0,t.length)],hasChanges:o.length>0,quality:"fallback"}}function Ot(e){if(e.length===0)return[];let t=e.replace(/\r\n/g,`
|
|
3
3
|
`).split(`
|
|
4
|
-
`);return e[e.length-1]===""&&e.pop(),e}var Ot=1e4,Ct=2e3,Fn=.52,Mn=.35,Pt=.38,_n=.33,Dt=.86,Ae=.08,Ce=.05,Le=-.12,Lt=5e3,On=2e3,Nt=4,Pn=8,qe=4;function Ut(t,e){if(t.length===0)return e.map(d=>({right:d}));if(e.length===0)return t.map(d=>({left:d}));if(t.length===1&&e.length===1){let d=Je(t[0],e[0]);return(d.eligible||d.score>=Mn)&&je(t[0],e[0])&&me(te(t[0]))&&me(te(e[0]))?[{left:t[0],right:e[0]}]:[{left:t[0]},{right:e[0]}]}if(t.length*e.length>Ot)return Wn(t,e);let n=Dn(t,e),r=Array.from({length:t.length+1},()=>new Array(e.length+1).fill(Number.NEGATIVE_INFINITY)),o=Array.from({length:t.length+1},()=>new Array(e.length+1).fill(null));r[0][0]=0;for(let d=1;d<=t.length;d++)r[d][0]=r[d-1][0]+Le,o[d][0]="left";for(let d=1;d<=e.length;d++)r[0][d]=r[0][d-1]+Le,o[0][d]="right";for(let d=1;d<=t.length;d++)for(let m=1;m<=e.length;m++){let p=n[d-1][m-1],x=[{move:"left",score:r[d-1][m]+Le},{move:"right",score:r[d][m-1]+Le},{move:"match",score:p===null?Number.NEGATIVE_INFINITY:r[d-1][m-1]+p}].reduce((E,C)=>C.score>E.score?C:E);r[d][m]=x.score,o[d][m]=x.move}let s=[],c=t.length,u=e.length;for(;c>0||u>0;){let d=o[c][u];d==="match"?s.push({left:t[--c],right:e[--u]}):d==="left"?s.push({left:t[--c]}):s.push({right:e[--u]})}return s.reverse()}function Je(t,e){let n=te(t),r=te(e),o=me(n),s=me(r);if(!o||!s||n.length>Ct||r.length>Ct)return{score:0,eligible:!1,characterSimilarity:0,tokenSimilarity:0,lengthSimilarity:0};if(n===r)return{score:1,eligible:!0,characterSimilarity:1,tokenSimilarity:1,lengthSimilarity:1};let c=Ye(n),u=Ye(r),d=Yn(n,r),m=jn(c,u),p=Math.min(n.length,r.length)/Math.max(n.length,r.length),a=Xn(c,u),x=d*.52+m*.32+p*.1+a*.06,E=d>=.52||m>=.45||d>=.48&&m>=.28;return{score:x,eligible:E&&x>=Fn,characterSimilarity:d,tokenSimilarity:m,lengthSimilarity:p}}function Dn(t,e){let n=t.map(k=>e.map(v=>Je(k,v))),r=Bt(t,e),o=n.map(k=>Ke(k)),s=e.map((k,v)=>Ke(n.map(w=>w[v]))),c=n.map((k,v)=>k.map((w,L)=>{if(r.has(`${v}:${L}`))return Math.max(w.score,1);if(!w.eligible)return null;let $=o[v],A=s[L],P=w.score===$.best&&w.score===A.best,D=w.score>=Dt?Ae/2:Ae,W=$.best-$.second>=D,z=A.best-A.second>=D;return P&&W&&z?w.score:null}));if(Math.max(t.length,e.length)>Pn||Math.abs(t.length-e.length)>qe)return c;let u=(k,v,w)=>k.score>=Pt&&je(t[v],e[w])&&Math.abs(v-w)<=qe,d=n.map((k,v)=>Ne(k,(w,L)=>u(w,v,L))),m=e.map((k,v)=>Ne(n.map(w=>w[v]),(w,L)=>u(w,L,v))),p=(k,v,w)=>k.score>=_n&&je(t[v],e[w])&&Math.abs(v-w)<=qe,a=n.map((k,v)=>Ne(k,(w,L)=>p(w,v,L))),x=e.map((k,v)=>Ne(n.map(w=>w[v]),(w,L)=>p(w,L,v))),E=(k,v)=>{let w=n[k][v];if(!u(w,k,v))return!1;let L=d[k],$=m[v];return w.score===L.best&&w.score===$.best&&L.best-L.second>=Ce&&$.best-$.second>=Ce},C=(k,v)=>{let w=n[k][v];if(!p(w,k,v))return!1;let L=a[k],$=x[v];return w.score===L.best&&w.score===$.best&&L.best-L.second>=Ce&&$.best-$.second>=Ce};return c.map((k,v)=>k.map((w,L)=>{if(w!==null)return w;let $=E(v,L)&&(Un(c,v,L)||Bn(n,v,L,E)),A=Hn(n,v,L,(P,D)=>p(n[P][D],P,D),C);return!$&&!A?null:n[v][L].score}))}function Un(t,e,n){return e>0&&n>0&&t[e-1][n-1]!==null||e+1<t.length&&n+1<t[e+1].length&&t[e+1][n+1]!==null}function Bn(t,e,n,r){return e>0&&n>0&&r(e-1,n-1)||e+1<t.length&&n+1<t[e+1].length&&r(e+1,n+1)}function Hn(t,e,n,r,o){let s=e,c=n;for(;s>0&&c>0&&r(s-1,c-1);)s--,c--;let u=e,d=n,m=t[e][n].score,p=1;for(;u+1<t.length&&d+1<t[u+1].length&&r(u+1,d+1);)u++,d++,m+=t[u][d].score,p++;for(let a=e-1,x=n-1;a>=s&&x>=c;a--,x--)m+=t[a][x].score,p++;return p>=3&&m/p>=Pt&&o(s,c)&&o(u,d)}function Ne(t,e){let n=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY;return t.forEach((o,s)=>{e(o,s)&&(o.score>n?(r=n,n=o.score):o.score>r&&(r=o.score))}),{best:n,second:r}}function Ke(t){let e=Number.NEGATIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let r of t)r.eligible&&(r.score>e?(n=e,e=r.score):r.score>n&&(n=r.score));return{best:e,second:n}}function Wn(t,e){let n=Gn(t,e),r=[],o=0,s=0;for(let c of n)Mt(r,t.slice(o,c.leftIndex),e.slice(s,c.rightIndex)),r.push({left:t[c.leftIndex],right:e[c.rightIndex]}),o=c.leftIndex+1,s=c.rightIndex+1;return Mt(r,t.slice(o),e.slice(s)),r}function Gn(t,e){let n=zn(t,e);if(n===null)return[];let r=Bt(t,e),o=n.map(({leftIndex:m,rightIndex:p,exact:a})=>({leftIndex:m,rightIndex:p,exact:a,structural:r.has(`${m}:${p}`),match:Je(t[m],e[p])})).filter(m=>m.exact||m.structural||m.match.eligible),s=Rt(o,"leftIndex"),c=Rt(o,"rightIndex"),u=o.filter(m=>{if(m.exact||m.structural)return!0;let p=s.get(m.leftIndex),a=c.get(m.rightIndex);if(!p||!a||m.match.score!==p.best||m.match.score!==a.best)return!1;let x=m.match.score>=Dt?Ae/2:Ae;return p.best-p.second>=x&&a.best-a.second>=x}),d=qn(u,e.length);return d.length<=On?d:[]}function zn(t,e){let n=$t(t,te),r=$t(e,te),o=new Map;for(let[u,d]of n){let m=r.get(u);if(!me(u)||d.length!==1||m?.length!==1)continue;let p=d[0],a=m[0];if(o.set(`${p}:${a}`,{leftIndex:p,rightIndex:a,exact:!0}),o.size>Lt)return null}let s=At(t),c=At(e);for(let[u,d]of s){let m=c.get(u);if(!(!m||d.length>Nt||m.length>Nt))for(let p of d)for(let a of m){let x=`${p}:${a}`;if(!o.has(x)&&(o.set(x,{leftIndex:p,rightIndex:a,exact:!1}),o.size>Lt))return null}}return[...o.values()]}function $t(t,e){let n=new Map;return t.forEach((r,o)=>{let s=e(r),c=n.get(s)??[];c.push(o),n.set(s,c)}),n}function At(t){let e=new Map;return t.forEach((n,r)=>{let o=new Set(Ye(te(n)).filter(Vn));for(let s of o){let c=e.get(s)??[];c.push(r),e.set(s,c)}}),e}function Vn(t){return t.length>=2&&/[\p{L}\p{N}_$]/u.test(t)}function Rt(t,e){let n=new Map;for(let r of t){let o=n.get(r[e])??[];o.push(r.match),n.set(r[e],o)}return new Map([...n].map(([r,o])=>[r,Ke(o)]))}function qn(t,e){let n=[...t].sort((m,p)=>m.leftIndex-p.leftIndex||m.rightIndex-p.rightIndex),r=new Array(e+2).fill(0),o=new Array(e+2).fill(-1),s=new Array(n.length).fill(0),c=new Array(n.length).fill(-1);for(let m=0;m<n.length;){let p=m+1;for(;p<n.length&&n[p].leftIndex===n[m].leftIndex;)p++;for(let a=m;a<p;a++){let x=Ft(r,o,n[a].rightIndex),E=n[a].exact||n[a].structural?.5:0;s[a]=x.score+n[a].match.score+E,c[a]=x.candidateIndex}for(let a=m;a<p;a++)Kn(r,o,n[a].rightIndex+1,s[a],a);m=p}let u=Ft(r,o,e+1),d=[];for(let m=u.candidateIndex;m>=0;m=c[m])d.push({leftIndex:n[m].leftIndex,rightIndex:n[m].rightIndex});return d.reverse()}function Ft(t,e,n){let r=0,o=-1;for(let s=n;s>0;s-=s&-s)t[s]>r&&(r=t[s],o=e[s]);return{score:r,candidateIndex:o}}function Kn(t,e,n,r,o){for(let s=n;s<t.length;s+=s&-s)r>t[s]&&(t[s]=r,e[s]=o)}function Mt(t,e,n){if(e.length*n.length<=Ot){t.push(...Ut(e,n));return}t.push(...e.map(r=>({left:r}))),t.push(...n.map(r=>({right:r})))}function te(t){return t.trim().replace(/\s+/g," ")}function Bt(t,e){let n=_t(t),r=_t(e),o=new Set;for(let[s,c]of n){let u=r.get(s);c.length===1&&u?.length===1&&o.add(`${c[0]}:${u[0]}`)}return o}function _t(t){let e=new Map;return t.forEach((n,r)=>{let o=Xe(n);if(!o)return;let s=e.get(o)??[];s.push(r),e.set(o,s)}),e}function je(t,e){let n=Xe(t),r=Xe(e);return!n||!r?n===r:n.split(":",1)[0]===r.split(":",1)[0]}function Xe(t){let e=te(t),n=[["function",/^(?:(?:export|default)\s+)*(?:async\s+)?function\s*\*?\s*([\p{L}_$][\p{L}\p{N}_$]*)\s*\(/u],["function",/^(?:async\s+)?def\s+([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["function",/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([\p{L}_][\p{L}\p{N}_]*)\s*(?:<[^>]*>)?\s*\(/u],["function",/^func\s+(?:\([^)]*\)\s*)?([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["class",/^(?:(?:export|default|abstract|public)\s+)*class\s+([\p{L}_$][\p{L}\p{N}_$]*)\b/u]];for(let[r,o]of n){let s=e.match(o);if(s)return`${r}:${s[1]}`}return null}function me(t){return t.length<3?!1:/[\p{L}\p{N}_$]/u.test(t)&&!/^[\s()[\]{};,.:+\-*/=>|&!?'"`]+$/.test(t)}function Ye(t){return t.toLowerCase().match(/[\p{L}_$][\p{L}\p{N}_$]*|\p{N}+(?:\.\p{N}+)?|[^\s\p{L}\p{N}_$]/gu)??[]}function jn(t,e){if(t.length+e.length===0)return 1;let n=new Map;t.forEach(o=>n.set(o,(n.get(o)??0)+1));let r=0;for(let o of e){let s=n.get(o)??0;s>0&&(r++,n.set(o,s-1))}return 2*r/(t.length+e.length)}function Xn(t,e){if(t.length===0||e.length===0)return 0;let n=t[0]===e[0]?.5:0,r=t[t.length-1]===e[e.length-1]?.5:0;return n+r}function Yn(t,e){let n=t.length+e.length;return n===0?1:2*xt(t,e).filter(o=>!o.added&&!o.removed).reduce((o,s)=>o+s.value.length,0)/n}function Jn(t,e){if(t.content.length>Et||e.content.length>Et)return;let{leftSegments:n,rightSegments:r,hasInlineChanges:o}=Zn(t.content,e.content);o&&(t.segments=n,e.segments=r)}function Zn(t,e){let n=St(t,e),r=[],o=[],s=!1;for(let c of n){let u=c.value;if(!c.added&&!c.removed){let m={kind:"context",text:u,emphasis:!1};r.push(m),o.push(m);continue}let d=/[^\s]/.test(u);s=s||d,c.removed&&r.push({kind:"removed",text:u,emphasis:d}),c.added&&o.push({kind:"added",text:u,emphasis:d})}return{leftSegments:r,rightSegments:o,hasInlineChanges:s}}function le(){return{kind:"placeholder",content:"",lineNumber:null}}function Q(t,e,n){return{kind:t,content:e,lineNumber:n}}function ee(t,e,n){return{kind:t,content:e,lineNumber:n}}function ce(t,e){return{left:t,right:e}}function $e(t,e,n,r,o){return{kind:t,leftStart:e,leftEnd:n,rightStart:r,rightEnd:o}}function Ht(t,e){let n=typeof process<"u"?process.env?.[t]:void 0,r=Number.parseInt(n??"",10);return Number.isFinite(r)&&r>0?r:e}function Wt(){return{leftFileName:"test-file-1.js",rightFileName:"test-file-2.js",leftContent:`// Test File 1 - Example JavaScript Code
|
|
4
|
+
`);return t[t.length-1]===""&&t.pop(),t}function ir(e,t,n,i,o,a,l,d){let p=Yt(e,t),m=p.filter(k=>k.left!==void 0&&k.right!==void 0&&nt(k.left,k.right)).length,f=sr(e,t,m),s=p.flatMap(k=>k.left===void 0||k.right===void 0||nt(k.left,k.right)?[k]:[{left:k.left},{right:k.right}]),x=n,T=i,A,I=a.length,y=l.length,E=()=>{A&&d.push(Oe(A,I,a.length,y,l.length))};for(let{left:k,right:N}of s){let L=f||k!==void 0&&N!==void 0?"replace":k!==void 0?"delete":"insert";A!==L&&(E(),A=L,I=a.length,y=l.length);let F,U;k!==void 0&&(F=X("removed",k,x),a.push(F)),N!==void 0&&(U=X("added",N,T),l.push(U)),F&&U?Cr(F,U):f&&(F&&Vt(F),U&&Vt(U)),o.push(se(k===void 0?ue():Z("removed",k,x++),N===void 0?ue():Z("added",N,T++)))}return E(),{left:x,right:T}}function nt(e,t){if(De(e,t).eligible)return!0;let i=pe(e);if(i&&i===pe(t))return!0;let o=new Set(we(Y(e)).filter(Dt));return we(Y(t)).some(a=>o.has(a)&&Dt(a))}var or=new Set(["and","are","for","from","into","that","the","this","to","with"]);function Dt(e){return e.length>=3&&/^[\p{L}\p{N}_$]+$/u.test(e)&&!or.has(e)}function sr(e,t,n){if(n===0)return!1;let i=Math.max(e.length,t.length);if(i<=2||n*2>=i)return!0;let o=[...e,...t].map(ar);return o[0]!==null&&o.every(a=>a===o[0])}function ar(e){let t=e.trimStart();return/^[-*+]\s+/.test(t)?"bullet":/^\d+[.)]\s+/.test(t)?"ordered":/^>\s+/.test(t)?"quote":null}var Kt=1e4,Pt=2e3,cr=.52,ur=.35,Zt=.38,lr=.33,Xt=.86,_e=.08,Re=.05,Me=-.12,Ut=5e3,dr=2e3,fr=5e7,Bt=4,hr=8,tt=4;function Yt(e,t){if(e.length===0)return t.map(f=>({right:f}));if(t.length===0)return e.map(f=>({left:f}));let n=e.reduce((f,s)=>f+s.length,0),i=t.reduce((f,s)=>f+s.length,0);if(n*i>fr)return[...e.map(f=>({left:f})),...t.map(f=>({right:f}))];if(e.length===1&&t.length===1){let f=De(e[0],t[0]);return(f.eligible||f.score>=ur)&&nt(e[0],t[0])&&it(e[0],t[0])&&be(Y(e[0]))&&be(Y(t[0]))?[{left:e[0],right:t[0]}]:[{left:e[0]},{right:t[0]}]}if(e.length*t.length>Kt)return wr(e,t);let o=gr(e,t),a=Array.from({length:e.length+1},()=>new Array(t.length+1).fill(Number.NEGATIVE_INFINITY)),l=Array.from({length:e.length+1},()=>new Array(t.length+1).fill(null));a[0][0]=0;for(let f=1;f<=e.length;f++)a[f][0]=a[f-1][0]+Me,l[f][0]="left";for(let f=1;f<=t.length;f++)a[0][f]=a[0][f-1]+Me,l[0][f]="right";for(let f=1;f<=e.length;f++)for(let s=1;s<=t.length;s++){let x=o[f-1][s-1],A=[{move:"left",score:a[f-1][s]+Me},{move:"right",score:a[f][s-1]+Me},{move:"match",score:x===null?Number.NEGATIVE_INFINITY:a[f-1][s-1]+x}].reduce((I,y)=>y.score>I.score?y:I);a[f][s]=A.score,l[f][s]=A.move}let d=[],p=e.length,m=t.length;for(;p>0||m>0;){let f=l[p][m];f==="match"?d.push({left:e[--p],right:t[--m]}):f==="left"?d.push({left:e[--p]}):d.push({right:t[--m]})}return d.reverse()}function De(e,t){let n=Y(e),i=Y(t),o=be(n),a=be(i);if(!o||!a||n.length>Pt||i.length>Pt)return{score:0,eligible:!1,characterSimilarity:0,tokenSimilarity:0,lengthSimilarity:0};if(n===i)return{score:1,eligible:!0,characterSimilarity:1,tokenSimilarity:1,lengthSimilarity:1};let l=we(n),d=we(i),p=Tr(n,i),m=Er(l,d),f=Math.min(n.length,i.length)/Math.max(n.length,i.length),s=kr(l,d),x=p*.52+m*.32+f*.1+s*.06,T=p>=.52||m>=.45||p>=.48&&m>=.28;return{score:x,eligible:T&&x>=cr,characterSimilarity:p,tokenSimilarity:m,lengthSimilarity:f}}function gr(e,t){let n=e.map(I=>t.map(y=>De(I,y))),i=Jt(e,t),o=n.map(I=>rt(I)),a=t.map((I,y)=>rt(n.map(E=>E[y]))),l=n.map((I,y)=>I.map((E,k)=>{if(i.has(`${y}:${k}`))return Math.max(E.score,1);if(!E.eligible)return null;let N=o[y],L=a[k],F=E.score===N.best&&E.score===L.best,U=E.score>=Xt?_e/2:_e,J=N.best-N.second>=U,ne=L.best-L.second>=U;return F&&J&&ne?E.score:null}));if(Math.max(e.length,t.length)>hr||Math.abs(e.length-t.length)>tt)return l;let d=(I,y,E)=>I.score>=Zt&&it(e[y],t[E])&&Math.abs(y-E)<=tt,p=n.map((I,y)=>Fe(I,(E,k)=>d(E,y,k))),m=t.map((I,y)=>Fe(n.map(E=>E[y]),(E,k)=>d(E,k,y))),f=(I,y,E)=>I.score>=lr&&it(e[y],t[E])&&Math.abs(y-E)<=tt,s=n.map((I,y)=>Fe(I,(E,k)=>f(E,y,k))),x=t.map((I,y)=>Fe(n.map(E=>E[y]),(E,k)=>f(E,k,y))),T=(I,y)=>{let E=n[I][y];if(!d(E,I,y))return!1;let k=p[I],N=m[y];return E.score===k.best&&E.score===N.best&&k.best-k.second>=Re&&N.best-N.second>=Re},A=(I,y)=>{let E=n[I][y];if(!f(E,I,y))return!1;let k=s[I],N=x[y];return E.score===k.best&&E.score===N.best&&k.best-k.second>=Re&&N.best-N.second>=Re};return l.map((I,y)=>I.map((E,k)=>{if(E!==null)return E;let N=T(y,k)&&(mr(l,y,k)||pr(n,y,k,T)),L=br(n,y,k,(F,U)=>f(n[F][U],F,U),A);return!N&&!L?null:n[y][k].score}))}function mr(e,t,n){return t>0&&n>0&&e[t-1][n-1]!==null||t+1<e.length&&n+1<e[t+1].length&&e[t+1][n+1]!==null}function pr(e,t,n,i){return t>0&&n>0&&i(t-1,n-1)||t+1<e.length&&n+1<e[t+1].length&&i(t+1,n+1)}function br(e,t,n,i,o){let a=t,l=n;for(;a>0&&l>0&&i(a-1,l-1);)a--,l--;let d=t,p=n,m=e[t][n].score,f=1;for(;d+1<e.length&&p+1<e[d+1].length&&i(d+1,p+1);)d++,p++,m+=e[d][p].score,f++;for(let s=t-1,x=n-1;s>=a&&x>=l;s--,x--)m+=e[s][x].score,f++;return f>=3&&m/f>=Zt&&o(a,l)&&o(d,p)}function Fe(e,t){let n=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return e.forEach((o,a)=>{t(o,a)&&(o.score>n?(i=n,n=o.score):o.score>i&&(i=o.score))}),{best:n,second:i}}function rt(e){let t=Number.NEGATIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let i of e)i.eligible&&(i.score>t?(n=t,t=i.score):i.score>n&&(n=i.score));return{best:t,second:n}}function wr(e,t){let n=yr(e,t),i=[],o=0,a=0;for(let l of n)qt(i,e.slice(o,l.leftIndex),t.slice(a,l.rightIndex)),i.push({left:e[l.leftIndex],right:t[l.rightIndex]}),o=l.leftIndex+1,a=l.rightIndex+1;return qt(i,e.slice(o),t.slice(a)),i}function yr(e,t){let n=xr(e,t);if(n===null)return[];let i=Jt(e,t),o=n.map(({leftIndex:m,rightIndex:f,exact:s})=>({leftIndex:m,rightIndex:f,exact:s,structural:i.has(`${m}:${f}`),match:De(e[m],t[f])})).filter(m=>m.exact||m.structural||m.match.eligible),a=Wt(o,"leftIndex"),l=Wt(o,"rightIndex"),d=o.filter(m=>{if(m.exact||m.structural)return!0;let f=a.get(m.leftIndex),s=l.get(m.rightIndex);if(!f||!s||m.match.score!==f.best||m.match.score!==s.best)return!1;let x=m.match.score>=Xt?_e/2:_e;return f.best-f.second>=x&&s.best-s.second>=x}),p=Ir(d,t.length);return p.length<=dr?p:[]}function xr(e,t){let n=Ht(e,Y),i=Ht(t,Y),o=new Map;for(let[d,p]of n){let m=i.get(d);if(!be(d)||p.length!==1||m?.length!==1)continue;let f=p[0],s=m[0];if(o.set(`${f}:${s}`,{leftIndex:f,rightIndex:s,exact:!0}),o.size>Ut)return null}let a=zt(e),l=zt(t);for(let[d,p]of a){let m=l.get(d);if(!(!m||p.length>Bt||m.length>Bt))for(let f of p)for(let s of m){let x=`${f}:${s}`;if(!o.has(x)&&(o.set(x,{leftIndex:f,rightIndex:s,exact:!1}),o.size>Ut))return null}}return[...o.values()]}function Ht(e,t){let n=new Map;return e.forEach((i,o)=>{let a=t(i),l=n.get(a)??[];l.push(o),n.set(a,l)}),n}function zt(e){let t=new Map;return e.forEach((n,i)=>{let o=new Set(we(Y(n)).filter(Sr));for(let a of o){let l=t.get(a)??[];l.push(i),t.set(a,l)}}),t}function Sr(e){return e.length>=2&&/[\p{L}\p{N}_$]/u.test(e)}function Wt(e,t){let n=new Map;for(let i of e){let o=n.get(i[t])??[];o.push(i.match),n.set(i[t],o)}return new Map([...n].map(([i,o])=>[i,rt(o)]))}function Ir(e,t){let n=[...e].sort((m,f)=>m.leftIndex-f.leftIndex||m.rightIndex-f.rightIndex),i=new Array(t+2).fill(0),o=new Array(t+2).fill(-1),a=new Array(n.length).fill(0),l=new Array(n.length).fill(-1);for(let m=0;m<n.length;){let f=m+1;for(;f<n.length&&n[f].leftIndex===n[m].leftIndex;)f++;for(let s=m;s<f;s++){let x=Gt(i,o,n[s].rightIndex),T=n[s].exact||n[s].structural?.5:0;a[s]=x.score+n[s].match.score+T,l[s]=x.candidateIndex}for(let s=m;s<f;s++)vr(i,o,n[s].rightIndex+1,a[s],s);m=f}let d=Gt(i,o,t+1),p=[];for(let m=d.candidateIndex;m>=0;m=l[m])p.push({leftIndex:n[m].leftIndex,rightIndex:n[m].rightIndex});return p.reverse()}function Gt(e,t,n){let i=0,o=-1;for(let a=n;a>0;a-=a&-a)e[a]>i&&(i=e[a],o=t[a]);return{score:i,candidateIndex:o}}function vr(e,t,n,i,o){for(let a=n;a<e.length;a+=a&-a)i>e[a]&&(e[a]=i,t[a]=o)}function qt(e,t,n){if(t.length*n.length<=Kt){e.push(...Yt(t,n));return}e.push(...t.map(i=>({left:i}))),e.push(...n.map(i=>({right:i})))}function Y(e){return e.trim().replace(/\s+/g," ")}function Jt(e,t){let n=jt(e),i=jt(t),o=new Set;for(let[a,l]of n){let d=i.get(a);l.length===1&&d?.length===1&&o.add(`${l[0]}:${d[0]}`)}return o}function jt(e){let t=new Map;return e.forEach((n,i)=>{let o=pe(n);if(!o)return;let a=t.get(o)??[];a.push(i),t.set(o,a)}),t}function it(e,t){let n=pe(e),i=pe(t);return!n||!i?n===i:n.split(":",1)[0]===i.split(":",1)[0]}function pe(e){let t=Y(e),n=[["function",/^(?:(?:export|default)\s+)*(?:async\s+)?function\s*\*?\s*([\p{L}_$][\p{L}\p{N}_$]*)\s*\(/u],["function",/^(?:async\s+)?def\s+([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["function",/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([\p{L}_][\p{L}\p{N}_]*)\s*(?:<[^>]*>)?\s*\(/u],["function",/^func\s+(?:\([^)]*\)\s*)?([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["class",/^(?:(?:export|default|abstract|public)\s+)*class\s+([\p{L}_$][\p{L}\p{N}_$]*)\b/u]];for(let[i,o]of n){let a=t.match(o);if(a)return`${i}:${a[1]}`}return null}function be(e){return e.length<3?!1:/[\p{L}\p{N}_$]/u.test(e)&&!/^[\s()[\]{};,.:+\-*/=>|&!?'"`]+$/.test(e)}function we(e){return e.toLowerCase().match(/[\p{L}_$][\p{L}\p{N}_$]*|\p{N}+(?:\.\p{N}+)?|[^\s\p{L}\p{N}_$]/gu)??[]}function Er(e,t){if(e.length+t.length===0)return 1;let n=new Map;e.forEach(o=>n.set(o,(n.get(o)??0)+1));let i=0;for(let o of t){let a=n.get(o)??0;a>0&&(i++,n.set(o,a-1))}return 2*i/(e.length+t.length)}function kr(e,t){if(e.length===0||t.length===0)return 0;let n=e[0]===t[0]?.5:0,i=e[e.length-1]===t[t.length-1]?.5:0;return n+i}function Tr(e,t){let n=e.length+t.length;return n===0?1:2*At(e,t).filter(o=>!o.added&&!o.removed).reduce((o,a)=>o+a.value.length,0)/n}function Cr(e,t){if(e.content.length>_t||t.content.length>_t)return;let{leftSegments:n,rightSegments:i,hasInlineChanges:o}=$r(e.content,t.content);o&&(e.segments=n,t.segments=i)}function Vt(e){/[^\s]/.test(e.content)&&(e.segments=[{kind:e.kind,text:e.content,emphasis:!0}])}function $r(e,t){let n=Rt(e,t),i=[],o=[],a=!1;for(let l of n){let d=l.value;if(!l.added&&!l.removed){let m={kind:"context",text:d,emphasis:!1};i.push(m),o.push(m);continue}let p=/[^\s]/.test(d);a=a||p,l.removed&&i.push({kind:"removed",text:d,emphasis:p}),l.added&&o.push({kind:"added",text:d,emphasis:p})}return{leftSegments:i,rightSegments:o,hasInlineChanges:a}}function ue(){return{kind:"placeholder",content:"",lineNumber:null}}function Z(e,t,n){return{kind:e,content:t,lineNumber:n}}function X(e,t,n){return{kind:e,content:t,lineNumber:n}}function se(e,t){return{left:e,right:t}}function Oe(e,t,n,i,o){return{kind:e,leftStart:t,leftEnd:n,rightStart:i,rightEnd:o}}function Qt(e,t){let n=typeof process<"u"?process.env?.[e]:void 0,i=Number.parseInt(n??"",10);return Number.isFinite(i)&&i>0?i:t}function en(){return{leftFileName:"test-file-1.js",rightFileName:"test-file-2.js",leftContent:`// Test File 1 - Example JavaScript Code
|
|
5
5
|
const fs = require('fs');
|
|
6
6
|
const path = require('path');
|
|
7
7
|
|
|
@@ -145,7 +145,7 @@ if (require.main === module) {
|
|
|
145
145
|
}
|
|
146
146
|
|
|
147
147
|
module.exports = FileProcessor;
|
|
148
|
-
`}}function Gt(t){if(!_(t)||t.version!==1)throw new Error("Unsupported or missing change-tour manifest version.");if(N(t.title,"title"),N(t.generatedAt,"generatedAt"),t.windowTitle!==void 0&&N(t.windowTitle,"windowTitle"),t.sourceUrl!==void 0&&N(t.sourceUrl,"sourceUrl"),!_(t.range))throw new Error("Change-tour manifest range must be an object.");for(let r of["baseRef","headRef","mergeBaseOid","headOid"])N(t.range[r],`range.${r}`);if(!_(t.summary))throw new Error("Change-tour manifest summary must be an object.");for(let r of["changedFiles","includedScenes","additions","deletions","commitCount"])J(t.summary[r],`summary.${r}`);if(pe(t.summary.omittedFiles,"summary.omittedFiles"),!Array.isArray(t.commits)||!Array.isArray(t.chapters)||!Array.isArray(t.scenes))throw new Error("Change-tour manifest commits, chapters, and scenes must be arrays.");if(t.files!==void 0&&!Array.isArray(t.files))throw new Error("Change-tour manifest files must be an array.");let e=new Set;for(let[r,o]of t.scenes.entries()){if(Qe(o,r),e.has(o.id))throw new Error(`Duplicate change-tour scene id: ${o.id}`);e.add(o.id)}for(let[r,o]of t.chapters.entries()){if(!_(o))throw new Error(`chapters[${r}] must be an object.`);N(o.id,`chapters[${r}].id`),N(o.title,`chapters[${r}].title`),pe(o.sceneIds,`chapters[${r}].sceneIds`);for(let s of o.sceneIds)if(!e.has(s))throw new Error(`Chapter references unknown scene id: ${s}`)}if(t.summary.includedScenes!==t.scenes.length)throw new Error("summary.includedScenes must match the number of scenes.");let n=t.files===void 0?nr(t.scenes):t.files.map((r,o)=>(tr(r,o),r));if(t.files!==void 0&&t.summary.changedFiles!==n.length)throw new Error("summary.changedFiles must match the number of files.");return{...t,files:n}}function Qe(t,e){if(!_(t)||!["text-diff","discussion","walkthrough","stacked-diff","deconstructed-diff"].includes(String(t.kind)))throw new Error(`scenes[${e}] must be a text-diff, discussion, walkthrough, stacked-diff, or deconstructed-diff scene.`);for(let n of["id","title"])N(t[n],`scenes[${e}].${n}`);if(rr(t,`scenes[${e}]`),t.kind!=="discussion"){if(t.kind==="walkthrough"){if(!Array.isArray(t.steps)||t.steps.length===0)throw new Error(`scenes[${e}].steps must be a non-empty array.`);for(let[n,r]of t.steps.entries()){let o=`scenes[${e}].steps[${n}]`;if(!_(r)||!_(r.focus)||!_(r.diff))throw new Error(`${o} must contain focus and diff objects.`);for(let s of["id","title","body"])N(r[s],`${o}.${s}`);if(r.depth!==void 0&&!["mentioned","explained","contextualized"].includes(String(r.depth)))throw new Error(`${o}.depth must be mentioned, explained, or contextualized.`);if(Ze(r.focus,`${o}.focus`),Qe(r.diff,e),r.diff.kind!=="text-diff")throw new Error(`${o}.diff must be a text-diff scene.`);if(r.connection!==void 0){if(!_(r.connection))throw new Error(`${o}.connection must be an object.`);N(r.connection.id,`${o}.connection.id`),N(r.connection.label,`${o}.connection.label`),Ze(r.connection.from,`${o}.connection.from`),Ze(r.connection.to,`${o}.connection.to`)}}return}if(t.kind==="stacked-diff"){Qn(t,e);return}if(t.kind==="deconstructed-diff"){er(t,e);return}for(let n of["path","leftLabel","rightLabel","leftContent","rightContent"])N(t[n],`scenes[${e}].${n}`);t.previousPath!==void 0&&N(t.previousPath,`scenes[${e}].previousPath`),N(t.changeKind,`scenes[${e}].changeKind`),J(t.additions,`scenes[${e}].additions`),J(t.deletions,`scenes[${e}].deletions`),t.focusChangeIndex!==void 0&&J(t.focusChangeIndex,`scenes[${e}].focusChangeIndex`)}}function Qn(t,e){if(!Array.isArray(t.stack)||t.stack.length<3||t.stack.length>6)throw new Error(`scenes[${e}].stack must contain between 3 and 6 revisions.`);for(let[n,r]of t.stack.entries()){if(!_(r))throw new Error(`scenes[${e}].stack[${n}] must be an object.`);for(let o of["id","ref","oid","label"])N(r[o],`scenes[${e}].stack[${n}].${o}`)}zt(t.files,t.stack.length,e),Vt(t.steps,t.stack.length,e,!1)}function er(t,e){if(t.stageLabel!=="Explanation stages")throw new Error(`scenes[${e}].stageLabel must be Explanation stages.`);if(!_(t.realRange))throw new Error(`scenes[${e}].realRange must be an object.`);for(let r of["baseRef","targetRef","baseOid","targetOid"])N(t.realRange[r],`scenes[${e}].realRange.${r}`);if(!Array.isArray(t.panels)||t.panels.length<2||t.panels.length>13)throw new Error(`scenes[${e}].panels must contain a baseline and between 1 and 12 stages.`);let n=t.panels;for(let[r,o]of n.entries()){if(!_(o))throw new Error(`scenes[${e}].panels[${r}] must be an object.`);for(let c of["id","label","role"])N(o[c],`scenes[${e}].panels[${r}].${c}`);let s=r===0?"baseline":"stage";if(o.role!==s)throw new Error(`scenes[${e}].panels[${r}].role must be ${s}.`);r>0&&N(o.stageId,`scenes[${e}].panels[${r}].stageId`)}if(zt(t.files,n.length,e),Vt(t.steps,n.length,e,!0),Array.isArray(t.steps)){let r=-1;t.steps.forEach((o,s)=>{if(!_(o))return;let c=Number(o.pairIndex);if(c<r)throw new Error(`scenes[${e}].steps must remain grouped in explanation stage order.`);if(r=c,o.stageId!==void 0&&N(o.stageId,`scenes[${e}].steps[${s}].stageId`),o.stageIndex!==void 0&&J(o.stageIndex,`scenes[${e}].steps[${s}].stageIndex`),o.focusIndex!==void 0&&J(o.focusIndex,`scenes[${e}].steps[${s}].focusIndex`),o.focusCount!==void 0&&be(o.focusCount,`scenes[${e}].steps[${s}].focusCount`),o.stageIndex!==void 0&&Number(o.stageIndex)!==c)throw new Error(`scenes[${e}].steps[${s}].stageIndex must match pairIndex.`);if(o.focusIndex!==void 0&&o.focusCount!==void 0&&Number(o.focusIndex)>=Number(o.focusCount))throw new Error(`scenes[${e}].steps[${s}].focusIndex must be less than focusCount.`)});for(let o=0;o<n.length-1;o+=1){let s=n[o+1],c=t.steps.filter(m=>_(m)&&Number(m.pairIndex)===o);if(!_(s)||c.length===0)throw new Error(`scenes[${e}].steps must cover every explanation stage.`);let u=c[0],d=_(u)?u.id:void 0;if(c.some(m=>_(m)?(m.stageId??d)!==s.stageId:!0))throw new Error(`scenes[${e}].panels must align with explanation stage ids.`)}}}function zt(t,e,n){if(!Array.isArray(t)||t.length===0)throw new Error(`scenes[${n}].files must be non-empty.`);for(let[r,o]of t.entries()){if(!_(o))throw new Error(`scenes[${n}].files[${r}] must be an object.`);if(N(o.path,`scenes[${n}].files[${r}].path`),!Array.isArray(o.panels)||o.panels.length!==e)throw new Error(`scenes[${n}].files[${r}].panels must match panel count.`);for(let[s,c]of o.panels.entries()){if(!_(c))throw new Error(`scenes[${n}].files[${r}].panels[${s}] must be an object.`);for(let u of["id","label","content"])N(c[u],`scenes[${n}].files[${r}].panels[${s}].${u}`);if(c.path!==void 0&&N(c.path,`scenes[${n}].files[${r}].panels[${s}].path`),typeof c.exists!="boolean")throw new Error(`scenes[${n}].files[${r}].panels[${s}].exists must be boolean.`)}}}function Vt(t,e,n,r){if(!Array.isArray(t)||t.length===0)throw new Error(`scenes[${n}].steps must be non-empty.`);for(let[o,s]of t.entries()){if(!_(s))throw new Error(`scenes[${n}].steps[${o}] must be an object.`);for(let c of["id","title","body","file","side"])N(s[c],`scenes[${n}].steps[${o}].${c}`);if(J(s.pairIndex,`scenes[${n}].steps[${o}].pairIndex`),Number(s.pairIndex)>=e-1)throw new Error(`scenes[${n}].steps[${o}].pairIndex is outside the panels.`);if(r&&(pe(s.introducedHunks,`scenes[${n}].steps[${o}].introducedHunks`),s.introducedHunks.length===0))throw new Error(`scenes[${n}].steps[${o}].introducedHunks must be non-empty.`);if(s.side!=="left"&&s.side!=="right")throw new Error(`scenes[${n}].steps[${o}].side must be left or right.`);s.startLine!==void 0&&be(s.startLine,`scenes[${n}].steps[${o}].startLine`),s.endLine!==void 0&&be(s.endLine,`scenes[${n}].steps[${o}].endLine`)}}function tr(t,e){if(!_(t))throw new Error(`files[${e}] must be an object.`);if(t.kind==="text-diff"){Qe(t,e);return}if(t.kind!=="omitted")throw new Error(`files[${e}].kind must be text-diff or omitted.`);for(let n of["id","title","path","changeKind","reason"])N(t[n],`files[${e}].${n}`);t.previousPath!==void 0&&N(t.previousPath,`files[${e}].previousPath`),J(t.additions,`files[${e}].additions`),J(t.deletions,`files[${e}].deletions`)}function nr(t){let e=new Map;for(let n of t){if(n.kind==="text-diff"){e.has(n.path)||e.set(n.path,n);continue}if(n.kind==="walkthrough")for(let r of n.steps)e.has(r.diff.path)||e.set(r.diff.path,r.diff)}return[...e.values()].sort((n,r)=>n.path.localeCompare(r.path))}function Ze(t,e){if(!_(t))throw new Error(`${e} must be an object.`);for(let n of["id","path","revision","excerpt"])N(t[n],`${e}.${n}`);if(t.revision!=="base"&&t.revision!=="head")throw new Error(`${e}.revision must be base or head.`);if(be(t.startLine,`${e}.startLine`),be(t.endLine,`${e}.endLine`),Number(t.endLine)<Number(t.startLine))throw new Error(`${e}.endLine must not precede startLine.`)}function rr(t,e){N(t.summary,`${e}.summary`),pe(t.bullets,`${e}.bullets`),pe(t.tags,`${e}.tags`),N(t.takeaway,`${e}.takeaway`)}function _(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function N(t,e){if(typeof t!="string")throw new Error(`${e} must be a string.`)}function pe(t,e){if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw new Error(`${e} must be an array of strings.`)}function J(t,e){if(!Number.isInteger(t)||Number(t)<0)throw new Error(`${e} must be a non-negative integer.`)}function be(t,e){if(!Number.isInteger(t)||Number(t)<1)throw new Error(`${e} must be a positive integer.`)}var ir=new Set(["modified-here","created-here","deleted-here"]);function et(t,e){let n=t.panels[e],r=t.panels[e+1];return!n||!r?"unchanged-here":n.exists&&r.exists?n.content===r.content?"unchanged-here":"modified-here":!n.exists&&r.exists?"created-here":n.exists&&!r.exists?"deleted-here":t.panels.slice(0,e).some(c=>c.exists)?"already-deleted":(t.panels.slice(e+2).some(c=>c.exists),"not-created-yet")}function qt(t,e,n,r){if(r!==-1&&r!==1||!n)return null;let o=t.findIndex(u=>u.path===n);if(o<0)return null;let s=t.map((u,d)=>({file:u,fileIndex:d,state:et(u,e)})).filter(({state:u})=>ir.has(u)),c=r<0?[...s].reverse().find(({fileIndex:u})=>u<o):s.find(({fileIndex:u})=>u>o);return c?{pairIndex:e,fileIndex:c.fileIndex,path:c.file.path}:null}function Kt(t,e,n){let r=t.findIndex(u=>u.id===e),o=r>=0?r:0,s=t[o];if(!s||s.kind!=="walkthrough"&&s.kind!=="stacked-diff"&&s.kind!=="deconstructed-diff"||!n)return{sceneIndex:o,stepIndex:0};let c=s.steps.findIndex(u=>u.id===n);return{sceneIndex:o,stepIndex:c>=0?c:0}}function Re(t,e,n){let r=t[e.sceneIndex];if(!r)return null;if(n>0)return(r.kind==="walkthrough"||r.kind==="stacked-diff"||r.kind==="deconstructed-diff")&&e.stepIndex<r.steps.length-1?{sceneIndex:e.sceneIndex,stepIndex:e.stepIndex+1}:e.sceneIndex<t.length-1?{sceneIndex:e.sceneIndex+1,stepIndex:0}:null;if((r.kind==="walkthrough"||r.kind==="stacked-diff"||r.kind==="deconstructed-diff")&&e.stepIndex>0)return{sceneIndex:e.sceneIndex,stepIndex:e.stepIndex-1};if(e.sceneIndex===0)return null;let o=t[e.sceneIndex-1];return{sceneIndex:e.sceneIndex-1,stepIndex:o.kind==="walkthrough"||o.kind==="stacked-diff"||o.kind==="deconstructed-diff"?o.steps.length-1:0}}function jt(t,e,n){if(!e)return null;let r=t.map((u,d)=>({file:u,fileIndex:d})).filter(({file:u})=>u.kind==="text-diff"),o=r.findIndex(({file:u})=>u.path===e),s=o+n,c=o>=0?r[s]:null;return c?{fileIndex:c.fileIndex,path:c.file.path}:null}function Yt(t,e,n){let r=t.scenes[e.sceneIndex];if(!r)return null;let o=tt(r)?Math.min(Math.max(e.stepIndex,0),r.steps.length-1):0,s={sceneIndex:e.sceneIndex,stepIndex:o},c=tt(r)?r.steps[o]:void 0,u=[],d=!c||o===0,m=!!(c&&o>0&&n.entry==="playback-start");if(d){let E=t.chapters.find(C=>C.sceneIds.includes(r.id));E&&u.push({source:{field:"chapter"},text:E.title})}(d||m)&&u.push({source:{field:"scene-title"},text:r.title}),d&&(u.push({source:{field:"summary"},text:r.summary}),r.bullets.forEach((E,C)=>{u.push({source:{field:"bullet",itemIndex:C},text:E})})),c&&(u.push({source:{field:"step-title"},text:c.title}),u.push({source:{field:"step-body"},text:c.body}),"connection"in c&&c.connection?.label&&u.push({source:{field:"connection"},text:c.connection.label})),(!c||tt(r)&&o===r.steps.length-1)&&u.push({source:{field:"takeaway"},text:r.takeaway});let p=`${r.id}:${c?.id||"scene"}`,a=n.segmentLimit??240,x=u.flatMap(E=>ar(p,E,a));return{id:p,position:s,segments:x}}function or(t,e=240){if(!Number.isInteger(e)||e<40)throw new Error("Narration segment limit must be an integer of at least 40 characters.");return lr(t).flatMap(r=>cr(t,r.startOffset,r.endOffset,e))}function sr(t){return t.replace(/https?:\/\/\S+/giu," ").replace(/\b(?=[0-9a-f]{7,40}\b)(?=[0-9a-f]*\d)[0-9a-f]+\b/giu," ").replace(/[`*_~]/gu,"").replace(/([\p{Ll}\d])(\p{Lu})/gu,"$1 $2").replace(/([\p{Lu}])(\p{Lu}\p{Ll})/gu,"$1 $2").replace(/\s+/gu," ").trim()}function ar(t,e,n){let r=e.source.itemIndex===void 0?e.source.field:`${e.source.field}-${e.source.itemIndex}`;return or(e.text,n).map((o,s)=>({id:`${t}:${r}:${s}`,text:o.text,speechText:sr(o.text),source:e.source,startOffset:o.startOffset,endOffset:o.endOffset})).filter(o=>o.speechText.length>0)}function lr(t){let e=[],n=0;for(let r=0;r<t.length;r+=1){if(!".!?".includes(t[r]))continue;let o=r+1;for(;o<t.length&&`"'\u201D\u2019)]}`.includes(t[o]);)o+=1;o<t.length&&!/\s/u.test(t[o])||(Fe(t,e,n,o),n=o)}return Fe(t,e,n,t.length),e}function cr(t,e,n,r){let o=[],s=e;for(;n-s>r;){let c=s+r,u=s+Math.floor(r*.55),d=Xt(t,u,c,/[;,:—–-]/u);d<=s&&(d=Xt(t,u,c,/\s/u)),d<=s&&(d=c),Fe(t,o,s,d),s=d}return Fe(t,o,s,n),o}function Xt(t,e,n,r){for(let o=n;o>=e;o-=1)if(r.test(t[o]))return o+1;return-1}function Fe(t,e,n,r){let o=n,s=r;for(;o<s&&/\s/u.test(t[o]);)o+=1;for(;s>o&&/\s/u.test(t[s-1]);)s-=1;o<s&&e.push({text:t.slice(o,s),startOffset:o,endOffset:s})}function tt(t){return t.kind==="walkthrough"||t.kind==="stacked-diff"||t.kind==="deconstructed-diff"}var Me=class{constructor(e,n){this.engine=e;this.callbacks=n;this.generation=0;this.continuous=!0;this.currentState={kind:"idle"}}get state(){return this.currentState}get engaged(){return this.currentState.kind==="playing"||this.currentState.kind==="paused"}start(e,n=!0){if(this.resetEngine(),this.continuous=n,e.segments.length===0){this.finishUnit(e);return}this.callbacks.claimAudio(),this.setState({kind:"playing",unit:e,segmentIndex:0}),this.speakCurrent()}togglePause(){if(this.currentState.kind==="playing"){this.engine.pause();let n={kind:"paused",unit:this.currentState.unit,segmentIndex:this.currentState.segmentIndex,pendingStart:!1};this.setState(n),this.callbacks.onSegmentChange(n.unit.segments[n.segmentIndex]||null,!0);return}if(this.currentState.kind!=="paused")return;this.callbacks.claimAudio();let e=this.currentState;this.setState({kind:"playing",unit:e.unit,segmentIndex:e.segmentIndex}),e.pendingStart?this.speakCurrent():(this.engine.resume(),this.callbacks.onSegmentChange(e.unit.segments[e.segmentIndex]||null,!1))}stop(){this.resetEngine(),this.setState({kind:"idle"}),this.callbacks.onSegmentChange(null,!1)}pauseForExternalOwner(){this.currentState.kind==="playing"&&this.togglePause()}canSkipSegment(e){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return!1;let n=this.currentState.segmentIndex+e;return n>=0&&n<this.currentState.unit.segments.length?!0:this.callbacks.canNavigateUnit(this.currentState.unit,e)}skipSegment(e){if(!this.canSkipSegment(e))return!1;let n=this.currentState,r=n.kind==="paused",o=n.unit,s=n.segmentIndex+e;if(s<0||s>=o.segments.length){let c=this.callbacks.navigateUnit(o,e);if(!c||c.segments.length===0)return!1;o=c,s=e<0?o.segments.length-1:0}return this.resetEngine(),r?(this.setState({kind:"paused",unit:o,segmentIndex:s,pendingStart:!0}),this.callbacks.onSegmentChange(o.segments[s]||null,!0)):(this.setState({kind:"playing",unit:o,segmentIndex:s}),this.speakCurrent()),!0}followLinearNavigation(e){this.currentState.kind==="playing"?this.start(e,this.continuous):this.currentState.kind==="paused"&&this.preparePaused(e)}followDirectNavigation(e){this.engaged&&this.preparePaused(e)}interruptForExploration(){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return;let e=this.currentState;this.resetEngine(),this.setState({kind:"paused",unit:e.unit,segmentIndex:e.segmentIndex,pendingStart:!0}),this.callbacks.onSegmentChange(e.unit.segments[e.segmentIndex]||null,!0)}dispose(){this.stop()}preparePaused(e){this.resetEngine(),this.setState({kind:"paused",unit:e,segmentIndex:0,pendingStart:!0}),this.callbacks.onSegmentChange(e.segments[0]||null,!0)}speakCurrent(){if(this.currentState.kind!=="playing")return;let e=this.generation,n=this.currentState.unit.segments[this.currentState.segmentIndex];if(!n){this.finishUnit(this.currentState.unit);return}this.callbacks.onSegmentChange(n,!1),this.engine.speak(n,{onEnd:()=>{if(e!==this.generation||this.currentState.kind!=="playing")return;let r=this.currentState.segmentIndex+1;r<this.currentState.unit.segments.length?(this.setState({kind:"playing",unit:this.currentState.unit,segmentIndex:r}),this.speakCurrent()):this.finishUnit(this.currentState.unit)},onError:r=>{e===this.generation&&(this.setState({kind:"error",message:r}),this.callbacks.onSegmentChange(null,!1))}})}finishUnit(e){if(this.continuous){let n=this.callbacks.navigateUnit(e,1);if(n){if(this.generation+=1,n.segments.length===0){this.finishUnit(n);return}this.setState({kind:"playing",unit:n,segmentIndex:0}),this.speakCurrent();return}}this.setState({kind:"completed"}),this.callbacks.onSegmentChange(null,!1)}resetEngine(){this.generation+=1,this.engine.cancel()}setState(e){this.currentState=e,this.callbacks.onStateChange(e)}};function Zt(t,e,n="all",r=300){let o=e.trim().toLocaleLowerCase();if(!o||r<=0)return[];let s=[];if(n!=="code"){let c=new Map;t.chapters.forEach(u=>u.sceneIds.forEach(d=>c.set(d,u.title))),t.scenes.forEach((u,d)=>{let m=[c.get(u.id),u.title,u.summary,...u.bullets,...u.tags,u.takeaway],p=Jt(m,o);p&&s.push({kind:"narrative",sceneIndex:d,label:u.title,preview:p}),dr(u)&&u.steps.forEach((a,x)=>{let E=Jt([a.title,a.body,"connection"in a?a.connection?.label:void 0],o);E&&s.push({kind:"narrative",sceneIndex:d,stepIndex:x,label:`${u.title} \xB7 ${a.title}`,preview:E})})})}if(n!=="narrative"&&s.length<r)for(let c=0;c<t.files.length;c+=1){let u=t.files[c];if(u.kind==="text-diff"){for(let[d,m]of[[0,u.leftContent],[1,u.rightContent]])for(let p of ur(m,o))if(s.push({kind:"code",fileIndex:c,sideIndex:d,label:`${u.path} \xB7 ${d===0?"base":"head"}`,...p}),s.length>=r)return s}}return s.slice(0,r)}function Jt(t,e){return t.find(n=>n?.toLocaleLowerCase().includes(e))}function ur(t,e){let n=[];return t.replace(/\r\n/g,`
|
|
148
|
+
`}}function tn(e,t){if(e!==void 0){if(!Nr(e))throw new Error(`${t} must be an object.`);if(Ar(e,["id","text","status","source","confidence"],t),ot(e.id,`${t}.id`),ot(e.text,`${t}.text`),e.status!==void 0&&!["fulfilled","gap"].includes(String(e.status)))throw new Error(`${t}.status must be fulfilled or gap.`);if(Lr(e.source,`${t}.source`),e.confidence!==void 0&&!["high","medium","low"].includes(String(e.confidence)))throw new Error(`${t}.confidence must be high, medium, or low.`)}}function Nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ot(e,t){if(typeof e!="string"||e.length===0)throw new Error(`${t} must be a non-empty string.`)}function Lr(e,t){e!==void 0&&ot(e,t)}function Ar(e,t,n){let i=Object.keys(e).filter(o=>!t.includes(o));if(i.length>0)throw new Error(`${n} contains unknown field${i.length===1?"":"s"}: ${i.join(", ")}`)}var st=2;function rn(e){if(M(e)&&Number.isInteger(e.version)&&Number(e.version)>st)throw new Error(`This tour uses manifest format version ${e.version}, but this version of Bygone supports up to version ${st}. Upgrade Bygone to open it.`);if(!M(e)||e.version!==1&&e.version!==st)throw new Error("Unsupported or missing change-tour manifest version.");if(R(e.title,"title"),R(e.generatedAt,"generatedAt"),e.windowTitle!==void 0&&R(e.windowTitle,"windowTitle"),e.sourceUrl!==void 0&&R(e.sourceUrl,"sourceUrl"),!M(e.range))throw new Error("Change-tour manifest range must be an object.");for(let i of["baseRef","headRef","mergeBaseOid","headOid"])R(e.range[i],`range.${i}`);if(!M(e.summary))throw new Error("Change-tour manifest summary must be an object.");for(let i of["changedFiles","includedScenes","additions","deletions","commitCount"])G(e.summary[i],`summary.${i}`);if(xe(e.summary.omittedFiles,"summary.omittedFiles"),!Array.isArray(e.commits)||!Array.isArray(e.chapters)||!Array.isArray(e.scenes))throw new Error("Change-tour manifest commits, chapters, and scenes must be arrays.");if(e.files!==void 0&&!Array.isArray(e.files))throw new Error("Change-tour manifest files must be an array.");let t=new Set;for(let[i,o]of e.scenes.entries()){if(ye(o,i),t.has(o.id))throw new Error(`Duplicate change-tour scene id: ${o.id}`);t.add(o.id)}for(let[i,o]of e.chapters.entries()){if(!M(o))throw new Error(`chapters[${i}] must be an object.`);R(o.id,`chapters[${i}].id`),R(o.title,`chapters[${i}].title`),xe(o.sceneIds,`chapters[${i}].sceneIds`);for(let a of o.sceneIds)if(!t.has(a))throw new Error(`Chapter references unknown scene id: ${a}`)}if(e.summary.includedScenes!==e.scenes.length)throw new Error("summary.includedScenes must match the number of scenes.");let n=e.files===void 0?Dr(e.scenes):e.files.map((i,o)=>(Or(i,o),i));if(e.files!==void 0&&e.summary.changedFiles!==n.length)throw new Error("summary.changedFiles must match the number of files.");return e.authoringCoverage!==void 0&&Rr(e.authoringCoverage,e.version),e.version===2&&Mr(e),{...e,files:n}}function Rr(e,t){if(!M(e)||!M(e.walkthrough)||!Array.isArray(e.explanationAssignments))throw new Error("authoringCoverage must contain walkthrough and explanationAssignments.");let n=t===2?"final":"tour";if(e.walkthrough.scope!==n)throw new Error(`authoringCoverage.walkthrough.scope must be ${n}.`);if(G(e.walkthrough.coveredUnits,"authoringCoverage.walkthrough.coveredUnits"),G(e.walkthrough.includedUnits,"authoringCoverage.walkthrough.includedUnits"),nn(e.walkthrough.coveragePercent,"authoringCoverage.walkthrough.coveragePercent"),e.walkthrough.coveredUnits>e.walkthrough.includedUnits)throw new Error("authoringCoverage.walkthrough.coveredUnits must not exceed includedUnits.");for(let[i,o]of e.explanationAssignments.entries()){let a=`authoringCoverage.explanationAssignments[${i}]`;if(!M(o))throw new Error(`${a} must be an object.`);if(R(o.sceneId,`${a}.sceneId`),G(o.assignedUnits,`${a}.assignedUnits`),G(o.excludedUnits,`${a}.excludedUnits`),G(o.completeUnits,`${a}.completeUnits`),G(o.totalUnits,`${a}.totalUnits`),nn(o.assignmentPercent,`${a}.assignmentPercent`),o.assignedUnits+o.excludedUnits!==o.completeUnits||o.completeUnits>o.totalUnits)throw new Error(`${a} contains inconsistent unit counts.`)}}function Mr(e){if(!M(e.repository)||typeof e.repository.root!="string"||!e.repository.root)throw new Error("A v2 tour requires its originating repository.root.");if(!M(e.zoom)||!Array.isArray(e.zoom.revisions)||!M(e.zoom.final))throw new Error("A v2 tour requires zoom metadata and real revision evidence.");let t=e.scenes,n=e.zoom.revisions,i=new Set;for(let[m,f]of n.entries()){if(ye(f,m),f.kind!=="stacked-diff")throw new Error("zoom.revisions must contain real stacked-diff scenes.");if(i.has(f.id))throw new Error(`Duplicate zoom revision scene: ${f.id}`);i.add(f.id);let s=e.range;if(f.stack[0].oid!==s.mergeBaseOid||f.stack[f.stack.length-1].oid!==s.headOid)throw new Error(`Revision scene ${f.id} endpoints must match the final diff range.`)}for(let m of t){if(m.kind!=="deconstructed-diff"&&m.kind!=="stacked-diff")continue;let f=n.find(s=>s.id===m.id);if(!f)throw new Error(`Scene ${m.id} is missing its real revision evidence.`);if(m.kind==="deconstructed-diff"&&(f.stack[0].oid!==m.realRange.baseOid||f.stack[f.stack.length-1].oid!==m.realRange.targetOid))throw new Error(`Deconstructed scene ${m.id} real stack endpoints must match its explanation range.`)}let o=t.some(m=>m.kind==="deconstructed-diff"),a=n.some(m=>m.stack.length>2),l=o?"explanation":a?"revisions":"final",d=[...o?["explanation"]:[],...a?["revisions"]:[],"final","history"];if(e.zoom.authoredDepth!==l||JSON.stringify(e.zoom.modes)!==JSON.stringify(d))throw new Error("zoom depth and modes must match the maximum authored depth.");if(!Array.isArray(e.files))throw new Error("A v2 tour requires final endpoint file evidence.");if(!Array.isArray(e.zoom.final.scenes)||!Array.isArray(e.zoom.final.chapters))throw new Error("A v2 tour requires a non-stacked final tour.");let p=new Set;for(let[m,f]of e.zoom.final.scenes.entries()){if(ye(f,m),f.kind==="stacked-diff"||f.kind==="deconstructed-diff")throw new Error("zoom.final must contain only non-stacked scenes.");if(p.has(f.id))throw new Error(`Duplicate final tour scene: ${f.id}`);p.add(f.id)}for(let[m,f]of e.zoom.final.chapters.entries()){if(!M(f)||!Array.isArray(f.sceneIds))throw new Error(`zoom.final.chapters[${m}] must contain sceneIds.`);R(f.id,`zoom.final.chapters[${m}].id`),R(f.title,`zoom.final.chapters[${m}].title`);for(let s of f.sceneIds)if(R(s,`zoom.final.chapters[${m}].sceneIds`),!p.has(s))throw new Error(`Final tour chapter references unknown scene: ${s}`)}}function ye(e,t){if(!M(e)||!["text-diff","discussion","walkthrough","stacked-diff","deconstructed-diff"].includes(String(e.kind)))throw new Error(`scenes[${t}] must be a text-diff, discussion, walkthrough, stacked-diff, or deconstructed-diff scene.`);for(let n of["id","title"])R(e[n],`scenes[${t}].${n}`);if(Pr(e,`scenes[${t}]`),e.kind!=="discussion"){if(e.kind==="walkthrough"){if(!Array.isArray(e.steps)||e.steps.length===0)throw new Error(`scenes[${t}].steps must be a non-empty array.`);for(let[n,i]of e.steps.entries()){let o=`scenes[${t}].steps[${n}]`;if(!M(i)||!M(i.focus)||!M(i.diff))throw new Error(`${o} must contain focus and diff objects.`);for(let a of["id","title","body"])R(i[a],`${o}.${a}`);if(i.depth!==void 0&&!["mentioned","explained","contextualized"].includes(String(i.depth)))throw new Error(`${o}.depth must be mentioned, explained, or contextualized.`);if(tn(i.requirement,`${o}.requirement`),at(i.focus,`${o}.focus`),ye(i.diff,t),i.diff.kind!=="text-diff")throw new Error(`${o}.diff must be a text-diff scene.`);if(i.connection!==void 0){if(!M(i.connection))throw new Error(`${o}.connection must be an object.`);R(i.connection.id,`${o}.connection.id`),R(i.connection.label,`${o}.connection.label`),at(i.connection.from,`${o}.connection.from`),at(i.connection.to,`${o}.connection.to`)}}return}if(e.kind==="stacked-diff"){Fr(e,t);return}if(e.kind==="deconstructed-diff"){_r(e,t);return}for(let n of["path","leftLabel","rightLabel","leftContent","rightContent"])R(e[n],`scenes[${t}].${n}`);e.previousPath!==void 0&&R(e.previousPath,`scenes[${t}].previousPath`),R(e.changeKind,`scenes[${t}].changeKind`),G(e.additions,`scenes[${t}].additions`),G(e.deletions,`scenes[${t}].deletions`),e.focusChangeIndex!==void 0&&G(e.focusChangeIndex,`scenes[${t}].focusChangeIndex`)}}function Fr(e,t){if(!Array.isArray(e.stack)||e.stack.length<2||e.stack.length>6)throw new Error(`scenes[${t}].stack must contain between 2 and 6 revisions.`);for(let[n,i]of e.stack.entries()){if(!M(i))throw new Error(`scenes[${t}].stack[${n}] must be an object.`);for(let o of["id","ref","oid","label"])R(i[o],`scenes[${t}].stack[${n}].${o}`)}on(e.files,e.stack.length,t),sn(e.steps,e.stack.length,t,!1)}function _r(e,t){if(e.stageLabel!=="Explanation stages")throw new Error(`scenes[${t}].stageLabel must be Explanation stages.`);if(!M(e.realRange))throw new Error(`scenes[${t}].realRange must be an object.`);for(let i of["baseRef","targetRef","baseOid","targetOid"])R(e.realRange[i],`scenes[${t}].realRange.${i}`);if(!Array.isArray(e.panels)||e.panels.length<2||e.panels.length>13)throw new Error(`scenes[${t}].panels must contain a baseline and between 1 and 12 stages.`);let n=e.panels;for(let[i,o]of n.entries()){if(!M(o))throw new Error(`scenes[${t}].panels[${i}] must be an object.`);for(let l of["id","label","role"])R(o[l],`scenes[${t}].panels[${i}].${l}`);let a=i===0?"baseline":"stage";if(o.role!==a)throw new Error(`scenes[${t}].panels[${i}].role must be ${a}.`);i>0&&R(o.stageId,`scenes[${t}].panels[${i}].stageId`)}if(on(e.files,n.length,t),sn(e.steps,n.length,t,!0),Array.isArray(e.steps)){let i=-1;e.steps.forEach((o,a)=>{if(!M(o))return;let l=Number(o.pairIndex);if(l<i)throw new Error(`scenes[${t}].steps must remain grouped in explanation stage order.`);if(i=l,o.stageId!==void 0&&R(o.stageId,`scenes[${t}].steps[${a}].stageId`),o.stageIndex!==void 0&&G(o.stageIndex,`scenes[${t}].steps[${a}].stageIndex`),o.focusIndex!==void 0&&G(o.focusIndex,`scenes[${t}].steps[${a}].focusIndex`),o.focusCount!==void 0&&Se(o.focusCount,`scenes[${t}].steps[${a}].focusCount`),o.stageIndex!==void 0&&Number(o.stageIndex)!==l)throw new Error(`scenes[${t}].steps[${a}].stageIndex must match pairIndex.`);if(o.focusIndex!==void 0&&o.focusCount!==void 0&&Number(o.focusIndex)>=Number(o.focusCount))throw new Error(`scenes[${t}].steps[${a}].focusIndex must be less than focusCount.`)});for(let o=0;o<n.length-1;o+=1){let a=n[o+1],l=e.steps.filter(m=>M(m)&&Number(m.pairIndex)===o);if(!M(a)||l.length===0)throw new Error(`scenes[${t}].steps must cover every explanation stage.`);let d=l[0],p=M(d)?d.id:void 0;if(l.some(m=>M(m)?(m.stageId??p)!==a.stageId:!0))throw new Error(`scenes[${t}].panels must align with explanation stage ids.`)}}}function on(e,t,n){if(!Array.isArray(e)||e.length===0)throw new Error(`scenes[${n}].files must be non-empty.`);for(let[i,o]of e.entries()){if(!M(o))throw new Error(`scenes[${n}].files[${i}] must be an object.`);if(R(o.path,`scenes[${n}].files[${i}].path`),!Array.isArray(o.panels)||o.panels.length!==t)throw new Error(`scenes[${n}].files[${i}].panels must match panel count.`);for(let[a,l]of o.panels.entries()){if(!M(l))throw new Error(`scenes[${n}].files[${i}].panels[${a}] must be an object.`);for(let d of["id","label","content"])R(l[d],`scenes[${n}].files[${i}].panels[${a}].${d}`);if(l.path!==void 0&&R(l.path,`scenes[${n}].files[${i}].panels[${a}].path`),typeof l.exists!="boolean")throw new Error(`scenes[${n}].files[${i}].panels[${a}].exists must be boolean.`)}}}function sn(e,t,n,i){if(!Array.isArray(e)||e.length===0)throw new Error(`scenes[${n}].steps must be non-empty.`);for(let[o,a]of e.entries()){if(!M(a))throw new Error(`scenes[${n}].steps[${o}] must be an object.`);for(let l of["id","title","body","file","side"])R(a[l],`scenes[${n}].steps[${o}].${l}`);if(G(a.pairIndex,`scenes[${n}].steps[${o}].pairIndex`),Number(a.pairIndex)>=t-1)throw new Error(`scenes[${n}].steps[${o}].pairIndex is outside the panels.`);if(i&&(xe(a.introducedHunks,`scenes[${n}].steps[${o}].introducedHunks`),a.introducedHunks.length===0))throw new Error(`scenes[${n}].steps[${o}].introducedHunks must be non-empty.`);if(a.side!=="left"&&a.side!=="right")throw new Error(`scenes[${n}].steps[${o}].side must be left or right.`);a.startLine!==void 0&&Se(a.startLine,`scenes[${n}].steps[${o}].startLine`),a.endLine!==void 0&&Se(a.endLine,`scenes[${n}].steps[${o}].endLine`)}}function Or(e,t){if(!M(e))throw new Error(`files[${t}] must be an object.`);if(e.kind==="text-diff"){ye(e,t);return}if(e.kind!=="omitted")throw new Error(`files[${t}].kind must be text-diff or omitted.`);for(let n of["id","title","path","changeKind","reason"])R(e[n],`files[${t}].${n}`);e.previousPath!==void 0&&R(e.previousPath,`files[${t}].previousPath`),G(e.additions,`files[${t}].additions`),G(e.deletions,`files[${t}].deletions`)}function Dr(e){let t=new Map;for(let n of e){if(n.kind==="text-diff"){t.has(n.path)||t.set(n.path,n);continue}if(n.kind==="walkthrough")for(let i of n.steps)t.has(i.diff.path)||t.set(i.diff.path,i.diff)}return[...t.values()].sort((n,i)=>n.path.localeCompare(i.path))}function at(e,t){if(!M(e))throw new Error(`${t} must be an object.`);for(let n of["id","path","revision","excerpt"])R(e[n],`${t}.${n}`);if(e.revision!=="base"&&e.revision!=="head")throw new Error(`${t}.revision must be base or head.`);if(Se(e.startLine,`${t}.startLine`),Se(e.endLine,`${t}.endLine`),Number(e.endLine)<Number(e.startLine))throw new Error(`${t}.endLine must not precede startLine.`)}function Pr(e,t){R(e.summary,`${t}.summary`),xe(e.bullets,`${t}.bullets`),xe(e.tags,`${t}.tags`),R(e.takeaway,`${t}.takeaway`)}function M(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function R(e,t){if(typeof e!="string")throw new Error(`${t} must be a string.`)}function xe(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of strings.`)}function G(e,t){if(!Number.isInteger(e)||Number(e)<0)throw new Error(`${t} must be a non-negative integer.`)}function nn(e,t){if(typeof e!="number"||!Number.isFinite(e)||e<0||e>100)throw new Error(`${t} must be a number from 0 to 100.`)}function Se(e,t){if(!Number.isInteger(e)||Number(e)<1)throw new Error(`${t} must be a positive integer.`)}var Ur=new Set(["modified-here","created-here","deleted-here"]);function ct(e,t){let n=e.panels[t],i=e.panels[t+1];return!n||!i?"unchanged-here":n.exists&&i.exists?n.content===i.content?"unchanged-here":"modified-here":!n.exists&&i.exists?"created-here":n.exists&&!i.exists?"deleted-here":e.panels.slice(0,t).some(l=>l.exists)?"already-deleted":(e.panels.slice(t+2).some(l=>l.exists),"not-created-yet")}function an(e,t,n,i){if(i!==-1&&i!==1||!n)return null;let o=e.findIndex(d=>d.path===n);if(o<0)return null;let a=e.map((d,p)=>({file:d,fileIndex:p,state:ct(d,t)})).filter(({state:d})=>Ur.has(d)),l=i<0?[...a].reverse().find(({fileIndex:d})=>d<o):a.find(({fileIndex:d})=>d>o);return l?{pairIndex:t,fileIndex:l.fileIndex,path:l.file.path}:null}function cn(e,t,n){let i=e.findIndex(d=>d.id===t),o=i>=0?i:0,a=e[o];if(!a||a.kind!=="walkthrough"&&a.kind!=="stacked-diff"&&a.kind!=="deconstructed-diff"||!n)return{sceneIndex:o,stepIndex:0};let l=a.steps.findIndex(d=>d.id===n);return{sceneIndex:o,stepIndex:l>=0?l:0}}function Pe(e,t,n){let i=e[t.sceneIndex];if(!i)return null;if(n>0)return(i.kind==="walkthrough"||i.kind==="stacked-diff"||i.kind==="deconstructed-diff")&&t.stepIndex<i.steps.length-1?{sceneIndex:t.sceneIndex,stepIndex:t.stepIndex+1}:t.sceneIndex<e.length-1?{sceneIndex:t.sceneIndex+1,stepIndex:0}:null;if((i.kind==="walkthrough"||i.kind==="stacked-diff"||i.kind==="deconstructed-diff")&&t.stepIndex>0)return{sceneIndex:t.sceneIndex,stepIndex:t.stepIndex-1};if(t.sceneIndex===0)return null;let o=e[t.sceneIndex-1];return{sceneIndex:t.sceneIndex-1,stepIndex:o.kind==="walkthrough"||o.kind==="stacked-diff"||o.kind==="deconstructed-diff"?o.steps.length-1:0}}function un(e,t,n){if(!t)return null;let i=e.map((d,p)=>({file:d,fileIndex:p})).filter(({file:d})=>d.kind==="text-diff"),o=i.findIndex(({file:d})=>d.path===t),a=o+n,l=o>=0?i[a]:null;return l?{fileIndex:l.fileIndex,path:l.file.path}:null}function dn(e,t,n){let i=e.scenes[t.sceneIndex];if(!i)return null;let o=ut(i)?Math.min(Math.max(t.stepIndex,0),i.steps.length-1):0,a={sceneIndex:t.sceneIndex,stepIndex:o},l=ut(i)?i.steps[o]:void 0,d=[],p=!l||o===0,m=!!(l&&o>0&&n.entry==="playback-start");if(p){let T=e.chapters.find(A=>A.sceneIds.includes(i.id));T&&d.push({source:{field:"chapter"},text:T.title})}(p||m)&&d.push({source:{field:"scene-title"},text:i.title}),p&&(d.push({source:{field:"summary"},text:i.summary}),i.bullets.forEach((T,A)=>{d.push({source:{field:"bullet",itemIndex:A},text:T})})),l&&(d.push({source:{field:"step-title"},text:l.title}),d.push({source:{field:"step-body"},text:l.body}),"connection"in l&&l.connection?.label&&d.push({source:{field:"connection"},text:l.connection.label})),(!l||ut(i)&&o===i.steps.length-1)&&d.push({source:{field:"takeaway"},text:i.takeaway});let f=`${i.id}:${l?.id||"scene"}`,s=n.segmentLimit??240,x=d.flatMap(T=>zr(f,T,s));return{id:f,position:a,segments:x}}function Br(e,t=240){if(!Number.isInteger(t)||t<40)throw new Error("Narration segment limit must be an integer of at least 40 characters.");return Wr(e).flatMap(i=>Gr(e,i.startOffset,i.endOffset,t))}function Hr(e){return e.replace(/https?:\/\/\S+/giu," ").replace(/\b(?=[0-9a-f]{7,40}\b)(?=[0-9a-f]*\d)[0-9a-f]+\b/giu," ").replace(/[`*_~]/gu,"").replace(/([\p{Ll}\d])(\p{Lu})/gu,"$1 $2").replace(/([\p{Lu}])(\p{Lu}\p{Ll})/gu,"$1 $2").replace(/\s+/gu," ").trim()}function zr(e,t,n){let i=t.source.itemIndex===void 0?t.source.field:`${t.source.field}-${t.source.itemIndex}`;return Br(t.text,n).map((o,a)=>({id:`${e}:${i}:${a}`,text:o.text,speechText:Hr(o.text),source:t.source,startOffset:o.startOffset,endOffset:o.endOffset})).filter(o=>o.speechText.length>0)}function Wr(e){let t=[],n=0;for(let i=0;i<e.length;i+=1){if(!".!?".includes(e[i]))continue;let o=i+1;for(;o<e.length&&`"'\u201D\u2019)]}`.includes(e[o]);)o+=1;o<e.length&&!/\s/u.test(e[o])||(Ue(e,t,n,o),n=o)}return Ue(e,t,n,e.length),t}function Gr(e,t,n,i){let o=[],a=t;for(;n-a>i;){let l=a+i,d=a+Math.floor(i*.55),p=ln(e,d,l,/[;,:—–-]/u);p<=a&&(p=ln(e,d,l,/\s/u)),p<=a&&(p=l),Ue(e,o,a,p),a=p}return Ue(e,o,a,n),o}function ln(e,t,n,i){for(let o=n;o>=t;o-=1)if(i.test(e[o]))return o+1;return-1}function Ue(e,t,n,i){let o=n,a=i;for(;o<a&&/\s/u.test(e[o]);)o+=1;for(;a>o&&/\s/u.test(e[a-1]);)a-=1;o<a&&t.push({text:e.slice(o,a),startOffset:o,endOffset:a})}function ut(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}var Be=class{constructor(t,n){this.engine=t;this.callbacks=n;this.generation=0;this.continuous=!0;this.currentState={kind:"idle"}}get state(){return this.currentState}get engaged(){return this.currentState.kind==="playing"||this.currentState.kind==="paused"}start(t,n=!0){if(this.resetEngine(),this.continuous=n,t.segments.length===0){this.finishUnit(t);return}this.callbacks.claimAudio(),this.setState({kind:"playing",unit:t,segmentIndex:0}),this.speakCurrent()}togglePause(){if(this.currentState.kind==="playing"){this.engine.pause();let n={kind:"paused",unit:this.currentState.unit,segmentIndex:this.currentState.segmentIndex,pendingStart:!1};this.setState(n),this.callbacks.onSegmentChange(n.unit.segments[n.segmentIndex]||null,!0);return}if(this.currentState.kind!=="paused")return;this.callbacks.claimAudio();let t=this.currentState;this.setState({kind:"playing",unit:t.unit,segmentIndex:t.segmentIndex}),t.pendingStart?this.speakCurrent():(this.engine.resume(),this.callbacks.onSegmentChange(t.unit.segments[t.segmentIndex]||null,!1))}stop(){this.resetEngine(),this.setState({kind:"idle"}),this.callbacks.onSegmentChange(null,!1)}pauseForExternalOwner(){this.currentState.kind==="playing"&&this.togglePause()}canSkipSegment(t){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return!1;let n=this.currentState.segmentIndex+t;return n>=0&&n<this.currentState.unit.segments.length?!0:this.callbacks.canNavigateUnit(this.currentState.unit,t)}skipSegment(t){if(!this.canSkipSegment(t))return!1;let n=this.currentState,i=n.kind==="paused",o=n.unit,a=n.segmentIndex+t;if(a<0||a>=o.segments.length){let l=this.callbacks.navigateUnit(o,t);if(!l||l.segments.length===0)return!1;o=l,a=t<0?o.segments.length-1:0}return this.resetEngine(),i?(this.setState({kind:"paused",unit:o,segmentIndex:a,pendingStart:!0}),this.callbacks.onSegmentChange(o.segments[a]||null,!0)):(this.setState({kind:"playing",unit:o,segmentIndex:a}),this.speakCurrent()),!0}followLinearNavigation(t){this.currentState.kind==="playing"?this.start(t,this.continuous):this.currentState.kind==="paused"&&this.preparePaused(t)}followDirectNavigation(t){this.engaged&&this.preparePaused(t)}interruptForExploration(){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return;let t=this.currentState;this.resetEngine(),this.setState({kind:"paused",unit:t.unit,segmentIndex:t.segmentIndex,pendingStart:!0}),this.callbacks.onSegmentChange(t.unit.segments[t.segmentIndex]||null,!0)}dispose(){this.stop()}preparePaused(t){this.resetEngine(),this.setState({kind:"paused",unit:t,segmentIndex:0,pendingStart:!0}),this.callbacks.onSegmentChange(t.segments[0]||null,!0)}speakCurrent(){if(this.currentState.kind!=="playing")return;let t=this.generation,n=this.currentState.unit.segments[this.currentState.segmentIndex];if(!n){this.finishUnit(this.currentState.unit);return}this.callbacks.onSegmentChange(n,!1),this.engine.speak(n,{onEnd:()=>{if(t!==this.generation||this.currentState.kind!=="playing")return;let i=this.currentState.segmentIndex+1;i<this.currentState.unit.segments.length?(this.setState({kind:"playing",unit:this.currentState.unit,segmentIndex:i}),this.speakCurrent()):this.finishUnit(this.currentState.unit)},onError:i=>{t===this.generation&&(this.setState({kind:"error",message:i}),this.callbacks.onSegmentChange(null,!1))}})}finishUnit(t){if(this.continuous){let n=this.callbacks.navigateUnit(t,1);if(n){if(this.generation+=1,n.segments.length===0){this.finishUnit(n);return}this.setState({kind:"playing",unit:n,segmentIndex:0}),this.speakCurrent();return}}this.setState({kind:"completed"}),this.callbacks.onSegmentChange(null,!1)}resetEngine(){this.generation+=1,this.engine.cancel()}setState(t){this.currentState=t,this.callbacks.onStateChange(t)}};function hn(e,t,n="all",i=300){let o=t.trim().toLocaleLowerCase();if(!o||i<=0)return[];let a=[];if(n!=="code"){let l=new Map;e.chapters.forEach(d=>d.sceneIds.forEach(p=>l.set(p,d.title))),e.scenes.forEach((d,p)=>{let m=[l.get(d.id),d.title,d.summary,...d.bullets,...d.tags,d.takeaway],f=fn(m,o);f&&a.push({kind:"narrative",sceneIndex:p,label:d.title,preview:f}),jr(d)&&d.steps.forEach((s,x)=>{let T=fn([s.title,s.body,"connection"in s?s.connection?.label:void 0],o);T&&a.push({kind:"narrative",sceneIndex:p,stepIndex:x,label:`${d.title} \xB7 ${s.title}`,preview:T})})})}if(n!=="narrative"&&a.length<i)for(let l=0;l<e.files.length;l+=1){let d=e.files[l];if(d.kind==="text-diff"){for(let[p,m]of[[0,d.leftContent],[1,d.rightContent]])for(let f of qr(m,o))if(a.push({kind:"code",fileIndex:l,sideIndex:p,label:`${d.path} \xB7 ${p===0?"base":"head"}`,...f}),a.length>=i)return a}}return a.slice(0,i)}function fn(e,t){return e.find(n=>n?.toLocaleLowerCase().includes(t))}function qr(e,t){let n=[];return e.replace(/\r\n/g,`
|
|
149
149
|
`).split(`
|
|
150
|
-
`).forEach((r,o)=>{let s=r.toLocaleLowerCase(),c=0;for(;c<=s.length-e.length;){let u=s.indexOf(e,c);if(u<0)break;n.push({lineNumber:o+1,startColumn:u+1,endColumn:u+e.length+1,preview:r}),c=u+Math.max(e.length,1)}}),n}function dr(t){return t.kind==="walkthrough"||t.kind==="stacked-diff"||t.kind==="deconstructed-diff"}function Qt(t,e){return fr(t,0,e)}function fr(t,e,n){let r=t?.blocks[e],o=n==="left"?t?.leftLines:t?.rightLines;if(!r||!o?.length)return;let s=n==="left"?r.leftStart:r.rightStart,c=n==="left"?r.leftEnd:r.rightEnd,u=o.slice(s,c),d=u[0]?.lineNumber??o[Math.min(s,o.length-1)]?.lineNumber;if(Number.isInteger(d))return{startLine:d,endLine:u.at(-1)?.lineNumber??d}}function en(t,e,n,r){let o=[];return t.scenes.forEach((s,c)=>{s.kind==="walkthrough"&&s.steps.forEach((u,d)=>{u.diff.path===e&&o.push({side:u.focus.revision==="base"?"left":"right",startLine:u.focus.startLine,endLine:u.focus.endLine,label:`${s.title} \xB7 ${u.title}: ${u.body}`,active:c===n&&d===r,jumpTarget:{sceneIndex:c,stepIndex:d}})})}),o}function tn(t,e,n,r,o){let s=[];return t.scenes.forEach((c,u)=>{c.kind!=="stacked-diff"&&c.kind!=="deconstructed-diff"||c.steps.forEach((d,m)=>{if(d.file!==e)return;let p=d.startLine===void 0?o?.(d.pairIndex,d.side):{startLine:d.startLine,endLine:d.endLine??d.startLine};if(!p)return;let a=d.pairIndex+(d.side==="right"?1:0);s.push({pairIndex:d.pairIndex,panelIndex:a,side:d.side,startLine:p.startLine,endLine:p.endLine,label:`${c.title} \xB7 ${d.title}: ${d.body}`,active:u===n&&m===r,jumpTarget:{sceneIndex:u,stepIndex:m}})})}),s}function gr(t,e=120){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function nn(t,e="Bygone"){let n=t?.windowTitle?.trim()||t?.title?.trim();return n?gr(n):`${e} Tour`}(function(){let e="bygone.tourSidebarWidth",o="bygone.tourNarrativeHeight",u="bygone.tourNarrationVoice",d="bygone.tourNarrationRate",m=new Set([.75,1,1.25,1.5]),p="speechSynthesis"in window&&"SpeechSynthesisUtterance"in window,a={mode:"empty",left:null,right:null,comparisonId:0,tour:null,activeSceneIndex:-1,activeStepIndex:0,activeTourFilePath:null,tourFocusFilePath:null,tourSidebarWidth:an(),tourSidebarHidden:!1,tourNarrativeHeight:cn(),narrationVoiceURI:window.localStorage.getItem(u)||"",narrationRate:w(),narrationVoices:[],renderedNarrationUnit:null},x=new Me(L(),{claimAudio:ye,onStateChange:ie,onSegmentChange:rn,canNavigateUnit:W,navigateUnit:z});window.__BYGONE_HOST__={environment:"web",editorWorkerUrl:"/media/editor.worker.js",diffWorkerUrl:"/media/diff.worker.js",postMessage(i){C(i)}},window.addEventListener("DOMContentLoaded",()=>{k(),X("Browser host ready.")});function E(i){window.dispatchEvent(new window.CustomEvent("bygone:host-message",{detail:i}))}async function C(i){if(!(!i||typeof i!="object")){if(i.type==="ready"){let l=new URLSearchParams(window.location.search),h=l.get("manifest");h?un(h):l.get("demo")==="1"&&yt();return}if(i.type==="navigateFile"&&a.mode==="tour"){gn(i.direction==="previous"?-1:1);return}if(i.type==="navigateTourStep"&&a.mode==="tour"){let l=i.sceneIndex,h=i.stepIndex;Number.isInteger(l)&&Number.isInteger(h)&&oe(l,h);return}i.type==="recomputeDiff"&&a.mode==="diff"&&a.left&&a.right&&(a.left.content=i.leftContent,a.right.content=i.rightContent,E({type:"showDiff",file1:a.left.name,file2:a.right.name,comparisonId:`web-${a.comparisonId}`,leftContent:a.left.content,rightContent:a.right.content,diffModel:re(a.left.content,a.right.content),history:null}))}}function k(){let i=document.getElementById("web-compare-test"),l=document.getElementById("web-open-diff"),h=document.getElementById("web-open-diff3"),f=document.getElementById("web-diff-input"),g=document.getElementById("web-diff3-input"),b=document.getElementById("tour-previous"),y=document.getElementById("tour-next"),S=document.getElementById("tour-return-focus"),T=document.getElementById("tour-search-input"),O=document.getElementById("tour-search-scope"),F=document.getElementById("tour-listen"),V=document.getElementById("tour-stop"),q=document.getElementById("tour-narration-skip-back"),B=document.getElementById("tour-narration-skip-ahead"),U=document.getElementById("tour-narration-voice"),j=document.getElementById("tour-narration-rate");sn(),ln(),v(),i?.addEventListener("click",()=>{yt()}),l?.addEventListener("click",()=>{f.value="",f.click()}),h?.addEventListener("click",()=>{g.value="",g.click()}),f?.addEventListener("change",async()=>{let I=Array.from(f.files||[]);if(I.length!==2){X("Select exactly 2 files for a diff.");return}await In(I)}),g?.addEventListener("change",async()=>{let I=Array.from(g.files||[]);if(I.length<1){X("Select one or more files.");return}await wn(I)}),b?.addEventListener("click",()=>Se(-1)),y?.addEventListener("click",()=>Se(1)),S?.addEventListener("click",hn),T?.addEventListener("input",_e),O?.addEventListener("change",_e),F?.addEventListener("click",P),V?.addEventListener("click",()=>x.stop()),q?.addEventListener("click",()=>x.skipSegment(-1)),B?.addEventListener("click",()=>x.skipSegment(1)),U?.addEventListener("change",()=>{a.narrationVoiceURI=U.value,window.localStorage.setItem(u,a.narrationVoiceURI)}),j&&(j.value=String(a.narrationRate),j.addEventListener("change",()=>{let I=Number(j.value);a.narrationRate=m.has(I)?I:1,j.value=String(a.narrationRate),window.localStorage.setItem(d,String(a.narrationRate))})),document.getElementById("tour-search-results")?.addEventListener("click",I=>{let G=I.target instanceof Element?I.target.closest("[data-tour-search-result]"):null;G&&on(Number(G.getAttribute("data-tour-search-result")))}),window.addEventListener("keydown",I=>{if(a.mode==="tour"&&(I.metaKey||I.ctrlKey)&&I.shiftKey&&I.key.toLocaleLowerCase()==="f"){I.preventDefault(),I.stopImmediatePropagation(),a.tourSidebarHidden&&Pe(!1),T?.focus(),T?.select();return}a.mode!=="tour"||I.metaKey||I.ctrlKey||I.altKey||bn(I.target)||(I.key==="PageUp"||I.key==="ArrowLeft"?(I.preventDefault(),Se(-1)):(I.key==="PageDown"||I.key==="ArrowRight")&&(I.preventDefault(),Se(1)))},!0),window.addEventListener("bygone:tour-command",I=>{I.detail==="toggleNarration"&&P(),I.detail==="pauseNarration"&&x.pauseForExternalOwner()}),window.addEventListener("beforeunload",()=>x.dispose(),{once:!0}),ie(x.state)}function v(){let i=document.getElementById("tour-narration-voice"),l=document.getElementById("tour-listen");if(!p){l&&(l.disabled=!0,l.title="Device narration is not supported by this browser."),i&&(i.disabled=!0),ue("Device narration unavailable");return}let h=()=>{if(a.narrationVoices=window.speechSynthesis.getVoices().slice().sort((f,g)=>Number(g.default)-Number(f.default)||f.lang.localeCompare(g.lang)||f.name.localeCompare(g.name)),a.narrationVoiceURI&&a.narrationVoices.length>0&&!a.narrationVoices.some(f=>f.voiceURI===a.narrationVoiceURI)&&(a.narrationVoiceURI="",window.localStorage.removeItem(u)),i){let f=document.createElement("option");f.value="",f.textContent="System default voice",i.replaceChildren(f,...a.narrationVoices.map(g=>{let b=document.createElement("option");return b.value=g.voiceURI,b.textContent=`${g.name} (${g.lang})${g.default?" \u2014 default":""}`,b})),i.value=a.narrationVoiceURI,i.disabled=a.narrationVoices.length===0}};h(),window.speechSynthesis.addEventListener("voiceschanged",h)}function w(){let i=Number(window.localStorage.getItem(d));return m.has(i)?i:1}function L(){let i=null;return{speak(l,h){if(!p){h.onError("Device narration is not supported by this browser.");return}let f=new window.SpeechSynthesisUtterance(l.speechText),g=a.narrationVoices.find(b=>b.voiceURI===a.narrationVoiceURI);g&&(f.voice=g),f.rate=a.narrationRate,f.onend=()=>{i===f&&(i=null),h.onEnd()},f.onerror=b=>{i===f&&(i=null),h.onError($(b.error))},i=f,window.speechSynthesis.speak(f)},pause(){p&&window.speechSynthesis.pause()},resume(){p&&window.speechSynthesis.resume()},cancel(){i=null,p&&window.speechSynthesis.cancel()}}}function $(i){return i==="not-allowed"?"Device narration needs permission to play audio.":i==="language-unavailable"||i==="voice-unavailable"?"The selected device voice is unavailable.":`Device narration failed${i?`: ${i}`:"."}`}function A(){if(!p||a.mode!=="tour")return;let i=D("playback-start");i&&(a.renderedNarrationUnit=i,yn(i),x.start(i,!0))}function P(){x.state.kind==="playing"||x.state.kind==="paused"?x.togglePause():A()}function D(i){return!a.tour||a.activeSceneIndex<0?null:Yt(a.tour,{sceneIndex:a.activeSceneIndex,stepIndex:a.activeStepIndex},{entry:i})}function W(i,l){let h=a.tour;return!!(h&&Re(h.scenes,i.position,l))}function z(i,l){let h=a.tour;if(!h)return null;let f=Re(h.scenes,i.position,l);return f?oe(f.sceneIndex,f.stepIndex,{narrationNavigation:"controller",narrationEntry:"continuous"}):null}function ye(){fetch("/narration/claim",{method:"POST",cache:"no-store"}).catch(()=>{})}function ie(i){let l=document.getElementById("tour-listen"),h=document.getElementById("tour-stop"),f=document.getElementById("tour-narration-skip-back"),g=document.getElementById("tour-narration-skip-ahead");if(l){l.disabled=!p||a.mode!=="tour";let b=i.kind==="playing";l.querySelector(".tour-play-pause-icon")?.setAttribute("d",b?"M7 5h4v14H7zM13 5h4v14h-4z":"m8 5 11 7-11 7Z");let y=b?"Pause narration":i.kind==="paused"?"Resume narration":"Listen from the current tour item";l.title=y,l.setAttribute("aria-label",y)}if(h&&(h.disabled=i.kind!=="playing"&&i.kind!=="paused"),f&&(f.disabled=!x.canSkipSegment(-1)),g&&(g.disabled=!x.canSkipSegment(1)),i.kind==="playing"||i.kind==="paused"){let b=i.segmentIndex+1,y=i.unit.segments.length;ue(`${i.kind==="paused"?"Paused":"Speaking"} \xB7 segment ${b} of ${y}`)}else i.kind==="completed"?ue("Narration complete"):i.kind==="error"?ue(i.message):p&&ue("Device voice ready")}function ue(i){let l=document.getElementById("tour-narration-status");l&&(l.textContent=i)}function rn(i,l){if(document.querySelectorAll(".tour-narration-segment.is-speaking").forEach(y=>{y.classList.remove("is-speaking","is-paused")}),!i)return;let h=[...document.querySelectorAll("[data-narration-segment-id]")].find(y=>y.dataset.narrationSegmentId===i.id);if(!h)return;h.classList.add("is-speaking"),h.classList.toggle("is-paused",l);let f=document.getElementById("tour-narrative");if(!f)return;let g=h.getBoundingClientRect(),b=f.getBoundingClientRect();(g.top<b.top||g.bottom>b.bottom)&&h.scrollIntoView({block:"nearest"})}let de=[];function _e(){let i=document.getElementById("tour-search-input"),l=document.getElementById("tour-search-scope"),h=document.getElementById("tour-search-status"),f=document.getElementById("tour-search-results");if(!(!a.tour||!i||!l||!h||!f)){if(de=Zt(a.tour,i.value,l.value),!i.value.trim()){h.textContent="Cmd/Ctrl+Shift+F",f.replaceChildren();return}h.textContent=`${de.length} result${de.length===1?"":"s"}`,f.replaceChildren(...de.map((g,b)=>{let y=document.createElement("button");y.type="button",y.className="tour-search-result",y.setAttribute("role","option"),y.dataset.tourSearchResult=String(b),y.title=`Open ${g.kind==="code"?`${g.label}:${g.lineNumber}`:g.label}`;let S=document.createElement("span");S.className="tour-search-location",S.textContent=g.kind==="code"?`${g.label}:${g.lineNumber}`:g.label;let T=document.createElement("span");return T.className="tour-search-preview",T.textContent=g.preview.trim(),y.append(S,T),y}))}}function on(i){let l=de[i];if(l){if(l.kind==="narrative"){oe(l.sceneIndex,l.stepIndex??0);return}ut(l.fileIndex)&&window.requestAnimationFrame(()=>E({type:"revealSearchResult",sideIndex:l.sideIndex,lineNumber:l.lineNumber,startColumn:l.startColumn,endColumn:l.endColumn}))}}function sn(){let i=document.getElementById("tour-shell"),l=document.getElementById("tour-sidebar-resizer"),h=document.getElementById("tour-sidebar-hide"),f=document.getElementById("tour-sidebar-show");!i||!l||!h||!f||(rt(),h.addEventListener("click",()=>Pe(!0)),f.addEventListener("click",()=>Pe(!1)),l.addEventListener("pointerdown",g=>{g.preventDefault(),document.body.classList.add("is-resizing-tour-sidebar"),l.setPointerCapture?.(g.pointerId);let b=S=>nt(S.clientX),y=()=>{document.body.classList.remove("is-resizing-tour-sidebar"),window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),window.localStorage.setItem(e,String(a.tourSidebarWidth))};window.addEventListener("pointermove",b),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y)}),l.addEventListener("keydown",g=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(g.key))return;g.preventDefault();let b=a.tourSidebarWidth;g.key==="Home"?b=240:g.key==="End"?b=Oe():b+=g.key==="ArrowLeft"?-16:16,nt(b),window.localStorage.setItem(e,String(a.tourSidebarWidth))}))}function an(){let i=Number.parseInt(window.localStorage.getItem(e)||"",10);return Number.isFinite(i)?Math.min(600,Math.max(240,i)):360}function Oe(){return Math.max(240,Math.min(600,Math.floor(window.innerWidth*.6)))}function nt(i){a.tourSidebarWidth=Math.min(Oe(),Math.max(240,Math.round(i))),rt(),window.dispatchEvent(new Event("resize"))}function rt(){document.documentElement.style.setProperty("--tour-rail-width",`${a.tourSidebarWidth}px`);let i=document.getElementById("tour-sidebar-resizer");i?.setAttribute("aria-valuemax",String(Oe())),i?.setAttribute("aria-valuenow",String(a.tourSidebarWidth))}function Pe(i){a.tourSidebarHidden=i,document.body.classList.toggle("tour-sidebar-hidden",i);let l=document.getElementById("tour-sidebar-show");l&&(l.hidden=!i),window.dispatchEvent(new Event("resize"))}function ln(){let i=document.getElementById("tour-narrative-resizer");i&&(De(),i.addEventListener("pointerdown",l=>{l.preventDefault(),document.body.classList.add("is-resizing-tour-narrative"),i.setPointerCapture?.(l.pointerId),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-start"));let h=document.getElementById("tour-narrative")?.getBoundingClientRect().top||0,f=b=>it(b.clientY-h),g=()=>{document.body.classList.remove("is-resizing-tour-narrative"),window.removeEventListener("pointermove",f),window.removeEventListener("pointerup",g),window.removeEventListener("pointercancel",g),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-end")),ot()};window.addEventListener("pointermove",f),window.addEventListener("pointerup",g),window.addEventListener("pointercancel",g)}),i.addEventListener("keydown",l=>{if(!["ArrowUp","ArrowDown","Home","End"].includes(l.key))return;l.preventDefault();let h=l.key==="Home"?180:l.key==="End"?Ie():a.tourNarrativeHeight+(l.key==="ArrowUp"?-16:16);it(h),ot()}),window.addEventListener("resize",()=>{a.tourNarrativeHeight=Math.min(Ie(),a.tourNarrativeHeight),De()}))}function cn(){let i=Number.parseInt(window.localStorage.getItem(o)||"",10);if(Number.isFinite(i))return Math.max(180,i);let l=Number.parseInt(window.getComputedStyle(document.documentElement).getPropertyValue("--tour-narrative-height"),10);return Number.isFinite(l)?l:296}function Ie(){let i=document.getElementById("tour-narrative")?.getBoundingClientRect().top||0;return Math.max(180,window.innerHeight-i-180)}function it(i){a.tourNarrativeHeight=Math.min(Ie(),Math.max(180,Math.round(i))),De(),window.dispatchEvent(new Event("resize"))}function De(){document.documentElement.style.setProperty("--tour-narrative-height",`${a.tourNarrativeHeight}px`);let i=document.getElementById("tour-narrative-resizer");i?.setAttribute("aria-valuemax",String(Ie())),i?.setAttribute("aria-valuenow",String(a.tourNarrativeHeight))}function ot(){window.localStorage.setItem(o,String(a.tourNarrativeHeight))}async function un(i){X("Loading change tour\u2026");try{x.stop();let l=await fetch(i,{cache:"no-store"});if(!l.ok)throw new Error(`Manifest request failed (${l.status}).`);a.tour=Gt(await l.json()),a.mode="tour",document.body.classList.add("tour-mode"),dn(),_e();let h=new URLSearchParams(window.location.search),f=Kt(a.tour.scenes,h.get("scene"),h.get("step"));oe(f.sceneIndex,f.stepIndex),ie(x.state),X("")}catch(l){X(`Could not load change tour: ${l instanceof Error?l.message:String(l)}`)}}function dn(){let i=a.tour;if(!i)return;let l=document.getElementById("tour-shell"),h=document.getElementById("tour-title"),f=document.getElementById("tour-source"),g=document.getElementById("tour-range"),b=document.getElementById("tour-stats"),y=document.getElementById("tour-scenes"),S=document.getElementById("tour-scene-count"),T=document.getElementById("tour-files"),O=document.getElementById("tour-file-count"),F=document.getElementById("tour-commits"),V=document.getElementById("tour-commits-summary");if(!l||!h||!f||!g||!b||!y||!S||!T||!O||!F||!V)throw new Error("Presenter UI is incomplete.");l.hidden=!1,h.textContent=i.title,document.title=nn(i),i.sourceUrl?(f.href=i.sourceUrl,f.hidden=!1):f.hidden=!0;let q=Te(i.range.baseRef),B=Te(i.range.headRef),U=i.range.headOid.slice(0,7);g.textContent=`${q} \u2192 ${B}${B===U?"":` \xB7 ${U}`}`,b.textContent=`${ae(i.summary.changedFiles,"file")} \xB7 +${i.summary.additions} \u2212${i.summary.deletions} \xB7 ${ae(i.summary.commitCount,"commit")}`,S.textContent=String(i.scenes.length),O.textContent=String(i.files.length),V.textContent=ae(i.summary.commitCount,"commit"),y.replaceChildren();let j=new Map(i.scenes.map(I=>[I.id,I]));for(let I of i.chapters){let G=document.createElement("h2");G.className="tour-chapter-title",G.textContent=I.title,y.append(G);for(let M of I.sceneIds){let R=j.get(M);if(!R)continue;let K=i.scenes.indexOf(R),H=document.createElement("button");H.type="button",H.className="tour-scene",H.dataset.sceneId=R.id,R.kind==="text-diff"&&(H.dataset.filePath=R.path),H.title=`Open scene: ${R.kind==="text-diff"?R.path:R.title}`,H.addEventListener("click",()=>oe(K));let ne=document.createElement("span");ne.className="tour-scene-number",ne.textContent=String(K+1).padStart(2,"0");let We=document.createElement("span");We.className="tour-scene-copy";for(let[xn,Sn]of[["tour-scene-title",R.title],["tour-scene-path",R.kind==="text-diff"?R.path:R.kind==="deconstructed-diff"?`${ae(R.panels.length-1,"comparison stage")} \xB7 ${ae(R.steps.length,"tour slide")}`:ge(R)?ae(R.steps.length,"code step"):"Discussion"],["tour-scene-note",R.takeaway]]){let Ge=document.createElement("span");Ge.className=xn,Ge.textContent=Sn,We.append(Ge)}H.append(ne,We),y.append(H)}}T.replaceChildren(...i.files.map((I,G)=>{let M=document.createElement("button");M.type="button",M.className=`tour-file${I.kind==="omitted"?" is-omitted":""}`,M.dataset.filePath=I.path,M.disabled=I.kind==="omitted",M.title=I.kind==="omitted"?`${I.path}: ${I.reason}`:`Open file: ${I.path}`,I.kind==="text-diff"&&M.addEventListener("click",()=>dt(G));let R=document.createElement("span");R.className="tour-file-marker",R.textContent=I.kind==="omitted"?"\xD7":gt(I.changeKind);let K=document.createElement("span");K.className="tour-file-copy";let H=document.createElement("span");H.className="tour-file-path",H.textContent=I.path;let ne=document.createElement("span");return ne.className="tour-file-meta",ne.textContent=I.kind==="omitted"?`Not rendered \xB7 ${I.reason}`:`${ht(I.changeKind)} \xB7 +${I.additions} \u2212${I.deletions}`,K.append(H,ne),M.append(R,K),M})),F.replaceChildren(...i.commits.map(I=>{let G=document.createElement("li"),M=document.createElement("span");return M.className="tour-commit-oid",M.textContent=I.shortOid,G.append(M,document.createTextNode(I.summary)),G}))}function oe(i,l=0,h={}){let f=a.tour;if(!f||i<0||i>=f.scenes.length)return null;let g=f.scenes[i];a.activeSceneIndex=i,a.activeStepIndex=ge(g)?Math.min(Math.max(l,0),Math.max(g.steps.length-1,0)):0,a.tourFocusFilePath=g.kind==="text-diff"?g.path:g.kind==="walkthrough"?g.steps[a.activeStepIndex]?.diff.path??null:se(g)?g.steps[a.activeStepIndex]?.file??null:null;let b=mt(f,i);document.querySelectorAll(".tour-scene").forEach(T=>{T.classList.toggle("is-active",T.dataset.sceneId===g.id)}),document.querySelector(`.tour-scene[data-scene-id="${g.id}"]`)?.scrollIntoView({block:"nearest"});let y=D(h.narrationEntry||"playback-start");a.renderedNarrationUnit=y,bt(g,b,y),y&&(h.narrationNavigation==="linear"?x.followLinearNavigation(y):h.narrationNavigation!=="controller"&&x.followDirectNavigation(y));let S=new URLSearchParams(window.location.search);return S.set("scene",g.id),ge(g)?S.set("step",g.steps[a.activeStepIndex].id):S.delete("step"),window.history.replaceState(null,"",`${window.location.pathname}?${S.toString()}`),g.kind==="discussion"?(document.body.classList.add("tour-discussion"),He(),y):(document.body.classList.remove("tour-discussion"),g.kind==="walkthrough"?(at(g),y):se(g)?(lt(g),y):(xe(g,we(g.path)),y))}function we(i){let l=a.tour;return!l||!i?[]:en(l,i,a.activeSceneIndex,a.activeStepIndex)}function fn(i,l){let h=a.tour;return!h||!i?[]:tn(h,i,a.activeSceneIndex,a.activeStepIndex,(f,g)=>Qt(l?.[f]?.diffModel,g))}function Ue(i){return`file::${i}`}function xe(i,l=[],h=Ue(i.path)){if(!a.tour)return;a.activeTourFilePath=i.path,He();let g=re(i.leftContent,i.rightContent),b=st(i,i.leftLabel,"base"),y=st(i,i.rightLabel,"head"),S=l.find(T=>T.active);E({type:"showDiff",file1:b,file2:y,comparisonId:`tour-${h}`,leftContent:i.leftContent,rightContent:i.rightContent,sourceInfo:{leftPath:i.path,rightPath:i.path},diffModel:g,history:null,fileNavigation:{canGoPrevious:!!fe(-1),canGoNext:!!fe(1)},editableSides:{left:!1,right:!1},comparisonSummary:`${i.path} \xB7 ${i.takeaway}`,initialChangeIndex:S?pt(g,S.side,S.startLine):i.focusChangeIndex,tourAnnotations:l})}function st(i,l,h){let f=l.startsWith(i.path)?l.slice(i.path.length).trim():l.trim();return f?`${h} ${f}`:h}function at(i){let l=i.steps[a.activeStepIndex];l&&xe(l.diff,we(l.diff.path),Ue(l.diff.path))}function lt(i){let l=i.steps[a.activeStepIndex];l&&ct(i,l.file,l)}function ct(i,l,h){let f=ve(i,l);if(!h||!f)return;a.activeTourFilePath=f.path,He();let g=f.panels.map((B,U)=>({id:`${i.id}-${f.path}-${B.id}`,label:B.label,path:B.path||f.path,content:B.content,savedContent:B.content,dirty:!1,editable:!1,stackId:ft(i)[U].id})),b=g.slice(0,-1).map((B,U)=>({leftIndex:U,rightIndex:U+1,diffModel:re(B.content,g[U+1].content)})),y=fn(f.path,b),S=y.find(B=>B.active),T=S?.pairIndex??h.pairIndex,O=S?.side??h.side,F=S?.startLine??h.startLine,V=b[T]?.diffModel,q=V&&F?pt(V,O,F):0;E({type:"showMultiDiff",panels:g,pairs:b,activePanelId:g[T+(O==="right"?1:0)]?.id,activePairIndex:T,initialChangeIndex:q,revealFirstChangeInEachPanel:i.kind==="deconstructed-diff",history:null,fileNavigation:{canGoPrevious:!!fe(-1),canGoNext:!!fe(1)},mutationEnabled:!1,comparisonSummary:i.kind==="deconstructed-diff"?`${i.stageLabel} \xB7 ${f.path} \xB7 ${Te(i.realRange.baseRef)} \u2192 ${Te(i.realRange.targetRef)}`:`${f.path} \xB7 ${i.takeaway}`,tourAnnotations:y})}function Be(i){let l=a.tour;return!l||i!==-1&&i!==1?null:Re(l.scenes,{sceneIndex:a.activeSceneIndex,stepIndex:a.activeStepIndex},i)}function Se(i){let l=Be(i);return l?(oe(l.sceneIndex,l.stepIndex,{narrationNavigation:"linear",narrationEntry:"playback-start"}),!0):!1}function fe(i){let l=a.tour;if(!l||i!==-1&&i!==1)return null;let h=l.scenes[a.activeSceneIndex];if(se(h)){let f=h.steps[a.activeStepIndex]?.pairIndex;if(!Number.isInteger(f))return null;let g=l.files.flatMap(S=>{if(S.kind!=="text-diff")return[];let T=ve(h,S.path);return T?[T]:[]}),b=qt(g,f,a.activeTourFilePath,i);if(!b)return null;let y=l.files.findIndex(S=>S.kind==="text-diff"&&S.path===b.path);return y>=0?{fileIndex:y,path:b.path}:null}return jt(l.files,a.activeTourFilePath,i)}function gn(i){let l=fe(i);return l?dt(l.fileIndex):!1}function ut(i,l=!0){let h=a.tour?.files[i];return!h||h.kind!=="text-diff"?!1:(l&&x.interruptForExploration(),xe(h,we(h.path),Ue(h.path)),!0)}function dt(i){let l=a.tour?.files[i];if(!l||l.kind!=="text-diff")return!1;x.interruptForExploration();let h=a.tour?.scenes[a.activeSceneIndex];if(se(h)){let f=h.steps[a.activeStepIndex];return f&&ve(h,l.path)?(ct(h,l.path,f),!0):!1}return ut(i,!1)}function ve(i,l){let h=i?.files?.find(b=>b.path===l);if(h||i?.kind!=="deconstructed-diff")return h;let f=a.tour?.files.find(b=>b.kind==="text-diff"&&b.path===l);if(!f||f.kind!=="text-diff")return null;let g=f.changeKind!=="deleted";return{path:f.path,panels:ft(i).map(b=>({id:b.id,label:`${b.label} / ${f.path}${g?"":" (absent)"}`,path:g?f.path:void 0,content:g?f.rightContent:"",exists:g}))}}function hn(){let i=a.tour?.scenes[a.activeSceneIndex];if(!i||!a.tourFocusFilePath)return!1;if(i.kind==="walkthrough")at(i);else if(se(i))lt(i);else if(i.kind==="text-diff")xe(i,we(i.path));else return!1;return!0}function He(){let i=a.tour?.scenes[a.activeSceneIndex],l=se(i)?i.steps[a.activeStepIndex]:null;document.querySelectorAll(".tour-file").forEach(f=>{let g=f.dataset.filePath;f.classList.toggle("is-active",g===a.activeTourFilePath),f.classList.toggle("is-tour-focus",g===a.tourFocusFilePath),f.classList.remove("is-comparison-changed","is-comparison-empty"),delete f.dataset.comparisonState;let b=a.tour?.files.find(T=>T.path===g),y=f.querySelector(".tour-file-marker"),S=f.querySelector(".tour-file-meta");if(l&&b?.kind==="text-diff"){let T=ve(i,g);if(T){let O=et(T,l.pairIndex),F=mn(O);f.dataset.comparisonState=O,f.classList.add(F.changed?"is-comparison-changed":"is-comparison-empty"),f.setAttribute("title",`${b.path} \xB7 ${F.label}`),f.setAttribute("aria-label",`${b.path}, ${F.label}`),y&&(y.textContent=F.marker),S&&(S.textContent=F.label);return}}if(b){let T=b.kind==="omitted"?`${b.path}: ${b.reason}`:`Open file: ${b.path}`;f.setAttribute("title",T),f.setAttribute("aria-label",T),y&&(y.textContent=b.kind==="omitted"?"\xD7":gt(b.changeKind)),S&&(S.textContent=b.kind==="omitted"?`Not rendered \xB7 ${b.reason}`:`${ht(b.changeKind)} \xB7 +${b.additions} \u2212${b.deletions}`)}}),document.querySelector(".tour-file.is-active")?.scrollIntoView({block:"nearest"});let h=document.getElementById("tour-return-focus");h&&(h.hidden=!a.tourFocusFilePath||a.activeTourFilePath===a.tourFocusFilePath)}function mn(i){return{"modified-here":{label:"Modified here",marker:"\u2022",changed:!0},"created-here":{label:"Created here",marker:"+",changed:!0},"deleted-here":{label:"Deleted here",marker:"\u2212",changed:!0},"unchanged-here":{label:"Unchanged here",marker:"\u25CB",changed:!1},"not-created-yet":{label:"Not created yet",marker:"\u2026",changed:!1},"already-deleted":{label:"Already deleted",marker:"\xD7",changed:!1}}[i]}function ge(i){return i.kind==="walkthrough"||i.kind==="stacked-diff"||i.kind==="deconstructed-diff"}function se(i){return i?.kind==="stacked-diff"||i?.kind==="deconstructed-diff"}function ft(i){return i.kind==="deconstructed-diff"?i.panels:i.stack}function gt(i){return{added:"+",deleted:"\u2212",renamed:"\u2192",modified:"\u2022"}[i]||"\u2022"}function ht(i){return`${i.charAt(0).toUpperCase()}${i.slice(1)}`}function mt(i,l){let h=i.scenes[l],f=i.chapters.findIndex(S=>S.sceneIds.includes(h.id)),g=f>=0?i.chapters[f]:null,b=g?g.sceneIds.indexOf(h.id)+1:l+1,y=g?g.sceneIds.length:i.scenes.length;return{chapter:g,chapterIndex:f,chapterNumber:f>=0?f+1:l+1,sceneInChapter:b,scenesInChapter:y}}function pn(i,l,h){let f=[`Ch ${i.chapterNumber}`,`Scene ${i.sceneInChapter}/${i.scenesInChapter}`];return ge(l)&&f.push(`Step ${h+1}/${l.steps.length}`),f.join(" \xB7 ")}function pt(i,l,h){let g=(l==="left"?i.leftLines:i.rightLines).findIndex(F=>F.lineNumber===h);if(g<0)return 0;let b=l==="left"?"leftStart":"rightStart",y=l==="left"?"leftEnd":"rightEnd",S=i.blocks.findIndex(F=>g>=F[b]&&g<F[y]);if(S>=0)return S;let T=0,O=Number.POSITIVE_INFINITY;return i.blocks.forEach((F,V)=>{let q=Math.min(Math.abs(g-F[b]),Math.abs(g-F[y]));q<O&&(T=V,O=q)}),T}function Te(i){return/^[0-9a-f]{40}$/i.test(i)?i.slice(0,7):i}function ae(i,l){return`${i} ${i===1?l:`${l}s`}`}function bn(i){return i instanceof Element&&!!i.closest('a, button, input, select, summary, textarea, [contenteditable="true"], [role="textbox"], .monaco-editor')}function yn(i){let l=a.tour?.scenes[a.activeSceneIndex];!a.tour||!l||bt(l,mt(a.tour,a.activeSceneIndex),i)}function bt(i,l,h){let f=document.getElementById("tour-narrative"),g=document.getElementById("tour-breadcrumb"),b=document.getElementById("tour-narrative-chapter"),y=document.getElementById("tour-narrative-title"),S=document.getElementById("tour-narrative-summary"),T=document.getElementById("tour-narrative-bullets"),O=document.getElementById("tour-narrative-tags"),F=document.getElementById("tour-narrative-takeaway"),V=document.getElementById("tour-step"),q=document.getElementById("tour-step-title"),B=document.getElementById("tour-step-body"),U=document.getElementById("tour-connection"),j=document.getElementById("tour-previous"),I=document.getElementById("tour-next");if(!f||!g||!b||!y||!S||!T||!O||!F||!V||!q||!B||!U||!j||!I)throw new Error("Tour narrative UI is incomplete.");f.hidden=!1,g.textContent=pn(l,i,a.activeStepIndex);let G=l.chapter?.title||"Change tour";Z(b,G,{field:"chapter"},h,{suffix:i.kind==="deconstructed-diff"?` \xB7 ${i.stageLabel}`:""}),Z(y,i.title,{field:"scene-title"},h),Z(S,i.summary,{field:"summary"},h),T.replaceChildren(...i.bullets.map((R,K)=>{let H=document.createElement("li");return Z(H,R,{field:"bullet",itemIndex:K},h),H})),O.replaceChildren(...i.tags.map(R=>{let K=document.createElement("span");return K.textContent=R,K})),Z(F,i.takeaway,{field:"takeaway"},h);let M=ge(i)?i.steps[a.activeStepIndex]:null;V.hidden=!M,M?(Z(q,M.title,{field:"step-title"},h,{prefix:i.kind==="deconstructed-diff"?`Stage ${a.activeStepIndex+1}: `:""}),Z(B,M.body,{field:"step-body"},h),"connection"in M&&M.connection?(U.hidden=!1,Z(U,M.connection.label,{field:"connection"},h,{prefix:`${M.connection.from.path} \u2192 ${M.connection.to.path} \xB7 `})):(U.hidden=!0,U.textContent="")):(q.textContent="",B.textContent="",U.hidden=!0,U.textContent=""),j.disabled=!Be(-1),I.disabled=!Be(1)}function Z(i,l,h,f,g={}){let b=f?.segments.filter(T=>T.source.field===h.field&&T.source.itemIndex===h.itemIndex)||[];if(b.length===0){i.textContent=`${g.prefix||""}${l}${g.suffix||""}`;return}let y=[];g.prefix&&y.push(document.createTextNode(g.prefix));let S=0;for(let T of b){T.startOffset>S&&y.push(document.createTextNode(l.slice(S,T.startOffset)));let O=document.createElement("span");O.className="tour-narration-segment",O.dataset.narrationSegmentId=T.id,O.textContent=l.slice(T.startOffset,T.endOffset),y.push(O),S=T.endOffset}S<l.length&&y.push(document.createTextNode(l.slice(S))),g.suffix&&y.push(document.createTextNode(g.suffix)),i.replaceChildren(...y)}function yt(){x.stop();let i=Wt();a.mode="diff",a.comparisonId+=1,a.left={name:i.leftFileName,content:i.leftContent},a.right={name:i.rightFileName,content:i.rightContent},X("Loaded sample diff."),E({type:"showDiff",file1:a.left.name,file2:a.right.name,comparisonId:`web-${a.comparisonId}`,leftContent:a.left.content,rightContent:a.right.content,diffModel:re(a.left.content,a.right.content),history:null})}async function In(i){x.stop();let[l,h]=i,[f,g]=await Promise.all([l.text(),h.text()]);a.mode="diff",a.comparisonId+=1,a.left={name:l.name,content:f},a.right={name:h.name,content:g},X(`Loaded ${l.name} and ${h.name}.`),E({type:"showDiff",file1:l.name,file2:h.name,comparisonId:`web-${a.comparisonId}`,leftContent:f,rightContent:g,diffModel:re(f,g),history:null})}async function wn(i){x.stop();let l=await Promise.all(i.map(async(h,f)=>{let g=await h.text();return{id:`web-panel-${f}`,label:h.name,content:g,savedContent:g,dirty:!1,editable:!0}}));a.mode="multi-diff",X(`Loaded ${l.length}-panel diff for ${l.map(h=>h.label).join(", ")}.`),E({type:"showMultiDiff",panels:l,pairs:l.slice(0,-1).map((h,f)=>({leftIndex:f,rightIndex:f+1,diffModel:re(h.content,l[f+1].content)}))})}function X(i){let l=document.getElementById("web-status");l&&(l.textContent=i)}})();})();
|
|
150
|
+
`).forEach((i,o)=>{let a=i.toLocaleLowerCase(),l=0;for(;l<=a.length-t.length;){let d=a.indexOf(t,l);if(d<0)break;n.push({lineNumber:o+1,startColumn:d+1,endColumn:d+t.length+1,preview:i}),l=d+Math.max(t.length,1)}}),n}function jr(e){return e.kind==="walkthrough"||e.kind==="stacked-diff"||e.kind==="deconstructed-diff"}function gn(e,t){return Vr(e,0,t)}function Vr(e,t,n){let i=e?.blocks[t],o=n==="left"?e?.leftLines:e?.rightLines;if(!i||!o?.length)return;let a=n==="left"?i.leftStart:i.rightStart,l=n==="left"?i.leftEnd:i.rightEnd,d=o.slice(a,l),p=d[0]?.lineNumber??o[Math.min(a,o.length-1)]?.lineNumber;if(Number.isInteger(p))return{startLine:p,endLine:d.at(-1)?.lineNumber??p}}function mn(e,t,n,i){let o=[];return e.scenes.forEach((a,l)=>{a.kind==="walkthrough"&&a.steps.forEach((d,p)=>{d.diff.path===t&&o.push({side:d.focus.revision==="base"?"left":"right",startLine:d.focus.startLine,endLine:d.focus.endLine,label:`${a.title} \xB7 ${d.title}: ${d.body}`,active:l===n&&p===i,jumpTarget:{sceneIndex:l,stepIndex:p}})})}),o}function pn(e,t,n,i,o){let a=[];return e.scenes.forEach((l,d)=>{d!==n||l.kind!=="stacked-diff"&&l.kind!=="deconstructed-diff"||l.steps.forEach((p,m)=>{if(p.file!==t)return;let f=p.startLine===void 0?o?.(p.pairIndex,p.side):{startLine:p.startLine,endLine:p.endLine??p.startLine};if(!f)return;let s=p.pairIndex+(p.side==="right"?1:0);a.push({pairIndex:p.pairIndex,panelIndex:s,side:p.side,startLine:f.startLine,endLine:f.endLine,label:`${l.title} \xB7 ${p.title}: ${p.body}`,active:d===n&&m===i,jumpTarget:{sceneIndex:d,stepIndex:m}})})}),a}function Kr(e,t=120){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function bn(e,t="Bygone"){let n=e?.windowTitle?.trim()||e?.title?.trim();return n?Kr(n):`${t} Tour`}var He=class{constructor(t){this.mode=t;this.cursors=new Map;this.epoch=0;this.dirty=!1;this.origin=null}navigate(){this.dirty=!0}depart(t){return this.dirty||!this.origin?(this.dirty&&this.epoch++,this.origin=t,this.cursors.set(this.mode,{location:t,epoch:this.epoch})):this.cursors.has(this.mode)||this.cursors.set(this.mode,{location:t,epoch:this.epoch}),this.dirty=!1,this.origin}enter(t,n){let i=this.cursors.get(t);return this.mode=t,this.dirty=!1,i&&(i.epoch===this.epoch||!n)?{location:i.location,restore:!0}:{location:n||{sceneIndex:0,stepIndex:0,path:null},restore:!1}}};function wn(e,t,n){let i=n.find(d=>d.path===e.path||d.previousPath===e.path),o=new Set([e.path,i?.path,i?.previousPath].filter(Boolean)),a=null,l=1/0;return t.forEach((d,p)=>{(d.steps||[{file:d.path}]).forEach((f,s)=>{let x=f.diff?.path||f.file||d.path;if(!o.has(x))return;let T=f.startLine||1,A=f.endLine||T,I=e.line||T,y=Math.max(T-I,I-A,0);y<l&&(l=y,a={sceneIndex:p,stepIndex:s,path:x??null,line:e.line,commit:e.commit})})}),!a&&i?.kind==="text-diff"?{sceneIndex:0,stepIndex:0,path:i.path??null,line:e.line,commit:e.commit}:a}(function(){let t="bygone.tourSidebarWidth",o="bygone.tourNarrativeHeight",d="bygone.tourNarrationVoice",p="bygone.tourNarrationRate",m=new Set([.75,1,1.25,1.5]),f="speechSynthesis"in window&&"SpeechSynthesisUtterance"in window,s={mode:"empty",left:null,right:null,comparisonId:0,tour:null,authoredTour:null,zoom:null,zoomSwitching:!1,historyCommit:null,historyEntries:[],activeSceneIndex:-1,activeStepIndex:0,activeTourFilePath:null,tourFocusFilePath:null,tourSidebarWidth:Nn(),tourSidebarHidden:!1,tourNarrativeHeight:An(),narrationVoiceURI:window.localStorage.getItem(d)||"",narrationRate:yn(),narrationVoices:[],renderedNarrationUnit:null},x=new Be(xn(),{claimAudio:kn,onStateChange:ze,onSegmentChange:Tn,canNavigateUnit:vn,navigateUnit:En});window.__BYGONE_HOST__={environment:"web",editorWorkerUrl:"/media/editor.worker.js",diffWorkerUrl:"/media/diff.worker.js",postMessage(r){ne(r)}},window.addEventListener("DOMContentLoaded",()=>{Ie(),Q("Browser host ready.")});function T(r){window.dispatchEvent(new window.CustomEvent("bygone:host-message",{detail:r}))}let A=0,I=new Map,y=null;function E(){s.zoomSwitching||s.zoom?.navigate()}function k(){return new Promise(r=>{let c=++A,g=h=>{I.delete(c);let b=s.tour?.scenes[s.activeSceneIndex],w=h?.activeMultiPairIndex,v=b&&ie(b)?Xe(b):[],S=h?.editorStates?.[h.activeMultiPanelId||h.activePaneSide];r({sceneIndex:s.activeSceneIndex,stepIndex:s.activeStepIndex,path:s.activeTourFilePath,line:S?.selection?.startLineNumber,commit:s.historyCommit||v[w+1]?.oid||s.authoredTour.range.headOid,navigation:h,focusId:document.activeElement?.id,narrativeScroll:document.getElementById("tour-narrative")?.scrollTop||0})},u=window.setTimeout(()=>g(null),1e3);I.set(c,h=>{window.clearTimeout(u),g(h)}),T({type:"captureNavigationState",requestId:c})})}function N(r){let c=s.authoredTour;if(r===c.zoom.authoredDepth)return c;if(r==="final")return{...c,...c.zoom.final};let g=c.zoom.revisions;return{...c,scenes:g,chapters:[{id:"zoom-revisions",title:"Revisions",sceneIds:g.map(u=>u.id)}]}}function L(){let r=document.getElementById("tour-mode-controls");if(!r||(r.hidden=!s.zoom,!s.zoom))return;let c={explanation:"Explanation stages",revisions:"Revisions",final:"Final diff",history:"Git history"},g=document.getElementById("tour-mode-select");g.replaceChildren(...s.authoredTour.zoom.modes.map(h=>{let b=document.createElement("option");return b.value=h,b.textContent=c[h],b})),g.value=s.zoom.mode;let u=s.zoom.mode==="history";document.getElementById("tour-history-select").hidden=!u,document.getElementById("tour-history-label").hidden=!u,document.body.classList.toggle("tour-derived-mode",s.zoom.mode==="revisions"||s.zoom.mode==="history")}async function F(r,c){let g=await fetch(`/history/${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),u=await g.json();if(!g.ok)throw new Error(u.error||`History request failed (${g.status}).`);return u}async function U(r,c,g=!0){if(g){let b=await F("list",{path:r,commit:c});s.historyEntries=b.entries,c=b.selectedCommit,document.getElementById("tour-mode-status").textContent=b.fallback||"",document.getElementById("tour-history-select").replaceChildren(...b.entries.map(v=>{let S=document.createElement("option");return S.value=v.commit,S.textContent=`${v.shortCommit} ${v.summary}`,S}))}if(!c)throw new Error("No file history is available for this path.");let u=s.historyEntries.find(b=>b.commit===c),h=await F("diff",{path:u?.path||r,commit:c});s.historyCommit=c,document.getElementById("tour-history-select").value=c,fe({...h,kind:"text-diff",takeaway:"",focusChangeIndex:0},[],`history-${c}-${h.path}`)}async function J(r){if(!(!s.zoom||s.zoomSwitching||r===s.zoom.mode)){s.zoomSwitching=!0;try{let c=s.zoom.depart(await k());x.pauseForExternalOwner(),s.tour=N(r);let g=wn(c,s.tour.scenes,s.tour.files),u=s.zoom.enter(r,g);if(pt(),Ee(),L(),document.getElementById("tour-mode-status").textContent=g||u.restore?"":"No corresponding location; showing the first available change.",y=u.restore?u.location:null,r==="history")await U(u.location.path||s.tour.files.find(h=>h.kind==="text-diff")?.path,u.location.commit||c.commit);else{if(s.historyCommit=null,re(Math.max(0,u.location.sceneIndex),u.location.stepIndex,{zoomLanding:!0}),u.location.path&&s.activeTourFilePath!==u.location.path){let h=s.tour.files.findIndex(b=>b.path===u.location.path);h>=0&&Ke(h)}!u.restore&&u.location.line&&T({type:"revealSearchResult",lineNumber:u.location.line})}}catch(c){document.getElementById("tour-mode-status").textContent=c instanceof Error?c.message:String(c)}finally{s.zoomSwitching=!1}}}async function ne(r){if(!(!r||typeof r!="object")){if(r.type==="navigationState"){I.get(r.requestId)?.(r.navigation);return}if(r.type==="renderComplete"&&y){let c=y;y=null,T({type:"restoreNavigationState",navigation:c.navigation});let g=document.getElementById("tour-narrative");g&&(g.scrollTop=c.narrativeScroll||0),c.focusId&&c.focusId!=="tour-mode-select"&&document.getElementById(c.focusId)?.focus({preventScroll:!0})}if(r.type==="ready"){let c=new URLSearchParams(window.location.search),g=c.get("manifest");g?Rn(g):c.get("demo")==="1"&&$t();return}if(r.type==="navigateFile"&&s.mode==="tour"){_n(r.direction==="previous"?-1:1);return}if(r.type==="navigateTourStep"&&s.mode==="tour"){let c=r.sceneIndex,g=r.stepIndex;Number.isInteger(c)&&Number.isInteger(g)&&re(c,g,{userNavigation:!0});return}r.type==="recomputeDiff"&&s.mode==="diff"&&s.left&&s.right&&(s.left.content=r.leftContent,s.right.content=r.rightContent,T({type:"showDiff",file1:s.left.name,file2:s.right.name,comparisonId:`web-${s.comparisonId}`,leftContent:s.left.content,rightContent:s.right.content,diffModel:ae(s.left.content,s.right.content),history:null}))}}function Ie(){document.getElementById("tour-mode-select")?.addEventListener("change",C=>{J(C.target.value)}),document.getElementById("tour-history-select")?.addEventListener("change",C=>{E(),U(s.activeTourFilePath,C.target.value,!1).catch($=>{document.getElementById("tour-mode-status").textContent=$.message})});for(let C of["wheel","pointerdown","keydown"])document.addEventListener(C,$=>{!$.isTrusted||$.target?.closest?.("#tour-mode-controls")||$.target?.closest?.(".monaco-editor, .diff-toolbar, #tour-narrative")&&E()},{capture:!0,passive:!0});let r=document.getElementById("web-compare-test"),c=document.getElementById("web-open-diff"),g=document.getElementById("web-open-diff3"),u=document.getElementById("web-diff-input"),h=document.getElementById("web-diff3-input"),b=document.getElementById("tour-previous"),w=document.getElementById("tour-next"),v=document.getElementById("tour-return-focus"),S=document.getElementById("tour-search-input"),O=document.getElementById("tour-search-scope"),D=document.getElementById("tour-listen"),j=document.getElementById("tour-stop"),q=document.getElementById("tour-narration-skip-back"),B=document.getElementById("tour-narration-skip-ahead"),z=document.getElementById("tour-narration-voice"),H=document.getElementById("tour-narration-rate");$n(),Ln(),ve(),r?.addEventListener("click",()=>{$t()}),c?.addEventListener("click",()=>{u.value="",u.click()}),g?.addEventListener("click",()=>{h.value="",h.click()}),u?.addEventListener("change",async()=>{let C=Array.from(u.files||[]);if(C.length!==2){Q("Select exactly 2 files for a diff.");return}await zn(C)}),h?.addEventListener("change",async()=>{let C=Array.from(h.files||[]);if(C.length<1){Q("Select one or more files.");return}await Wn(C)}),b?.addEventListener("click",()=>Ce(-1)),w?.addEventListener("click",()=>Ce(1)),v?.addEventListener("click",On),S?.addEventListener("input",Ee),O?.addEventListener("change",Ee),D?.addEventListener("click",lt),j?.addEventListener("click",()=>x.stop()),q?.addEventListener("click",()=>x.skipSegment(-1)),B?.addEventListener("click",()=>x.skipSegment(1)),z?.addEventListener("change",()=>{s.narrationVoiceURI=z.value,window.localStorage.setItem(d,s.narrationVoiceURI)}),H&&(H.value=String(s.narrationRate),H.addEventListener("change",()=>{let C=Number(H.value);s.narrationRate=m.has(C)?C:1,H.value=String(s.narrationRate),window.localStorage.setItem(p,String(s.narrationRate))})),document.getElementById("tour-search-results")?.addEventListener("click",C=>{let $=C.target instanceof Element?C.target.closest("[data-tour-search-result]"):null;$&&Cn(Number($.getAttribute("data-tour-search-result")))}),window.addEventListener("keydown",C=>{if(s.mode==="tour"&&(C.metaKey||C.ctrlKey)&&C.shiftKey&&C.key.toLocaleLowerCase()==="f"){C.preventDefault(),C.stopImmediatePropagation(),s.tourSidebarHidden&&Ge(!1),S?.focus(),S?.select();return}s.mode!=="tour"||C.metaKey||C.ctrlKey||C.altKey||Un(C.target)||(C.key==="PageUp"||C.key==="ArrowLeft"?(C.preventDefault(),Ce(-1)):(C.key==="PageDown"||C.key==="ArrowRight")&&(C.preventDefault(),Ce(1)))},!0),window.addEventListener("bygone:tour-command",C=>{C.detail==="toggleNarration"&<(),C.detail==="pauseNarration"&&x.pauseForExternalOwner()}),window.addEventListener("beforeunload",()=>x.dispose(),{once:!0}),ze(x.state)}function ve(){let r=document.getElementById("tour-narration-voice"),c=document.getElementById("tour-listen");if(!f){c&&(c.disabled=!0,c.title="Device narration is not supported by this browser."),r&&(r.disabled=!0),le("Device narration unavailable");return}let g=()=>{if(s.narrationVoices=window.speechSynthesis.getVoices().slice().sort((u,h)=>Number(h.default)-Number(u.default)||u.lang.localeCompare(h.lang)||u.name.localeCompare(h.name)),s.narrationVoiceURI&&s.narrationVoices.length>0&&!s.narrationVoices.some(u=>u.voiceURI===s.narrationVoiceURI)&&(s.narrationVoiceURI="",window.localStorage.removeItem(d)),r){let u=document.createElement("option");u.value="",u.textContent="System default voice",r.replaceChildren(u,...s.narrationVoices.map(h=>{let b=document.createElement("option");return b.value=h.voiceURI,b.textContent=`${h.name} (${h.lang})${h.default?" \u2014 default":""}`,b})),r.value=s.narrationVoiceURI,r.disabled=s.narrationVoices.length===0}};g(),window.speechSynthesis.addEventListener("voiceschanged",g)}function yn(){let r=Number(window.localStorage.getItem(p));return m.has(r)?r:1}function xn(){let r=null;return{speak(c,g){if(!f){g.onError("Device narration is not supported by this browser.");return}let u=new window.SpeechSynthesisUtterance(c.speechText),h=s.narrationVoices.find(b=>b.voiceURI===s.narrationVoiceURI);h&&(u.voice=h),u.rate=s.narrationRate,u.onend=()=>{r===u&&(r=null),g.onEnd()},u.onerror=b=>{r===u&&(r=null),g.onError(Sn(b.error))},r=u,window.speechSynthesis.speak(u)},pause(){f&&window.speechSynthesis.pause()},resume(){f&&window.speechSynthesis.resume()},cancel(){r=null,f&&window.speechSynthesis.cancel()}}}function Sn(r){return r==="not-allowed"?"Device narration needs permission to play audio.":r==="language-unavailable"||r==="voice-unavailable"?"The selected device voice is unavailable.":`Device narration failed${r?`: ${r}`:"."}`}function In(){if(!f||s.mode!=="tour")return;let r=dt("playback-start");r&&(s.renderedNarrationUnit=r,Bn(r),x.start(r,!0))}function lt(){x.state.kind==="playing"||x.state.kind==="paused"?x.togglePause():In()}function dt(r){return!s.tour||s.activeSceneIndex<0?null:dn(s.tour,{sceneIndex:s.activeSceneIndex,stepIndex:s.activeStepIndex},{entry:r})}function vn(r,c){let g=s.tour;return!!(g&&Pe(g.scenes,r.position,c))}function En(r,c){let g=s.tour;if(!g)return null;let u=Pe(g.scenes,r.position,c);return u?re(u.sceneIndex,u.stepIndex,{narrationNavigation:"controller",narrationEntry:"continuous"}):null}function kn(){fetch("/narration/claim",{method:"POST",cache:"no-store"}).catch(()=>{})}function ze(r){let c=document.getElementById("tour-listen"),g=document.getElementById("tour-stop"),u=document.getElementById("tour-narration-skip-back"),h=document.getElementById("tour-narration-skip-ahead");if(c){c.disabled=!f||s.mode!=="tour";let b=r.kind==="playing";c.querySelector(".tour-play-pause-icon")?.setAttribute("d",b?"M7 5h4v14H7zM13 5h4v14h-4z":"m8 5 11 7-11 7Z");let w=b?"Pause narration":r.kind==="paused"?"Resume narration":"Listen from the current tour item";c.title=w,c.setAttribute("aria-label",w)}if(g&&(g.disabled=r.kind!=="playing"&&r.kind!=="paused"),u&&(u.disabled=!x.canSkipSegment(-1)),h&&(h.disabled=!x.canSkipSegment(1)),r.kind==="playing"||r.kind==="paused"){let b=r.segmentIndex+1,w=r.unit.segments.length;le(`${r.kind==="paused"?"Paused":"Speaking"} \xB7 segment ${b} of ${w}`)}else r.kind==="completed"?le("Narration complete"):r.kind==="error"?le(r.message):f&&le("Device voice ready")}function le(r){let c=document.getElementById("tour-narration-status");c&&(c.textContent=r)}function Tn(r,c){if(document.querySelectorAll(".tour-narration-segment.is-speaking").forEach(w=>{w.classList.remove("is-speaking","is-paused")}),!r)return;let g=[...document.querySelectorAll("[data-narration-segment-id]")].find(w=>w.dataset.narrationSegmentId===r.id);if(!g)return;g.classList.add("is-speaking"),g.classList.toggle("is-paused",c);let u=document.getElementById("tour-narrative");if(!u)return;let h=g.getBoundingClientRect(),b=u.getBoundingClientRect();(h.top<b.top||h.bottom>b.bottom)&&g.scrollIntoView({block:"nearest"})}let de=[];function Ee(){let r=document.getElementById("tour-search-input"),c=document.getElementById("tour-search-scope"),g=document.getElementById("tour-search-status"),u=document.getElementById("tour-search-results");if(!(!s.tour||!r||!c||!g||!u)){if(de=hn(s.tour,r.value,c.value),!r.value.trim()){g.textContent="Cmd/Ctrl+Shift+F",u.replaceChildren();return}g.textContent=`${de.length} result${de.length===1?"":"s"}`,u.replaceChildren(...de.map((h,b)=>{let w=document.createElement("button");w.type="button",w.className="tour-search-result",w.setAttribute("role","option"),w.dataset.tourSearchResult=String(b),w.title=`Open ${h.kind==="code"?`${h.label}:${h.lineNumber}`:h.label}`;let v=document.createElement("span");v.className="tour-search-location",v.textContent=h.kind==="code"?`${h.label}:${h.lineNumber}`:h.label;let S=document.createElement("span");return S.className="tour-search-preview",S.textContent=h.preview.trim(),w.append(v,S),w}))}}function Cn(r){let c=de[r];if(c){if(c.kind==="narrative"){E(),re(c.sceneIndex,c.stepIndex??0);return}St(c.fileIndex)&&window.requestAnimationFrame(()=>T({type:"revealSearchResult",sideIndex:c.sideIndex,lineNumber:c.lineNumber,startColumn:c.startColumn,endColumn:c.endColumn}))}}function $n(){let r=document.getElementById("tour-shell"),c=document.getElementById("tour-sidebar-resizer"),g=document.getElementById("tour-sidebar-hide"),u=document.getElementById("tour-sidebar-show");!r||!c||!g||!u||(ht(),g.addEventListener("click",()=>Ge(!0)),u.addEventListener("click",()=>Ge(!1)),c.addEventListener("pointerdown",h=>{h.preventDefault(),document.body.classList.add("is-resizing-tour-sidebar"),c.setPointerCapture?.(h.pointerId);let b=v=>ft(v.clientX),w=()=>{document.body.classList.remove("is-resizing-tour-sidebar"),window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",w),window.removeEventListener("pointercancel",w),window.localStorage.setItem(t,String(s.tourSidebarWidth))};window.addEventListener("pointermove",b),window.addEventListener("pointerup",w),window.addEventListener("pointercancel",w)}),c.addEventListener("keydown",h=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(h.key))return;h.preventDefault();let b=s.tourSidebarWidth;h.key==="Home"?b=240:h.key==="End"?b=We():b+=h.key==="ArrowLeft"?-16:16,ft(b),window.localStorage.setItem(t,String(s.tourSidebarWidth))}))}function Nn(){let r=Number.parseInt(window.localStorage.getItem(t)||"",10);return Number.isFinite(r)?Math.min(600,Math.max(240,r)):360}function We(){return Math.max(240,Math.min(600,Math.floor(window.innerWidth*.6)))}function ft(r){s.tourSidebarWidth=Math.min(We(),Math.max(240,Math.round(r))),ht(),window.dispatchEvent(new Event("resize"))}function ht(){document.documentElement.style.setProperty("--tour-rail-width",`${s.tourSidebarWidth}px`);let r=document.getElementById("tour-sidebar-resizer");r?.setAttribute("aria-valuemax",String(We())),r?.setAttribute("aria-valuenow",String(s.tourSidebarWidth))}function Ge(r){s.tourSidebarHidden=r,document.body.classList.toggle("tour-sidebar-hidden",r);let c=document.getElementById("tour-sidebar-show");c&&(c.hidden=!r),window.dispatchEvent(new Event("resize"))}function Ln(){let r=document.getElementById("tour-narrative-resizer");r&&(qe(),r.addEventListener("pointerdown",c=>{c.preventDefault(),document.body.classList.add("is-resizing-tour-narrative"),r.setPointerCapture?.(c.pointerId),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-start"));let g=document.getElementById("tour-narrative")?.getBoundingClientRect().top||0,u=b=>gt(b.clientY-g),h=()=>{document.body.classList.remove("is-resizing-tour-narrative"),window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",h),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-end")),mt()};window.addEventListener("pointermove",u),window.addEventListener("pointerup",h),window.addEventListener("pointercancel",h)}),r.addEventListener("keydown",c=>{if(!["ArrowUp","ArrowDown","Home","End"].includes(c.key))return;c.preventDefault();let g=c.key==="Home"?180:c.key==="End"?ke():s.tourNarrativeHeight+(c.key==="ArrowUp"?-16:16);gt(g),mt()}),window.addEventListener("resize",()=>{s.tourNarrativeHeight=Math.min(ke(),s.tourNarrativeHeight),qe()}))}function An(){let r=Number.parseInt(window.localStorage.getItem(o)||"",10);if(Number.isFinite(r))return Math.max(180,r);let c=Number.parseInt(window.getComputedStyle(document.documentElement).getPropertyValue("--tour-narrative-height"),10);return Number.isFinite(c)?c:296}function ke(){let r=document.getElementById("tour-narrative")?.getBoundingClientRect().top||0;return Math.max(180,window.innerHeight-r-180)}function gt(r){s.tourNarrativeHeight=Math.min(ke(),Math.max(180,Math.round(r))),qe(),window.dispatchEvent(new Event("resize"))}function qe(){document.documentElement.style.setProperty("--tour-narrative-height",`${s.tourNarrativeHeight}px`);let r=document.getElementById("tour-narrative-resizer");r?.setAttribute("aria-valuemax",String(ke())),r?.setAttribute("aria-valuenow",String(s.tourNarrativeHeight))}function mt(){window.localStorage.setItem(o,String(s.tourNarrativeHeight))}async function Rn(r){Q("Loading change tour\u2026");try{x.stop();let c=await fetch(r,{cache:"no-store"});if(!c.ok)throw new Error(`Manifest request failed (${c.status}).`);s.tour=rn(await c.json()),s.authoredTour=s.tour,s.zoom=s.tour.version===2?new He(s.tour.zoom.authoredDepth):null,s.mode="tour",document.body.classList.add("tour-mode"),pt(),L(),Ee();let g=new URLSearchParams(window.location.search),u=cn(s.tour.scenes,g.get("scene"),g.get("step"));re(u.sceneIndex,u.stepIndex),ze(x.state),Q("")}catch(c){Q(`Could not load change tour: ${c instanceof Error?c.message:String(c)}`)}}function pt(){let r=s.tour;if(!r)return;let c=document.getElementById("tour-shell"),g=document.getElementById("tour-title"),u=document.getElementById("tour-source"),h=document.getElementById("tour-range"),b=document.getElementById("tour-stats"),w=document.getElementById("tour-authoring-coverage"),v=document.getElementById("tour-scenes"),S=document.getElementById("tour-scene-count"),O=document.getElementById("tour-files"),D=document.getElementById("tour-file-count"),j=document.getElementById("tour-commits"),q=document.getElementById("tour-commits-summary");if(!c||!g||!u||!h||!b||!w||!v||!S||!O||!D||!j||!q)throw new Error("Presenter UI is incomplete.");c.hidden=!1,g.textContent=r.title,document.title=bn(r),r.sourceUrl?(u.href=r.sourceUrl,u.hidden=!1):(u.removeAttribute("href"),u.hidden=!0);let B=Ne(r.range.baseRef),z=Ne(r.range.headRef),H=r.range.headOid.slice(0,7);h.textContent=`${B} \u2192 ${z}${z===H?"":` \xB7 ${H}`}`,b.textContent=`${ce(r.summary.changedFiles,"file")} \xB7 +${r.summary.additions} \u2212${r.summary.deletions} \xB7 ${ce(r.summary.commitCount,"commit")}`,Mn(w,r.authoringCoverage),S.textContent=String(r.scenes.length),D.textContent=String(r.files.length),q.textContent=ce(r.summary.commitCount,"commit"),v.replaceChildren();let C=new Map(r.scenes.map($=>[$.id,$]));for(let $ of r.chapters){let K=document.createElement("h2");K.className="tour-chapter-title",K.textContent=$.title,v.append(K);for(let _ of $.sceneIds){let P=C.get(_);if(!P)continue;let V=r.scenes.indexOf(P),W=document.createElement("button");W.type="button",W.className="tour-scene",W.dataset.sceneId=P.id,P.kind==="text-diff"&&(W.dataset.filePath=P.path),W.title=`Open scene: ${P.kind==="text-diff"?P.path:P.title}`,W.addEventListener("click",()=>re(V,0,{userNavigation:!0}));let oe=document.createElement("span");oe.className="tour-scene-number",oe.textContent=String(V+1).padStart(2,"0");let Ye=document.createElement("span");Ye.className="tour-scene-copy";for(let[Gn,qn]of[["tour-scene-title",P.title],["tour-scene-path",P.kind==="text-diff"?P.path:P.kind==="deconstructed-diff"?`${ce(P.panels.length-1,"comparison stage")} \xB7 ${ce(P.steps.length,"tour slide")}`:ge(P)?ce(P.steps.length,"code step"):"Discussion"],["tour-scene-note",P.takeaway]]){let Je=document.createElement("span");Je.className=Gn,Je.textContent=qn,Ye.append(Je)}W.append(oe,Ye),v.append(W)}}O.replaceChildren(...r.files.map(($,K)=>{let _=document.createElement("button");_.type="button",_.className=`tour-file${$.kind==="omitted"?" is-omitted":""}`,_.dataset.filePath=$.path,_.disabled=$.kind==="omitted",_.title=$.kind==="omitted"?`${$.path}: ${$.reason}`:`Open file: ${$.path}`,$.kind==="text-diff"&&_.addEventListener("click",()=>Ke(K));let P=document.createElement("span");P.className="tour-file-marker",P.textContent=$.kind==="omitted"?"\xD7":It($.changeKind);let V=document.createElement("span");V.className="tour-file-copy";let W=document.createElement("span");W.className="tour-file-path",W.textContent=$.path;let oe=document.createElement("span");return oe.className="tour-file-meta",oe.textContent=$.kind==="omitted"?`Not rendered \xB7 ${$.reason}`:`${vt($.changeKind)} \xB7 +${$.additions} \u2212${$.deletions}`,V.append(W,oe),_.append(P,V),_})),j.replaceChildren(...r.commits.map($=>{let K=document.createElement("li"),_=document.createElement("span");return _.className="tour-commit-oid",_.textContent=$.shortOid,K.append(_,document.createTextNode($.summary)),K}))}function Mn(r,c){if(r.replaceChildren(),r.hidden=!c,!c)return;let g=[{metric:"walkthrough",label:c.walkthrough.scope==="final"?"Final walkthrough":"Walkthrough",covered:c.walkthrough.coveredUnits,total:c.walkthrough.includedUnits,percent:c.walkthrough.coveragePercent,description:"Distinct change hunks referenced by authored focus anchors."},...c.explanationAssignments.map(u=>({metric:"assignment",label:c.explanationAssignments.length>1?`Explanation assignment \xB7 ${u.sceneId}`:"Explanation assignment",covered:u.completeUnits,total:u.totalUnits,percent:u.assignmentPercent,description:`${u.assignedUnits} assigned, ${u.excludedUnits} explicitly excluded.`}))];for(let u of g){let h=document.createElement("div");h.className="tour-coverage-item",h.dataset.metric=u.metric,h.title=u.description;let b=document.createElement("div");b.className="tour-coverage-heading";let w=document.createElement("span");w.textContent=u.label;let v=document.createElement("strong");v.textContent=`${u.covered}/${u.total} \xB7 ${u.percent}%`,b.append(w,v);let S=document.createElement("div");S.className="tour-coverage-meter",S.setAttribute("role","progressbar"),S.setAttribute("aria-label",u.label),S.setAttribute("aria-valuemin","0"),S.setAttribute("aria-valuemax","100"),S.setAttribute("aria-valuenow",String(u.percent));let O=document.createElement("span");O.style.width=`${u.percent}%`,S.append(O),h.append(b,S),r.append(h)}}function re(r,c=0,g={}){let u=s.tour;if(!u||r<0||r>=u.scenes.length)return null;if(g.userNavigation&&E(),s.zoom?.mode==="history"&&!s.zoomSwitching){let S=u.scenes[r],O=S.path||S.steps?.[c]?.file||s.activeTourFilePath;return U(O,s.historyCommit).catch(D=>{document.getElementById("tour-mode-status").textContent=D.message}),null}let h=u.scenes[r];s.activeSceneIndex=r,s.activeStepIndex=ge(h)?Math.min(Math.max(c,0),Math.max(h.steps.length-1,0)):0,s.tourFocusFilePath=h.kind==="text-diff"?h.path:h.kind==="walkthrough"?h.steps[s.activeStepIndex]?.diff.path??null:ie(h)?h.steps[s.activeStepIndex]?.file??null:null;let b=Et(u,r);document.querySelectorAll(".tour-scene").forEach(S=>{S.classList.toggle("is-active",S.dataset.sceneId===h.id)}),document.querySelector(`.tour-scene[data-scene-id="${h.id}"]`)?.scrollIntoView({block:"nearest"});let w=dt(g.narrationEntry||"playback-start");s.renderedNarrationUnit=w,Tt(h,b,w),w&&!g.zoomLanding&&(!s.zoom||s.zoom.mode===s.authoredTour.zoom.authoredDepth||s.zoom.mode==="final")&&(g.narrationNavigation==="linear"?x.followLinearNavigation(w):g.narrationNavigation!=="controller"&&x.followDirectNavigation(w));let v=new URLSearchParams(window.location.search);return v.set("scene",h.id),ge(h)?v.set("step",h.steps[s.activeStepIndex].id):v.delete("step"),window.history.replaceState(null,"",`${window.location.pathname}?${v.toString()}`),h.kind==="discussion"?(document.body.classList.add("tour-discussion"),Ze(),w):(document.body.classList.remove("tour-discussion"),h.kind==="walkthrough"?(wt(h),w):ie(h)?(yt(h),w):(fe(h,Te(h.path)),w))}function Te(r){let c=s.tour;return!c||!r?[]:mn(c,r,s.activeSceneIndex,s.activeStepIndex)}function Fn(r,c){let g=s.tour;return!g||!r?[]:pn(g,r,s.activeSceneIndex,s.activeStepIndex,(u,h)=>gn(c?.[u]?.diffModel,h))}function je(r){return`file::${r}`}function fe(r,c=[],g=je(r.path)){if(!s.tour)return;s.activeTourFilePath=r.path,Ze();let h=ae(r.leftContent,r.rightContent),b=bt(r,r.leftLabel,"base"),w=bt(r,r.rightLabel,"head"),v=c.find(S=>S.active);T({type:"showDiff",file1:b,file2:w,comparisonId:`tour-${g}`,leftContent:r.leftContent,rightContent:r.rightContent,sourceInfo:{leftPath:r.path,rightPath:r.path},diffModel:h,history:null,fileNavigation:{canGoPrevious:!!he(-1),canGoNext:!!he(1)},editableSides:{left:!1,right:!1},comparisonSummary:`${r.path} \xB7 ${r.takeaway}`,initialChangeIndex:v?kt(h,v.side,v.startLine):r.focusChangeIndex,tourAnnotations:c})}function bt(r,c,g){let u=c.startsWith(r.path)?c.slice(r.path.length).trim():c.trim();return u?`${g} ${u}`:g}function wt(r){let c=r.steps[s.activeStepIndex];c&&fe(c.diff,Te(c.diff.path),je(c.diff.path))}function yt(r){let c=r.steps[s.activeStepIndex];c&&xt(r,c.file,c)}function xt(r,c,g){let u=$e(r,c);if(!g||!u)return;s.activeTourFilePath=u.path,Ze();let h=u.panels.map((B,z)=>({id:`${r.id}-${u.path}-${B.id}`,label:B.label,path:B.path||u.path,content:B.content,savedContent:B.content,dirty:!1,editable:!1,stackId:Xe(r)[z].id})),b=h.slice(0,-1).map((B,z)=>({leftIndex:z,rightIndex:z+1,diffModel:ae(B.content,h[z+1].content)})),w=Fn(u.path,b),v=w.find(B=>B.active),S=v?.pairIndex??g.pairIndex,O=v?.side??g.side,D=v?.startLine??g.startLine,j=b[S]?.diffModel,q=j&&D?kt(j,O,D):0;T({type:"showMultiDiff",panels:h,pairs:b,activePanelId:h[S+(O==="right"?1:0)]?.id,activePairIndex:S,initialChangeIndex:q,revealFirstChangeInEachPanel:r.kind==="deconstructed-diff",history:null,fileNavigation:{canGoPrevious:!!he(-1),canGoNext:!!he(1)},mutationEnabled:!1,comparisonSummary:r.kind==="deconstructed-diff"?`${r.stageLabel} \xB7 ${u.path} \xB7 ${Ne(r.realRange.baseRef)} \u2192 ${Ne(r.realRange.targetRef)}`:`${u.path} \xB7 ${r.takeaway}`,tourAnnotations:w})}function Ve(r){let c=s.tour;return!c||r!==-1&&r!==1?null:Pe(c.scenes,{sceneIndex:s.activeSceneIndex,stepIndex:s.activeStepIndex},r)}function Ce(r){let c=Ve(r);return c?(re(c.sceneIndex,c.stepIndex,{userNavigation:!0,narrationNavigation:"linear",narrationEntry:"playback-start"}),!0):!1}function he(r){let c=s.tour;if(!c||r!==-1&&r!==1)return null;let g=c.scenes[s.activeSceneIndex];if(ie(g)){let u=g.steps[s.activeStepIndex]?.pairIndex;if(!Number.isInteger(u))return null;let h=c.files.flatMap(v=>{if(v.kind!=="text-diff")return[];let S=$e(g,v.path);return S?[S]:[]}),b=an(h,u,s.activeTourFilePath,r);if(!b)return null;let w=c.files.findIndex(v=>v.kind==="text-diff"&&v.path===b.path);return w>=0?{fileIndex:w,path:b.path}:null}return un(c.files,s.activeTourFilePath,r)}function _n(r){let c=he(r);return c?Ke(c.fileIndex):!1}function St(r,c=!0){let g=s.tour?.files[r];return!g||g.kind!=="text-diff"?!1:(c&&x.interruptForExploration(),fe(g,Te(g.path),je(g.path)),!0)}function Ke(r){let c=s.tour?.files[r];if(!c||c.kind!=="text-diff")return!1;if(E(),s.zoom?.mode==="history")return U(c.path,s.historyCommit).catch(u=>{document.getElementById("tour-mode-status").textContent=u.message}),!0;s.zoomSwitching||x.interruptForExploration();let g=s.tour?.scenes[s.activeSceneIndex];if(ie(g)){let u=g.steps[s.activeStepIndex];return u&&$e(g,c.path)?(xt(g,c.path,u),!0):!1}return St(r,!1)}function $e(r,c){let g=r?.files?.find(b=>b.path===c);if(g||r?.kind!=="deconstructed-diff")return g;let u=s.tour?.files.find(b=>b.kind==="text-diff"&&b.path===c);if(!u||u.kind!=="text-diff")return null;let h=u.changeKind!=="deleted";return{path:u.path,panels:Xe(r).map(b=>({id:b.id,label:`${b.label} / ${u.path}${h?"":" (absent)"}`,path:h?u.path:void 0,content:h?u.rightContent:"",exists:h}))}}function On(){let r=s.tour?.scenes[s.activeSceneIndex];if(!r||!s.tourFocusFilePath)return!1;if(r.kind==="walkthrough")wt(r);else if(ie(r))yt(r);else if(r.kind==="text-diff")fe(r,Te(r.path));else return!1;return!0}function Ze(){let r=s.tour?.scenes[s.activeSceneIndex],c=ie(r)?r.steps[s.activeStepIndex]:null;document.querySelectorAll(".tour-file").forEach(u=>{let h=u.dataset.filePath;u.classList.toggle("is-active",h===s.activeTourFilePath),u.classList.toggle("is-tour-focus",h===s.tourFocusFilePath),u.classList.remove("is-comparison-changed","is-comparison-empty"),delete u.dataset.comparisonState;let b=s.tour?.files.find(S=>S.path===h),w=u.querySelector(".tour-file-marker"),v=u.querySelector(".tour-file-meta");if(c&&b?.kind==="text-diff"){let S=$e(r,h);if(S){let O=ct(S,c.pairIndex),D=Dn(O);u.dataset.comparisonState=O,u.classList.add(D.changed?"is-comparison-changed":"is-comparison-empty"),u.setAttribute("title",`${b.path} \xB7 ${D.label}`),u.setAttribute("aria-label",`${b.path}, ${D.label}`),w&&(w.textContent=D.marker),v&&(v.textContent=D.label);return}}if(b){let S=b.kind==="omitted"?`${b.path}: ${b.reason}`:`Open file: ${b.path}`;u.setAttribute("title",S),u.setAttribute("aria-label",S),w&&(w.textContent=b.kind==="omitted"?"\xD7":It(b.changeKind)),v&&(v.textContent=b.kind==="omitted"?`Not rendered \xB7 ${b.reason}`:`${vt(b.changeKind)} \xB7 +${b.additions} \u2212${b.deletions}`)}}),document.querySelector(".tour-file.is-active")?.scrollIntoView({block:"nearest"});let g=document.getElementById("tour-return-focus");if(g){let u=!s.zoom||s.zoom.mode===s.authoredTour.zoom.authoredDepth||s.zoom.mode==="final";g.hidden=!u||!s.tourFocusFilePath||s.activeTourFilePath===s.tourFocusFilePath}}function Dn(r){return{"modified-here":{label:"Modified here",marker:"\u2022",changed:!0},"created-here":{label:"Created here",marker:"+",changed:!0},"deleted-here":{label:"Deleted here",marker:"\u2212",changed:!0},"unchanged-here":{label:"Unchanged here",marker:"\u25CB",changed:!1},"not-created-yet":{label:"Not created yet",marker:"\u2026",changed:!1},"already-deleted":{label:"Already deleted",marker:"\xD7",changed:!1}}[r]}function ge(r){return r.kind==="walkthrough"||r.kind==="stacked-diff"||r.kind==="deconstructed-diff"}function ie(r){return r?.kind==="stacked-diff"||r?.kind==="deconstructed-diff"}function Xe(r){return r.kind==="deconstructed-diff"?r.panels:r.stack}function It(r){return{added:"+",deleted:"\u2212",renamed:"\u2192",modified:"\u2022"}[r]||"\u2022"}function vt(r){return`${r.charAt(0).toUpperCase()}${r.slice(1)}`}function Et(r,c){let g=r.scenes[c],u=r.chapters.findIndex(v=>v.sceneIds.includes(g.id)),h=u>=0?r.chapters[u]:null,b=h?h.sceneIds.indexOf(g.id)+1:c+1,w=h?h.sceneIds.length:r.scenes.length;return{chapter:h,chapterIndex:u,chapterNumber:u>=0?u+1:c+1,sceneInChapter:b,scenesInChapter:w}}function Pn(r,c,g){let u=[`Ch ${r.chapterNumber}`,`Scene ${r.sceneInChapter}/${r.scenesInChapter}`];return ge(c)&&u.push(`Step ${g+1}/${c.steps.length}`),u.join(" \xB7 ")}function kt(r,c,g){let h=(c==="left"?r.leftLines:r.rightLines).findIndex(D=>D.lineNumber===g);if(h<0)return 0;let b=c==="left"?"leftStart":"rightStart",w=c==="left"?"leftEnd":"rightEnd",v=r.blocks.findIndex(D=>h>=D[b]&&h<D[w]);if(v>=0)return v;let S=0,O=Number.POSITIVE_INFINITY;return r.blocks.forEach((D,j)=>{let q=Math.min(Math.abs(h-D[b]),Math.abs(h-D[w]));q<O&&(S=j,O=q)}),S}function Ne(r){return/^[0-9a-f]{40}$/i.test(r)?r.slice(0,7):r}function ce(r,c){return`${r} ${r===1?c:`${c}s`}`}function Un(r){return r instanceof Element&&!!r.closest('a, button, input, select, summary, textarea, [contenteditable="true"], [role="textbox"], .monaco-editor')}function Bn(r){let c=s.tour?.scenes[s.activeSceneIndex];!s.tour||!c||Tt(c,Et(s.tour,s.activeSceneIndex),r)}function Tt(r,c,g){let u=document.getElementById("tour-narrative"),h=document.getElementById("tour-breadcrumb"),b=document.getElementById("tour-narrative-chapter"),w=document.getElementById("tour-narrative-title"),v=document.getElementById("tour-narrative-summary"),S=document.getElementById("tour-narrative-bullets"),O=document.getElementById("tour-narrative-tags"),D=document.getElementById("tour-narrative-takeaway"),j=document.getElementById("tour-step"),q=document.getElementById("tour-step-title"),B=document.getElementById("tour-step-body"),z=document.getElementById("tour-step-requirement"),H=document.getElementById("tour-connection"),C=document.getElementById("tour-previous"),$=document.getElementById("tour-next");if(!u||!h||!b||!w||!v||!S||!O||!D||!j||!q||!B||!z||!H||!C||!$)throw new Error("Tour narrative UI is incomplete.");u.hidden=!1,h.textContent=Pn(c,r,s.activeStepIndex);let K=c.chapter?.title||"Change tour";te(b,K,{field:"chapter"},g,{suffix:r.kind==="deconstructed-diff"?` \xB7 ${r.stageLabel}`:""}),te(w,r.title,{field:"scene-title"},g),te(v,r.summary,{field:"summary"},g),S.replaceChildren(...r.bullets.map((P,V)=>{let W=document.createElement("li");return te(W,P,{field:"bullet",itemIndex:V},g),W})),O.replaceChildren(...r.tags.map(P=>{let V=document.createElement("span");return V.textContent=P,V})),te(D,r.takeaway,{field:"takeaway"},g);let _=ge(r)?r.steps[s.activeStepIndex]:null;j.hidden=!_,_?(te(q,_.title,{field:"step-title"},g,{prefix:r.kind==="deconstructed-diff"?`Stage ${(_.stageIndex??_.pairIndex)+1}: `:""}),te(B,_.body,{field:"step-body"},g),Ct(z,"requirement"in _?_.requirement:null),"connection"in _&&_.connection?(H.hidden=!1,te(H,_.connection.label,{field:"connection"},g,{prefix:`${_.connection.from.path} \u2192 ${_.connection.to.path} \xB7 `})):(H.hidden=!0,H.textContent="")):(q.textContent="",B.textContent="",Ct(z,null),H.hidden=!0,H.textContent=""),C.disabled=!Ve(-1),$.disabled=!Ve(1)}function Hn(r){let c=[];return r.source&&c.push(r.source),r.confidence&&c.push(`${r.confidence} confidence`),c.join(" \xB7 ")}function Ct(r,c){if(!c){r.hidden=!0,r.replaceChildren(),r.removeAttribute("title");return}let g=document.createElement("span");g.className="tour-requirement-chip",g.dataset.status=c.status||"unspecified",g.textContent=c.status?`${c.id} \xB7 ${c.status}`:c.id;let u=document.createElement("span");u.className="tour-requirement-text",u.textContent=c.text;let h=[g,u],b=Hn(c);if(b){let w=document.createElement("span");w.className="tour-requirement-meta",w.textContent=b,h.push(w)}r.replaceChildren(...h),r.title=[`${c.id}: ${c.text}`,b].filter(Boolean).join(" \u2014 "),r.hidden=!1}function te(r,c,g,u,h={}){let b=u?.segments.filter(S=>S.source.field===g.field&&S.source.itemIndex===g.itemIndex)||[];if(b.length===0){r.textContent=`${h.prefix||""}${c}${h.suffix||""}`;return}let w=[];h.prefix&&w.push(document.createTextNode(h.prefix));let v=0;for(let S of b){S.startOffset>v&&w.push(document.createTextNode(c.slice(v,S.startOffset)));let O=document.createElement("span");O.className="tour-narration-segment",O.dataset.narrationSegmentId=S.id,O.textContent=c.slice(S.startOffset,S.endOffset),w.push(O),v=S.endOffset}v<c.length&&w.push(document.createTextNode(c.slice(v))),h.suffix&&w.push(document.createTextNode(h.suffix)),r.replaceChildren(...w)}function $t(){x.stop();let r=en();s.mode="diff",s.comparisonId+=1,s.left={name:r.leftFileName,content:r.leftContent},s.right={name:r.rightFileName,content:r.rightContent},Q("Loaded sample diff."),T({type:"showDiff",file1:s.left.name,file2:s.right.name,comparisonId:`web-${s.comparisonId}`,leftContent:s.left.content,rightContent:s.right.content,diffModel:ae(s.left.content,s.right.content),history:null})}async function zn(r){x.stop();let[c,g]=r,[u,h]=await Promise.all([c.text(),g.text()]);s.mode="diff",s.comparisonId+=1,s.left={name:c.name,content:u},s.right={name:g.name,content:h},Q(`Loaded ${c.name} and ${g.name}.`),T({type:"showDiff",file1:c.name,file2:g.name,comparisonId:`web-${s.comparisonId}`,leftContent:u,rightContent:h,diffModel:ae(u,h),history:null})}async function Wn(r){x.stop();let c=await Promise.all(r.map(async(g,u)=>{let h=await g.text();return{id:`web-panel-${u}`,label:g.name,content:h,savedContent:h,dirty:!1,editable:!0}}));s.mode="multi-diff",Q(`Loaded ${c.length}-panel diff for ${c.map(g=>g.label).join(", ")}.`),T({type:"showMultiDiff",panels:c,pairs:c.slice(0,-1).map((g,u)=>({leftIndex:u,rightIndex:u+1,diffModel:ae(g.content,c[u+1].content)}))})}function Q(r){let c=document.getElementById("web-status");c&&(c.textContent=r)}})();})();
|
|
151
151
|
//# sourceMappingURL=web-host.js.map
|