@withgraphite/graphite-cli 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@withgraphite/graphite-cli",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "license": "None",
5
5
  "main": "./graphite.js",
6
6
  "homepage": "https://github.com/withgraphite/graphite-cli",
package/60.js DELETED
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";exports.id=60,exports.ids=[60],exports.modules={33800:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.labelForComparison=t.ComparisonType=void 0,function(e){e.UncommittedChanges="UNCOMMITTED",e.HeadChanges="HEAD",e.StackChanges="STACK",e.Committed="InCommit",e.Commit="Commit",e.Range="Range"}(r=t.ComparisonType||(t.ComparisonType={})),t.labelForComparison=function(e){switch(e.type){case r.UncommittedChanges:return"Uncommitted changes";case r.HeadChanges:return"Changes in current commit";case r.StackChanges:return"Changes in current branch";case r.Committed:return`Changes in ${e.hash}`;case r.Commit:return`In ${e.sha}`;case r.Range:return`From ${e.fromSha} to ${e.toSha}`}}},2982:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cached=t.LRU=void 0;const n=r(30826);class s{constructor(e,t=3){this.maxItems=e,this.maxHashCollision=t,this.cache=new Map}get(e){let t;const r=i(e),s=this.cache.get(r);if(void 0!==s){const i=s.get(e);if(void 0!==i)t=i;else for(const[r,i]of s)if((0,n.is)(e,r)){t=i;break}this.cache.delete(r),this.cache.set(r,s)}return t}set(e,t){const r=i(e);let n=this.cache.get(r);if(void 0===n||n.size>=this.maxHashCollision?n=new Map([[e,t]]):n.set(e,t),this.cache.delete(r),void 0!==t&&(this.cache.set(r,n),this.cache.size>this.maxItems)){const e=this.cache.keys().next();e.done||this.cache.delete(e.value)}}delete(e){const t=i(e);this.cache.delete(t)}clear(){this.cache.clear()}}function i(e){const t=null==e?void 0:e.hashCode;return void 0!==t?t.apply(e):e}function o(e,t){var r,i;const o=null!==(r=null==t?void 0:t.cache)&&void 0!==r?r:new s(null!==(i=null==t?void 0:t.cacheSize)&&void 0!==i?i:10),a=null==t?void 0:t.getExtraKeys,l=function(...t){var r,s,i;const l=o.stats;if(!t.every(c))return null!=l&&(l.skip=(null!==(r=l.skip)&&void 0!==r?r:0)+1),e.apply(this,t);const u=(0,n.List)(a?[...a.apply(this),...t]:t),h=o.get(u);if(void 0!==h)return null!=l&&(l.hit=(null!==(s=l.hit)&&void 0!==s?s:0)+1),h;null!=l&&(l.miss=(null!==(i=l.miss)&&void 0!==i?i:0)+1);const d=e.apply(this,t);return o.set(u,d),d};return l.cache=o,l}t.LRU=s,t.cached=function(e,t){return"function"==typeof e?o(e,t):function(e){var t;const r=null!==(t=null==e?void 0:e.getExtraKeys)&&void 0!==t?t:function(){return(0,n.isValueObject)(this)?[this]:null!=this&&"object"==typeof this?Object.values(this).filter(c):[]};return function(t,n,s){const i=s.value;s.value=o(i,Object.assign(Object.assign({},e),{getExtraKeys:r}))}}(e)};const a=new Set(["number","string","boolean","symbol","bigint","undefined","null"]);function c(e){if(null==e)return!0;const t=typeof e;return!!a.has(t)||!("object"!==t||!(0,n.isValueObject)(e))}},61110:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5693:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),s(r(61110),t),s(r(52568),t),s(r(11268),t),s(r(66877),t)},52568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},11268:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Tracker=void 0;const n=r(48427);class s{constructor(e,t){this.sendData=e,this.context=t}error(e,t,r,n){const s=r instanceof Error?r.message||String(r):r;return this.track(e,Object.assign(Object.assign({},null!=n?n:{}),{errorMessage:s,errorName:t}))}operation(e,t,r,s){var i;const o=Date.now(),a=null!==(i=null==r?void 0:r.id)&&void 0!==i?i:(0,n.randomId)();try{const i=s({parentId:a});if((0,n.isPromise)(i))return i.then((t=>{const n=Date.now()-o;return this.track(e,Object.assign(Object.assign({},null!=r?r:{}),{duration:n,id:a})),t})).catch((n=>{const s=Date.now()-o;return this.error(e,t,n,Object.assign(Object.assign({},null!=r?r:{}),{duration:s,id:a})),Promise.reject(n)}));{const t=Date.now()-o;return this.track(e,Object.assign(Object.assign({},null!=r?r:{}),{duration:t,id:a})),i}}catch(n){const s=Date.now()-o;throw this.error(e,t,n,Object.assign(Object.assign({},null!=r?r:{}),{duration:s,id:a})),n}}trackAsParent(e,t){var r;const i=null!==(r=null==t?void 0:t.id)&&void 0!==r?r:(0,n.randomId)();return this.trackData(Object.assign(Object.assign({},t),{eventName:e,id:i})),new s(((e,t)=>this.trackData(Object.assign(Object.assign({},e),t))),{parentId:i})}track(e,t){return this.trackData(Object.assign(Object.assign({},t),{eventName:e}))}trackData(e){var t,r;const s=null!==(t=null==e?void 0:e.id)&&void 0!==t?t:(0,n.randomId)(),i=null!==(r=null==e?void 0:e.timestamp)&&void 0!==r?r:Date.now(),o=Object.assign({timestamp:i,id:s},null!=e?e:{});this.sendData(o,this.context)}}t.Tracker=s},66877:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},66960:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0,t.debounce=function(e,t,r=void 0,n=!1){let s,i=!0;function o(...a){let c;if(n){if(c=function(){i=!0,s=void 0},!i)return clearTimeout(s),void(s=setTimeout(c,t));i=!1,e.apply(r,a)}else o.reset(),c=function(){s=void 0,e.apply(r,a)};s=setTimeout(c,t)}return o.reset=function(){clearTimeout(s),s=void 0,i=!0},o.isPending=function(){return null!=s},o}},98696:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),s(r(5693),t),s(r(33800),t),s(r(66960),t),s(r(2982),t),s(r(75905),t),s(r(85249),t),s(r(40256),t),s(r(86099),t),s(r(66224),t),s(r(48427),t)},75905:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.parsePatch=t.DiffType=void 0,function(e){e.Modified="Modified",e.Added="Added",e.Removed="Removed",e.Renamed="Renamed",e.Copied="Copied"}(r=t.DiffType||(t.DiffType={}));const n=/^diff --git (.*) (.*)$/,s=/^rename from (.*)$/,i=/^rename to (.*)$/,o=/^copy from (.*)$/,a=/^copy to (.*)$/,c=/^new file mode (\d{6})$/,l=/^deleted file mode (\d{6})$/,u=/^old mode (\d{6})$/,h=/^new mode (\d{6})$/,d=/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/,m=/^--- (.*)$/,p=/^\+\+\+ (.*)$/,g=/\r\n|[\n\v\f\r\x85]/g;function f(e,t){if(!1===e)throw new Error(t)}t.parsePatch=function(e){const t=e.split(g),v=e.match(g)||[],y=[];let C=0;function b(){const e={hunks:[]};for(y.push(e),function(e){for(;C<t.length;){const r=t[C],s=n.exec(r);if(s){e.oldFileName=s[1],e.newFileName=s[2],C++;break}C++}}(e);C<t.length;){const r=t[C];if(/^old mode/.test(r))w(e);else if(/^new mode/.test(r))S(e);else if(/^deleted file mode/.test(r))O(e);else if(/^new file mode/.test(r))R(e);else if(/^copy /.test(r))E(e);else if(/^rename /.test(r))k(e);else{if(/^--- /.test(r)){M(e);break}if(/^diff --git/.test(r))break;C++}}!function(e){for(;C<t.length;){const r=t[C];if(n.test(r))break;/^@@/.test(r)?e.hunks.push(_()):C++}}(e)}function w(e){const n=u.exec(t[C]);f(null!==n,`invalid format '${t[C]}'`),e.oldMode=n[1],e.type=r.Modified,C++}function S(e){const n=h.exec(t[C]);f(null!==n,`invalid format '${t[C]}'`),e.newMode=n[1],e.type=r.Modified,C++}function O(e){const n=l.exec(t[C]);f(null!==n,`invalid format '${t[C]}'`),e.newMode=n[1],e.type=r.Removed,C++}function R(e){const n=c.exec(t[C]);f(null!==n,`invalid format '${t[C]}'`),e.newMode=n[1],e.type=r.Added,C++}function E(e){f(o.test(t[C]),`invalid format '${t[C]}'`),f(a.test(t[C+1]),`invalid format '${t[C+1]}'`),e.type=r.Copied,C+=2}function k(e){f(s.test(t[C]),`invalid format '${t[C]}'`),f(i.test(t[C+1]),`invalid format '${t[C+1]}'`),e.type=r.Renamed,C+=2}function M(e){f(m.test(t[C]),`invalid format '${t[C]}'`),f(p.test(t[C+1]),`invalid format '${t[C+1]}'`),void 0===e.type&&(e.type=r.Modified),C+=2}function _(){const e=t[C++].split(d),r={oldStart:+e[1],oldLines:void 0===e[2]?1:+e[2],newStart:+e[3],newLines:void 0===e[4]?1:+e[4],lines:[],linedelimiters:[]};0===r.oldLines&&(r.oldStart+=1),0===r.newLines&&(r.newStart+=1);let n=0,s=0;for(;C<t.length&&!(0===t[C].indexOf("--- ")&&C+2<t.length&&0===t[C+1].indexOf("+++ ")&&0===t[C+2].indexOf("@@"));C++){const e=0==t[C].length&&C!=t.length-1?" ":t[C][0];if("+"!==e&&"-"!==e&&" "!==e&&"\\"!==e)break;r.lines.push(t[C]),r.linedelimiters.push(v[C]||"\n"),"+"===e?n++:"-"===e?s++:" "===e&&(n++,s++)}return n||1!==r.newLines||(r.newLines=0),s||1!==r.oldLines||(r.oldLines=0),r}for(;C<t.length;)b();return y}},85249:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deserializeFromString=t.deserialize=t.serializeToString=t.serialize=void 0;const r={__rpcType:"undefined"};function n(e){if(void 0===e)return r;if("number"==typeof e||"boolean"==typeof e||"string"==typeof e||null===e)return e;if(e instanceof Map)return{__rpcType:"Map",data:Array.from(e.entries()).map((([e,t])=>[n(e),n(t)]))};if(e instanceof Set)return{__rpcType:"Set",data:Array.from(e.values()).map(n)};if(e instanceof Error)return{__rpcType:"Error",data:{message:e.message,stack:e.stack}};if(e instanceof Date)return{__rpcType:"Date",data:e.valueOf()};if(Array.isArray(e))return e.map((e=>n(e)));if("object"==typeof e){const t={__rpcType:"object"};for(const[r,s]of Object.entries(e))t[r]=n(s);return t}throw new Error(`cannot serialize argument ${e}`)}function s(e){if("object"!=typeof e||null==e)return e;if(Array.isArray(e))return e.map((e=>s(e)));const t=e;switch(t.__rpcType){case"undefined":return;case"Map":return new Map(t.data.map((([e,t])=>[s(e),s(t)])));case"Set":return new Set(t.data.map(s));case"Error":{const e=new Error;return e.stack=t.data.stack,e.message=t.data.message,e}case"Date":return new Date(t.data);case"object":{const t=e,r={};for(const[e,n]of Object.entries(t))"__rpcType"!==e&&(r[e]=s(n));return r}default:throw new Error(`cannot deserialize unknown type ${t}`)}}t.serialize=n,t.serializeToString=function(e){return JSON.stringify(n(e))},t.deserialize=s,t.deserializeFromString=function(e){return s(JSON.parse(e))}},40256:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},66224:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},50209:(e,t)=>{var r;Object.defineProperty(t,"__esModule",{value:!0}),t.SucceedableRevset=t.CommandRunner=void 0,(r=t.CommandRunner||(t.CommandRunner={})).Graphite="gt",r.CodeReviewProvider="codeReviewProvider",t.SucceedableRevset=function(e){return{type:"succeedable-revset",revset:e}}},74259:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},45852:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},1018:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorShortMessages=t.DEFAULT_DAYS_OF_COMMITS_TO_LOAD=t.ONE_MINUTE_MS=t.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE=void 0,t.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE=4100,t.ONE_MINUTE_MS=6e4,t.DEFAULT_DAYS_OF_COMMITS_TO_LOAD=void 0,(t.ErrorShortMessages||(t.ErrorShortMessages={})).NoCommitsFetched="No commits found"},29641:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},86099:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),s(r(50209),t),s(r(74259),t),s(r(45852),t),s(r(1018),t),s(r(29641),t),s(r(85119),t)},85119:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},48427:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPromise=t.truncate=t.zip=t.generatorContains=t.mapObject=t.findParentWithClassName=t.basename=t.defer=t.randomId=t.unwrap=t.notEmpty=void 0,t.notEmpty=function(e){return null!=e},t.unwrap=function(e){if(null==e)throw new Error(`expected value not to be ${e}`);return e},t.randomId=function(){return Date.now().toString(36)+Math.random().toString(36)},t.defer=function(){const e={promise:void 0,resolve:void 0,reject:void 0};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e},t.basename=function(e,t="/"){const r=e.lastIndexOf(t);return-1===r?e:e.slice(r+1)},t.findParentWithClassName=function(e,t){var r;let n=e;for(;n;){if(null===(r=n.classList)||void 0===r?void 0:r.contains(t))return n;n=n.parentElement}},t.mapObject=function(e,t){return Object.fromEntries(Object.entries(e).map(t))},t.generatorContains=function(e,t){const r="function"==typeof t?t:e=>e===t;for(const t of e)if(r(t))return!0;return!1},t.zip=function*(e,t){const r=e[Symbol.iterator](),n=t[Symbol.iterator]();for(;;){const e=r.next(),t=n.next();if(e.done||t.done)break;yield[e.value,t.value]}},t.truncate=function(e,t=100){return e.length>t?e.substring(0,Math.max(0,t-1))+"…":e},t.isPromise=function(e){return"function"==typeof(null==e?void 0:e.then)}},68060:(e,t,r)=>{r.r(t),r.d(t,{startServer:()=>te});var n=r(98696),s=r(57147),i=r.n(s),o=r(13685),a=r.n(o),c=r(71017),l=r.n(c),u=r(57310),h=r.n(u),d=r(95352),m=r.n(d),p=r(22037),g=r.n(p);function f(){try{return g().userInfo().username}catch(e){try{const{env:e}=process;return(0,n.unwrap)(e.LOGNAME||e.USER||e.LNAME||e.USERNAME)}catch(t){throw new Error(String(t)+String(e))}}}class v{logger;data;constructor(e,t){this.logger=e,this.data=t}setRepo(e){this.data.repo=e?.codeReviewProvider?.getSummaryName()}}const y=e=>{};var C=r(73837),b=r.n(C);const w=console;var S=r(34987),O=r.n(S),R=r(59778),E=r.n(R),k=r(82361);class M extends k.EventEmitter{}class _{codeReviewSystem;runCommand;constructor(e,t){this.codeReviewSystem=e,this.runCommand=t}diffSummaries=new M;onChangeDiffSummaries(e){const t=t=>e({value:t}),r=t=>e({error:t});return this.diffSummaries.on("data",t),this.diffSummaries.on("error",r),{dispose:()=>{this.diffSummaries.off("data",t),this.diffSummaries.off("error",r)}}}async triggerDiffSummariesFetch(e){const t=await this.runCommand(["internal-only","prs"]),r=JSON.parse(t.stdout);this.diffSummaries.emit("data",r)}dispose(){this.diffSummaries.removeAllListeners()}getSummaryName(){return`github:${this.codeReviewSystem.hostname}/${this.codeReviewSystem.owner}/${this.codeReviewSystem.repo}`}runExternalCommand(e,t,r,n){throw new Error("GitHub code review provider does not support running external commands")}async typeahead(e,t){return Promise.resolve([])}}class D{logger;runCallback;constructor(e,t){this.logger=e,this.runCallback=t}queuedOperations=[];runningOperation=void 0;abortController=void 0;async runOrQueueOperation(e,t,r,n){if(null!=this.runningOperation)return this.queuedOperations.push({...e,tracker:r}),void t({id:e.id,kind:"queue",queue:this.queuedOperations.map((e=>e.id))});this.runningOperation=e;const s=(...r)=>{switch(r[0]){case"spawn":t({id:e.id,kind:"spawn",queue:this.queuedOperations.map((e=>e.id))});break;case"stdout":t({id:e.id,kind:"stdout",message:r[1]});break;case"stderr":t({id:e.id,kind:"stderr",message:r[1]});break;case"exit":t({id:e.id,kind:"exit",exitCode:r[1],timestamp:Date.now()})}};try{const i=new AbortController;if(this.abortController=i,await r.operation(e.trackEventName,"RunOperationError",{extras:{args:e.args,runner:e.runner}},(t=>this.runCallback(e,n,s,i.signal))),this.runningOperation=void 0,this.queuedOperations.length>0){const e=this.queuedOperations.shift();null!=e&&this.runOrQueueOperation(e,t,e.tracker,n)}}catch(r){const n=r.toString();this.logger.log("error running operation: ",e.args[0],n),t({id:e.id,kind:"error",error:n}),this.queuedOperations=[],this.runningOperation=void 0}}abortRunningOperation(e){this.runningOperation?.id==e&&this.abortController?.abort()}}class T{focusedPages=new Set;visiblePages=new Set;onChangeHandlers=new Set;setState(e,t){switch(t){case"focused":this.focusedPages.add(e),this.visiblePages.add(e);break;case"visible":this.focusedPages.delete(e),this.visiblePages.add(e);break;case"hidden":this.focusedPages.delete(e),this.visiblePages.delete(e)}for(const e of this.onChangeHandlers)e(t)}disposePage(e){this.focusedPages.delete(e),this.visiblePages.delete(e)}hasPageWithFocus(){return this.focusedPages.size>0}hasVisiblePage(){return this.visiblePages.size>0}onChange(e){return this.onChangeHandlers.add(e),()=>this.onChangeHandlers.delete(e)}}class N{maxSimultaneousRunning;log;queued=[];running=[];runs=new M;constructor(e,t){this.maxSimultaneousRunning=e,this.log=t}nextId=1;generateId(){return this.nextId++}async enqueueRun(e){const t=this.generateId();this.queued.push(t),this.tryDequeueNext(),this.running.includes(t)||(this.log?.(`${this.running.length} tasks are already running, enqueuing ID:${t}`),await new Promise((e=>{this.runs.on("run",(r=>{r===t&&(this.log?.(`now allowing ID:${t} to run`),e(void 0))}))})));try{return await e()}finally{this.notifyFinished(t)}}notifyFinished(e){this.running=this.running.filter((t=>t!==e)),this.tryDequeueNext()}tryDequeueNext(){if(this.running.length<this.maxSimultaneousRunning){const e=this.queued.shift();null!=e&&this.run(e)}}run(e){this.running.push(e),this.runs.emit("run",e)}}function I(e){let t,r;const n=()=>{const t=e();return r=t.then((()=>r=void 0),(()=>r=void 0)),t},s=()=>(t=void 0,n());return()=>null==r?n():(()=>{if(null==t){if(null==r)throw new Error("pendingCall must not be null!");t=r.then(s,s)}return t})()}function P(e){switch(e.type){case n.ComparisonType.UncommittedChanges:return["uncommitted"];case n.ComparisonType.HeadChanges:return["head"];case n.ComparisonType.StackChanges:return["stack"];case n.ComparisonType.Committed:return["stack","--ref",e.hash];default:throw new Error("Unsupported comparison type: "+e.type)}}var j=r(44828);const F="1.0.14";class x{info;logger;IGNORE_COMMIT_MESSAGE_LINES_REGEX=/^((?:HG|SL):.*)/gm;mergeConflicts=void 0;uncommittedChanges=null;smartlogCommits=null;mergeConflictsEmitter=new M;uncommittedChangesEmitter=new M;smartlogCommitsChangesEmitter=new M;smartlogCommitsBeginFetchingEmitter=new M;uncommittedChangesBeginFetchingEmitter=new M;disposables=[()=>this.mergeConflictsEmitter.removeAllListeners(),()=>this.uncommittedChangesEmitter.removeAllListeners(),()=>this.smartlogCommitsChangesEmitter.removeAllListeners(),()=>this.smartlogCommitsBeginFetchingEmitter.removeAllListeners(),()=>this.uncommittedChangesBeginFetchingEmitter.removeAllListeners()];onDidDispose(e){this.disposables.push(e)}operationQueue;watchForChangesDisposer;pageFocusTracker=new T;codeReviewProvider;currentVisibleCommitRangeIndex=0;visibleCommitRanges=[n.DEFAULT_DAYS_OF_COMMITS_TO_LOAD,60,void 0];constructor(e,t){this.info=e,this.logger=t;const r=e.codeReviewSystem;"github"===r.type&&(this.codeReviewProvider=new _(r,this.runCommand.bind(this))),this.watchForChangesDisposer=function(e,t,r){if("success"!==e.type)return;const{repoRoot:n,dotdir:s}=e;if(null==n||null==s)return void t.error(`skipping chokidar subscription since ${n} is not a repository`);const i=j.watch(s,{cwd:s});i.on("ready",(()=>{r("everything")})),i.on("all",((e,t)=>{t.startsWith("rebase-merge")&&r("merge conflicts"),(t.startsWith("index")||t.startsWith("HEAD"))&&r("uncommitted changes"),(t.startsWith("refs/heads")||t.startsWith("refs/branch-metadata")||t.startsWith("HEAD"))&&r("branches")}));const o=l().relative(n,s),a=j.watch(n,{cwd:n,ignored:`${o}/**`});return a.on("all",(()=>{r("uncommitted changes")})),()=>{a.close().catch((()=>t.error(`failed to close chokidar worktree watcher for ${n}`))),i.close().catch((()=>t.error(`failed to close chokidar dotdir watcher for ${s}`)))}}(e,t,(e=>{"uncommitted changes"===e?(this.fetchUncommittedChanges(),this.checkForMergeConflicts()):"branches"===e?this.fetchSmartlogCommits():"merge conflicts"===e?this.checkForMergeConflicts():"everything"===e&&(this.fetchUncommittedChanges(),this.fetchSmartlogCommits(),this.checkForMergeConflicts())})),this.operationQueue=new D(this.logger,((e,t,r,s)=>{if(e.runner===n.CommandRunner.Graphite)return this.runOperation(e,r,t,s);if(e.runner===n.CommandRunner.CodeReviewProvider){const n=this.normalizeOperationArgs(t,e.args);return null==this.codeReviewProvider?.runExternalCommand?Promise.reject(Error("CodeReviewProvider does not support running external commands")):this.codeReviewProvider?.runExternalCommand(t,n,r,s)??Promise.resolve()}return Promise.resolve()}));const s=new Set,i=this.subscribeToSmartlogCommitsChanges((e=>{if(e.commits.value){const t=[],r=e.commits.value.filter((e=>e.pr)).map((e=>e.pr?.number));for(const e of r)s.has(e)||(t.push(e),s.add(e));t.length>0&&this.codeReviewProvider?.triggerDiffSummariesFetch(this.getAllDiffIds())}}));this.checkForMergeConflicts(),this.disposables.push((()=>i.dispose()))}nextVisibleCommitRangeInDays(){return this.currentVisibleCommitRangeIndex+1<this.visibleCommitRanges.length&&this.currentVisibleCommitRangeIndex++,this.visibleCommitRanges[this.currentVisibleCommitRangeIndex]}dispose(){this.disposables.forEach((e=>e())),this.codeReviewProvider?.dispose(),this.watchForChangesDisposer?.()}onChangeConflictState(e){return this.mergeConflictsEmitter.on("change",e),this.mergeConflicts&&e(this.mergeConflicts),{dispose:()=>this.mergeConflictsEmitter.off("change",e)}}checkForMergeConflicts=(0,n.debounce)(I((async()=>{this.logger.info("checking for merge conflicts");const e=null!=this.mergeConflicts;if(!e&&!await(t=l().join(this.info.dotdir,"rebase-merge"),i().promises.stat(t).then((()=>!0)).catch((e=>{if("ENOENT"===e.code)return!1;throw e}))))return void this.logger.info(`conflict state still the same (${e?"IN merge conflict":"NOT in conflict"})`);var t;null==this.mergeConflicts&&(this.mergeConflicts={state:"loading"},this.mergeConflictsEmitter.emit("change",this.mergeConflicts));const r=Date.now();let n;try{const e=await this.runCommand(["internal-only","status"]);n=JSON.parse(e.stdout)}catch(e){return this.logger.error(`failed to check for merge conflicts: ${e}`),this.mergeConflicts=void 0,void this.mergeConflictsEmitter.emit("change",this.mergeConflicts)}const s=await i().promises.readFile(l().join(this.info.dotdir,"rebase-merge","head-name")).then((e=>{const t=e.toString();return t.startsWith("refs/heads/")?t.slice(11).trimEnd():void 0}),(()=>{}));if(this.mergeConflicts=function(e,t,r,n){const s=r;if(!s?.conflicts||!t)return;const i=s.files.filter((e=>"UNRESOLVED"===e.status)),o={state:"loaded",branchName:t,files:[],fetchStartTimestamp:n,fetchCompletedTimestamp:Date.now()};if(null!=e?.files&&e.files.length>0){const t=new Set(i.map((e=>e.path)));o.files=e.files.map((e=>t.has(e.path)?{path:e.path,status:"UNRESOLVED"}:{path:e.path,status:"RESOLVED"}))}else o.files=i.map((e=>({path:e.path,status:"UNRESOLVED"})));return o}(this.mergeConflicts,s,n,r),this.logger.info(`repo ${this.mergeConflicts?"IS":"IS NOT"} in merge conflicts`,{mergeConflicts:this.mergeConflicts,files:this.mergeConflicts?.files}),this.mergeConflicts){const e=20,t=(this.mergeConflicts.files??[]).filter((e=>"UNRESOLVED"===e.status)).map((e=>e.path)).slice(0,e);this.logger.info("remaining files with conflicts: ",{branchName:s,remainingConflicts:t})}this.mergeConflictsEmitter.emit("change",this.mergeConflicts)})),100);getMergeConflicts(){return this.mergeConflicts}static async getRepoInfo(e,t,r){const n=await async function(e,t,r){try{return(await A({command:e,args:["--version"],logger:t,cwd:r})).stdout}catch(e){throw t.error(`Failed to find gt version in ${r}`,e),e}}(e,t,r).catch((e=>e));if(n instanceof Error)return{type:"invalidCommand",command:e??"gt"};if("local"!==n&&"dev"!==n&&E().lt(n,F))return{type:"invalidVersion",command:e??"gt",versionFound:n,versionRequired:F};const[s,i,o,a]=await Promise.all([$(e,t,r),L(e,t,r),U(e,t,r,"graphite.branch_edit").then((e=>e??"amend")),U(e,t,r,"graphite.create_prs_as").then((e=>e??"draft"))]);if(null==i)return{type:"cwdNotARepository",cwd:r};let c;if(void 0===i.remote)c={type:"none"};else{const{owner:e,name:t,hostname:r}=i.remote;c={type:"github",owner:e,repo:t,hostname:r}}const l={type:"success",command:e,dotdir:i.dotDir,repoRoot:i.rootDir,codeReviewSystem:c,preferredBranchEdit:o,createPrsAs:a,profile:s,trunkBranch:i.trunkBranch};return t.info("repo info: ",l),l}async runOrQueueOperation(e,t,r,n){await this.operationQueue.runOrQueueOperation(e,t,r,n)}abortRunningOpeation(e){this.operationQueue.abortRunningOperation(e)}normalizeOperationArgs(e,t){const r=(0,n.unwrap)(this.info.repoRoot);return t.map((t=>{if("object"==typeof t)switch(t.type){case"repo-relative-file":return l().normalize(l().relative(e,l().join(r,t.path)));case"succeedable-revset":return`max(successors(${t.revset}))`}return t}))}async runOperation(e,t,r,n){const s=this.normalizeOperationArgs(r,e.args),{stdin:i}=e,{command:o,args:a,options:c}=q(this.info.command,s,r,i?{input:i}:void 0);this.logger.log("run operation: ",o,s.join(" "));const l=O()(o,a,{...c,stdout:"pipe",stderr:"pipe"});t("spawn"),l.stdout?.on("data",(e=>{t("stdout",e.toString())})),l.stderr?.on("data",(e=>{t("stderr",e.toString())})),l.on("exit",(e=>{t("exit",e||0)})),n.addEventListener("abort",(()=>{this.logger.log("kill operation: ",o,s.join(" "))})),function(e,t){t.addEventListener("abort",(()=>{"win32"==g().platform()?e.kill("SIGKILL",{forceKillAfterTimeout:!1}):(e.kill("SIGCONT"),e.kill("SIGTERM",{forceKillAfterTimeout:5e3}))}))}(l,n),await l}setPageFocus(e,t){this.pageFocusTracker.setState(e,t)}getUncommittedChanges(){return this.uncommittedChanges}subscribeToUncommittedChanges(e){return this.uncommittedChangesEmitter.on("change",e),{dispose:()=>{this.uncommittedChangesEmitter.off("change",e)}}}fetchUncommittedChanges=(0,n.debounce)(I((async()=>{const e=Date.now();try{this.uncommittedChangesBeginFetchingEmitter.emit("start");const t=await this.runCommand(["internal-only","status"]),r=JSON.parse(t.stdout).files.map((e=>{return{...e,path:(t=e.path,t.startsWith(l().sep)?t.slice(1):t)};var t}));this.uncommittedChanges={fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),files:{value:r}},this.uncommittedChangesEmitter.emit("change",this.uncommittedChanges)}catch(r){if(this.logger.error("Error fetching files: ",r),null!=(t=r)&&"object"==typeof t&&"stderr"in t&&r.stderr.includes("checkout is currently in progress"))return void this.logger.info("Ignoring `hg status` error caused by in-progress checkout");this.uncommittedChangesEmitter.emit("change",{fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),files:{error:r instanceof Error?r:new Error(r)}})}var t})),100);getSmartlogCommits(){return this.smartlogCommits}subscribeToSmartlogCommitsChanges(e){return this.smartlogCommitsChangesEmitter.on("change",e),{dispose:()=>{this.smartlogCommitsChangesEmitter.off("change",e)}}}subscribeToSmartlogCommitsBeginFetching(e){const t=()=>e(!0);return this.smartlogCommitsBeginFetchingEmitter.on("start",t),{dispose:()=>{this.smartlogCommitsBeginFetchingEmitter.off("start",t)}}}subscribeToUncommittedChangesBeginFetching(e){const t=()=>e(!0);return this.uncommittedChangesBeginFetchingEmitter.on("start",t),{dispose:()=>{this.uncommittedChangesBeginFetchingEmitter.off("start",t)}}}fetchSmartlogCommits=(0,n.debounce)(I((async()=>{const e=Date.now();try{this.smartlogCommitsBeginFetchingEmitter.emit("start");const t=await this.runCommand(["internal-only","log"]),r=function(e,t){let r=[];try{r=JSON.parse(t)}catch(t){e.error("failed to parse branch info",t)}return r}(this.logger,t.stdout.trim());if(0===r.length)throw new Error(n.ErrorShortMessages.NoCommitsFetched);this.smartlogCommits={fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),commits:{value:r}},this.smartlogCommitsChangesEmitter.emit("change",this.smartlogCommits)}catch(t){this.logger.error("Error fetching commits: ",t),this.smartlogCommitsChangesEmitter.emit("change",{fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),commits:{error:t instanceof Error?t:new Error(t)}})}})),100);subscribeToHeadCommit(e){let t=this.smartlogCommits?.commits.value?.find((e=>e.isHead));null!=t&&e(t);const r=r=>{const n=r?.commits.value?.find((e=>e.isHead));null!=n&&n.branch!==t?.branch&&(e(n),t=n)};return this.smartlogCommitsChangesEmitter.on("change",r),{dispose:()=>{this.smartlogCommitsChangesEmitter.off("change",r)}}}catLimiter=new N(4,(e=>this.logger.info("[cat]",e)));relativeCat(e,t){const r=l().relative(this.info.repoRoot,e);return this.catLimiter.enqueueRun((async()=>(await this.runCommand(["internal-only","relative-cat",...this.catArgs(t,r)],void 0,{stripFinalNewline:!1})).stdout))}cat(e,t){const r=l().relative(this.info.repoRoot,e);return this.catLimiter.enqueueRun((async()=>(await this.runCommand(["internal-only","cat",t,r],void 0,{stripFinalNewline:!1})).stdout))}catArgs(e,t){switch(e.type){case n.ComparisonType.UncommittedChanges:return["uncommitted",t];case n.ComparisonType.HeadChanges:return["head",t];case n.ComparisonType.StackChanges:return["stack",t];case n.ComparisonType.Committed:return["stack",t,"--ref",e.hash]}}getAllDiffIds(){return this.getSmartlogCommits()?.commits.value?.map((e=>e.pr?.number)).filter(n.notEmpty)??[]}runCommand(e,t,r){return A({command:this.info.command,args:e,logger:this.logger,cwd:(0,n.unwrap)(t??this.info.repoRoot),options:r})}getConfig(e){return U(this.info.command,this.logger,this.info.repoRoot,e)}setConfig(e,t,r){return async function({command:e,logger:t,cwd:r,level:n,configName:s,configValue:i}){await A({command:e,args:["internal-only","set-config","--level",n,s,i],logger:t,cwd:r})}({command:this.info.command,logger:this.logger,cwd:this.info.repoRoot,level:e,configName:t,configValue:r})}}function A({command:e,args:t,logger:r,cwd:n,options:s}){const{command:i,args:o,options:a}=q(e,t,n,s);return r&&r.log("run command: ",i,...o,a),O()(i,o,a)}async function L(e,t,r){try{return JSON.parse((await A({command:e,args:["internal-only","repo-info"],logger:t,cwd:r})).stdout)}catch(e){return void t.error(`Failed to find repository info in ${r}`,e)}}async function $(e,t,r){try{return JSON.parse((await A({command:e,args:["internal-only","profile"],logger:t,cwd:r})).stdout)}catch(e){return t.error(`Failed to find repository profile in ${r}`,e),{appUrl:"https://app.graphite.dev/"}}}async function U(e,t,r,n){try{return(await A({command:e,args:["internal-only","config",n],logger:t,cwd:r})).stdout.trim()}catch{return}}function q(e,t,r,n){let s=[...t];"win32"!==process.platform&&(s=s.map((e=>e.replace(/\\\\/g,"\\"))));const i={...n,env:{LANG:"en_US.utf-8",EDITOR:void 0,GRAPHITE_INTERACTIVE:"true",GIT_OPTIONAL_LOCKS:"0"},cwd:r};return!e&&process.argv[1].startsWith("/snapshot/")?(e=process.argv[0],s=["/snapshot/monologue/apps/public/cli/dist/graphite.js",...s]):e||(e="gt"),{command:e,args:s,options:i}}var B=r(32081);const H={platformName:"browser",handleMessageFromClient:(e,t)=>{switch(t.type){case"platform/openFile":{const r=l().join((0,n.unwrap)(e?.info.repoRoot),t.path);let s;if(null==s)switch(process.platform){case"darwin":s="/usr/bin/open";break;case"win32":s="notepad.exe";break;case"linux":s="xdg-open"}if(s){e?.logger.log("open file",r);const t=(0,B.spawn)(s,[r],{detached:!0,stdio:"ignore",windowsHide:!1,windowsVerbatimArguments:!0});t.on("error",(t=>{e?.logger.log("failed to open",r,t)})),t.unref()}break}}}};var z=r(73292),W=r(9826),V=r.n(W);class G{promise;disposeFunc;constructor(e,t){this.promise=e,this.disposeFunc=t}unref(){this.disposed||(this.disposed=!0,this.disposeFunc())}internalReference;disposed=!1}class J{value;constructor(e){this.value=e}references=0;isDisposed=!1;ref(){this.references++}getNumberOfReferences(){return this.references}dispose(){this.references--,this.isDisposed||0!==this.references||(this.isDisposed=!0,this.value.dispose())}}const Q=new class{RepositoryType;constructor(e=x){this.RepositoryType=e}reposByRoot=new Map;activeReposEmitter=new M;lookup(e){for(const r of this.reposByRoot.values())if((e===r.value.info.repoRoot||e.startsWith((t=r.value.info.repoRoot).endsWith(l().sep)?t:t+l().sep))&&!r.isDisposed)return r;var t}getOrCreate(e,t,r){const n=this.lookup(r);if(n)return n.ref(),new G(Promise.resolve(n.value),(()=>n.dispose()));let s;return s=new G((async()=>{const n=await this.RepositoryType.getRepoInfo(e,t,r);if(t.info("repoInfo",n),"success"!==n.type)return n;if(s.disposed)return{type:"unknownError",error:new Error("Repository already disposed")};const i=this.lookup(n.repoRoot);if(i)return i.ref(),s.internalReference=i,i.value;const o=new this.RepositoryType(n,t),a=new J(o);return a.ref(),s.internalReference=a,this.reposByRoot.set(n.repoRoot,a),this.activeReposEmitter.emit("change"),o})(),(()=>{s.internalReference&&s.internalReference.dispose(),s.unref()})),s}cachedRepositoryForPath(e){const t=this.lookup(e);return t?.value}onChangeActiveRepos(e){const t=()=>{e([...this.reposByRoot.values()].map((e=>e.value)))};return this.activeReposEmitter.on("change",t),t(),()=>this.activeReposEmitter.off("change",t)}clearCache(){this.reposByRoot.forEach((e=>e.dispose())),this.reposByRoot=new Map,this.activeReposEmitter.removeAllListeners()}numberOfActiveServers(){let e=0;for(const t of this.reposByRoot.values())e+=t.getNumberOfReferences();return e}};class K{platform;connection;tracker;logger;listenersByType=new Map;incomingListener;repoDisposables=[];subscriptions=new Map;activeRepoRef;queuedMessages=[];currentState={type:"loading"};pageId=(0,n.randomId)();constructor(e,t,r,s){this.platform=e,this.connection=t,this.tracker=r,this.logger=s;let i=null;this.incomingListener=this.connection.onDidReceiveMessage(((e,r)=>{if(r)return null==i?void t.logger?.error("Error: got a binary message when not expecting one"):(this.handleIncomingMessageWithPayload(i,e),void(i=null));if(null!=i)return t.logger?.error("Error: didnt get binary payload after a message that requires one"),void(i=null);const s=e.toString("utf-8"),o=(0,n.deserializeFromString)(s);if(function(e){return null!=e&&"object"==typeof e&&!0===e.hasBinaryPayload}(o))i=o;else if("loading"===this.currentState.type)this.queuedMessages.push(o);else try{this.handleIncomingMessage(o)}catch(e){t.logger?.error("error handling incoming message: ",o,e)}}))}setRepoError(e){this.disposeRepoDisposables(),this.currentState={type:"error",error:e},this.tracker.context.setRepo(void 0),this.processQueuedMessages()}setCurrentRepo(e,t){this.disposeRepoDisposables(),this.currentState={type:"repo",repo:e,cwd:t},this.tracker.context.setRepo(e),null!=e.codeReviewProvider&&this.repoDisposables.push(e.codeReviewProvider.onChangeDiffSummaries((e=>{this.postMessage({type:"fetchedDiffSummaries",summaries:e})}))),this.repoDisposables.push(e.subscribeToHeadCommit((t=>{const r=e.getSmartlogCommits(),n=function(e,t){let r;if(null!=e){const n=new Map(e.map((e=>[e.branch,e])));let s=t;for(;null!=s;){if(s.partOfTrunk){r=s;break}if(null==s.parents[0])break;s=n.get(s.parents[0])}}return r}(r?.commits.value,t);this.tracker.track("HeadCommitChanged",{extras:{hash:t.branch,public:n?.branch}})}))),this.processQueuedMessages()}postMessage(e){this.connection.postMessage((0,n.serializeToString)(e)).catch((()=>{console.warn("Failed to post message to client")}))}setActiveRepoForCwd(e){void 0!==this.activeRepoRef&&this.activeRepoRef.unref(),this.logger.info(`Setting active repo cwd to ${e}`),this.currentState={type:"loading"};const t=this.connection.command;this.activeRepoRef=Q.getOrCreate(t,this.logger,e),this.activeRepoRef.promise.then((t=>{t instanceof x?this.setCurrentRepo(t,e):this.setRepoError(t)}))}dispose(){this.incomingListener.dispose(),this.disposeRepoDisposables(),void 0!==this.activeRepoRef&&this.activeRepoRef.unref()}disposeRepoDisposables(){this.repoDisposables.forEach((e=>e.dispose())),this.repoDisposables=[],this.subscriptions.forEach((e=>e.dispose())),this.subscriptions.clear()}processQueuedMessages(){for(const e of this.queuedMessages)try{this.handleIncomingMessage(e)}catch(t){this.connection.logger?.error("error handling queued message: ",e,t)}this.queuedMessages=[]}handleIncomingMessageWithPayload(e,t){switch(e.type){case"uploadFile":{const{id:r,filename:s}=e,i=null;if(null==i)return;this.tracker.operation("UploadImage","UploadImageError",{},(()=>i((0,n.unwrap)(this.connection.logger),{filename:s,data:t}))).then((e=>{this.connection.logger?.info("sucessfully uploaded file",s,e),this.postMessage({type:"uploadFileResult",id:r,result:{value:e}})})).catch((e=>{this.connection.logger?.info("error uploading file",s,e),this.postMessage({type:"uploadFileResult",id:r,result:{error:e}})}));break}}}handleIncomingMessage(e){this.handleIncomingGeneralMessage(e);const{currentState:t}=this;switch(t.type){case"repo":{const{repo:r,cwd:n}=t;this.handleIncomingMessageWithRepo(e,r,n);break}case"loading":case"error":e.type.startsWith("platform/")&&(this.platform.handleMessageFromClient(void 0,e,(e=>this.postMessage(e)),(e=>{this.repoDisposables.push({dispose:e})})),this.notifyListeners(e))}}handleIncomingGeneralMessage(e){switch(this.logger.info("GeneralMessage",e),e.type){case"installCli":("brew"===e.method?O()("brew",["install","withgraphite/tap/graphite"]):O()("npm",["install","-g","@withgraphite/graphite-cli@stable"])).then((()=>{this.postMessage({type:"installCliResult",result:"success"})})).catch((e=>{const t=e instanceof Error?e.message:"Unknown error";this.postMessage({type:"installCliResult",result:"error",error:t})}));break;case"updateCli":V()("gt").then((async e=>{const t=await(0,z.realpath)(e),r="lib/node_modules/@withgraphite/graphite-cli/graphite.js";if(t.endsWith(r)){const e=t.replace(r,"bin/npm");return O()(e,["install","-g","@withgraphite/graphite-cli@stable"])}if(t.endsWith("/bin/gt")&&t.includes("Cellar"))return await O()("brew",["update"]),O()("brew",["upgrade","withgraphite/tap/graphite"]);throw new Error("Couldn't determine installation method")})).then((()=>{this.postMessage({type:"updateCliResult",result:"success"})})).catch((e=>{this.postMessage({type:"updateCliResult",result:"error",error:e instanceof Error?e.message:"Unknown error"})}));break;case"fetchAllBranches":A({command:this.connection.command||"gt",args:["internal-only","all-branches"],cwd:this.connection.cwd}).then((e=>({value:JSON.parse(e.stdout)}))).catch((e=>(this.logger?.error("error fetching auth status",e.toString()),{error:e}))).then((e=>{e.value&&this.postMessage({type:"fetchedAllBranches",message:e.value})}));break;case"initializeRepository":this.logger.info("init"),A({command:this.connection.command||"gt",args:["init","--trunk",e.trunkBranch],cwd:this.connection.cwd}).then((e=>{this.logger.info("initializeRepository",e),e.exitCode&&this.postMessage({type:"failedToInitializeRepository"}),this.postMessage({type:"initializedRepository"})})).catch((()=>{this.postMessage({type:"failedToInitializeRepository"})}));break;case"track":this.tracker.trackData(e.data);break;case"changeCwd":this.setActiveRepoForCwd(e.cwd);break;case"requestRepoInfo":switch(this.currentState.type){case"repo":this.postMessage({type:"repoInfo",info:this.currentState.repo.info,cwd:this.currentState.cwd});break;case"error":this.postMessage({type:"repoInfo",info:this.currentState.error})}break;case"requestApplicationInfo":this.postMessage({type:"applicationInfo",platformName:this.platform.platformName,version:this.connection.version})}}handleIncomingMessageWithRepo(e,t,r){const{logger:s}=t;switch(e.type){case"subscribe":{const{subscriptionID:r,kind:n}=e;switch(n){case"uncommittedChanges":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"uncommittedChanges",subscriptionID:r,data:e})},n=t.getUncommittedChanges();null!=n&&e(n);const s=[];s.push(t.subscribeToUncommittedChanges(e)),t.fetchUncommittedChanges(),s.push(t.subscribeToUncommittedChangesBeginFetching((()=>this.postMessage({type:"beganFetchingUncommittedChangesEvent"})))),this.subscriptions.set(r,{dispose:()=>{s.forEach((e=>e.dispose()))}});break}case"smartlogCommits":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"smartlogCommits",subscriptionID:r,data:e})},n=t.getSmartlogCommits();null!=n&&e(n);const s=[];s.push(t.subscribeToSmartlogCommitsChanges(e)),t.fetchSmartlogCommits(),s.push(t.subscribeToSmartlogCommitsBeginFetching((()=>this.postMessage({type:"beganFetchingSmartlogCommitsEvent"})))),this.subscriptions.set(r,{dispose:()=>{s.forEach((e=>e.dispose()))}});break}case"mergeConflicts":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"mergeConflicts",subscriptionID:r,data:e})},n=t.getMergeConflicts();null!=n&&e(n),this.subscriptions.set(r,t.onChangeConflictState(e));break}}break}case"unsubscribe":{const t=this.subscriptions.get(e.subscriptionID);t?.dispose(),this.subscriptions.delete(e.subscriptionID);break}case"runOperation":{const{operation:n}=e;t.runOrQueueOperation(n,(e=>{this.postMessage({type:"operationProgress",...e}),"queue"===e.kind&&this.tracker.track("QueueOperation",{extras:{operation:n.trackEventName}})}),this.tracker,r);break}case"abortRunningOperation":{const{operationId:r}=e;t.abortRunningOpeation(r);break}case"getConfig":t.getConfig(e.name).catch((()=>{})).then((t=>{s.info("got config",e.name,t),this.postMessage({type:"gotConfig",name:e.name,value:t})}));break;case"fetchRepoMessage":t.runCommand(["internal-only","repo-message"]).then((e=>({value:e.stdout}))).catch((e=>(s?.error("error fetching repo message",e.toString()),{error:e}))).then((e=>this.postMessage({type:"fetchedRepoMessage",message:e.value||""})));break;case"fetchUpgradePrompt":s.info("fetchUpgradePrompt"),t.runCommand(["internal-only","upgrade-prompt"]).then((e=>({value:e.stdout}))).catch((e=>(s?.error("error fetching upgrade prompt",e.toString()),{error:e}))).then((e=>this.postMessage({type:"fetchedUpgradePrompt",message:e.value||""})));break;case"fetchAuthStatus":t.runCommand(["internal-only","check-auth"]).then((e=>({value:JSON.parse(e.stdout)}))).catch((e=>(s?.error("error fetching auth status",e.toString()),{error:e}))).then((e=>{e.value&&this.postMessage({type:"fetchedAuthStatus",message:e.value})}));break;case"fetchPotentialParents":{const{branchToTrack:r}=e;t.runCommand(["internal-only","potential-parents",r]).then((e=>({value:JSON.parse(e.stdout)}))).catch((e=>(s?.error("error fetching potential parents",e.toString()),{error:e}))).then((e=>{e.value&&this.postMessage({type:"fetchedPotentialParents",message:e.value})}));break}case"setConfig":s.info("set config",e.name,e.value),t.setConfig("user",e.name,e.value).catch((t=>{s.error("error setting config",e.name,e.value,t)}));break;case"deleteFile":{const{filePath:r}=e,n=function(e,t,r=l()){const n=r.resolve(t.info.repoRoot,e);return n.startsWith(t.info.repoRoot+r.sep)?n:null}(r,t);if(null==n)return void s.warn("can't delete file outside of the repo",r);i().promises.rm(n).then((()=>{s.info("deleted file from filesystem",n)})).catch((e=>{s.error("unable to delete file",n,e)}));break}case"requestComparison":{const{comparison:r}=e;t.runCommand(["internal-only","diff",...P(r)]).then((e=>({value:e.stdout}))).catch((e=>(s?.error("error running diff",e.toString()),{error:e}))).then((e=>this.postMessage({type:"comparison",comparison:r,data:{diff:e}})));break}case"requestChangedFiles":{const{branch:r}=e;t.runCommand(["internal-only","changed-files",r]).then((e=>JSON.parse(e.stdout))).catch((e=>(s?.error("error running diff",e.toString()),{error:e}))).then((e=>this.postMessage({type:"changedFiles",branch:r,data:e})));break}case"requestComparisonContextLines":{const{id:{path:r,comparison:s},start:i,numLines:o}=e;if(s.type===n.ComparisonType.Commit||s.type===n.ComparisonType.Range)throw new Error("Not implemented");t.relativeCat(r,s).catch((()=>"")).then((e=>this.postMessage({type:"comparisonContextLines",lines:e.split("\n").slice(i-1,i-1+o),path:r})));break}case"requestChangedFilesInRange":{const{fromSha:r,toSha:n}=e;t.runCommand(["internal-only","changed-files",n,"--from",r]).then((e=>JSON.parse(e.stdout))).catch((e=>(s?.error("error running diff",e.toString()),{error:e}))).then((e=>this.postMessage({type:"changedFilesInRange",fromSha:r,toSha:n,data:e})));break}case"requestCommitsInBranch":{const{branch:r}=e;t.runCommand(["internal-only","list-commits",r]).then((e=>JSON.parse(e.stdout))).catch((e=>(s?.error("error running diff",e.toString()),{error:e}))).then((e=>this.postMessage({type:"commitsInBranch",branch:r,data:e})));break}case"requestChangedFilesInCommit":{const{commitSha:r}=e;t.runCommand(["internal-only","changed-files",r,"--from",`${r}~`]).then((e=>JSON.parse(e.stdout))).catch((e=>(s?.error("error running diff",e.toString()),{error:e}))).then((e=>this.postMessage({type:"changedFilesInCommit",commitSha:r,data:e})));break}case"refresh":s?.log("refresh requested"),t.fetchSmartlogCommits(),t.fetchUncommittedChanges(),t.codeReviewProvider?.triggerDiffSummariesFetch(t.getAllDiffIds());break;case"pageVisibility":t.setPageFocus(this.pageId,e.state);break;case"fetchCommitMessageTemplate":t.runCommand(["internal-only","templates"]).then((e=>{const r=JSON.parse(e.stdout);this.postMessage({type:"fetchedCommitMessageTemplate",templates:Object.fromEntries(Object.entries(r).map((([e,r])=>[e,r.replace(t.IGNORE_COMMIT_MESSAGE_LINES_REGEX,"")])))})})).catch((e=>{s?.error("Could not fetch commit message template",e)}));break;case"typeahead":t.codeReviewProvider?.typeahead?.(e.kind,e.query)?.then((t=>this.postMessage({type:"typeaheadResult",id:e.id,result:t})));break;case"fetchDiffSummaries":t.codeReviewProvider?.triggerDiffSummariesFetch(t.getAllDiffIds());break;case"loadMoreCommits":{const e=t.nextVisibleCommitRangeInDays();return this.postMessage({type:"commitsShownRange",rangeInDays:e}),this.postMessage({type:"beganLoadingMoreCommits"}),t.fetchSmartlogCommits(),void this.tracker.track("LoadMoreCommits",{extras:{daysToFetch:e??"Infinity"}})}default:this.platform.handleMessageFromClient(t,e,(e=>this.postMessage(e)),(e=>{this.repoDisposables.push({dispose:e})}))}this.notifyListeners(e)}notifyListeners(e){const t=this.listenersByType.get(e.type);t&&t.forEach((t=>t(e)))}}var X=r(6113);const Y="win32"==process.platform?l().join((0,n.unwrap)(process.env.LOCALAPPDATA),"cache"):"darwin"==process.platform?l().join(g().homedir(),"Library/Caches"):process.env.XDG_CACHE_HOME||l().join(g().homedir(),".cache");function Z(e,t){const r=Buffer.from(e),n=Buffer.from(t);return r.length===n.length&&(0,X.timingSafeEqual)(r,n)}function ee(e){const t=e.logger??(e.logFileLocation?function(e){const t=(...t)=>{const r=b().format(...t)+"\n";i().promises.appendFile(e,r)};return{info:t,log:t,warn:t,error:t,getLogFileContents:()=>i().promises.readFile(e,"utf-8")}}(e.logFileLocation):w);e.logger=t;const r=e?.platform??H,s=e?.version??"unknown";t.log(`establish client connection for ${e.cwd}`),t.log(`platform '${r.platformName}', version '${s}', command '${e.command}'`);const o=function(e,t,r,s=y){return new n.Tracker(((e,t)=>{const{logger:r}=t;r.log("[track]",e.eventName,e.errorName??"",e.errorMessage??"",null!=e.extras?JSON.stringify(e.extras):"");try{Promise.resolve(s({...e,...t.data})).catch((e=>{}))}catch{}}),new v(e,function(e,t){return{platform:e,version:t,repo:void 0,sessionId:(0,n.randomId)(),unixname:f(),osArch:g().arch(),osType:g().platform(),osRelease:g().release(),hostname:g().hostname()}}(t.platformName,r)))}(t,r,s,(t=>A({command:e.command||"gt",args:["internal-only","log-action",t.eventName||t.errorName||"UNKNOWN_CLI_EVENT",(t.timestamp?new Date(t.timestamp):new Date).toISOString(),JSON.stringify(t)],cwd:e.cwd})));o.track("ClientConnection",{extras:{cwd:e.cwd}});let a=new K(r,e,o,t);return a.setActiveRepoForCwd(e.cwd),()=>{a?.dispose(),a=null}}function te({port:e,sensitiveToken:t,challengeToken:r,logFileLocation:s,logInfo:o,command:c,gtVersion:u,foreground:d,frontendDir:p}){return new Promise((g=>{try{const e=JSON.parse(i().readFileSync(l().join(p,"build/asset-manifest.json"),"utf-8"));for(const t of Object.values(e.files))t.startsWith("/")||g({type:"error",error:`expected entry to start with / but was: \`${t}\``}),se[t]=t.slice(1)}catch(e){}se["/favicon.ico"]="favicon.ico";const f=a().createServer((async(e,n)=>{if(e.url){const{pathname:o}=h().parse(e.url);if(null!=o&&se.hasOwnProperty(o)){const e=se[o];let t;try{t=await i().promises.readFile(l().join(p,"build",e))}catch(e){return n.writeHead(500,{"Content-Type":"text/plain"}),void n.end((s=e.toString(),s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#27;")))}const r=e.lastIndexOf("."),a=e.slice(r+1),c=ne[a]??"text/plain";return n.writeHead(200,{"Content-Type":c}),void n.end(t)}if("/challenge_authenticity"===o){const s=re(e.url).get("token");if(s&&Z(s,t)){n.writeHead(200,{"Content-Type":"text/json"});const e={challengeToken:r,pid:process.pid};n.end(JSON.stringify(e))}else n.writeHead(401,{"Content-Type":"text/json"}),n.end(JSON.stringify({error:"invalid token"}));return}}var s;n.writeHead(404,{"Content-Type":"text/html"}),n.end("<html><body>Not Found!</body></html>")})),v=f.listen(e),y=new(m().Server)({noServer:!0,path:"/ws"});y.on("connection",((e,r)=>{let i,a,l;if(r.url){const e=re(r.url);i=e.get("token");const t=e.get("cwd");l=e.get("platform"),t&&(a=decodeURIComponent(t))}if(!i){const t="No token provided in websocket request";return o("closing ws:",t),void e.close(n.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE,t)}if(!Z(i,t)){const t="Invalid token";return o("closing ws:",t),void e.close(n.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE,t)}const h=ee({postMessage:t=>(e.send(t),Promise.resolve(!0)),onDidReceiveMessage(t){const r=e.on("message",t);return{dispose:()=>r.off("message",t)}},cwd:a??process.cwd(),logFileLocation:"stdout"===s?void 0:s,command:c,version:u,platform:void 0});e.on("close",(()=>{h(),d||setTimeout((()=>{0===Q.numberOfActiveServers()&&process.exit(0)}),6e4)}))})),v.on("upgrade",((e,t,r)=>{y.handleUpgrade(e,t,r,(t=>{y.emit("connection",t,e)}))})),f.on("error",(function(t){if("listen"!==t.syscall)throw g({type:"error",error:t.toString()}),t;switch(t.code){case"EACCES":throw g({type:"error",error:`Port ${e} requires elevated privileges`}),t;case"EADDRINUSE":return void g({type:"addressInUse"});default:throw g({type:"error",error:t.toString()}),t}})),f.on("listening",(()=>g({type:"success",port:f.address().port,pid:process.pid})))}))}function re(e){const t=h().parse(e).search?.replace(/^\?/,"").split("&").map((e=>e.split("=")));return new Map(t)}l().join(Y,"graphite-gti");const ne={css:"text/css",html:"text/html",js:"text/javascript",ttf:"font/ttf"},se={"/":"index.html"}}};
3
- //# sourceMappingURL=60.js.map