@night-slayer18/leetcode-cli 2.2.2 → 2.3.0
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/.prettierignore +26 -0
- package/.prettierrc +10 -0
- package/README.md +95 -76
- package/dist/index.js +273 -243
- package/package.json +8 -2
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {Command}from'commander';import
|
|
2
|
+
import {Command}from'commander';import f from'chalk';import To from'inquirer';import Gt from'ora';import yi from'got';import {z}from'zod';import hi from'conf';import {homedir}from'os';import*as $e from'path';import $e__default,{join,dirname,basename,extname,resolve,sep}from'path';import po from'cli-table3';import Mi from'striptags';import*as Pe from'fs/promises';import {mkdir,writeFile,readFile,readdir}from'fs/promises';import {existsSync,writeFileSync,readFileSync,unlinkSync,mkdirSync}from'fs';import {execSync,spawn}from'child_process';import Ui from'open';import {createClient}from'@supabase/supabase-js';import {diffLines}from'diff';import {fileURLToPath}from'url';import {stdin,stdout}from'process';import so from'ansi-escapes';import ao from'cli-cursor';var di=z.object({name:z.string(),slug:z.string()}),fi=z.object({name:z.string(),slug:z.string()}),mi=z.object({lang:z.string(),langSlug:z.string(),code:z.string()}),vt=z.object({questionId:z.string(),questionFrontendId:z.string(),title:z.string(),titleSlug:z.string(),difficulty:z.enum(["Easy","Medium","Hard"]),isPaidOnly:z.boolean(),acRate:z.number().optional().default(0),topicTags:z.array(di),status:z.enum(["ac","notac"]).nullable()}),un=vt.extend({content:z.string().nullable(),codeSnippets:z.array(mi).nullable(),sampleTestCase:z.string(),exampleTestcases:z.string(),hints:z.array(z.string()),companyTags:z.array(fi).nullable(),stats:z.string()}),pn=z.object({date:z.string(),link:z.string(),question:vt}),gn=z.object({id:z.string(),statusDisplay:z.string(),lang:z.string(),runtime:z.string(),timestamp:z.string(),memory:z.string()}),dn=z.object({code:z.string(),lang:z.object({name:z.string()})}),fn=z.object({status_code:z.number(),status_msg:z.string(),state:z.string(),run_success:z.boolean(),code_answer:z.array(z.string()).optional(),expected_code_answer:z.array(z.string()).optional(),correct_answer:z.boolean().optional(),std_output_list:z.array(z.string()).optional(),compile_error:z.string().optional(),runtime_error:z.string().optional()}),mn=z.object({status_code:z.number(),status_msg:z.string(),state:z.string(),run_success:z.boolean(),total_correct:z.number(),total_testcases:z.number(),status_runtime:z.string(),status_memory:z.string(),runtime_percentile:z.number(),memory_percentile:z.number(),code_output:z.string().optional(),std_output:z.string().optional(),expected_output:z.string().optional(),compile_error:z.string().optional(),runtime_error:z.string().optional(),last_testcase:z.string().optional()}),yn=z.object({username:z.string(),profile:z.object({realName:z.string(),ranking:z.number()}),submitStatsGlobal:z.object({acSubmissionNum:z.array(z.object({difficulty:z.string(),count:z.number()}))}),userCalendar:z.object({streak:z.number(),totalActiveDays:z.number(),submissionCalendar:z.string().optional()})}),hn=z.object({isSignedIn:z.boolean(),username:z.string().nullable()});var Sn=`
|
|
3
3
|
query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) {
|
|
4
4
|
problemsetQuestionList: questionList(
|
|
5
5
|
categorySlug: $categorySlug
|
|
@@ -24,7 +24,7 @@ import {Command}from'commander';import l from'chalk';import to from'inquirer';im
|
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
|
-
`,
|
|
27
|
+
`,bn=`
|
|
28
28
|
query questionData($titleSlug: String!) {
|
|
29
29
|
question(titleSlug: $titleSlug) {
|
|
30
30
|
questionId
|
|
@@ -54,14 +54,14 @@ import {Command}from'commander';import l from'chalk';import to from'inquirer';im
|
|
|
54
54
|
status
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
|
-
`,
|
|
57
|
+
`,Cn=`
|
|
58
58
|
query globalData {
|
|
59
59
|
userStatus {
|
|
60
60
|
isSignedIn
|
|
61
61
|
username
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
|
-
|
|
64
|
+
`,En=`
|
|
65
65
|
query userPublicProfile($username: String!) {
|
|
66
66
|
matchedUser(username: $username) {
|
|
67
67
|
username
|
|
@@ -82,7 +82,7 @@ import {Command}from'commander';import l from'chalk';import to from'inquirer';im
|
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
|
-
`,
|
|
85
|
+
`,wn=`
|
|
86
86
|
query skillStats($username: String!) {
|
|
87
87
|
matchedUser(username: $username) {
|
|
88
88
|
tagProblemCounts {
|
|
@@ -104,7 +104,7 @@ import {Command}from'commander';import l from'chalk';import to from'inquirer';im
|
|
|
104
104
|
}
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
|
-
`,
|
|
107
|
+
`,Mn=`
|
|
108
108
|
query questionOfToday {
|
|
109
109
|
activeDailyCodingChallengeQuestion {
|
|
110
110
|
date
|
|
@@ -125,7 +125,7 @@ import {Command}from'commander';import l from'chalk';import to from'inquirer';im
|
|
|
125
125
|
}
|
|
126
126
|
}
|
|
127
127
|
}
|
|
128
|
-
`,
|
|
128
|
+
`,_n=`
|
|
129
129
|
query submissionList($questionSlug: String!, $limit: Int, $offset: Int) {
|
|
130
130
|
questionSubmissionList(
|
|
131
131
|
questionSlug: $questionSlug
|
|
@@ -142,13 +142,13 @@ import {Command}from'commander';import l from'chalk';import to from'inquirer';im
|
|
|
142
142
|
}
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
|
-
`,
|
|
145
|
+
`,kn=`
|
|
146
146
|
query randomQuestion($categorySlug: String, $filters: QuestionListFilterInput) {
|
|
147
147
|
randomQuestion(categorySlug: $categorySlug, filters: $filters) {
|
|
148
148
|
titleSlug
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
|
-
`,
|
|
151
|
+
`,Tn=`
|
|
152
152
|
query submissionDetails($submissionId: Int!) {
|
|
153
153
|
submissionDetails(submissionId: $submissionId) {
|
|
154
154
|
code
|
|
@@ -157,51 +157,51 @@ import {Command}from'commander';import l from'chalk';import to from'inquirer';im
|
|
|
157
157
|
}
|
|
158
158
|
}
|
|
159
159
|
}
|
|
160
|
-
`;var
|
|
161
|
-
${
|
|
162
|
-
`)}function
|
|
163
|
-
`)}function
|
|
164
|
-
`):String(e)}function
|
|
165
|
-
Showing ${e.length} of ${
|
|
160
|
+
`;var lo="https://leetcode.com",co=class{client;credentials=null;constructor(){this.client=yi.extend({prefixUrl:lo,headers:{"Content-Type":"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",Origin:lo,Referer:`${lo}/`},timeout:{request:3e4},retry:{limit:2}});}setCredentials(t){this.credentials=t,this.client=this.client.extend({headers:{Cookie:`LEETCODE_SESSION=${t.session}; csrftoken=${t.csrfToken}`,"X-CSRFToken":t.csrfToken}});}getCredentials(){return this.credentials}async graphql(t,o={}){let n=await this.client.post("graphql",{json:{query:t,variables:o}}).json();if(n.errors?.length)throw new Error(`GraphQL Error: ${n.errors[0].message}`);return n.data}async checkAuth(){let t=await this.graphql(Cn);return hn.parse(t.userStatus)}async getProblems(t={}){let o={categorySlug:"",limit:t.limit??50,skip:t.skip??0,filters:{}};t.difficulty&&(o.filters.difficulty=t.difficulty),t.status&&(o.filters.status=t.status),t.tags?.length&&(o.filters.tags=t.tags),t.searchKeywords&&(o.filters.searchKeywords=t.searchKeywords);let n=await this.graphql(Sn,o),r=z.array(vt).parse(n.problemsetQuestionList.questions);return {total:n.problemsetQuestionList.total,problems:r}}async getProblem(t){let o=await this.graphql(bn,{titleSlug:t});return un.parse(o.question)}async getProblemById(t){let{problems:o}=await this.getProblems({searchKeywords:t,limit:10}),n=o.find(r=>r.questionFrontendId===t);if(!n)throw new Error(`Problem #${t} not found`);return this.getProblem(n.titleSlug)}async getDailyChallenge(){let t=await this.graphql(Mn);return pn.parse(t.activeDailyCodingChallengeQuestion)}async getRandomProblem(t={}){let o={categorySlug:"",filters:{}};t.difficulty&&(o.filters.difficulty=t.difficulty),t.tags?.length&&(o.filters.tags=t.tags);let n=await this.graphql(kn,o);return z.object({titleSlug:z.string()}).parse(n.randomQuestion).titleSlug}async getUserProfile(t){let n=(await this.graphql(En,{username:t})).matchedUser,r=yn.parse(n);return {username:r.username,realName:r.profile.realName,ranking:r.profile.ranking,acSubmissionNum:r.submitStatsGlobal.acSubmissionNum,streak:r.userCalendar.streak,totalActiveDays:r.userCalendar.totalActiveDays,submissionCalendar:n.userCalendar.submissionCalendar}}async getSkillStats(t){return (await this.graphql(wn,{username:t})).matchedUser.tagProblemCounts}async getSubmissionList(t,o=20,n=0){let r=await this.graphql(_n,{questionSlug:t,limit:o,offset:n});return z.array(gn).parse(r.questionSubmissionList.submissions)}async getSubmissionDetails(t){let o=await this.graphql(Tn,{submissionId:t});return dn.parse(o.submissionDetails)}async testSolution(t,o,n,r,s){let i=await this.client.post(`problems/${t}/interpret_solution/`,{json:{data_input:r,lang:n,typed_code:o,question_id:s}}).json();return this.pollSubmission(i.interpret_id,"interpret",fn)}async submitSolution(t,o,n,r){let s=await this.client.post(`problems/${t}/submit/`,{json:{lang:n,typed_code:o,question_id:r}}).json();return this.pollSubmission(s.submission_id.toString(),"submission",mn)}async pollSubmission(t,o,n){let r=`submissions/detail/${t}/check/`,s=12,i=500,a=3e3;for(let u=0;u<s;u++){try{let d=await this.client.get(r).json();if(d.state==="SUCCESS"||d.state==="FAILURE")return n.parse(d)}catch(d){if(u===s-1){let m=o==="interpret"?"Test":"Submission";throw new Error(`${m} check failed: ${d instanceof Error?d.message:"Network error"}`)}}let g=Math.min(i*Math.pow(2,u),a);await new Promise(d=>setTimeout(d,g));}let l=o==="interpret"?"Test":"Submission";throw new Error(`${l} timeout: Result not available after 30 seconds`)}},S=new co;var qe=new hi({configName:"credentials",cwd:join(homedir(),".leetcode"),defaults:{}}),ae={get(){let e=qe.get("session"),t=qe.get("csrfToken");return !e||!t?null:{session:e,csrfToken:t}},set(e){qe.set("session",e.session),qe.set("csrfToken",e.csrfToken);},clear(){qe.clear();},getPath(){return qe.path}};async function Rn(){console.log(),console.log(f.cyan("LeetCode CLI Login")),console.log(f.gray("\u2500".repeat(40))),console.log(),console.log(f.yellow("To login, you need to provide your LeetCode session cookies.")),console.log(f.gray("1. Open https://leetcode.com in your browser")),console.log(f.gray("2. Login to your account")),console.log(f.gray("3. Open DevTools (F12) \u2192 Application \u2192 Cookies \u2192 leetcode.com")),console.log(f.gray("4. Copy the values of LEETCODE_SESSION and csrftoken")),console.log();let e=await To.prompt([{type:"password",name:"session",message:"LEETCODE_SESSION:",mask:"*",validate:n=>n.length>0||"Session token is required"},{type:"password",name:"csrfToken",message:"csrftoken:",mask:"*",validate:n=>n.length>0||"CSRF token is required"}]),t={session:e.session.trim(),csrfToken:e.csrfToken.trim()},o=Gt("Verifying credentials...").start();try{S.setCredentials(t);let{isSignedIn:n,username:r}=await S.checkAuth();if(!n||!r){o.fail("Invalid credentials"),console.log(f.red("Please check your session cookies and try again."));return}ae.set(t),o.succeed(`Logged in as ${f.green(r)}`),console.log(),console.log(f.gray(`Credentials saved to ${ae.getPath()}`));}catch(n){o.fail("Authentication failed"),n instanceof Error&&console.log(f.red(n.message));}}async function xn(){ae.clear(),console.log(f.green("\u2713 Logged out successfully"));}async function On(){let e=ae.get();if(!e){console.log(f.yellow('Not logged in. Run "leetcode login" to authenticate.'));return}let t=Gt("Checking session...").start();try{S.setCredentials(e);let{isSignedIn:o,username:n}=await S.checkAuth();if(!o||!n){t.fail("Session expired"),console.log(f.yellow('Please run "leetcode login" to re-authenticate.'));return}t.succeed(`Logged in as ${f.green(n)}`);}catch(o){t.fail("Failed to check session"),o instanceof Error&&console.log(f.red(o.message));}}async function v(){let e=ae.get();if(!e)return console.log(f.yellow("\u26A0\uFE0F Please login first: leetcode login")),{authorized:false};try{S.setCredentials(e);let{isSignedIn:t,username:o}=await S.checkAuth();return t?{authorized:!0,username:o??void 0}:(console.log(f.yellow("\u26A0\uFE0F Session expired. Please run: leetcode login")),{authorized:!1})}catch{return console.log(f.yellow("\u26A0\uFE0F Session validation failed. Please run: leetcode login")),{authorized:false}}}var Ei={"Linked List":"linkedlist","Doubly-Linked List":"linkedlist",Tree:"tree","Binary Tree":"tree","Binary Search Tree":"tree",Trie:"tree","Segment Tree":"tree","Binary Indexed Tree":"tree",Graph:"graph",Matrix:"matrix",Array:"array","Hash Table":"array",Stack:"array",Queue:"array","Monotonic Stack":"array","Monotonic Queue":"array","Heap (Priority Queue)":"array",String:"string"};function wi(e){for(let t of e){let o=Ei[t.name];if(o)return o}return null}function Pn(e){try{return JSON.parse(e)}catch{return e}}function ve(e){return Array.isArray(e)&&e.length>0&&Array.isArray(e[0])}function $n(e,t){if(!Array.isArray(e)||e.length===0)return String(e);let o=Math.max(...e.map(i=>String(i).length),1),n=Math.max(o,3),r=e.map((i,a)=>`[${a}]`.padStart(n).padEnd(n)).join(" "),s=e.map((i,a)=>{let l=String(i).padStart(n).padEnd(n);return t&&Array.isArray(t)&&t[a]!==i?f.red.bold(l):l}).join(" ");return `${f.gray(r)}
|
|
161
|
+
${s}`}function vn(e,t){return Array.isArray(e)?e.length===0?f.gray("(empty)"):e.map((n,r)=>{let s=String(n);return t&&Array.isArray(t)&&(r>=t.length||t[r]!==n)?f.red.bold(s):s}).join(f.gray(" \u2192 ")):String(e)}function An(e){if(!Array.isArray(e)||e.length===0)return f.gray("(empty tree)");let t=[],o=Math.floor(Math.log2(e.length))+1,n=Math.pow(2,o)*3;function r(s,i,a,l){if(i>e.length-1)return;let u=[],g=[],d=Math.floor(n/Math.pow(2,s+1));for(let m=i;m<=a&&m<e.length;m++){let b=e[m],_=b===null?" ":String(b);u.push(_.padStart(d).padEnd(d));let w=2*m+1,R=2*m+2,G=w<e.length&&e[w]!==null,K=R<e.length&&e[R]!==null;if(G||K){let z="";G?z+="/":z+=" ",z+=" ",K?z+="\\":z+=" ",g.push(z.padStart(d).padEnd(d));}}u.length>0&&(t.push(u.join("")),g.length>0&&s<o-1&&t.push(g.join("")));}for(let s=0;s<o;s++){let i=Math.pow(2,s)-1,a=Math.pow(2,s+1)-2;r(s,i,a);}return t.join(`
|
|
162
|
+
`)}function Dt(e,t){if(!ve(e)||e.length===0)return String(e);let o=e.length,n=e[0].length,r=3,s=[],i=" "+e[0].map((a,l)=>String(l).padStart(r).padEnd(r)).join(" ");s.push(f.gray(i)),s.push(" \u250C"+Array(n).fill("\u2500\u2500\u2500").join("\u252C")+"\u2510");for(let a=0;a<o;a++){let l=e[a].map((u,g)=>{let d=String(u).padStart(2);return t&&ve(t)&&t[a]&&t[a][g]!==u?f.red.bold(d):d}).join(" \u2502 ");s.push(f.gray(` ${a} `)+`\u2502 ${l} \u2502`),a<o-1?s.push(" \u251C"+Array(n).fill("\u2500\u2500\u2500").join("\u253C")+"\u2524"):s.push(" \u2514"+Array(n).fill("\u2500\u2500\u2500").join("\u2534")+"\u2518");}return s.join(`
|
|
163
|
+
`)}function Dn(e){return ve(e)?e.map((o,n)=>{let r=Array.isArray(o)?o.join(", "):String(o);return ` ${f.cyan(String(n))} \u2192 [${r}]`}).join(`
|
|
164
|
+
`):String(e)}function In(e,t,o){let n=Pn(e),r=Pn(t),s=e===t,i=wi(o),a,l;if(ve(n)){let u=ve(r)?r:void 0;return a=Dt(n,u),l=ve(r)?Dt(r):String(t),{outputVis:a,expectedVis:l,matches:s}}if(i===null)return {outputVis:String(e),expectedVis:String(t),matches:s,unsupported:true};switch(i){case "linkedlist":a=vn(n,r),l=vn(r);break;case "tree":a=An(n),l=An(r);break;case "graph":a=Dn(n),l=Dn(r);break;case "matrix":let u=ve(r)?r:void 0;a=Dt(n,u),l=ve(r)?Dt(r):String(t);break;case "array":case "string":Array.isArray(n)?(a=$n(n,r),l=Array.isArray(r)?$n(r):String(t)):(a=s?String(e):f.red.bold(String(e)),l=String(t));break}return {outputVis:a,expectedVis:l,matches:s}}function Nn(e,t){let o=new po({head:[f.cyan("ID"),f.cyan("Title"),f.cyan("Difficulty"),f.cyan("Rate"),f.cyan("Status")],colWidths:[8,45,12,10,10],style:{head:[],border:[]}});for(let n of e){let r=n.title;n.isPaidOnly&&(r=`\u{1F512} ${r}`),o.push([n.questionFrontendId,r.length>42?r.slice(0,39)+"...":r,It(n.difficulty),`${n.acRate.toFixed(1)}%`,_i(n.status)]);}console.log(o.toString()),console.log(f.gray(`
|
|
165
|
+
Showing ${e.length} of ${t} problems`));}function Fn(e){console.log();let t=e.isPaidOnly?"\u{1F512} ":"";if(console.log(f.bold.cyan(` ${e.questionFrontendId}. ${t}${e.title}`)),console.log(` ${It(e.difficulty)}`),console.log(f.gray(` https://leetcode.com/problems/${e.titleSlug}/`)),console.log(),e.isPaidOnly&&(console.log(f.yellow(" \u26A0\uFE0F Premium Problem")),console.log(f.gray(" This problem requires a LeetCode Premium subscription.")),console.log(f.gray(" Visit the URL above to view on LeetCode.")),console.log()),e.topicTags.length){let n=e.topicTags.map(r=>f.bgBlue.white(` ${r.name} `)).join(" ");console.log(` ${n}`),console.log();}console.log(f.gray("\u2500".repeat(60))),console.log();let o=e.content;if(!o){console.log(f.yellow(" \u{1F512} Premium Content")),console.log(f.gray(" Problem description is not available directly.")),console.log(f.gray(" Please visit the URL above to view on LeetCode.")),console.log();return}console.log(go(o)),console.log();}function go(e){return e=e.replace(/<sup>(.*?)<\/sup>/gi,"^$1"),e=e.replace(/<strong class="example">Example (\d+):<\/strong>/gi,"\xA7EXAMPLE\xA7$1\xA7"),e=e.replace(/Input:/gi,"\xA7INPUT\xA7"),e=e.replace(/Output:/gi,"\xA7OUTPUT\xA7"),e=e.replace(/Explanation:/gi,"\xA7EXPLAIN\xA7"),e=e.replace(/<strong>Constraints:<\/strong>/gi,"\xA7CONSTRAINTS\xA7"),e=e.replace(/Constraints:/gi,"\xA7CONSTRAINTS\xA7"),e=e.replace(/<strong>Follow-up:/gi,"\xA7FOLLOWUP\xA7"),e=e.replace(/Follow-up:/gi,"\xA7FOLLOWUP\xA7"),e=e.replace(/<li>/gi," \u2022 "),e=e.replace(/<\/li>/gi,`
|
|
166
|
+
`),e=e.replace(/<\/p>/gi,`
|
|
167
|
+
|
|
168
|
+
`),e=e.replace(/<br\s*\/?>/gi,`
|
|
169
|
+
`),e=Mi(e),e=e.replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/≤/g,"\u2264").replace(/≥/g,"\u2265").replace(/&#(\d+);/g,(t,o)=>String.fromCharCode(parseInt(o,10))).replace(/&/g,"&"),e=e.replace(/\n{3,}/g,`
|
|
170
|
+
|
|
171
|
+
`).trim(),e=e.replace(/§EXAMPLE§(\d+)§/g,(t,o)=>f.green.bold(`\u{1F4CC} Example ${o}:`)),e=e.replace(/§INPUT§/g,f.yellow("Input:")),e=e.replace(/§OUTPUT§/g,f.yellow("Output:")),e=e.replace(/§EXPLAIN§/g,f.gray("Explanation:")),e=e.replace(/§CONSTRAINTS§/g,f.cyan.bold(`
|
|
172
|
+
\u{1F4CB} Constraints:`)),e=e.replace(/§FOLLOWUP§/g,f.magenta.bold(`
|
|
173
|
+
\u{1F4A1} Follow-up:`)),e}function Hn(e,t){if(console.log(),e.compile_error){console.log(f.red.bold("\u274C Compile Error")),console.log(f.red(e.compile_error));return}if(e.runtime_error){console.log(f.red.bold("\u274C Runtime Error")),console.log(f.red(e.runtime_error));return}e.correct_answer?console.log(f.green.bold("\u2713 All test cases passed!")):console.log(f.yellow.bold("\u2717 Some test cases failed"));let o=e.code_answer??[],n=e.expected_code_answer??[];if(t&&o.length>0){console.log(),console.log(f.gray.bold("\u2500".repeat(50)));let s=o.map((i,a)=>({out:i,exp:n[a]??""})).filter(({out:i,exp:a})=>i!==""||a!=="");for(let i=0;i<s.length;i++){let{out:a,exp:l}=s[i],{outputVis:u,expectedVis:g,matches:d,unsupported:m}=In(a,l,t);console.log(),console.log(f.gray(`Test Case ${i+1}:`)),m&&(console.log(f.yellow(" \u26A0 No visualization available for this problem type")),console.log(f.gray(` Tags: ${t.map(b=>b.name).join(", ")}`))),console.log(),console.log(f.cyan(" Your Output:")),u.split(`
|
|
174
|
+
`).forEach(b=>console.log(` ${b}`)),console.log(),console.log(f.cyan(" Expected:")),g.split(`
|
|
175
|
+
`).forEach(b=>console.log(` ${b}`)),console.log(),console.log(d?f.green(" \u2713 Match"):f.red(" \u2717 Mismatch"));}console.log(f.gray.bold("\u2500".repeat(50)));}else {console.log(),console.log(f.gray("Your Output:"));for(let s of o)console.log(f.white(` ${s}`));console.log(),console.log(f.gray("Expected Output:"));for(let s of n)console.log(f.white(` ${s}`));}let r=(e.std_output_list??[]).filter(s=>s);if(r.length>0){console.log(),console.log(f.gray("Stdout:"));for(let s of r)console.log(f.gray(` ${s}`));}}function Un(e){if(console.log(),e.compile_error){console.log(f.red.bold("\u274C Compile Error")),console.log(f.red(e.compile_error));return}if(e.runtime_error){console.log(f.red.bold("\u274C Runtime Error")),console.log(f.red(e.runtime_error)),e.last_testcase&&console.log(f.gray("Last testcase:"),e.last_testcase);return}e.status_msg==="Accepted"?(console.log(f.green.bold("\u2713 Accepted!")),console.log(),console.log(f.gray("Runtime:"),f.white(e.status_runtime),f.gray(`(beats ${e.runtime_percentile?.toFixed(1)??"N/A"}%)`)),console.log(f.gray("Memory:"),f.white(e.status_memory),f.gray(`(beats ${e.memory_percentile?.toFixed(1)??"N/A"}%)`))):(console.log(f.red.bold(`\u274C ${e.status_msg}`)),console.log(),console.log(f.gray(`Passed ${e.total_correct}/${e.total_testcases} testcases`)),e.code_output&&console.log(f.gray("Your Output:"),e.code_output),e.expected_output&&console.log(f.gray("Expected:"),e.expected_output),e.last_testcase&&console.log(f.gray("Failed testcase:"),e.last_testcase));}function Bn(e,t,o,n,r,s){console.log(),console.log(f.bold.white(`\u{1F464} ${e}`)+(t?f.gray(` (${t})`):"")),console.log(f.gray(`Ranking: #${o.toLocaleString()}`)),console.log();let i=new po({head:[f.cyan("Difficulty"),f.cyan("Solved")],style:{head:[],border:[]}});for(let l of n)l.difficulty!=="All"&&i.push([It(l.difficulty),l.count.toString()]);let a=n.find(l=>l.difficulty==="All")?.count??0;i.push([f.white.bold("Total"),f.white.bold(a.toString())]),console.log(i.toString()),console.log(),console.log(f.gray("\u{1F525} Current streak:"),f.hex("#FFA500")(r.toString()),f.gray("days")),console.log(f.gray("\u{1F4C5} Total active days:"),f.white(s.toString()));}function Wn(e,t){if(console.log(),console.log(f.bold.yellow("\u{1F3AF} Daily Challenge"),f.gray(`(${e})`)),console.log(),console.log(f.white(`${t.questionFrontendId}. ${t.title}`)),console.log(It(t.difficulty)),console.log(f.gray(`https://leetcode.com/problems/${t.titleSlug}/`)),t.topicTags.length){console.log();let o=t.topicTags.map(n=>f.blue(n.name)).join(" ");console.log(f.gray("Tags:"),o);}}function It(e){switch(e.toLowerCase()){case "easy":return f.green(e);case "medium":return f.yellow(e);case "hard":return f.red(e);default:return e}}function _i(e){switch(e){case "ac":return f.green("\u2713");case "notac":return f.yellow("\u25CB");default:return f.gray("-")}}function fo(e){let t=new po({head:[f.cyan("ID"),f.cyan("Status"),f.cyan("Lang"),f.cyan("Runtime"),f.cyan("Memory"),f.cyan("Date")],colWidths:[12,18,15,12,12,25],style:{head:[],border:[]}});for(let o of e){let n=o.statusDisplay==="Accepted",r=new Date(parseInt(o.timestamp)*1e3).toLocaleString();t.push([o.id,n?f.green(o.statusDisplay):f.red(o.statusDisplay),o.lang,o.runtime,o.memory,r]);}console.log(t.toString());}async function jn(e){let{authorized:t}=await v();if(!t)return;let o=Gt("Fetching problems...").start();try{let n={},r=parseInt(e.limit??"20",10),s=parseInt(e.page??"1",10);if(n.limit=r,n.skip=(s-1)*r,e.difficulty){let l={easy:"EASY",e:"EASY",medium:"MEDIUM",m:"MEDIUM",hard:"HARD",h:"HARD"};n.difficulty=l[e.difficulty.toLowerCase()];}if(e.status){let l={todo:"NOT_STARTED",solved:"AC",ac:"AC",attempted:"TRIED",tried:"TRIED"};n.status=l[e.status.toLowerCase()];}e.tag?.length&&(n.tags=e.tag),e.search&&(n.searchKeywords=e.search);let{total:i,problems:a}=await S.getProblems(n);if(o.stop(),a.length===0){console.log(f.yellow("No problems found matching your criteria."));return}Nn(a,i),s*r<i&&console.log(f.gray(`
|
|
176
|
+
Page ${s} of ${Math.ceil(i/r)}. Use --page to navigate.`));}catch(n){o.fail("Failed to fetch problems"),n instanceof Error&&console.log(f.red(n.message));}}async function Nt(e){let{authorized:t}=await v();if(!t)return;let o=Gt("Fetching problem...").start();try{let n;if(/^\d+$/.test(e)?n=await S.getProblemById(e):n=await S.getProblem(e),!n){o.fail(`Problem "${e}" not found`);return}o.stop(),Fn(n);}catch(n){o.fail("Failed to fetch problem"),n instanceof Error&&console.log(f.red(n.message));}}async function Gn(e,t){let{authorized:o}=await v();if(!o)return;let n=Gt("Fetching problem hints...").start();try{let r;if(/^\d+$/.test(e)?r=await S.getProblemById(e):r=await S.getProblem(e),!r){n.fail(`Problem "${e}" not found`);return}n.stop(),console.log(),console.log(f.bold.cyan(`${r.questionFrontendId}. ${r.title}`)),console.log();let s=r.hints||[];if(s.length===0){console.log(f.yellow("\u26A0 No hints available for this problem.")),console.log(f.gray("Try working through the problem description and examples first!"));return}t.all?s.forEach((i,a)=>{Kn(i,a+1,s.length);}):await Pi(s);}catch(r){n.fail("Failed to fetch problem hints"),r instanceof Error&&console.log(f.red(r.message));}}function Kn(e,t,o){let n=Oi(e);console.log(f.bold.yellow(`\u{1F4A1} Hint ${t}/${o}`)),console.log(f.white(n)),console.log();}function Oi(e){let t=e.replace(/<code>/g,f.cyan("`")).replace(/<\/code>/g,f.cyan("`")).replace(/<b>/g,f.bold("")).replace(/<\/b>/g,"").replace(/<i>/g,f.italic("")).replace(/<\/i>/g,"").replace(/<br\s*\/?>/g,`
|
|
177
|
+
`).replace(/<p>/g,"").replace(/<\/p>/g,`
|
|
178
|
+
`);return (Mi(t)??"").replace(/</g,"<").replace(/>/g,">").replace(/ /g," ").replace(/"/g,'"').replace(/&/g,"&").trim()}async function Pi(e){let o=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),n=r=>new Promise(s=>{if(r>=e.length){console.log(f.green("\u2713 All hints revealed! Good luck solving the problem!")),o.close(),s();return}Kn(e[r],r+1,e.length),r<e.length-1?o.question(f.gray(`Press Enter for next hint (${e.length-r-1} remaining), or 'q' to quit: `),i=>{i.toLowerCase()==="q"?(console.log(f.gray(`
|
|
179
|
+
Good luck! You can always run this command again for more hints.`)),o.close(),s()):s(n(r+1));}):(console.log(f.green("\u2713 All hints revealed! Good luck solving the problem!")),o.close(),s());});await n(0);}function Ae(e){return /^\d+$/.test(e)}function Ft(e){return !e.includes("/")&&!e.includes("\\")&&e.includes(".")}var $i=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/,vi=/^[a-zA-Z0-9][a-zA-Z0-9 _-]{0,63}$/;function Ve(e){return $i.test(e.trim())}function zn(e){return vi.test(e.trim())}function ze(e,t){let o=resolve(e),n=resolve(t),r=n.endsWith(sep)?n:n+sep;return o===n||o.startsWith(r)}var bo=join(homedir(),".leetcode"),ho=join(bo,"workspaces.json"),Ht=join(bo,"workspaces");function Ut(e){existsSync(e)||mkdirSync(e,{recursive:true});}function Ue(){return existsSync(ho)?JSON.parse(readFileSync(ho,"utf-8")):{active:"default",workspaces:[]}}function mt(e){Ut(bo),writeFileSync(ho,JSON.stringify(e,null,2));}function Le(e){let t=e.trim();return Ve(t)?t:null}var T={ensureInitialized(){let e=Ue(),t=e.workspaces.map(r=>Le(r)).filter(r=>r!==null),o=false;if(t.length!==e.workspaces.length&&(e.workspaces=[...new Set(t)],o=true),e.workspaces.length===0){this.create("default",{workDir:join(homedir(),"leetcode"),lang:"typescript"}),e.workspaces=["default"],e.active="default",mt(e);return}let n=Le(e.active);!n||!e.workspaces.includes(n)?(e.active=e.workspaces[0],o=true):n!==e.active&&(e.active=n,o=true),o&&mt(e);},getActive(){return this.ensureInitialized(),Ue().active},setActive(e){let t=Le(e);if(!t)return false;let o=Ue();return o.workspaces.includes(t)?(o.active=t,mt(o),true):false},list(){return this.ensureInitialized(),Ue().workspaces},exists(e){let t=Le(e);return t?(this.ensureInitialized(),Ue().workspaces.includes(t)):false},create(e,t){let o=Le(e);if(!o)return false;let n=Ue();if(n.workspaces.includes(o))return false;let r=join(Ht,o);Ut(r),Ut(join(r,"snapshots"));let s=join(r,"config.json");return writeFileSync(s,JSON.stringify(t,null,2)),writeFileSync(join(r,"timer.json"),JSON.stringify({solveTimes:{},activeTimer:null},null,2)),writeFileSync(join(r,"collab.json"),JSON.stringify({session:null},null,2)),n.workspaces.push(o),mt(n),true},delete(e){let t=Le(e);if(!t||t==="default")return false;let o=Ue();return o.workspaces.includes(t)?(o.workspaces=o.workspaces.filter(n=>n!==t),o.active===t&&(o.active="default"),mt(o),true):false},getWorkspaceDir(e){let t=e?Le(e)||"default":this.getActive();return join(Ht,t)},getConfig(e){let t=e?Le(e)||"default":this.getActive(),o=join(Ht,t,"config.json");return existsSync(o)?JSON.parse(readFileSync(o,"utf-8")):{workDir:join(homedir(),"leetcode"),lang:"typescript"}},setConfig(e,t){let o=t?Le(t)||"default":this.getActive(),n=join(Ht,o);Ut(n);let s={...this.getConfig(o),...e};writeFileSync(join(n,"config.json"),JSON.stringify(s,null,2));},getSnapshotsDir(){return join(this.getWorkspaceDir(),"snapshots")},getTimerPath(){return join(this.getWorkspaceDir(),"timer.json")},getCollabPath(){return join(this.getWorkspaceDir(),"collab.json")}};var M={getConfig(){let e=T.getConfig();return {language:e.lang,editor:e.editor,workDir:e.workDir,repo:e.syncRepo}},setLanguage(e){T.setConfig({lang:e});},setEditor(e){T.setConfig({editor:e});},setWorkDir(e){T.setConfig({workDir:e});},setRepo(e){T.setConfig({syncRepo:e});},deleteRepo(){let e=T.getConfig();delete e.syncRepo,T.setConfig(e);},getLanguage(){return T.getConfig().lang},getEditor(){return T.getConfig().editor},getWorkDir(){return T.getConfig().workDir},getRepo(){return T.getConfig().syncRepo},getPath(){return join(T.getWorkspaceDir(),"config.json")},getActiveWorkspace(){return T.getActive()}};var Ye={typescript:"ts",javascript:"js",python3:"py",java:"java",cpp:"cpp",c:"c",csharp:"cs",go:"go",rust:"rs",kotlin:"kt",swift:"swift"},Be={typescript:"typescript",javascript:"javascript",python3:"python3",python:"python3",java:"java","c++":"cpp",cpp:"cpp",c:"c","c#":"csharp",csharp:"csharp",go:"go",golang:"go",rust:"rust",kotlin:"kotlin",swift:"swift"};function Bt(e,t){let o=e.find(n=>Be[n.langSlug.toLowerCase()]===t);return o||(e[0]??null)}function Wt(e,t,o,n,r,s,i){let a=Ni(s);return `${Hi(a,e,o,n,t,i)}
|
|
180
|
+
|
|
181
|
+
${r}
|
|
182
|
+
`}function Ni(e){return e==="python3"?{single:"#",blockStart:'"""',blockEnd:'"""',linePrefix:""}:{single:"//",blockStart:"/*",blockEnd:"*/",linePrefix:" * "}}function Fi(e){let t=e;return t=t.replace(/<sup>(.*?)<\/sup>/gi,"^$1"),t=t.replace(/<strong class="example">Example (\d+):<\/strong>/gi,`
|
|
183
|
+
Example $1:`),t=t.replace(/<li>/gi,"\u2022 "),t=t.replace(/<\/li>/gi,`
|
|
166
184
|
`),t=t.replace(/<\/p>/gi,`
|
|
167
185
|
|
|
168
186
|
`),t=t.replace(/<br\s*\/?>/gi,`
|
|
169
|
-
`),t=
|
|
170
|
-
|
|
171
|
-
`).trim(),t
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
`).
|
|
175
|
-
|
|
176
|
-
Page ${r} of ${Math.ceil(i/s)}. Use --page to navigate.`));}catch(n){t.fail("Failed to fetch problems"),n instanceof Error&&console.log(l.red(n.message));}}async function Re(e){let{authorized:o}=await $();if(!o)return;let t=Ue("Fetching problem...").start();try{let n;if(/^\d+$/.test(e)?n=await h.getProblemById(e):n=await h.getProblem(e),!n){t.fail(`Problem "${e}" not found`);return}t.stop(),jo(n);}catch(n){t.fail("Failed to fetch problem"),n instanceof Error&&console.log(l.red(n.message));}}async function Vo(e,o){let{authorized:t}=await $();if(!t)return;let n=Ue("Fetching problem hints...").start();try{let s;if(/^\d+$/.test(e)?s=await h.getProblemById(e):s=await h.getProblem(e),!s){n.fail(`Problem "${e}" not found`);return}n.stop(),console.log(),console.log(l.bold.cyan(`${s.questionFrontendId}. ${s.title}`)),console.log();let r=s.hints||[];if(r.length===0){console.log(l.yellow("\u26A0 No hints available for this problem.")),console.log(l.gray("Try working through the problem description and examples first!"));return}o.all?r.forEach((i,a)=>{zo(i,a+1,r.length);}):await Un(r);}catch(s){n.fail("Failed to fetch problem hints"),s instanceof Error&&console.log(l.red(s.message));}}function zo(e,o,t){let n=In(e);console.log(l.bold.yellow(`\u{1F4A1} Hint ${o}/${t}`)),console.log(l.white(n)),console.log();}function In(e){let o=e.replace(/<code>/g,l.cyan("`")).replace(/<\/code>/g,l.cyan("`")).replace(/<b>/g,l.bold("")).replace(/<\/b>/g,"").replace(/<i>/g,l.italic("")).replace(/<\/i>/g,"").replace(/<br\s*\/?>/g,`
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
`),o=o.replace(/<\/p>/gi,`
|
|
185
|
-
|
|
186
|
-
`),o=o.replace(/<br\s*\/?>/gi,`
|
|
187
|
-
`),o=En(o)??"",o=o.replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/≤/g,"<=").replace(/≥/g,">=").replace(/&#(\d+);/g,(t,n)=>String.fromCharCode(parseInt(n,10))).replace(/&/g,"&"),o=o.replace(/\n{3,}/g,`
|
|
188
|
-
|
|
189
|
-
`).trim(),o}function Wn(e,o,t,n,s,r){let i=e.linePrefix,a=[e.blockStart,`${i}${o}. ${t}`,`${i}Difficulty: ${n}`,`${i}https://leetcode.com/problems/${s}/`];if(r){a.push(`${i}`),a.push(`${i}${"\u2500".repeat(50)}`),a.push(`${i}`);let g=Hn(r).split(`
|
|
190
|
-
`);for(let u of g)if(u.length>70){let p=u.split(" "),b="";for(let x of p)(b+" "+x).length>70?(a.push(`${i}${b.trim()}`),b=x):b+=" "+x;b.trim()&&a.push(`${i}${b.trim()}`);}else a.push(`${i}${u}`);}return a.push(e.blockEnd),a.join(`
|
|
191
|
-
`)}function Qo(e,o,t){let n=me[t];return `${e}.${o}.${n}`}var Gn=["vim","nvim","vi","nano","emacs","micro","helix"],Yn=["code","code-insiders","cursor","codium","vscodium"];async function ke(e,o){let t=w.getEditor()??process.env.EDITOR??"code",n=w.getWorkDir();if(Gn.includes(t)){console.log(),console.log(l.gray(`Open with: ${t} ${e}`));return}try{if(Yn.includes(t)){spawn(t,["-r",n,"-g",e],{detached:!0,stdio:"ignore"}).unref();return}await zn(e,{app:{name:t}});}catch{}}async function Q(e,o){let{authorized:t}=await $();if(!t)return false;let n=Ue({text:"Fetching problem details...",spinner:"dots"}).start();try{let s;if(/^\d+$/.test(e)?s=await h.getProblemById(e):s=await h.getProblem(e),!s)return n.fail(`Problem "${e}" not found`),!1;n.text="Generating solution file...";let r=o.lang?.toLowerCase()??w.getLanguage(),i=$e[r]??r,a=s.codeSnippets??[],c=Go(a,i),g;if(a.length===0)n.warn(l.yellow("Premium Problem (No code snippets available)")),console.log(l.gray("Generating placeholder file with problem info...")),g=`// \u{1F512} Premium Problem - ${s.title}
|
|
192
|
-
// Solution stub not available - visit LeetCode to view`;else if(c)g=c.code;else return n.fail(`No code template available for ${i}`),console.log(l.gray(`Available languages: ${a.map(ee=>ee.langSlug).join(", ")}`)),!1;let u=Yo(s.questionFrontendId,s.titleSlug,s.title,s.difficulty,g,i,s.content??void 0),p=w.getWorkDir(),b=s.difficulty,x=s.topicTags.length>0?s.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",I=join(p,b,x);existsSync(I)||await mkdir(I,{recursive:!0});let F=Qo(s.questionFrontendId,s.titleSlug,i),q=join(I,F);return existsSync(q)?(n.warn(`File already exists: ${F}`),console.log(l.gray(`Path: ${q}`)),o.open!==!1&&await ke(q),!0):(await writeFile(q,u,"utf-8"),n.succeed(`Created ${l.green(F)}`),console.log(l.gray(`Path: ${q}`)),console.log(),console.log(l.cyan(`${s.questionFrontendId}. ${s.title}`)),console.log(l.gray(`Difficulty: ${s.difficulty} | Category: ${x}`)),o.open!==!1&&await ke(q),!0)}catch(s){if(n.fail("Failed to fetch problem"),s instanceof Error)if(s.message.includes("expected object, received null"))console.log(l.red(`Problem "${e}" not found`));else try{let r=JSON.parse(s.message);Array.isArray(r)?console.log(l.red("API Response Validation Failed")):console.log(l.red(s.message));}catch{console.log(l.red(s.message));}return false}}async function Xo(e,o){if(e.length===0){console.log(l.yellow("Please provide at least one problem ID"));return}let{authorized:t}=await $();if(!t)return;console.log(l.cyan(`\u{1F4E6} Picking ${e.length} problem${e.length!==1?"s":""}...`)),console.log(),console.log();let n=0,s=0;for(let r of e)await Q(r,{...o,open:false})?n++:s++,console.log();console.log(l.gray("\u2500".repeat(50))),console.log(l.bold(`Done! ${l.green(`${n} succeeded`)}${s>0?`, ${l.red(`${s} failed`)}`:""}`));}var tt=5;async function H(e,o,t=0){if(!existsSync(e)||t>=tt)return null;let n=await readdir(e,{withFileTypes:true});for(let s of n){if(s.name.startsWith("."))continue;let r=join(e,s.name);if(s.isDirectory()){let i=await H(r,o,t+1);if(i)return i}else if(s.name.startsWith(`${o}.`)){let i=s.name.split(".").pop()?.toLowerCase();if(i&&i in Xn)return r}}return null}async function ve(e,o,t=0){if(!existsSync(e)||t>=tt)return null;let n=await readdir(e,{withFileTypes:true});for(let s of n){let r=join(e,s.name);if(s.isDirectory()){let i=await ve(r,o,t+1);if(i)return i}else if(s.name===o)return r}return null}var Xn={ts:"typescript",js:"javascript",py:"python3",java:"java",cpp:"cpp",c:"c",cs:"csharp",go:"go",rs:"rust",kt:"kotlin",swift:"swift"};function le(e){return {ts:"typescript",js:"javascript",py:"python3",java:"java",cpp:"cpp",c:"c",cs:"csharp",go:"golang",rs:"rust",kt:"kotlin",swift:"swift"}[e.toLowerCase()]??null}function te(e){return /^\d+$/.test(e)}function Ie(e){return !e.includes("/")&&!e.includes("\\")&&e.includes(".")}function de(e,o){let t=resolve(e),n=resolve(o),s=n.endsWith(sep)?n:n+sep;return t===n||t.startsWith(s)}async function rt(e,o){let{authorized:t}=await $();if(!t)return;let n=e,s=w.getWorkDir();if(te(e)){let i=await H(s,e);if(!i){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.gray(`Looking in: ${s}`)),console.log(l.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}n=i,console.log(l.gray(`Found: ${n}`));}else if(Ie(e)){let i=await ve(s,e);if(!i){console.log(l.red(`File not found: ${e}`)),console.log(l.gray(`Looking in: ${s}`));return}n=i,console.log(l.gray(`Found: ${n}`));}if(!existsSync(n)){console.log(l.red(`File not found: ${n}`));return}if(!de(n,s)){console.log(l.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(l.gray(`File: ${n}`)),console.log(l.gray(`Workspace: ${s}`)),console.log(l.yellow(`
|
|
193
|
-
For security reasons, you can only test files from within your workspace.`)),console.log(l.gray('Use "leetcode config workdir <path>" to change your workspace.'));return}let r=Ue({text:"Reading solution file...",spinner:"dots"}).start();try{let i=basename(n),a=i.match(/^(\d+)\.([^.]+)\./);if(!a){r.fail("Invalid filename format"),console.log(l.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(l.gray("Example: 1.two-sum.ts"));return}let c=a[2],g=i.split(".").pop(),u=le(g);if(!u){r.fail(`Unsupported file extension: .${g}`);return}let p=await readFile(n,"utf-8");r.text="Fetching problem details...";let b=await h.getProblem(c),x=o.testcase??b.exampleTestcases??b.sampleTestCase;r.text="Running tests...";let I=await h.testSolution(c,p,u,x,b.questionId);r.stop(),Mo(I,o.visualize?b.topicTags:void 0);}catch(i){r.fail("Test failed"),i instanceof Error&&console.log(l.red(i.message));}}function at(){return k.getTimerPath()}function ce(){let e=at();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{solveTimes:{},activeTimer:null}}function Je(e){let o=at(),t=dirname(o);existsSync(t)||mkdirSync(t,{recursive:true}),writeFileSync(o,JSON.stringify(e,null,2));}var G={startTimer(e,o,t,n){let s=ce();s.activeTimer={problemId:e,title:o,difficulty:t,startedAt:new Date().toISOString(),durationMinutes:n},Je(s);},getActiveTimer(){return ce().activeTimer},stopTimer(){let e=ce(),o=e.activeTimer;if(!o)return null;let t=new Date(o.startedAt),s=Math.floor((new Date().getTime()-t.getTime())/1e3);return e.activeTimer=null,Je(e),{durationSeconds:s}},recordSolveTime(e,o,t,n,s){let r=ce();r.solveTimes[e]||(r.solveTimes[e]=[]),r.solveTimes[e].push({problemId:e,title:o,difficulty:t,solvedAt:new Date().toISOString(),durationSeconds:n,timerMinutes:s}),Je(r);},getSolveTimes(e){return ce().solveTimes[e]??[]},getAllSolveTimes(){return ce().solveTimes??{}},getStats(){let e=ce().solveTimes??{},o=0,t=0;for(let n of Object.values(e)){o+=n.length;for(let s of n)t+=s.durationSeconds;}return {totalProblems:o,totalTime:t,avgTime:o>0?Math.floor(t/o):0}}};async function lt(e){let{authorized:o}=await $();if(!o)return;let t=e,n=w.getWorkDir();if(te(e)){let r=await H(n,e);if(!r){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.gray(`Looking in: ${n}`)),console.log(l.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}t=r,console.log(l.gray(`Found: ${t}`));}else if(Ie(e)){let r=await ve(n,e);if(!r){console.log(l.red(`File not found: ${e}`)),console.log(l.gray(`Looking in: ${n}`));return}t=r,console.log(l.gray(`Found: ${t}`));}if(!existsSync(t)){console.log(l.red(`File not found: ${t}`));return}if(!de(t,n)){console.log(l.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(l.gray(`File: ${t}`)),console.log(l.gray(`Workspace: ${n}`)),console.log(l.yellow(`
|
|
194
|
-
For security reasons, you can only submit files from within your workspace.`)),console.log(l.gray('Use "leetcode config workdir <path>" to change your workspace.'));return}let s=Ue({text:"Reading solution file...",spinner:"dots"}).start();try{let r=basename(t),i=r.match(/^(\d+)\.([^.]+)\./);if(!i){s.fail("Invalid filename format"),console.log(l.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(l.gray("Example: 1.two-sum.ts"));return}let[,a,c]=i,g=r.split(".").pop(),u=le(g);if(!u){s.fail(`Unsupported file extension: .${g}`);return}let p=await readFile(t,"utf-8");s.text="Fetching problem details...";let b=await h.getProblem(c);s.text="Submitting solution...";let x=await h.submitSolution(c,p,u,b.questionId);if(s.stop(),qo(x),x.status_msg==="Accepted"){let I=G.getActiveTimer();if(I&&I.problemId===a){let F=G.stopTimer();if(F){G.recordSolveTime(a,b.title,b.difficulty,F.durationSeconds,I.durationMinutes);let q=Math.floor(F.durationSeconds/60),ee=F.durationSeconds%60,ie=`${q}m ${ee}s`,V=F.durationSeconds<=I.durationMinutes*60;console.log(),console.log(l.bold("\u23F1\uFE0F Timer Result:")),console.log(` Solved in ${V?l.green(ie):l.yellow(ie)} (limit: ${I.durationMinutes}m)`),console.log(V?l.green(" \u2713 Within time limit!"):l.yellow(" \u26A0 Exceeded time limit"));}}}}catch(r){s.fail("Submission failed"),r instanceof Error&&console.log(l.red(r.message));}}var ct=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function gt(e){let o=JSON.parse(e),t=new Date,n=[];for(let i=11;i>=0;i--){let a=new Date(t);a.setDate(a.getDate()-i*7-a.getDay());let c=0,g=0;for(let p=0;p<7;p++){let b=new Date(a);if(b.setDate(b.getDate()+p),b>t)break;let x=new Date(Date.UTC(b.getFullYear(),b.getMonth(),b.getDate())),I=Math.floor(x.getTime()/1e3).toString(),F=o[I]||0;c+=F,F>0&&g++;}let u=new Date(a);u.setDate(u.getDate()+6),n.push({start:`${ct[a.getMonth()]} ${a.getDate()}`,end:`${ct[u.getMonth()]} ${u.getDate()}`,count:c,days:g});}let s=n.reduce((i,a)=>i+a.count,0),r=n.reduce((i,a)=>i+a.days,0);console.log(),console.log(l.bold("\u{1F4C5} Activity (Last 12 Weeks)")),console.log(l.gray("How many problems you submitted and days you practiced.")),console.log(l.gray("\u2500".repeat(50))),console.log();for(let i of n){let a=`${i.start} - ${i.end}`.padEnd(18),c=i.count>0?l.green("\u2588".repeat(Math.min(i.count,10))).padEnd(10):l.gray("\xB7").padEnd(10),g=i.count>0?`${i.count} subs`.padEnd(10):"".padEnd(10),u=i.days>0?`${i.days}d active`:"";console.log(` ${l.white(a)} ${c} ${l.cyan(g)} ${l.yellow(u)}`);}console.log(l.gray("\u2500".repeat(50))),console.log(` ${l.bold.white("Total:")} ${l.cyan.bold(s+" submissions")}, ${l.yellow.bold(r+" days active")}`),console.log();}function mt(e,o,t){console.log(),console.log(l.bold("\u{1F3AF} Skill Breakdown")),console.log(l.gray("\u2500".repeat(45)));let n=(s,r,i)=>{if(r.length===0)return;console.log(),console.log(i.bold(` ${s}`));let a=[...r].sort((c,g)=>g.problemsSolved-c.problemsSolved);for(let c of a.slice(0,8)){let g=c.tagName.padEnd(22),u=i("\u2588".repeat(Math.min(c.problemsSolved,15)));console.log(` ${l.white(g)} ${u} ${l.white(c.problemsSolved)}`);}};n("Fundamental",e,l.green),n("Intermediate",o,l.yellow),n("Advanced",t,l.red),console.log();}function dt(e){let o=JSON.parse(e),t=new Date,n=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=[];for(let c=6;c>=0;c--){let g=new Date(t);g.setDate(g.getDate()-c);let u=new Date(Date.UTC(g.getFullYear(),g.getMonth(),g.getDate())),p=Math.floor(u.getTime()/1e3).toString();s.push({label:n[g.getDay()],count:o[p]||0});}let r=Math.max(...s.map(c=>c.count),1),i=6;console.log(),console.log(l.bold("\u{1F4C8} Submission Trend (Last 7 Days)")),console.log(l.gray("\u2500".repeat(35))),console.log();for(let c=i;c>=1;c--){let g=` ${c===i?r.toString().padStart(2):" "} \u2502`;for(let u of s)Math.round(u.count/r*i)>=c?g+=l.green(" \u2588\u2588 "):g+=" ";console.log(g);}console.log(` 0 \u2514${"\u2500\u2500\u2500\u2500".repeat(7)}`),console.log(` ${s.map(c=>c.label.padEnd(4)).join("")}`),console.log(l.gray(` ${s.map(c=>c.count.toString().padEnd(4)).join("")}`));let a=s.reduce((c,g)=>c+g.count,0);console.log(),console.log(l.white(` Total: ${a} submissions this week`)),console.log();}async function ut(e,o={}){let{authorized:t,username:n}=await $();if(!t)return;let s=Ue("Fetching statistics...").start();try{let r=e||n;if(!r){s.fail("No username found");return}let i=await h.getUserProfile(r);if(s.stop(),!o.calendar&&!o.skills&&!o.trend){Oo(i.username,i.realName,i.ranking,i.acSubmissionNum,i.streak,i.totalActiveDays);return}if(o.calendar&&(i.submissionCalendar?gt(i.submissionCalendar):console.log(l.yellow("Calendar data not available."))),o.trend&&(i.submissionCalendar?dt(i.submissionCalendar):console.log(l.yellow("Calendar data not available."))),o.skills){s.start("Fetching skill stats...");let a=await h.getSkillStats(r);s.stop(),mt(a.fundamental,a.intermediate,a.advanced);}}catch(r){s.fail("Failed to fetch statistics"),r instanceof Error&&console.log(l.red(r.message));}}async function pt(){let{authorized:e}=await $();if(!e)return;let o=Ue("Fetching daily challenge...").start();try{let t=await h.getDailyChallenge();o.stop(),Ho(t.date,t.question),console.log(),console.log(l.gray("Run the following to start working on this problem:")),console.log(l.cyan(` leetcode pick ${t.question.titleSlug}`));}catch(t){o.fail("Failed to fetch daily challenge"),t instanceof Error&&console.log(l.red(t.message));}}async function ft(e){let{authorized:o}=await $();if(!o)return;let t=Ue("Fetching random problem...").start();try{let n={};if(e.difficulty){let i={easy:"EASY",e:"EASY",medium:"MEDIUM",m:"MEDIUM",hard:"HARD",h:"HARD"}[e.difficulty.toLowerCase()];if(i)n.difficulty=i;else {t.fail(`Invalid difficulty: ${e.difficulty}`);return}}e.tag&&(n.tags=[e.tag]);let s=await h.getRandomProblem(n);t.succeed("Found random problem!"),console.log(),e.pick?await Q(s,{open:e.open??!0}):(await Re(s),console.log(l.gray("Run following to start solving:")),console.log(l.cyan(` leetcode pick ${s}`)));}catch(n){t.fail("Failed to fetch random problem"),n instanceof Error&&console.log(l.red(n.message));}}async function bt(e,o){let{authorized:t}=await $();if(!t)return;let n=Ue("Fetching problem info...").start();try{let s;if(/^\d+$/.test(e)?s=await h.getProblemById(e):s=await h.getProblem(e),!s){n.fail(`Problem "${e}" not found`);return}let r=s.titleSlug;n.text="Fetching submissions...";let i=o.limit?parseInt(o.limit,10):20,a=await h.getSubmissionList(r,i);if(n.stop(),a.length===0){console.log(l.yellow("No submissions found."));return}if(o.last){let c=a.find(g=>g.statusDisplay==="Accepted");c?(console.log(l.bold("Last Accepted Submission:")),Ve([c])):console.log(l.yellow("No accepted submissions found in recent history."));}else Ve(a);if(o.download){let c=Ue("Downloading submission...").start(),g=a.find(bn=>bn.statusDisplay==="Accepted");if(!g){c.fail("No accepted submission found to download.");return}let u=parseInt(g.id,10);if(isNaN(u)){c.fail("Invalid submission ID format");return}let p=await h.getSubmissionDetails(u),b=w.getWorkDir(),x=s.difficulty,I=s.topicTags.length>0?s.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",F=join(b,x,I);existsSync(F)||await mkdir(F,{recursive:!0});let q=p.lang.name,ee=$e[q]??"txt",ie=me[ee]??q,V=`${s.questionFrontendId}.${s.titleSlug}.submission-${g.id}.${ie}`,lo=join(F,V);await writeFile(lo,p.code,"utf-8"),c.succeed(`Downloaded to ${l.green(V)}`),console.log(l.gray(`Path: ${lo}`));}}catch(s){n.fail("Failed to fetch submissions"),s instanceof Error&&console.log(l.red(s.message));}}var eo=["typescript","javascript","python3","java","cpp","c","csharp","go","rust","kotlin","swift"];async function wt(e){if(!e.lang&&!e.editor&&!e.workdir){$t();return}if(e.lang){let o=e.lang.toLowerCase();if(!eo.includes(o)){console.log(l.red(`Unsupported language: ${e.lang}`)),console.log(l.gray(`Supported: ${eo.join(", ")}`));return}let t=o;w.setLanguage(t),console.log(l.green(`\u2713 Default language set to ${t}`));}e.editor&&(w.setEditor(e.editor),console.log(l.green(`\u2713 Editor set to ${e.editor}`))),e.workdir&&(w.setWorkDir(e.workdir),console.log(l.green(`\u2713 Work directory set to ${e.workdir}`))),e.repo!==void 0&&(e.repo.trim()===""?(w.deleteRepo(),console.log(l.green("\u2713 Repository URL cleared"))):(w.setRepo(e.repo),console.log(l.green(`\u2713 Repository URL set to ${e.repo}`))));}async function St(){let e=w.getConfig(),o=w.getActiveWorkspace();console.log(),console.log(l.bold.cyan(`\u{1F4C1} Configuring workspace: ${o}`)),console.log(l.gray("\u2500".repeat(40)));let t=await to.prompt([{type:"list",name:"language",message:"Default programming language:",choices:eo,default:e.language},{type:"input",name:"editor",message:"Editor command (e.g., code, vim, nvim):",default:e.editor??"code"},{type:"input",name:"workDir",message:"Working directory for solution files:",default:e.workDir},{type:"input",name:"repo",message:"Git repository URL (optional):",default:e.repo}]);w.setLanguage(t.language),w.setEditor(t.editor),w.setWorkDir(t.workDir),t.repo?w.setRepo(t.repo):w.deleteRepo(),console.log(),console.log(l.green("\u2713 Configuration saved")),$t();}function $t(){let e=w.getConfig(),o=X.get(),t=w.getActiveWorkspace();console.log(),console.log(l.bold.cyan(`\u{1F4C1} Workspace: ${t}`)),console.log(l.gray("\u2500".repeat(40))),console.log(),console.log(l.gray("Config file:"),w.getPath()),console.log(),console.log(l.gray("Language: "),l.white(e.language)),console.log(l.gray("Editor: "),l.white(e.editor??"(not set)")),console.log(l.gray("Work Dir: "),l.white(e.workDir)),console.log(l.gray("Repo URL: "),l.white(e.repo??"(not set)")),console.log(l.gray("Logged in: "),o?l.green("Yes"):l.yellow("No"));}var ne=new vn({projectName:"leetcode-cli-bookmarks",defaults:{bookmarks:[]}}),pe={add(e){let o=ne.get("bookmarks");return o.includes(e)?false:(ne.set("bookmarks",[...o,e]),true)},remove(e){let o=ne.get("bookmarks");return o.includes(e)?(ne.set("bookmarks",o.filter(t=>t!==e)),true):false},list(){return ne.get("bookmarks")},has(e){return ne.get("bookmarks").includes(e)},count(){return ne.get("bookmarks").length},clear(){ne.set("bookmarks",[]);}};async function kt(e,o){if(!["add","remove","list","clear"].includes(e)){console.log(l.red(`Invalid action: ${e}`)),console.log(l.gray("Valid actions: add, remove, list, clear"));return}switch(e){case "add":if(!o){console.log(l.red("Please provide a problem ID to bookmark"));return}if(!te(o)){console.log(l.red(`Invalid problem ID: ${o}`)),console.log(l.gray("Problem ID must be a positive integer"));return}pe.add(o)?console.log(l.green(`\u2713 Bookmarked problem ${o}`)):console.log(l.yellow(`Problem ${o} is already bookmarked`));break;case "remove":if(!o){console.log(l.red("Please provide a problem ID to remove"));return}pe.remove(o)?console.log(l.green(`\u2713 Removed bookmark for problem ${o}`)):console.log(l.yellow(`Problem ${o} is not bookmarked`));break;case "list":await $s();break;case "clear":let n=pe.count();n===0?console.log(l.yellow("No bookmarks to clear")):(pe.clear(),console.log(l.green(`\u2713 Cleared ${n} bookmark${n!==1?"s":""}`)));break}}async function $s(){let e=pe.list();if(e.length===0){console.log(l.yellow("\u{1F4CC} No bookmarked problems")),console.log(l.gray('Use "leetcode bookmark add <id>" to bookmark a problem'));return}console.log(),console.log(l.bold.cyan(`\u{1F4CC} Bookmarked Problems (${e.length})`)),console.log();let{authorized:o}=await $();if(o){let t=Ue({text:"Fetching problem details...",spinner:"dots"}).start();try{let n=new We({head:[l.cyan("ID"),l.cyan("Title"),l.cyan("Difficulty"),l.cyan("Status")],colWidths:[8,45,12,10],style:{head:[],border:[]}});for(let s of e)try{let r=await h.getProblemById(s);r?n.push([r.questionFrontendId,r.title.length>42?r.title.slice(0,39)+"...":r.title,ks(r.difficulty),r.status==="ac"?l.green("\u2713"):l.gray("-")]):n.push([s,l.gray("(not found)"),"-","-"]);}catch{n.push([s,l.gray("(error fetching)"),"-","-"]);}t.stop(),console.log(n.toString());}catch{t.stop(),console.log(l.gray("IDs: ")+e.join(", "));}}else console.log(l.gray("IDs: ")+e.join(", ")),console.log(),console.log(l.gray("Login to see problem details"));}function ks(e){switch(e.toLowerCase()){case "easy":return l.green(e);case "medium":return l.yellow(e);case "hard":return l.red(e);default:return e}}async function Ct(e,o){if(!te(e)){console.log(l.red(`Invalid problem ID: ${e}`)),console.log(l.gray("Problem ID must be a positive integer"));return}let t=o==="view"?"view":"edit",n=join(w.getWorkDir(),".notes"),s=join(n,`${e}.md`);existsSync(n)||await mkdir(n,{recursive:true}),t==="view"?await Ts(s,e):await Ds(s,e);}async function Ts(e,o){if(!existsSync(e)){console.log(l.yellow(`No notes found for problem ${o}`)),console.log(l.gray(`Use "leetcode note ${o} edit" to create notes`));return}try{let t=await readFile(e,"utf-8");console.log(),console.log(l.bold.cyan(`\u{1F4DD} Notes for Problem ${o}`)),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(t);}catch(t){console.log(l.red("Failed to read notes")),t instanceof Error&&console.log(l.gray(t.message));}}async function Ds(e,o){if(!existsSync(e)){let t=await xs(o);await writeFile(e,t,"utf-8"),console.log(l.green(`\u2713 Created notes file for problem ${o}`));}console.log(l.gray(`Opening: ${e}`)),await ke(e);}async function xs(e){let o=`# Problem ${e} Notes
|
|
195
|
-
|
|
196
|
-
`,{authorized:t}=await $();if(t)try{let n=await h.getProblemById(e);n&&(o=`# ${e}. ${n.title}
|
|
197
|
-
|
|
198
|
-
`,o+=`**Difficulty:** ${n.difficulty}
|
|
199
|
-
`,o+=`**URL:** https://leetcode.com/problems/${n.titleSlug}/
|
|
200
|
-
`,n.topicTags.length>0&&(o+=`**Topics:** ${n.topicTags.map(s=>s.name).join(", ")}
|
|
201
|
-
`),o+=`
|
|
187
|
+
`),t=Mi(t)??"",t=t.replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/≤/g,"<=").replace(/≥/g,">=").replace(/&#(\d+);/g,(o,n)=>String.fromCharCode(parseInt(n,10))).replace(/&/g,"&"),t=t.replace(/\n{3,}/g,`
|
|
188
|
+
|
|
189
|
+
`).trim(),t}function Hi(e,t,o,n,r,s){let i=e.linePrefix,a=[e.blockStart,`${i}${t}. ${o}`,`${i}Difficulty: ${n}`,`${i}https://leetcode.com/problems/${r}/`];if(s){a.push(`${i}`),a.push(`${i}${"\u2500".repeat(50)}`),a.push(`${i}`);let u=Fi(s).split(`
|
|
190
|
+
`);for(let g of u)if(g.length>70){let d=g.split(" "),m="";for(let b of d)(m+" "+b).length>70?(a.push(`${i}${m.trim()}`),m=b):m+=" "+b;m.trim()&&a.push(`${i}${m.trim()}`);}else a.push(`${i}${g}`);}return a.push(e.blockEnd),a.join(`
|
|
191
|
+
`)}function Qe(e,t,o){let n=Ye[o];return `${e}.${t}.${n}`}var Bi=["vim","nvim","vi","nano","emacs","micro","helix"],Wi=["code","code-insiders","cursor","codium","vscodium"];async function ht(e,t){let o=M.getEditor()??process.env.EDITOR??"code",n=M.getWorkDir();if(Bi.includes(o)){let r=spawn(o,[e],{stdio:"inherit"});return new Promise((s,i)=>{r.on("exit",a=>{a===0?s():i(new Error(`Editor exited with code ${a}`));}),r.on("error",a=>{i(new Error(`Failed to start editor: ${a.message}`));});})}try{if(Wi.includes(o)){spawn(o,["-r",n,"-g",e],{detached:!0,stdio:"ignore"}).unref();return}await Ui(e,{app:{name:o}});}catch{throw new Error(`Failed to open editor '${o}'. Make sure it is installed and in your PATH.`)}}async function _e(e,t){let{authorized:o}=await v();if(!o)return false;let n=Gt({text:"Fetching problem details...",spinner:"dots"}).start();try{let r;if(/^\d+$/.test(e)?r=await S.getProblemById(e):r=await S.getProblem(e),!r)return n.fail(`Problem "${e}" not found`),!1;n.text="Generating solution file...";let s=t.lang?.toLowerCase()??M.getLanguage(),i=Be[s]??s,a=r.codeSnippets??[],l=Bt(a,i),u;if(a.length===0)n.warn(f.yellow("Premium Problem (No code snippets available)")),console.log(f.gray("Generating placeholder file with problem info...")),u=`// \u{1F512} Premium Problem - ${r.title}
|
|
192
|
+
// Solution stub not available - visit LeetCode to view`;else if(l)u=l.code;else return n.fail(`No code template available for ${i}`),console.log(f.gray(`Available languages: ${a.map(G=>G.langSlug).join(", ")}`)),!1;let g=Wt(r.questionFrontendId,r.titleSlug,r.title,r.difficulty,u,i,r.content??void 0),d=M.getWorkDir(),m=r.difficulty,b=r.topicTags.length>0?r.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",_=join(d,m,b);existsSync(_)||await mkdir(_,{recursive:!0});let w=Qe(r.questionFrontendId,r.titleSlug,i),R=join(_,w);return existsSync(R)?(n.warn(`File already exists: ${w}`),console.log(f.gray(`Path: ${R}`)),t.open!==!1&&await ht(R),!0):(await writeFile(R,g,"utf-8"),n.succeed(`Created ${f.green(w)}`),console.log(f.gray(`Path: ${R}`)),console.log(),console.log(f.cyan(`${r.questionFrontendId}. ${r.title}`)),console.log(f.gray(`Difficulty: ${r.difficulty} | Category: ${b}`)),t.open!==!1&&await ht(R),!0)}catch(r){if(n.fail("Failed to fetch problem"),r instanceof Error)if(r.message.includes("expected object, received null"))console.log(f.red(`Problem "${e}" not found`));else try{let s=JSON.parse(r.message);Array.isArray(s)?console.log(f.red("API Response Validation Failed")):console.log(f.red(r.message));}catch{console.log(f.red(r.message));}return false}}async function Zn(e,t){if(e.length===0){console.log(f.yellow("Please provide at least one problem ID"));return}let{authorized:o}=await v();if(!o)return;console.log(f.cyan(`\u{1F4E6} Picking ${e.length} problem${e.length!==1?"s":""}...`)),console.log(),console.log();let n=0,r=0;for(let s of e)await _e(s,{...t,open:false})?n++:r++,console.log();console.log(f.gray("\u2500".repeat(50))),console.log(f.bold(`Done! ${f.green(`${n} succeeded`)}${r>0?`, ${f.red(`${r} failed`)}`:""}`));}var nr=5;async function ge(e,t,o=0){if(!existsSync(e)||o>=nr)return null;let n=await readdir(e,{withFileTypes:true});for(let r of n){if(r.name.startsWith("."))continue;let s=join(e,r.name);if(r.isDirectory()){let i=await ge(s,t,o+1);if(i)return i}else if(r.name.startsWith(`${t}.`)){let i=r.name.split(".").pop()?.toLowerCase();if(i&&i in qi)return s}}return null}async function St(e,t,o=0){if(!existsSync(e)||o>=nr)return null;let n=await readdir(e,{withFileTypes:true});for(let r of n){let s=join(e,r.name);if(r.isDirectory()){let i=await St(s,t,o+1);if(i)return i}else if(r.name===t)return s}return null}var qi={ts:"typescript",js:"javascript",py:"python3",java:"java",cpp:"cpp",c:"c",cs:"csharp",go:"go",rs:"rust",kt:"kotlin",swift:"swift"};function We(e){return {ts:"typescript",js:"javascript",py:"python3",java:"java",cpp:"cpp",c:"c",cs:"csharp",go:"golang",rs:"rust",kt:"kotlin",swift:"swift"}[e.toLowerCase()]??null}async function rr(e,t){let{authorized:o}=await v();if(!o)return;let n=e,r=M.getWorkDir();if(Ae(e)){let i=await ge(r,e);if(!i){console.log(f.red(`No solution file found for problem ${e}`)),console.log(f.gray(`Looking in: ${r}`)),console.log(f.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}n=i,console.log(f.gray(`Found: ${n}`));}else if(Ft(e)){let i=await St(r,e);if(!i){console.log(f.red(`File not found: ${e}`)),console.log(f.gray(`Looking in: ${r}`));return}n=i,console.log(f.gray(`Found: ${n}`));}if(!existsSync(n)){console.log(f.red(`File not found: ${n}`));return}if(!ze(n,r)){console.log(f.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(f.gray(`File: ${n}`)),console.log(f.gray(`Workspace: ${r}`)),console.log(f.yellow(`
|
|
193
|
+
For security reasons, you can only test files from within your workspace.`)),console.log(f.gray('Use "leetcode config workdir <path>" to change your workspace.'));return}let s=Gt({text:"Reading solution file...",spinner:"dots"}).start();try{let i=basename(n),a=i.match(/^(\d+)\.([^.]+)\./);if(!a){s.fail("Invalid filename format"),console.log(f.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(f.gray("Example: 1.two-sum.ts"));return}let l=a[2],u=i.split(".").pop(),g=We(u);if(!g){s.fail(`Unsupported file extension: .${u}`);return}let d=await readFile(n,"utf-8");s.text="Fetching problem details...";let m=await S.getProblem(l),b=t.testcase??m.exampleTestcases??m.sampleTestCase;s.text="Running tests...";let _=await S.testSolution(l,d,g,b,m.questionId);s.stop(),Hn(_,t.visualize?m.topicTags:void 0);}catch(i){s.fail("Test failed"),i instanceof Error&&console.log(f.red(i.message));}}function ir(){return T.getTimerPath()}function je(){let e=ir();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{solveTimes:{},activeTimer:null}}function Co(e){let t=ir(),o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true}),writeFileSync(t,JSON.stringify(e,null,2));}var Ce={startTimer(e,t,o,n){let r=je();r.activeTimer={problemId:e,title:t,difficulty:o,startedAt:new Date().toISOString(),durationMinutes:n},Co(r);},getActiveTimer(){return je().activeTimer},stopTimer(){let e=je(),t=e.activeTimer;if(!t)return null;let o=new Date(t.startedAt),r=Math.floor((new Date().getTime()-o.getTime())/1e3);return e.activeTimer=null,Co(e),{durationSeconds:r}},recordSolveTime(e,t,o,n,r){let s=je();s.solveTimes[e]||(s.solveTimes[e]=[]),s.solveTimes[e].push({problemId:e,title:t,difficulty:o,solvedAt:new Date().toISOString(),durationSeconds:n,timerMinutes:r}),Co(s);},getSolveTimes(e){return je().solveTimes[e]??[]},getAllSolveTimes(){return je().solveTimes??{}},getStats(){let e=je().solveTimes??{},t=0,o=0;for(let n of Object.values(e)){t+=n.length;for(let r of n)o+=r.durationSeconds;}return {totalProblems:t,totalTime:o,avgTime:t>0?Math.floor(o/t):0}}};async function ar(e){let{authorized:t}=await v();if(!t)return;let o=e,n=M.getWorkDir();if(Ae(e)){let s=await ge(n,e);if(!s){console.log(f.red(`No solution file found for problem ${e}`)),console.log(f.gray(`Looking in: ${n}`)),console.log(f.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}o=s,console.log(f.gray(`Found: ${o}`));}else if(Ft(e)){let s=await St(n,e);if(!s){console.log(f.red(`File not found: ${e}`)),console.log(f.gray(`Looking in: ${n}`));return}o=s,console.log(f.gray(`Found: ${o}`));}if(!existsSync(o)){console.log(f.red(`File not found: ${o}`));return}if(!ze(o,n)){console.log(f.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(f.gray(`File: ${o}`)),console.log(f.gray(`Workspace: ${n}`)),console.log(f.yellow(`
|
|
194
|
+
For security reasons, you can only submit files from within your workspace.`)),console.log(f.gray('Use "leetcode config workdir <path>" to change your workspace.'));return}let r=Gt({text:"Reading solution file...",spinner:"dots"}).start();try{let s=basename(o),i=s.match(/^(\d+)\.([^.]+)\./);if(!i){r.fail("Invalid filename format"),console.log(f.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(f.gray("Example: 1.two-sum.ts"));return}let[,a,l]=i,u=s.split(".").pop(),g=We(u);if(!g){r.fail(`Unsupported file extension: .${u}`);return}let d=await readFile(o,"utf-8");r.text="Fetching problem details...";let m=await S.getProblem(l);r.text="Submitting solution...";let b=await S.submitSolution(l,d,g,m.questionId);if(r.stop(),Un(b),b.status_msg==="Accepted"){let _=Ce.getActiveTimer();if(_&&_.problemId===a){let w=Ce.stopTimer();if(w){Ce.recordSolveTime(a,m.title,m.difficulty,w.durationSeconds,_.durationMinutes);let R=Math.floor(w.durationSeconds/60),G=w.durationSeconds%60,K=`${R}m ${G}s`,z=w.durationSeconds<=_.durationMinutes*60;console.log(),console.log(f.bold("\u23F1\uFE0F Timer Result:")),console.log(` Solved in ${z?f.green(K):f.yellow(K)} (limit: ${_.durationMinutes}m)`),console.log(z?f.green(" \u2713 Within time limit!"):f.yellow(" \u26A0 Exceeded time limit"));}}}}catch(s){r.fail("Submission failed"),s instanceof Error&&console.log(f.red(s.message));}}var lr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function cr(e){let t=JSON.parse(e),o=new Date,n=[];for(let i=11;i>=0;i--){let a=new Date(o);a.setDate(a.getDate()-i*7-a.getDay());let l=0,u=0;for(let d=0;d<7;d++){let m=new Date(a);if(m.setDate(m.getDate()+d),m>o)break;let b=new Date(Date.UTC(m.getFullYear(),m.getMonth(),m.getDate())),_=Math.floor(b.getTime()/1e3).toString(),w=t[_]||0;l+=w,w>0&&u++;}let g=new Date(a);g.setDate(g.getDate()+6),n.push({start:`${lr[a.getMonth()]} ${a.getDate()}`,end:`${lr[g.getMonth()]} ${g.getDate()}`,count:l,days:u});}let r=n.reduce((i,a)=>i+a.count,0),s=n.reduce((i,a)=>i+a.days,0);console.log(),console.log(f.bold("\u{1F4C5} Activity (Last 12 Weeks)")),console.log(f.gray("How many problems you submitted and days you practiced.")),console.log(f.gray("\u2500".repeat(50))),console.log();for(let i of n){let a=`${i.start} - ${i.end}`.padEnd(18),l=i.count>0?f.green("\u2588".repeat(Math.min(i.count,10))).padEnd(10):f.gray("\xB7").padEnd(10),u=i.count>0?`${i.count} subs`.padEnd(10):"".padEnd(10),g=i.days>0?`${i.days}d active`:"";console.log(` ${f.white(a)} ${l} ${f.cyan(u)} ${f.yellow(g)}`);}console.log(f.gray("\u2500".repeat(50))),console.log(` ${f.bold.white("Total:")} ${f.cyan.bold(r+" submissions")}, ${f.yellow.bold(s+" days active")}`),console.log();}function ur(e,t,o){console.log(),console.log(f.bold("\u{1F3AF} Skill Breakdown")),console.log(f.gray("\u2500".repeat(45)));let n=(r,s,i)=>{if(s.length===0)return;console.log(),console.log(i.bold(` ${r}`));let a=[...s].sort((l,u)=>u.problemsSolved-l.problemsSolved);for(let l of a.slice(0,8)){let u=l.tagName.padEnd(22),g=i("\u2588".repeat(Math.min(l.problemsSolved,15)));console.log(` ${f.white(u)} ${g} ${f.white(l.problemsSolved)}`);}};n("Fundamental",e,f.green),n("Intermediate",t,f.yellow),n("Advanced",o,f.red),console.log();}function pr(e){let t=JSON.parse(e),o=new Date,n=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],r=[];for(let l=6;l>=0;l--){let u=new Date(o);u.setDate(u.getDate()-l);let g=new Date(Date.UTC(u.getFullYear(),u.getMonth(),u.getDate())),d=Math.floor(g.getTime()/1e3).toString();r.push({label:n[u.getDay()],count:t[d]||0});}let s=Math.max(...r.map(l=>l.count),1),i=6;console.log(),console.log(f.bold("\u{1F4C8} Submission Trend (Last 7 Days)")),console.log(f.gray("\u2500".repeat(35))),console.log();for(let l=i;l>=1;l--){let u=` ${l===i?s.toString().padStart(2):" "} \u2502`;for(let g of r)Math.round(g.count/s*i)>=l?u+=f.green(" \u2588\u2588 "):u+=" ";console.log(u);}console.log(` 0 \u2514${"\u2500\u2500\u2500\u2500".repeat(7)}`),console.log(` ${r.map(l=>l.label.padEnd(4)).join("")}`),console.log(f.gray(` ${r.map(l=>l.count.toString().padEnd(4)).join("")}`));let a=r.reduce((l,u)=>l+u.count,0);console.log(),console.log(f.white(` Total: ${a} submissions this week`)),console.log();}async function gr(e,t={}){let{authorized:o,username:n}=await v();if(!o)return;let r=Gt("Fetching statistics...").start();try{let s=e||n;if(!s){r.fail("No username found");return}let i=await S.getUserProfile(s);if(r.stop(),!t.calendar&&!t.skills&&!t.trend){Bn(i.username,i.realName,i.ranking,i.acSubmissionNum,i.streak,i.totalActiveDays);return}if(t.calendar&&(i.submissionCalendar?cr(i.submissionCalendar):console.log(f.yellow("Calendar data not available."))),t.trend&&(i.submissionCalendar?pr(i.submissionCalendar):console.log(f.yellow("Calendar data not available."))),t.skills){r.start("Fetching skill stats...");let a=await S.getSkillStats(s);r.stop(),ur(a.fundamental,a.intermediate,a.advanced);}}catch(s){r.fail("Failed to fetch statistics"),s instanceof Error&&console.log(f.red(s.message));}}async function dr(){let{authorized:e}=await v();if(!e)return;let t=Gt("Fetching daily challenge...").start();try{let o=await S.getDailyChallenge();t.stop(),Wn(o.date,o.question),console.log(),console.log(f.gray("Run the following to start working on this problem:")),console.log(f.cyan(` leetcode pick ${o.question.titleSlug}`));}catch(o){t.fail("Failed to fetch daily challenge"),o instanceof Error&&console.log(f.red(o.message));}}async function fr(e){let{authorized:t}=await v();if(!t)return;let o=Gt("Fetching random problem...").start();try{let n={};if(e.difficulty){let i={easy:"EASY",e:"EASY",medium:"MEDIUM",m:"MEDIUM",hard:"HARD",h:"HARD"}[e.difficulty.toLowerCase()];if(i)n.difficulty=i;else {o.fail(`Invalid difficulty: ${e.difficulty}`);return}}e.tag&&(n.tags=[e.tag]);let r=await S.getRandomProblem(n);o.succeed("Found random problem!"),console.log(),e.pick?await _e(r,{open:e.open??!0}):(await Nt(r),console.log(f.gray("Run following to start solving:")),console.log(f.cyan(` leetcode pick ${r}`)));}catch(n){o.fail("Failed to fetch random problem"),n instanceof Error&&console.log(f.red(n.message));}}async function hr(e,t){let{authorized:o}=await v();if(!o)return;let n=Gt("Fetching problem info...").start();try{let r;if(/^\d+$/.test(e)?r=await S.getProblemById(e):r=await S.getProblem(e),!r){n.fail(`Problem "${e}" not found`);return}let s=r.titleSlug;n.text="Fetching submissions...";let i=t.limit?parseInt(t.limit,10):20,a=await S.getSubmissionList(s,i);if(n.stop(),a.length===0){console.log(f.yellow("No submissions found."));return}if(t.last){let l=a.find(u=>u.statusDisplay==="Accepted");l?(console.log(f.bold("Last Accepted Submission:")),fo([l])):console.log(f.yellow("No accepted submissions found in recent history."));}else fo(a);if(t.download){let l=Gt("Downloading submission...").start(),u=a.find($t=>$t.statusDisplay==="Accepted");if(!u){l.fail("No accepted submission found to download.");return}let g=parseInt(u.id,10);if(isNaN(g)){l.fail("Invalid submission ID format");return}let d=await S.getSubmissionDetails(g),m=M.getWorkDir(),b=r.difficulty,_=r.topicTags.length>0?r.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",w=join(m,b,_);existsSync(w)||await mkdir(w,{recursive:!0});let R=d.lang.name,G=Be[R]??"txt",K=Ye[G]??R,z=`${r.questionFrontendId}.${r.titleSlug}.submission-${u.id}.${K}`,Pt=join(w,z);await writeFile(Pt,d.code,"utf-8"),l.succeed(`Downloaded to ${f.green(z)}`),console.log(f.gray(`Path: ${Pt}`));}}catch(r){n.fail("Failed to fetch submissions"),r instanceof Error&&console.log(f.red(r.message));}}var _o=["typescript","javascript","python3","java","cpp","c","csharp","go","rust","kotlin","swift"];async function Sr(e){let t=e.repo!==void 0;if(!e.lang&&!e.editor&&!e.workdir&&!t){Cr();return}if(e.lang){let o=e.lang.toLowerCase();if(!_o.includes(o)){console.log(f.red(`Unsupported language: ${e.lang}`)),console.log(f.gray(`Supported: ${_o.join(", ")}`));return}let n=o;M.setLanguage(n),console.log(f.green(`\u2713 Default language set to ${n}`));}e.editor&&(M.setEditor(e.editor),console.log(f.green(`\u2713 Editor set to ${e.editor}`))),e.workdir&&(M.setWorkDir(e.workdir),console.log(f.green(`\u2713 Work directory set to ${e.workdir}`))),t&&(e.repo===true||typeof e.repo=="string"&&e.repo.trim()===""?(M.deleteRepo(),console.log(f.green("\u2713 Repository URL cleared"))):typeof e.repo=="string"&&(M.setRepo(e.repo),console.log(f.green(`\u2713 Repository URL set to ${e.repo}`))));}async function br(){let e=M.getConfig(),t=M.getActiveWorkspace();console.log(),console.log(f.bold.cyan(`\u{1F4C1} Configuring workspace: ${t}`)),console.log(f.gray("\u2500".repeat(40)));let o=await To.prompt([{type:"list",name:"language",message:"Default programming language:",choices:_o,default:e.language},{type:"input",name:"editor",message:"Editor command (e.g., code, vim, nvim):",default:e.editor??"code"},{type:"input",name:"workDir",message:"Working directory for solution files:",default:e.workDir},{type:"input",name:"repo",message:"Git repository URL (optional):",default:e.repo}]);M.setLanguage(o.language),M.setEditor(o.editor),M.setWorkDir(o.workDir),o.repo?M.setRepo(o.repo):M.deleteRepo(),console.log(),console.log(f.green("\u2713 Configuration saved")),Cr();}function Cr(){let e=M.getConfig(),t=ae.get(),o=M.getActiveWorkspace();console.log(),console.log(f.bold.cyan(`\u{1F4C1} Workspace: ${o}`)),console.log(f.gray("\u2500".repeat(40))),console.log(),console.log(f.gray("Config file:"),M.getPath()),console.log(),console.log(f.gray("Language: "),f.white(e.language)),console.log(f.gray("Editor: "),f.white(e.editor??"(not set)")),console.log(f.gray("Work Dir: "),f.white(e.workDir)),console.log(f.gray("Repo URL: "),f.white(e.repo??"(not set)")),console.log(f.gray("Logged in: "),t?f.green("Yes"):f.yellow("No"));}var De=new hi({projectName:"leetcode-cli-bookmarks",defaults:{bookmarks:[]}}),de={add(e){let t=De.get("bookmarks");return t.includes(e)?false:(De.set("bookmarks",[...t,e]),true)},remove(e){let t=De.get("bookmarks");return t.includes(e)?(De.set("bookmarks",t.filter(o=>o!==e)),true):false},list(){return De.get("bookmarks")},has(e){return De.get("bookmarks").includes(e)},count(){return De.get("bookmarks").length},clear(){De.set("bookmarks",[]);}};async function Er(e,t){if(!["add","remove","list","clear"].includes(e)){console.log(f.red(`Invalid action: ${e}`)),console.log(f.gray("Valid actions: add, remove, list, clear"));return}switch(e){case "add":if(!t){console.log(f.red("Please provide a problem ID to bookmark"));return}if(!Ae(t)){console.log(f.red(`Invalid problem ID: ${t}`)),console.log(f.gray("Problem ID must be a positive integer"));return}de.add(t)?console.log(f.green(`\u2713 Bookmarked problem ${t}`)):console.log(f.yellow(`Problem ${t} is already bookmarked`));break;case "remove":if(!t){console.log(f.red("Please provide a problem ID to remove"));return}de.remove(t)?console.log(f.green(`\u2713 Removed bookmark for problem ${t}`)):console.log(f.yellow(`Problem ${t} is not bookmarked`));break;case "list":await ma();break;case "clear":let n=de.count();n===0?console.log(f.yellow("No bookmarks to clear")):(de.clear(),console.log(f.green(`\u2713 Cleared ${n} bookmark${n!==1?"s":""}`)));break}}async function ma(){let e=de.list();if(e.length===0){console.log(f.yellow("\u{1F4CC} No bookmarked problems")),console.log(f.gray('Use "leetcode bookmark add <id>" to bookmark a problem'));return}console.log(),console.log(f.bold.cyan(`\u{1F4CC} Bookmarked Problems (${e.length})`)),console.log();let{authorized:t}=await v();if(t){let o=Gt({text:"Fetching problem details...",spinner:"dots"}).start();try{let n=new po({head:[f.cyan("ID"),f.cyan("Title"),f.cyan("Difficulty"),f.cyan("Status")],colWidths:[8,45,12,10],style:{head:[],border:[]}});for(let r of e)try{let s=await S.getProblemById(r);s?n.push([s.questionFrontendId,s.title.length>42?s.title.slice(0,39)+"...":s.title,ya(s.difficulty),s.status==="ac"?f.green("\u2713"):f.gray("-")]):n.push([r,f.gray("(not found)"),"-","-"]);}catch{n.push([r,f.gray("(error fetching)"),"-","-"]);}o.stop(),console.log(n.toString());}catch{o.stop(),console.log(f.gray("IDs: ")+e.join(", "));}}else console.log(f.gray("IDs: ")+e.join(", ")),console.log(),console.log(f.gray("Login to see problem details"));}function ya(e){switch(e.toLowerCase()){case "easy":return f.green(e);case "medium":return f.yellow(e);case "hard":return f.red(e);default:return e}}async function jt(e,t,o={}){if(!Ae(e)){o.silent||(console.log(f.red(`Invalid problem ID: ${e}`)),console.log(f.gray("Problem ID must be a positive integer")));return}let n=t==="view"?"view":"edit",r=join(M.getWorkDir(),".notes"),s=join(r,`${e}.md`);existsSync(r)||await mkdir(r,{recursive:true}),n==="view"?await Ca(s,e):await Ea(s,e,o);}async function Ca(e,t){if(!existsSync(e)){console.log(f.yellow(`No notes found for problem ${t}`)),console.log(f.gray(`Use "leetcode note ${t} edit" to create notes`));return}try{let o=await readFile(e,"utf-8");console.log(),console.log(f.bold.cyan(`\u{1F4DD} Notes for Problem ${t}`)),console.log(f.gray("\u2500".repeat(50))),console.log(),console.log(o);}catch(o){console.log(f.red("Failed to read notes")),o instanceof Error&&console.log(f.gray(o.message));}}async function Ea(e,t,o={}){if(!existsSync(e)){let n=await wa(t);await writeFile(e,n,"utf-8"),o.silent||console.log(f.green(`\u2713 Created notes file for problem ${t}`));}o.silent||console.log(f.gray(`Opening: ${e}`)),await ht(e);}async function wa(e){let t=`# Problem ${e} Notes
|
|
195
|
+
|
|
196
|
+
`,{authorized:o}=await v();if(o)try{let n=await S.getProblemById(e);n&&(t=`# ${e}. ${n.title}
|
|
197
|
+
|
|
198
|
+
`,t+=`**Difficulty:** ${n.difficulty}
|
|
199
|
+
`,t+=`**URL:** https://leetcode.com/problems/${n.titleSlug}/
|
|
200
|
+
`,n.topicTags.length>0&&(t+=`**Topics:** ${n.topicTags.map(r=>r.name).join(", ")}
|
|
201
|
+
`),t+=`
|
|
202
202
|
---
|
|
203
203
|
|
|
204
|
-
`);}catch{}return `${
|
|
204
|
+
`);}catch{}return `${t}## Approach
|
|
205
205
|
|
|
206
206
|
<!-- Describe your approach to solving this problem -->
|
|
207
207
|
|
|
@@ -226,211 +226,241 @@ For security reasons, you can only submit files from within your workspace.`)),c
|
|
|
226
226
|
|
|
227
227
|
<!-- What did you learn from this problem? -->
|
|
228
228
|
|
|
229
|
-
`}async function
|
|
230
|
-
Please create a new repository on your Git provider and copy the URL.`));let{url:
|
|
231
|
-
`).length,
|
|
232
|
-
`).length} lines from ${n}`))):
|
|
233
|
-
`);for(let
|
|
234
|
-
`);for(let
|
|
235
|
-
`).length,createdAt:new Date().toISOString()};return
|
|
236
|
-
`).filter(
|
|
237
|
-
`),n=
|
|
238
|
-
`).length,
|
|
239
|
-
`).length;console.log(),console.log(
|
|
240
|
-
`).filter(
|
|
241
|
-
`).filter(
|
|
242
|
-
For security reasons, you can only diff files from within your workspace.`));return}let
|
|
243
|
-
`)))):(console.log(),console.log(
|
|
244
|
-
`),r=false;for(let i of s)if(!(i.trim()===""&&!r)){if(i.startsWith("> **Release Date**")){let a=i.replace("> **Release Date**: ","").trim();console.log(l.gray(` \u{1F4C5} ${a}`));continue}if(i.startsWith("> **Focus**")){let a=i.replace("> **Focus**: ","").trim();console.log(l.gray(` \u{1F3AF} ${a}`)),console.log();continue}if(i.startsWith("### ")){let a=i.replace("### ","").trim();if(console.log(),/^[\u{1F300}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/u.test(a))console.log(l.bold.yellow(` ${a}`));else {let g="\u{1F4CC}";a.includes("Breaking")?g="\u26A0\uFE0F":a.includes("Feature")||a.includes("New")?g="\u{1F680}":a.includes("Fix")||a.includes("Bug")?g="\u{1F41B}":a.includes("Security")?g="\u{1F512}":a.includes("Improvement")?g="\u2728":a.includes("Architecture")?g="\u{1F3D7}\uFE0F":a.includes("Testing")?g="\u{1F9EA}":a.includes("Config")&&(g="\u2699\uFE0F"),console.log(l.bold.yellow(` ${g} ${a}`));}r=true;continue}if(i.startsWith("#### ")){let a=i.replace("#### ","").trim();console.log(l.bold.white(` ${a}`));continue}if(i.startsWith("- **")){let a=i.match(/^- \*\*(.+?)\*\*:?\s*(.*)/);console.log(a?l.cyan(` \u2022 ${l.bold(a[1])}`)+(a[2]?l.white(`: ${a[2]}`):""):l.cyan(` \u2022 ${i.replace("- ","")}`));continue}if(i.startsWith("- ")){let a=i.replace("- ","").trim();console.log(l.white(` \u2022 ${a}`));continue}i.startsWith("---")||i.trim()===">"||i.trim()&&console.log(l.gray(` ${i.trim()}`));}}async function hn(e,o={}){let t=Ue("Fetching changelog...").start();try{let n=await jr();t.stop();let s=Mr(n);if(s.length===0){console.log(l.yellow("No release entries found."));return}let r=Ur(),i=s;if(e){let a=e.startsWith("v")?e:`v${e}`;if(i=s.filter(c=>c.version===a),i.length===0){console.log(l.red(`Version ${e} not found in changelog.`)),console.log(l.gray("Available versions: "+s.map(c=>c.version).join(", ")));return}}else if(o.latest)i=s.slice(0,1);else if(o.breaking){if(i=s.filter(a=>a.hasBreakingChanges),i.length===0){console.log(l.green("\u2713 No breaking changes in any release."));return}}else if(o.all)i=s;else {if(i=s.filter(a=>he(a.version,r)),i.length===0){console.log(l.green(`\u2713 You're on the latest version (${r})`)),console.log(l.gray("Use --all to see the full changelog."));return}console.log(l.gray(`Showing changes since your version (${r})`)),console.log(l.gray("Use --all to see the full changelog."));}console.log(),console.log(l.bold.cyan("\u{1F4CB} LeetCode CLI Release Notes")),console.log(l.gray("\u2500".repeat(50))),console.log();for(let a of i)qr(a.version,a.content,a.hasBreakingChanges),console.log(l.gray("\u2500".repeat(60))),console.log();if(!e&&!o.latest){let a=s.filter(c=>c.hasBreakingChanges).length;console.log(l.gray(`Showing ${i.length} of ${s.length} releases`)),a>0&&!o.breaking&&console.log(l.yellow(`${a} release(s) contain breaking changes. Use --breaking to filter.`));}}catch{t.fail("Failed to fetch changelog"),console.log(l.gray(" Could not fetch release notes from GitHub.")),console.log(l.gray(" Visit: https://github.com/night-slayer18/leetcode-cli/blob/main/docs/releases.md"));}}var C=new Command;C.configureHelp({sortSubcommands:true,subcommandTerm:e=>{let o=e.name(),t=e.alias(),n=t?`${o}|${t}`:o;return l.cyan(n.padEnd(16))},subcommandDescription:e=>l.white(e.description()),optionTerm:e=>l.yellow(e.flags),optionDescription:e=>l.white(e.description)});C.name("leetcode").usage("[command] [options]").description(l.bold.cyan("\u{1F525} A modern LeetCode CLI built with TypeScript")).version("2.2.2","-v, --version","Output the version number").helpOption("-h, --help","Display help for command").addHelpText("after",`
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
${l.
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
${l.
|
|
252
|
-
`);
|
|
253
|
-
|
|
254
|
-
|
|
229
|
+
`}async function Mr(){let{authorized:e,username:t}=await v();if(!e||!t)return;let o=Gt({text:"Fetching your progress...",spinner:"dots"}).start();try{let[n,r]=await Promise.all([S.getUserProfile(t),S.getDailyChallenge()]);o.stop(),console.log(),console.log(f.bold.cyan("\u{1F4CA} Today's Summary"),f.gray(`- ${t}`)),console.log(f.gray("\u2500".repeat(50))),console.log(),console.log(f.yellow(`\u{1F525} Current Streak: ${n.streak} day${n.streak!==1?"s":""}`)),console.log(f.gray(` Total Active Days: ${n.totalActiveDays}`)),console.log();let s=n.acSubmissionNum.find(g=>g.difficulty==="All"),i=n.acSubmissionNum.find(g=>g.difficulty==="Easy"),a=n.acSubmissionNum.find(g=>g.difficulty==="Medium"),l=n.acSubmissionNum.find(g=>g.difficulty==="Hard");console.log(f.white("\u{1F4C8} Problems Solved:")),console.log(` ${f.green("Easy")}: ${i?.count??0} | ${f.yellow("Medium")}: ${a?.count??0} | ${f.red("Hard")}: ${l?.count??0}`),console.log(` ${f.bold("Total")}: ${s?.count??0}`),console.log(),console.log(f.bold.yellow("\u{1F3AF} Today's Challenge:")),console.log(` ${r.question.questionFrontendId}. ${r.question.title}`),console.log(` ${_a(r.question.difficulty)}`);let u=r.question.status;console.log(u==="ac"?f.green(" \u2713 Completed!"):u==="notac"?f.yellow(" \u25CB Attempted"):f.gray(" - Not started")),console.log(),console.log(f.gray(` leetcode pick ${r.question.questionFrontendId} # Start working on it`));}catch(n){o.fail("Failed to fetch progress"),n instanceof Error&&console.log(f.red(n.message));}}function _a(e){switch(e.toLowerCase()){case "easy":return f.green(e);case "medium":return f.yellow(e);case "hard":return f.red(e);default:return e}}function La(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-").replace(/--+/g,"-")}function Ra(e){let t=/^https:\/\/[\w.-]+\/[\w./-]+$/,o=/^git@[\w.-]+:[\w./-]+$/;return t.test(e)||o.test(e)}function xa(e){return `"${e.replace(/"/g,'\\"')}"`}function Oa(){try{return execSync("git --version",{stdio:"ignore"}),!0}catch{return false}}function Pa(e){try{return execSync("git rev-parse --is-inside-work-tree",{cwd:e,stdio:"ignore"}),!0}catch{return false}}function $a(){try{return execSync("gh --version",{stdio:"ignore"}),!0}catch{return false}}function Lo(e){try{return execSync("git config --get remote.origin.url",{cwd:e,encoding:"utf-8"}).trim()}catch{return null}}async function va(e){let{init:t}=await To.prompt([{type:"confirm",name:"init",message:"Work directory is not a git repository. Initialize?",default:true}]);if(!t)return console.log(f.yellow("Skipping basic git initialization.")),false;let o=Gt("Initializing git repository...").start();try{return execSync("git init",{cwd:e}),o.succeed("Initialized git repository"),!0}catch(n){throw o.fail("Failed to initialize git repository"),n}}async function Aa(e){let t=Gt(),o=M.getRepo();if(!o){if($a()){let{createGh:r}=await To.prompt([{type:"confirm",name:"createGh",message:"Create a new private GitHub repository?",default:true}]);if(r){t.start("Creating GitHub repository...");try{let s=$e__default.basename(e)||"leetcode-solutions",i=La(s);return execSync(`gh repo create ${i} --private --source=. --remote=origin`,{cwd:e}),t.succeed("Created and linked GitHub repository"),o=Lo(e)||"",o&&M.setRepo(o),o}catch(s){t.fail("Failed to create GitHub repository"),console.log(f.red(s));}}}if(!o){console.log(f.yellow(`
|
|
230
|
+
Please create a new repository on your Git provider and copy the URL.`));let{url:r}=await To.prompt([{type:"input",name:"url",message:"Enter remote repository URL:",validate:s=>s.length>0?true:"URL cannot be empty"}]);o=r;}}if(o&&!Ra(o))return console.log(f.red("Invalid repository URL format.")),console.log(f.gray("Expected: https://github.com/user/repo or git@github.com:user/repo")),"";if(o&&M.setRepo(o),!Lo(e)&&o)try{execSync(`git remote add origin ${o}`,{cwd:e}),console.log(f.green("\u2713 Added remote origin"));}catch{return console.log(f.red("Failed to add remote origin")),""}return o||""}async function _r(){let e=M.getWorkDir();if(!existsSync(e)){console.log(f.red(`Work directory does not exist: ${e}`));return}if(!Oa()){console.log(f.red("Git is not installed. Please install Git to use command."));return}if(!Pa(e)&&!await va(e))return;if(!await Aa(e)&&!Lo(e)){console.log(f.red("No valid remote repository configured. Sync aborted."));return}let o=Gt("Syncing solutions...").start();try{let n=execSync("git status --porcelain",{cwd:e,encoding:"utf-8"});if(!n){o.info("No changes to sync");return}execSync("git add .",{cwd:e});let s=n.trim().split(`
|
|
231
|
+
`).length,i=new Date().toISOString().replace("T"," ").substring(0,19),a=`Sync: ${s} solutions - ${i}`;execSync(`git commit -m ${xa(a)}`,{cwd:e});try{execSync("git push -u origin main",{cwd:e,stdio:"ignore"});}catch{try{execSync("git push -u origin master",{cwd:e,stdio:"ignore"});}catch{throw new Error("Failed to push to remote. Please check your git credentials and branch status.")}}o.succeed("Successfully synced solutions to remote");}catch(n){o.fail("Sync failed"),n instanceof Error&&n.message&&console.log(f.red(n.message));}}var Ia={Easy:20,Medium:40,Hard:60};function Xe(e){if(e<60)return `${e}s`;if(e<3600){let t=Math.floor(e/60),o=e%60;return o>0?`${t}m ${o}s`:`${t}m`}else {let t=Math.floor(e/3600),o=Math.floor(e%3600/60);return o>0?`${t}h ${o}m`:`${t}h`}}async function kr(e,t){if(t.stats){await Fa(e);return}if(t.stop){await Na();return}if(!e){console.log(f.yellow("Please provide a problem ID to start the timer.")),console.log(f.gray("Usage: leetcode timer <id>")),console.log(f.gray(" leetcode timer --stats")),console.log(f.gray(" leetcode timer --stop"));return}let{authorized:o}=await v();if(!o)return;let n=Ce.getActiveTimer();if(n){let s=new Date(n.startedAt),i=Math.floor((Date.now()-s.getTime())/1e3);console.log(f.yellow("\u26A0\uFE0F You have an active timer running:")),console.log(f.white(` Problem: ${n.title}`)),console.log(f.white(` Elapsed: ${Xe(i)}`)),console.log(),console.log(f.gray("Use `leetcode timer --stop` to stop it first."));return}let r=Gt("Fetching problem...").start();try{let s;if(/^\d+$/.test(e)?s=await S.getProblemById(e):s=await S.getProblem(e),!s){r.fail(`Problem "${e}" not found`);return}r.stop();let i=t.minutes??Ia[s.difficulty]??30;Ce.startTimer(s.questionFrontendId,s.title,s.difficulty,i),console.log(),console.log(f.bold.cyan("\u23F1\uFE0F Interview Mode Started!")),console.log(f.gray("\u2500".repeat(50))),console.log(),console.log(f.white(`Problem: ${s.questionFrontendId}. ${s.title}`)),console.log(f.white(`Difficulty: ${f.bold(s.difficulty)}`)),console.log(f.white(`Time Limit: ${f.bold.yellow(i+" minutes")}`)),console.log(),console.log(f.gray("\u2500".repeat(50))),console.log(f.green("\u2713 Timer is running in background")),console.log(f.gray(" When you submit successfully, your time will be recorded.")),console.log(f.gray(" Use `leetcode timer --stop` to cancel.")),console.log(),await _e(e,{open:!0});}catch(s){r.fail("Failed to start timer"),s instanceof Error&&console.log(f.red(s.message));}}async function Na(){let e=Ce.stopTimer();if(!e){console.log(f.yellow("No active timer to stop."));return}console.log(f.green("\u23F1\uFE0F Timer stopped.")),console.log(f.gray(`Elapsed time: ${Xe(e.durationSeconds)}`)),console.log(f.gray("(Time not recorded since problem was not submitted)"));}async function Fa(e){if(e&&/^\d+$/.test(e)){let t=Ce.getSolveTimes(e);if(t.length===0){console.log(f.yellow(`No solve times recorded for problem ${e}`));return}console.log(),console.log(f.bold(`\u23F1\uFE0F Solve Times for Problem ${e}`)),console.log(f.gray("\u2500".repeat(40)));for(let o of t){let n=new Date(o.solvedAt).toLocaleDateString(),r=Xe(o.durationSeconds),s=o.timerMinutes,i=o.durationSeconds<=s*60;console.log(` ${n} ${i?f.green(r):f.red(r)} (limit: ${s}m)`);}}else {let t=Ce.getStats(),o=Ce.getAllSolveTimes();console.log(),console.log(f.bold("\u23F1\uFE0F Timer Statistics")),console.log(f.gray("\u2500".repeat(40))),console.log(),console.log(` Problems timed: ${f.cyan(t.totalProblems)}`),console.log(` Total time: ${f.cyan(Xe(t.totalTime))}`),console.log(` Average time: ${f.cyan(Xe(t.avgTime))}`),console.log();let n=[];for(let[r,s]of Object.entries(o))for(let i of s)n.push({problemId:r,title:i.title,duration:i.durationSeconds,date:i.solvedAt});if(n.length>0){n.sort((r,s)=>new Date(s.date).getTime()-new Date(r.date).getTime()),console.log(f.bold(" Recent Solves:"));for(let r of n.slice(0,5)){let s=new Date(r.date).toLocaleDateString();console.log(f.gray(` ${s} `)+f.white(`${r.problemId}. ${r.title.substring(0,25)}`)+f.gray(" ")+f.cyan(Xe(r.duration)));}}console.log();}}var Ua="https://abagrmwdpvnfyuqizyym.supabase.co",Ba="sb_publishable_indrKu8VJmASdyLp7w8Hog_OyqT17cV",Ie=createClient(Ua,Ba);function xo(){return T.getCollabPath()}function qa(){let e=xo();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{session:null}}function Va(e){let t=xo(),o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true}),writeFileSync(t,JSON.stringify(e,null,2));}var Re={getSession(){return qa().session},setSession(e){Va({session:e});},getPath(){return xo()}};function za(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let o=0;o<6;o++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}var we={getSession(){return Re.getSession()},async createRoom(e,t){let o=za(),{error:n}=await Ie.from("collab_rooms").insert({room_code:o,problem_id:e,host_username:t,host_code:"",guest_username:null,guest_code:null});return n?{error:n.message}:(Re.setSession({roomCode:o,problemId:e,isHost:true,username:t}),{roomCode:o})},async joinRoom(e,t){let{data:o,error:n}=await Ie.from("collab_rooms").select("*").eq("room_code",e.toUpperCase()).single();if(n||!o)return {error:"Room not found"};if(o.guest_username&&o.guest_username!==t)return {error:"Room already has a guest"};let{error:r}=await Ie.from("collab_rooms").update({guest_username:t}).eq("room_code",e.toUpperCase());return r?{error:r.message}:(Re.setSession({roomCode:e.toUpperCase(),problemId:o.problem_id,isHost:false,username:t}),{problemId:o.problem_id})},async syncCode(e){let t=Re.getSession();if(!t)return {success:false,error:"No active session"};let o=t.isHost?"host_code":"guest_code",{error:n}=await Ie.from("collab_rooms").update({[o]:e}).eq("room_code",t.roomCode);return n?{success:false,error:n.message}:{success:true}},async getPartnerCode(){let e=Re.getSession();if(!e)return {error:"No active session"};let{data:t,error:o}=await Ie.from("collab_rooms").select("*").eq("room_code",e.roomCode).single();return o||!t?{error:"Room not found"}:e.isHost?{code:t.guest_code||"",username:t.guest_username||"Partner"}:{code:t.host_code||"",username:t.host_username||"Host"}},async getRoomStatus(){let e=Re.getSession();if(!e)return {error:"No active session"};let{data:t,error:o}=await Ie.from("collab_rooms").select("*").eq("room_code",e.roomCode).single();return o||!t?{error:"Room not found"}:{host:t.host_username,guest:t.guest_username,hasHostCode:!!t.host_code,hasGuestCode:!!t.guest_code}},async leaveRoom(){let e=Re.getSession();e&&e.isHost&&await Ie.from("collab_rooms").delete().eq("room_code",e.roomCode),Re.setSession(null);}};async function Rr(e){let{authorized:t,username:o}=await v();if(!t||!o)return;let n=Gt("Creating collaboration room...").start();try{let r=await we.createRoom(e,o);if("error"in r){n.fail(r.error);return}n.succeed("Room created!"),console.log(),console.log(f.bold.cyan("\u{1F465} Collaborative Coding Session")),console.log(f.gray("\u2500".repeat(50))),console.log(),console.log(f.white(`Room Code: ${f.bold.green(r.roomCode)}`)),console.log(f.white(`Problem: ${e}`)),console.log(),console.log(f.gray("Share this code with your partner:")),console.log(f.yellow(` leetcode collab join ${r.roomCode}`)),console.log(),console.log(f.gray("\u2500".repeat(50))),console.log(f.gray("After solving, sync and compare:")),console.log(f.gray(" leetcode collab sync - Upload your solution")),console.log(f.gray(" leetcode collab compare - See both solutions")),console.log(f.gray(" leetcode collab status - Check room status")),console.log(f.gray(" leetcode collab leave - End session")),console.log(),await _e(e,{open:!0});}catch(r){n.fail("Failed to create room"),r instanceof Error&&console.log(f.red(r.message));}}async function xr(e){let{authorized:t,username:o}=await v();if(!t||!o)return;let n=Gt(`Joining room ${e}...`).start();try{let r=await we.joinRoom(e.toUpperCase(),o);if("error"in r){n.fail(r.error);return}n.succeed("Joined room!"),console.log(),console.log(f.bold.cyan("\u{1F465} Collaborative Coding Session")),console.log(f.gray("\u2500".repeat(50))),console.log(),console.log(f.white(`Room Code: ${f.bold.green(e.toUpperCase())}`)),console.log(f.white(`Problem: ${r.problemId}`)),console.log(),console.log(f.gray("\u2500".repeat(50))),console.log(f.gray("After solving, sync and compare:")),console.log(f.gray(" leetcode collab sync - Upload your solution")),console.log(f.gray(" leetcode collab compare - See both solutions")),console.log(f.gray(" leetcode collab status - Check room status")),console.log(f.gray(" leetcode collab leave - End session")),console.log(),await _e(r.problemId,{open:!0});}catch(r){n.fail("Failed to join room"),r instanceof Error&&console.log(f.red(r.message));}}async function Or(){let e=we.getSession();if(!e){console.log(f.yellow("No active collaboration session.")),console.log(f.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` first."));return}let t=Gt("Syncing your code...").start();try{let o=M.getWorkDir(),n=await ge(o,e.problemId);if(!n){t.fail(`No solution file found for problem ${e.problemId}`);return}let r=await readFile(n,"utf-8"),s=await we.syncCode(r);s.success?(t.succeed("Code synced successfully!"),console.log(f.gray(`Uploaded ${r.split(`
|
|
232
|
+
`).length} lines from ${n}`))):t.fail(s.error||"Sync failed");}catch(o){t.fail("Sync failed"),o instanceof Error&&console.log(f.red(o.message));}}async function Pr(){let e=we.getSession();if(!e){console.log(f.yellow("No active collaboration session.")),console.log(f.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` first."));return}let t=Gt("Fetching solutions...").start();try{let o=M.getWorkDir(),n=await ge(o,e.problemId);if(!n){t.fail(`No solution file found for problem ${e.problemId}`);return}let r=await readFile(n,"utf-8"),s=await we.getPartnerCode();if("error"in s){t.fail(s.error);return}if(t.stop(),!s.code){console.log(f.yellow("Partner has not synced their code yet.")),console.log(f.gray("Ask them to run `leetcode collab sync`."));return}console.log(),console.log(f.bold.cyan("\u{1F4CA} Solution Comparison")),console.log(f.gray("\u2500".repeat(60))),console.log(),console.log(f.bold.green(`\u25B8 Your Solution (${e.username})`)),console.log(f.gray("\u2500".repeat(60)));let i=r.split(`
|
|
233
|
+
`);for(let l=0;l<i.length;l++){let u=String(l+1).padStart(3," ");console.log(`${f.gray(u)} ${i[l]}`);}console.log(),console.log(f.bold.blue(`\u25B8 ${s.username}'s Solution`)),console.log(f.gray("\u2500".repeat(60)));let a=s.code.split(`
|
|
234
|
+
`);for(let l=0;l<a.length;l++){let u=String(l+1).padStart(3," ");console.log(`${f.gray(u)} ${a[l]}`);}console.log(),console.log(f.gray("\u2500".repeat(60))),console.log(f.gray(`Your code: ${i.length} lines | Partner: ${a.length} lines`)),console.log();}catch(o){t.fail("Failed to fetch solutions"),o instanceof Error&&console.log(f.red(o.message));}}async function $r(){if(!we.getSession()){console.log(f.yellow("No active collaboration session."));return}await we.leaveRoom(),console.log(f.green("\u2713 Left the collaboration session."));}async function vr(){let e=we.getSession();if(!e){console.log(f.yellow("No active collaboration session.")),console.log(f.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` to start."));return}let t=await we.getRoomStatus();if("error"in t){console.log(f.red(t.error));return}console.log(),console.log(f.bold.cyan("\u{1F465} Collaboration Status")),console.log(f.gray("\u2500".repeat(40))),console.log(` Room: ${f.green(e.roomCode)}`),console.log(` Problem: ${e.problemId}`),console.log(` Role: ${e.isHost?"Host":"Guest"}`),console.log(),console.log(f.bold(" Participants:")),console.log(` Host: ${t.host} ${t.hasHostCode?f.green("\u2713 synced"):f.gray("pending")}`),console.log(` Guest: ${t.guest||f.gray("(waiting...)")} ${t.hasGuestCode?f.green("\u2713 synced"):f.gray("pending")}`),console.log();}function Ja(){return T.getSnapshotsDir()}function Nr(e){return join(Ja(),e)}function Fr(e){return join(Nr(e),"meta.json")}function Kt(e){return join(Nr(e),"files")}function Hr(e){let t=Kt(e);existsSync(t)||mkdirSync(t,{recursive:true});}function bt(e){let t=Fr(e);return existsSync(t)?JSON.parse(readFileSync(t,"utf-8")):{problemId:e,problemTitle:"",snapshots:[]}}function Ar(e,t){Hr(e),writeFileSync(Fr(e),JSON.stringify(t,null,2));}var J={save(e,t,o,n,r){Hr(e);let s=bt(e);t&&(s.problemTitle=t);let i=s.snapshots.length>0?Math.max(...s.snapshots.map(b=>b.id))+1:1,a=(r??`snapshot-${i}`).trim();if(!zn(a))return {error:'Invalid snapshot name. Use 1-64 characters: letters, numbers, spaces, "-" or "_".'};let l=s.snapshots.find(b=>b.name===a);if(l)return {error:`Snapshot with name "${a}" already exists (ID: ${l.id})`};let u=Ye[n]||n,g=`${i}_${a}.${u}`,d=join(Kt(e),g);writeFileSync(d,o,"utf-8");let m={id:i,name:a,fileName:g,language:n,lines:o.split(`
|
|
235
|
+
`).length,createdAt:new Date().toISOString()};return s.snapshots.push(m),Ar(e,s),m},list(e){return bt(e).snapshots},getMeta(e){return bt(e)},get(e,t){let o=bt(e),n=o.snapshots.find(s=>s.id===parseInt(t,10));return n||o.snapshots.find(s=>s.name===t)||null},getCode(e,t){let o=join(Kt(e),t.fileName);if(!existsSync(o))throw new Error(`Snapshot file not found: ${t.fileName}`);return readFileSync(o,"utf-8")},delete(e,t){let o=bt(e),n=this.get(e,t);if(!n)return false;let r=join(Kt(e),n.fileName);return existsSync(r)&&unlinkSync(r),o.snapshots=o.snapshots.filter(s=>s.id!==n.id),Ar(e,o),true},hasSnapshots(e){return this.list(e).length>0}};function tl(e){let t=new Date(e),n=new Date().getTime()-t.getTime(),r=Math.floor(n/6e4),s=Math.floor(r/60),i=Math.floor(s/24);return r<1?"just now":r<60?`${r}m ago`:s<24?`${s}h ago`:`${i}d ago`}async function Wr(e,t){let o=M.getWorkDir();try{let n=await ge(o,e);if(!n){console.log(f.red(`No solution file found for problem ${e}`)),console.log(f.gray("Run `leetcode pick "+e+"` first to create a solution file."));return}let r=await readFile(n,"utf-8"),s=extname(n).slice(1),i=We(s)||s,l=basename(n).match(/^\d+\.(.+)\.\w+$/),u=l?l[1]:"",g=J.save(e,u,r,i,t);if("error"in g){console.log(f.red("\u2717 "+g.error));return}let d=g;console.log(f.green("\u2713 Snapshot saved!")),console.log(),console.log(` ID: ${f.cyan(d.id)}`),console.log(` Name: ${f.white(d.name)}`),console.log(` Lines: ${f.gray(d.lines)}`),console.log(` File: ${f.gray(n)}`);}catch(n){console.log(f.red("Failed to save snapshot")),n instanceof Error&&console.log(f.gray(n.message));}}async function jr(e){let t=J.list(e);if(t.length===0){console.log(f.yellow(`No snapshots found for problem ${e}`)),console.log(f.gray("Use `leetcode snapshot save "+e+"` to create one."));return}let o=J.getMeta(e);console.log(),console.log(f.bold(`\u{1F4F8} Snapshots for Problem ${e}`)),o.problemTitle&&console.log(f.gray(` ${o.problemTitle}`)),console.log(f.gray("\u2500".repeat(50))),console.log();for(let n of t){let r=tl(n.createdAt);console.log(` ${f.cyan(n.id.toString().padStart(2))}. ${f.white(n.name.padEnd(25))} ${f.gray(n.lines+" lines")} ${f.gray("\xB7")} ${f.gray(r)}`);}console.log(),console.log(f.gray("Commands:")),console.log(f.gray(` restore: leetcode snapshot restore ${e} <id|name>`)),console.log(f.gray(` diff: leetcode snapshot diff ${e} <id1> <id2>`)),console.log(f.gray(` delete: leetcode snapshot delete ${e} <id|name>`));}async function Gr(e,t){let o=M.getWorkDir();try{let n=J.get(e,t);if(!n){console.log(f.red(`Snapshot "${t}" not found for problem ${e}`)),console.log(f.gray("Run `leetcode snapshot list "+e+"` to see available snapshots."));return}let r=await ge(o,e);if(!r){console.log(f.red(`No solution file found for problem ${e}`));return}let s=await readFile(r,"utf-8"),i=`backup-before-restore-${Date.now()}`,a=extname(r).slice(1),l=We(a)||a;J.save(e,"",s,l,i);let u=J.getCode(e,n);await writeFile(r,u,"utf-8"),console.log(f.green("\u2713 Snapshot restored!")),console.log(),console.log(` Restored: ${f.cyan(n.name)} (${n.lines} lines)`),console.log(` File: ${f.gray(r)}`),console.log(` Backup: ${f.gray(i)}`);}catch(n){console.log(f.red("Failed to restore snapshot")),n instanceof Error&&console.log(f.gray(n.message));}}async function Kr(e,t,o){try{let n=J.get(e,t),r=J.get(e,o);if(!n){console.log(f.red(`Snapshot "${t}" not found`));return}if(!r){console.log(f.red(`Snapshot "${o}" not found`));return}let s=J.getCode(e,n),i=J.getCode(e,r);console.log(),console.log(f.bold(`\u{1F4CA} Diff: ${n.name} \u2192 ${r.name}`)),console.log(f.gray("\u2500".repeat(50))),console.log();let a=diffLines(s,i),l=0,u=0;for(let g of a){let d=g.value.split(`
|
|
236
|
+
`).filter(m=>m!=="");if(g.added){l+=d.length;for(let m of d)console.log(f.green("+ "+m));}else if(g.removed){u+=d.length;for(let m of d)console.log(f.red("- "+m));}else if(d.length<=4)for(let m of d)console.log(f.gray(" "+m));else console.log(f.gray(" "+d[0])),console.log(f.gray(" "+d[1])),console.log(f.gray(` ... (${d.length-4} more lines)`)),console.log(f.gray(" "+d[d.length-2])),console.log(f.gray(" "+d[d.length-1]));}console.log(),console.log(f.gray("\u2500".repeat(50))),console.log(`${f.green("+"+l+" added")} ${f.gray("\xB7")} ${f.red("-"+u+" removed")} ${f.gray("\xB7")} ${f.gray(n.lines+" \u2192 "+r.lines+" lines")}`);}catch(n){console.log(f.red("Failed to diff snapshots")),n instanceof Error&&console.log(f.gray(n.message));}}async function qr(e,t){let o=J.get(e,t);if(!o){console.log(f.red(`Snapshot "${t}" not found for problem ${e}`));return}let n=J.delete(e,t);console.log(n?f.green(`\u2713 Deleted snapshot: ${o.name}`):f.red("Failed to delete snapshot"));}function zr(e,t){let o=e.split(`
|
|
237
|
+
`),n=o.length;console.log(),console.log(f.bold.cyan(`=== ${t} (${n} lines) ===`)),console.log(f.gray("\u2500".repeat(60))),o.forEach((r,s)=>{let i=(s+1).toString().padStart(3);console.log(f.gray(i+" \u2502 ")+r);});}function rl(e,t,o,n){let r=e.split(`
|
|
238
|
+
`).length,s=t.split(`
|
|
239
|
+
`).length;console.log(),console.log(f.bold(`\u{1F4CA} Unified Diff: ${o} \u2192 ${n}`)),console.log(f.gray("\u2500".repeat(60))),console.log();let i=diffLines(e,t),a=0,l=0;for(let u of i){let g=u.value.split(`
|
|
240
|
+
`).filter(d=>d!=="");if(u.added){a+=g.length;for(let d of g)console.log(f.green("+ "+d));}else if(u.removed){l+=g.length;for(let d of g)console.log(f.red("- "+d));}else if(g.length<=6)for(let d of g)console.log(f.gray(" "+d));else console.log(f.gray(" "+g[0])),console.log(f.gray(" "+g[1])),console.log(f.dim(` ... (${g.length-4} unchanged lines)`)),console.log(f.gray(" "+g[g.length-2])),console.log(f.gray(" "+g[g.length-1]));}console.log(),console.log(f.gray("\u2500".repeat(60))),console.log(`${f.green("+"+a+" added")} ${f.gray("\xB7")} ${f.red("-"+l+" removed")} ${f.gray("\xB7")} ${f.gray(r+" \u2192 "+s+" lines")}`);}function Oo(e,t,o,n,r){if(r)rl(e,t,o,n);else {zr(e,o),zr(t,n);let s=diffLines(e,t),i=0,a=0;for(let l of s){let u=l.value.split(`
|
|
241
|
+
`).filter(g=>g!=="");l.added?i+=u.length:l.removed&&(a+=u.length);}console.log(),console.log(f.gray("\u2500".repeat(60))),console.log(`${f.bold("Summary:")} ${f.green("+"+i+" added")} ${f.gray("\xB7")} ${f.red("-"+a+" removed")}`),console.log(f.gray("Tip: Use --unified for line-by-line diff"));}}async function Qr(e,t){let{authorized:o}=await v();if(!o)return;let n=M.getWorkDir(),r=Gt("Finding solution file...").start();try{let s=await ge(n,e);if(!s){r.fail(`No solution file found for problem ${e}`),console.log(f.gray("Run `leetcode pick "+e+"` first to create a solution file."));return}let i=await readFile(s,"utf-8");if(r.text="Fetching comparison target...",t.file){if(r.stop(),!existsSync(t.file)){console.log(f.red(`File not found: ${t.file}`));return}if(!ze(t.file,n)){console.log(f.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(f.gray(`File: ${t.file}`)),console.log(f.gray(`Workspace: ${n}`)),console.log(f.yellow(`
|
|
242
|
+
For security reasons, you can only diff files from within your workspace.`));return}let d=await readFile(t.file,"utf-8");Oo(i,d,"Your Solution",t.file,t.unified??!1);return}let a=await S.getProblemById(e);if(!a){r.fail(`Problem ${e} not found`);return}if(t.submission){let d=parseInt(t.submission,10),m=await S.getSubmissionDetails(d);r.stop(),Oo(i,m.code,"Your Solution",`Submission #${d}`,t.unified??!1);return}let u=(await S.getSubmissionList(a.titleSlug,50)).find(d=>d.statusDisplay==="Accepted");if(!u){r.fail("No accepted submissions found for this problem"),console.log(f.gray("Tip: Use --file to compare with a local file instead"));return}let g=await S.getSubmissionDetails(parseInt(u.id,10));r.stop(),Oo(i,g.code,"Your Solution","Last Accepted",t.unified??!1);}catch(s){r.fail("Failed to diff"),s instanceof Error&&console.log(f.red(s.message));}}async function Jr(){let e=T.getActive(),t=T.getConfig(e);console.log(),console.log(f.bold.cyan(`\u{1F4C1} Active Workspace: ${e}`)),console.log(f.gray("\u2500".repeat(40))),console.log(` workDir: ${f.white(t.workDir)}`),console.log(` lang: ${f.white(t.lang)}`),t.editor&&console.log(` editor: ${f.white(t.editor)}`),t.syncRepo&&console.log(` syncRepo: ${f.white(t.syncRepo)}`),console.log();}async function Xr(){let e=T.list(),t=T.getActive();console.log(),console.log(f.bold("Workspaces:")),console.log();for(let o of e){let n=T.getConfig(o),r=o===t?f.green("\u25B8 "):" ",s=o===t?f.green.bold(o):o;console.log(`${r}${s}`),console.log(` ${f.gray(n.workDir)}`);}console.log();}async function Zr(e,t){let o=e.trim();if(!Ve(o)){console.log(f.red("Invalid workspace name.")),console.log(f.gray('Use 1-64 characters: letters, numbers, "-" or "_".'));return}if(T.exists(o)){console.log(f.red(`Workspace "${o}" already exists`));return}let n=t.workdir??join(homedir(),"leetcode",o),r={workDir:n,lang:"typescript"};T.create(o,r)?(console.log(f.green(`\u2713 Created workspace "${o}"`)),console.log(` workDir: ${f.gray(n)}`),console.log(),console.log(f.gray(`Switch to it: leetcode workspace use ${o}`))):console.log(f.red("Failed to create workspace"));}async function es(e){let t=e.trim();if(!Ve(t)){console.log(f.red("Invalid workspace name."));return}if(!T.exists(t)){console.log(f.red(`Workspace "${t}" not found`)),console.log(f.gray("Use `leetcode workspace list` to see available workspaces"));return}if(T.setActive(t)){let n=T.getConfig(t);console.log(f.green(`\u2713 Switched to workspace "${t}"`)),console.log(` workDir: ${f.gray(n.workDir)}`);}else console.log(f.red("Failed to switch workspace"));}async function ts(e){let t=e.trim();if(!Ve(t)){console.log(f.red("Invalid workspace name."));return}if(t==="default"){console.log(f.red("Cannot delete the default workspace"));return}if(!T.exists(t)){console.log(f.red(`Workspace "${t}" not found`));return}let{confirmed:o}=await To.prompt([{type:"confirm",name:"confirmed",message:`Delete workspace "${t}"? (files in workDir will NOT be deleted)`,default:false}]);if(!o){console.log(f.gray("Cancelled"));return}let n=T.delete(t);console.log(n?f.green(`\u2713 Deleted workspace "${t}"`):f.red("Failed to delete workspace"));}var Po=join(homedir(),".leetcode"),Ct=join(Po,"version-cache.json"),dl=1440*60*1e3;function fl(){existsSync(Po)||mkdirSync(Po,{recursive:true});}function os(){if(existsSync(Ct))try{return JSON.parse(readFileSync(Ct,"utf-8"))}catch{return null}return null}function ml(e){fl(),writeFileSync(Ct,JSON.stringify(e,null,2));}var Ne={shouldCheck(){let e=os();return e?Date.now()-e.lastCheck>dl:true},getCached(){return os()},updateCache(e,t){ml({lastCheck:Date.now(),latestVersion:e,hasBreakingChanges:t});},clearCache(){if(existsSync(Ct))try{unlinkSync(Ct);}catch{}}};function et(e,t){let o=e.replace("v","").split(".").map(Number),n=t.replace("v","").split(".").map(Number);for(let r=0;r<3;r++){let s=o[r]||0,i=n[r]||0;if(s>i)return true;if(s<i)return false}return false}function rs(e,t){let o=parseInt(e.replace("v","").split(".")[0])||0;return (parseInt(t.replace("v","").split(".")[0])||0)>o}var El=fileURLToPath(import.meta.url),is=dirname(El),wl="https://registry.npmjs.org/@night-slayer18/leetcode-cli/latest",Ml="@night-slayer18/leetcode-cli";function tt(){let e=[join(is,"../package.json"),join(is,"../../package.json")];for(let t of e)try{let o=JSON.parse(readFileSync(t,"utf-8"));if(o.version)return o.version}catch{continue}throw new Error("Could not read package.json version. Ensure you are running from a valid installation.")}async function ls(){let t=(await yi(wl,{timeout:{request:1e4},retry:{limit:2}}).json()).version,o=tt(),n=rs(o,t);return {version:t,hasBreakingChanges:n}}function _l(e,t,o){console.log();let n=60,r="\u256D"+"\u2500".repeat(n-2)+"\u256E",s="\u2570"+"\u2500".repeat(n-2)+"\u256F";console.log(f.cyan(r));let i=` \u{1F680} Update available: ${f.gray(e)} \u2192 ${f.green(t)}`;if(console.log(f.cyan("\u2502")+i.padEnd(n+18)+f.cyan("\u2502")),o){console.log(f.cyan("\u2502")+"".padEnd(n-2)+f.cyan("\u2502"));let l=` ${f.yellow("\u26A0\uFE0F This update contains breaking changes!")}`;console.log(f.cyan("\u2502")+l.padEnd(n+20)+f.cyan("\u2502"));let u=` ${f.gray("Run:")} leetcode changelog ${f.gray("to review changes")}`;console.log(f.cyan("\u2502")+u.padEnd(n+16)+f.cyan("\u2502"));}console.log(f.cyan("\u2502")+"".padEnd(n-2)+f.cyan("\u2502"));let a=` ${f.gray("Run:")} npm update -g ${Ml}`;console.log(f.cyan("\u2502")+a.padEnd(n+8)+f.cyan("\u2502")),console.log(f.cyan(s)),console.log();}async function cs(e){let t=tt();e.force&&Ne.clearCache();let o=Ne.getCached(),n,r;if(o&&!Ne.shouldCheck()&&!e.force)n=o.latestVersion,r=o.hasBreakingChanges;else {let s=Gt("Checking for updates...").start();try{let i=await ls();n=i.version,r=i.hasBreakingChanges,Ne.updateCache(n,r),s.stop();}catch(i){s.fail("Failed to check for updates"),process.env.DEBUG&&console.log(f.gray(` Debug: ${i instanceof Error?i.message:String(i)}`)),console.log(f.gray(" Could not reach npm registry. Check your internet connection."));return}}et(n,t)?(_l(t,n,r),e.checkOnly||r&&(console.log(f.yellow("\u{1F4A1} Tip: Review the changelog before updating to check for breaking changes.")),console.log(f.gray(` Run: leetcode changelog
|
|
243
|
+
`)))):(console.log(),console.log(f.green("\u2713")+` You're on the latest version (${f.cyan(t)})`),console.log());}async function us(){if(!Ne.shouldCheck()){let e=Ne.getCached();e&&et(e.latestVersion,tt())&&as(tt(),e.latestVersion,e.hasBreakingChanges);return}try{let e=await ls();Ne.updateCache(e.version,e.hasBreakingChanges),et(e.version,tt())&&as(tt(),e.version,e.hasBreakingChanges);}catch{}}function as(e,t,o){console.log(),o?(console.log(f.yellow(`\u26A0\uFE0F Update ${e} \u2192 ${t} available (breaking changes!)`)),console.log(f.gray(" Run: leetcode changelog && leetcode update"))):(console.log(f.cyan(`\u{1F680} Update available: ${e} \u2192 ${t}`)),console.log(f.gray(" Run: leetcode update"))),console.log();}var Ol=fileURLToPath(import.meta.url),gs=dirname(Ol),Pl="https://raw.githubusercontent.com/night-slayer18/leetcode-cli/main/docs/releases.md";function $l(){let e=[join(gs,"../package.json"),join(gs,"../../package.json")];for(let t of e)try{let o=JSON.parse(readFileSync(t,"utf-8"));if(o.version)return o.version}catch{continue}throw new Error("Could not read package.json version. Ensure you are running from a valid installation.")}async function vl(){return await yi(Pl,{timeout:{request:1e4},retry:{limit:2}}).text()}function Al(e){let t=[],o=/^## v?([\d.]+)/gm,n=[...e.matchAll(o)];for(let r=0;r<n.length;r++){let s=n[r],i=`v${s[1]}`,a=s.index+s[0].length,l=r+1<n.length?n[r+1].index:e.length,u=e.slice(a,l).trim(),g=u.includes("\u26A0\uFE0F Breaking Change");t.push({version:i,content:u,hasBreakingChanges:g});}return t}function Dl(e,t,o){let n=o?f.bgRed.white.bold(` ${e} `)+f.red(" \u26A0\uFE0F BREAKING CHANGES"):f.bgCyan.black.bold(` ${e} `);console.log(n),console.log();let r=t.split(`
|
|
244
|
+
`),s=false;for(let i of r)if(!(i.trim()===""&&!s)){if(i.startsWith("> **Release Date**")){let a=i.replace("> **Release Date**: ","").trim();console.log(f.gray(` \u{1F4C5} ${a}`));continue}if(i.startsWith("> **Focus**")){let a=i.replace("> **Focus**: ","").trim();console.log(f.gray(` \u{1F3AF} ${a}`)),console.log();continue}if(i.startsWith("### ")){let a=i.replace("### ","").trim();if(console.log(),/^[\u{1F300}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/u.test(a))console.log(f.bold.yellow(` ${a}`));else {let u="\u{1F4CC}";a.includes("Breaking")?u="\u26A0\uFE0F":a.includes("Feature")||a.includes("New")?u="\u{1F680}":a.includes("Fix")||a.includes("Bug")?u="\u{1F41B}":a.includes("Security")?u="\u{1F512}":a.includes("Improvement")?u="\u2728":a.includes("Architecture")?u="\u{1F3D7}\uFE0F":a.includes("Testing")?u="\u{1F9EA}":a.includes("Config")&&(u="\u2699\uFE0F"),console.log(f.bold.yellow(` ${u} ${a}`));}s=true;continue}if(i.startsWith("#### ")){let a=i.replace("#### ","").trim();console.log(f.bold.white(` ${a}`));continue}if(i.startsWith("- **")){let a=i.match(/^- \*\*(.+?)\*\*:?\s*(.*)/);console.log(a?f.cyan(` \u2022 ${f.bold(a[1])}`)+(a[2]?f.white(`: ${a[2]}`):""):f.cyan(` \u2022 ${i.replace("- ","")}`));continue}if(i.startsWith("- ")){let a=i.replace("- ","").trim();console.log(f.white(` \u2022 ${a}`));continue}i.startsWith("---")||i.trim()===">"||i.trim()&&console.log(f.gray(` ${i.trim()}`));}}async function ds(e,t={}){let o=Gt("Fetching changelog...").start();try{let n=await vl();o.stop();let r=Al(n);if(r.length===0){console.log(f.yellow("No release entries found."));return}let s=$l(),i=r;if(e){let a=e.startsWith("v")?e:`v${e}`;if(i=r.filter(l=>l.version===a),i.length===0){console.log(f.red(`Version ${e} not found in changelog.`)),console.log(f.gray("Available versions: "+r.map(l=>l.version).join(", ")));return}}else if(t.latest)i=r.slice(0,1);else if(t.breaking){if(i=r.filter(a=>a.hasBreakingChanges),i.length===0){console.log(f.green("\u2713 No breaking changes in any release."));return}}else if(t.all)i=r;else {if(i=r.filter(a=>et(a.version,s)),i.length===0){console.log(f.green(`\u2713 You're on the latest version (${s})`)),console.log(f.gray("Use --all to see the full changelog."));return}console.log(f.gray(`Showing changes since your version (${s})`)),console.log(f.gray("Use --all to see the full changelog."));}console.log(),console.log(f.bold.cyan("\u{1F4CB} LeetCode CLI Release Notes")),console.log(f.gray("\u2500".repeat(50))),console.log();for(let a of i)Dl(a.version,a.content,a.hasBreakingChanges),console.log(f.gray("\u2500".repeat(60))),console.log();if(!e&&!t.latest){let a=r.filter(l=>l.hasBreakingChanges).length;console.log(f.gray(`Showing ${i.length} of ${r.length} releases`)),a>0&&!t.breaking&&console.log(f.yellow(`${a} release(s) contain breaking changes. Use --breaking to filter.`));}}catch{o.fail("Failed to fetch changelog"),console.log(f.gray(" Could not fetch release notes from GitHub.")),console.log(f.gray(" Visit: https://github.com/night-slayer18/leetcode-cli/blob/main/docs/releases.md"));}}var c={none:()=>({type:"CMD_NONE"}),batch:(...e)=>({type:"CMD_BATCH",commands:e}),fetchProblems:(e,t=false)=>({type:"CMD_FETCH_PROBLEMS",filters:e,append:t}),fetchProblemDetail:e=>({type:"CMD_FETCH_PROBLEM_DETAIL",slug:e}),fetchStats:()=>({type:"CMD_FETCH_STATS"}),fetchDaily:()=>({type:"CMD_FETCH_DAILY"}),fetchRandom:()=>({type:"CMD_FETCH_RANDOM"}),checkAuth:()=>({type:"CMD_CHECK_AUTH"}),pickProblem:(e,t)=>({type:"CMD_PICK_PROBLEM",slug:e,lang:t}),testSolution:e=>({type:"CMD_TEST_SOLUTION",slug:e}),submitSolution:e=>({type:"CMD_SUBMIT_SOLUTION",slug:e}),startTimer:(e=1e3)=>({type:"CMD_START_TIMER_SUBSCRIPTION",intervalMs:e}),stopTimer:()=>({type:"CMD_STOP_TIMER_SUBSCRIPTION"}),saveConfig:(e,t)=>({type:"CMD_SAVE_CONFIG",key:e,value:t}),openEditor:e=>({type:"CMD_OPEN_EDITOR",id:e}),fetchSubmissions:e=>({type:"CMD_FETCH_SUBMISSIONS",slug:e}),exit:()=>({type:"CMD_EXIT"}),loadNote:e=>({type:"CMD_LOAD_NOTE",problemId:e}),diffSnapshot:(e,t)=>({type:"CMD_DIFF_SNAPSHOT",slug:e,snapshotId:t}),restoreSnapshot:(e,t)=>({type:"CMD_RESTORE_SNAPSHOT",slug:e,snapshotId:t}),loadWorkspaces:()=>({type:"CMD_LOAD_WORKSPACES"}),createWorkspace:e=>({type:"CMD_CREATE_WORKSPACE",name:e}),deleteWorkspace:e=>({type:"CMD_DELETE_WORKSPACE",name:e}),switchWorkspace:e=>({type:"CMD_SWITCH_WORKSPACE",name:e}),fetchChangelog:()=>({type:"CMD_FETCH_CHANGELOG"}),logout:()=>({type:"CMD_LOGOUT"}),login:(e,t)=>({type:"CMD_LOGIN",session:e,csrf:t})};function fs(e){return {screenState:{screen:"home",model:{menuIndex:0}},history:[],user:e?{username:e,isLoggedIn:true}:null,isCheckingAuth:true,globalError:null,terminalWidth:process.stdout.columns||80,terminalHeight:process.stdout.rows||24,needsRender:true}}var Vt=50;function Il(){return {problems:[],total:0,cursor:0,scrollOffset:0,page:0,loading:true,loadingMore:false,error:null,searchQuery:"",searchMode:false,searchBuffer:"",difficultyFilter:null,statusFilter:null,bookmarkFilter:false}}function vo(){let e=Il(),t={limit:Vt,skip:0};return [e,c.fetchProblems(t,false)]}function Ao(e,t,o){let n=Math.max(3,o-13);switch(e.type){case "LIST_CURSOR_DOWN":{if(t.problems.length===0)return [t,c.none()];let r=Math.min(t.cursor+1,t.problems.length-1),s=t.scrollOffset;if(r>=t.scrollOffset+n&&(s=r-n+1),r>=t.problems.length-5&&t.problems.length<t.total&&!t.loadingMore&&!t.loading){let a=ot(t,t.page+1);return [{...t,cursor:r,scrollOffset:s,loadingMore:true},c.fetchProblems(a,true)]}return [{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_CURSOR_UP":{if(t.problems.length===0)return [t,c.none()];let r=Math.max(t.cursor-1,0),s=t.scrollOffset;return r<t.scrollOffset&&(s=r),[{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_PAGE_DOWN":{let r=Math.min(t.cursor+n,t.problems.length-1),s=Math.min(t.scrollOffset+n,Math.max(0,t.problems.length-n));return [{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_PAGE_UP":{let r=Math.max(t.cursor-n,0),s=Math.max(t.scrollOffset-n,0);return [{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_GO_TOP":return [{...t,cursor:0,scrollOffset:0},c.none()];case "LIST_GO_BOTTOM":{let r=Math.max(0,t.problems.length-1),s=Math.max(0,t.problems.length-n);return [{...t,cursor:r,scrollOffset:s},c.none()]}case "LIST_SELECT":return [t,c.none()];case "LIST_SEARCH_START":return [{...t,searchMode:true,searchBuffer:t.searchQuery},c.none()];case "LIST_SEARCH_INPUT":return [{...t,searchBuffer:t.searchBuffer+e.char},c.none()];case "LIST_SEARCH_BACKSPACE":return [{...t,searchBuffer:t.searchBuffer.slice(0,-1)},c.none()];case "LIST_SEARCH_SUBMIT":{let r=ot({...t,searchQuery:t.searchBuffer},0);return [{...t,searchMode:false,searchQuery:t.searchBuffer,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(r,false)]}case "LIST_SEARCH_CANCEL":return [{...t,searchMode:false,searchBuffer:""},c.none()];case "LIST_FILTER_DIFFICULTY":{let r=e.difficulty,s=ot({...t,difficultyFilter:r},0);return [{...t,difficultyFilter:r,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(s,false)]}case "LIST_FILTER_STATUS":{let r=e.status,s=ot({...t,statusFilter:r},0);return [{...t,statusFilter:r,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(s,false)]}case "LIST_FILTER_BOOKMARKS":{let r=!t.bookmarkFilter,s=ot({...t},0);return [{...t,bookmarkFilter:r,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(s,false)]}case "LIST_CLEAR_FILTERS":{let r={limit:Vt,skip:0};return [{...t,difficultyFilter:null,statusFilter:null,searchQuery:"",bookmarkFilter:false,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(r,false)]}case "LIST_REFRESH":{let r=ot(t,0);return [{...t,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(r,false)]}case "LIST_FETCH_START":return [{...t,loading:true,error:null},c.none()];case "LIST_FETCH_SUCCESS":{let r=e.append?[...t.problems,...e.problems]:e.problems;return t.bookmarkFilter&&(r=r.filter(s=>de.has(s.questionFrontendId))),[{...t,problems:r,total:t.bookmarkFilter?r.length:e.total,loading:false,loadingMore:false,page:e.append?t.page+1:0,error:null},c.none()]}case "LIST_FETCH_ERROR":return [{...t,loading:false,loadingMore:false,error:e.error},c.none()];default:return [t,c.none()]}}function ot(e,t){let o={limit:Vt,skip:t*Vt};if(e.difficultyFilter&&(o.difficulty=e.difficultyFilter.toUpperCase()),e.statusFilter){let n={solved:"AC",attempted:"TRIED",todo:"NOT_STARTED"};o.status=n[e.statusFilter];}return e.searchQuery&&(o.searchKeywords=e.searchQuery),o}var Et=[{key:"l",label:"Problem List",description:"Browse and search problems"},{key:"d",label:"Daily Challenge",description:"Today's daily problem"},{key:"r",label:"Random Problem",description:"Pick a random problem"},{key:"b",label:"Bookmarks",description:"View bookmarked problems"},{key:"t",label:"Timer",description:"Practice timer"},{key:"s",label:"Statistics",description:"View your progress"},{key:"y",label:"Sync",description:"Sync solutions to GitHub"},{key:"w",label:"Workspaces",description:"Manage workspaces"},{key:"c",label:"Config",description:"Settings and preferences"},{key:"v",label:"Changelog",description:"What's new in this version"},{key:"L",label:"Logout",description:"Sign out of LeetCode"},{key:"?",label:"Help",description:"Keyboard shortcuts and help"}];function zt(e,t){switch(e.type){case "HOME_MENU_UP":{let o=Math.max(0,t.menuIndex-1);return [{...t,menuIndex:o},c.none()]}case "HOME_MENU_DOWN":{let o=Math.min(Et.length-1,t.menuIndex+1);return [{...t,menuIndex:o},c.none()]}case "HOME_MENU_SELECT":return [t,c.none()];default:return [t,c.none()]}}function Yt(e,t){switch(e.type){case "TIMER_START":return t.status==="running"?[t,c.none()]:[{...t,status:"running"},c.startTimer(1e3)];case "TIMER_PAUSE":return t.status!=="running"?[t,c.none()]:[{...t,status:"paused"},c.stopTimer()];case "TIMER_RESET":return [{...t,remainingSeconds:t.totalSeconds,status:"idle"},c.stopTimer()];case "TIMER_TICK":return t.status!=="running"?[t,c.none()]:t.remainingSeconds<=1?[{...t,remainingSeconds:0,status:"completed"},c.stopTimer()]:[{...t,remainingSeconds:t.remainingSeconds-1},c.none()];case "TIMER_COMPLETE":return [{...t,status:"completed"},c.stopTimer()];case "TIMER_SWITCH_VIEW":return [{...t,viewMode:e.view},c.none()];default:return [t,c.none()]}}function Ul(){return {loading:true,error:null,stats:null,dailyChallenge:null,skillStats:null}}function ms(){return [Ul(),c.fetchStats()]}function Do(e,t){switch(e.type){case "STATS_FETCH_START":return [{...t,loading:true,error:null},c.none()];case "STATS_FETCH_SUCCESS":return [{...t,loading:false,stats:e.stats,dailyChallenge:e.daily,skillStats:e.skills},c.none()];case "STATS_FETCH_ERROR":return [{...t,loading:false,error:e.error},c.none()];case "STATS_REFRESH":return [{...t,loading:true,error:null},c.fetchStats()];default:return [t,c.none()]}}function Wl(e){return [{id:"language",label:"Default Language",description:"Language for new solutions (example: typescript, python3)",value:e.language},{id:"editor",label:"Editor Command",description:"Command used to open files (example: code, vim, nano)",value:e.editor||""},{id:"workdir",label:"Working Directory",description:"Directory where solution files are generated",value:e.workDir},{id:"repo",label:"Sync Repository",description:"Git repository URL used for sync operations",value:e.repo||""}]}function Io(e){return e.options[e.selectedOption]}function jl(e,t){let o=t.trim();return e.id==="language"&&!o?"Language cannot be empty":e.id==="workdir"&&!o?"Working directory cannot be empty":null}function Gl(){let e=M.getConfig(),t=Wl(e);return {selectedOption:0,options:t,paneFocus:"list",isEditing:false,draftValue:t[0]?.value??"",validationError:null,isDirty:false,config:e}}function hs(){return [Gl(),c.none()]}function ys(e,t){let o=(t+e.options.length)%e.options.length,n=e.options[o];return {...e,selectedOption:o,draftValue:n.value,isEditing:false,isDirty:false,validationError:null}}function No(e,t){switch(e.type){case "CONFIG_OPTION_UP":return t.isEditing?[t,c.none()]:[ys(t,t.selectedOption-1),c.none()];case "CONFIG_OPTION_DOWN":return t.isEditing?[t,c.none()]:[ys(t,t.selectedOption+1),c.none()];case "CONFIG_FOCUS_LIST":return [{...t,paneFocus:"list",isEditing:false,isDirty:false},c.none()];case "CONFIG_FOCUS_EDITOR":return [{...t,paneFocus:"editor"},c.none()];case "CONFIG_TOGGLE_FOCUS":return [{...t,paneFocus:t.paneFocus==="list"?"editor":"list"},c.none()];case "CONFIG_EDIT_START":{let o=Io(t);return [{...t,paneFocus:"editor",isEditing:true,draftValue:o.value,validationError:null,isDirty:false},c.none()]}case "CONFIG_EDIT_INPUT":return t.isEditing?[{...t,draftValue:t.draftValue+e.char,validationError:null,isDirty:true},c.none()]:[t,c.none()];case "CONFIG_EDIT_BACKSPACE":return t.isEditing?[{...t,draftValue:t.draftValue.slice(0,-1),validationError:null,isDirty:true},c.none()]:[t,c.none()];case "CONFIG_EDIT_CANCEL":{let o=Io(t);return [{...t,isEditing:false,isDirty:false,draftValue:o.value,validationError:null},c.none()]}case "CONFIG_EDIT_SAVE":{if(!t.isEditing)return [t,c.none()];let o=Io(t),n=jl(o,t.draftValue);if(n)return [{...t,validationError:n},c.none()];let r=[...t.options];return r[t.selectedOption]={...o,value:t.draftValue},[{...t,options:r,isEditing:false,isDirty:false,validationError:null},c.saveConfig(o.id,t.draftValue)]}default:return [t,c.none()]}}var p={primary:"#00B8D4",success:"#00E676",warning:"#FFEA00",error:"#FF1744",info:"#2979FF",text:"#FFFFFF",textMuted:"#90A4AE",textDim:"#546E7A",border:"#37474F",textBright:"#FFFFFF",bgHighlight:"#263238",cyan:"#00E5FF"},Y={check:"\u2714",cross:"\u2716",star:"\u2605",gear:"\u2699",folder:"\u{1F4C2}",target:"\u{1F3AF}",fire:"\u{1F525}",arrow:"\u2192",code:"\u{1F4DD}"},j={topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502",leftT:"\u251C",rightT:"\u2524",topT:"\u252C",bottomT:"\u2534",cross:"\u253C",roundTopLeft:"\u256D",roundTopRight:"\u256E",roundBottomLeft:"\u2570",roundBottomRight:"\u256F",heavyHorizontal:"\u2501",heavyVertical:"\u2503"},Qt={tableColumns:{selector:2,status:3,id:6,difficulty:10,acceptance:8,premium:2}};var Fo={filled:"\u2588",empty:"\u2591"};var ql=/\x1B\[[0-9;]*[a-zA-Z]/g;function P(e){return e.replace(ql,"")}function wt(e){return P(e).length}function A(e,t){if(t<=0)return "";if(t===1)return "\u2026";if(wt(e)<=t)return e;let o=t-1,n="",r=0;for(let s=0;s<e.length&&r<o;){if(e[s]==="\x1B"){let i=e.slice(s).match(/^\x1B\[[0-9;]*[a-zA-Z]/);if(i){n+=i[0],s+=i[0].length;continue}}n+=e[s],s+=1,r+=1;}return e.includes("\x1B[")?`${n}\u2026\x1B[0m`:`${n}\u2026`}function ue(e,t){let o=P(e),n=t-o.length;return n>0?e+" ".repeat(n):e}function Uo(e,t){let o=P(e),n=t-o.length;return n>0?" ".repeat(n)+e:e}function $(e,t){if(t<=0)return "";let n=P(e).length;if(n>=t)return e;let r=Math.floor((t-n)/2),s=t-n-r;return " ".repeat(r)+e+" ".repeat(s)}var Ho={light:j,round:j,heavy:{horizontal:"\u2501",vertical:"\u2503",topLeft:"\u250F",topRight:"\u2513",bottomLeft:"\u2517",bottomRight:"\u251B"},double:{horizontal:"\u2550",vertical:"\u2551",topLeft:"\u2554",topRight:"\u2557",bottomLeft:"\u255A",bottomRight:"\u255D"}};function he(e,t,o={}){let n=typeof o=="string"?{title:o}:o,{title:r,borderColor:s=p.textMuted,padding:i=0,borderStyle:a="round"}=n,l=Ho[a]||j,u=[],g=Math.max(4,t),d=Math.max(2,g-2),m=Math.max(1,d-i*2),b=f.hex(s)(l.topLeft||l.roundTopLeft);if(r){let _=f.hex(s).bold(` ${r} `),w=P(_).length;b+=f.hex(s)(l.horizontal),b+=_,b+=f.hex(s)(l.horizontal.repeat(Math.max(0,d-w-1)));}else b+=f.hex(s)(l.horizontal.repeat(d));b+=f.hex(s)(l.topRight||l.roundTopRight),u.push(b);for(let _=0;_<i;_++)u.push(f.hex(s)(l.vertical)+" ".repeat(d)+f.hex(s)(l.vertical));for(let _ of e){let w=P(_),R=_;w.length>m&&(R=A(_,m));let G=m-P(R).length,K=" ".repeat(i)+R+" ".repeat(G)+" ".repeat(i);u.push(f.hex(s)(l.vertical)+K+f.hex(s)(l.vertical));}for(let _=0;_<i;_++)u.push(f.hex(s)(l.vertical)+" ".repeat(d)+f.hex(s)(l.vertical));return u.push(f.hex(s)(l.bottomLeft||l.roundBottomLeft)+f.hex(s)(l.horizontal.repeat(d))+f.hex(s)(l.bottomRight||l.roundBottomRight)),u}function Jt(e,t="light",o=p.textMuted){let n=j.horizontal;return t==="heavy"&&(n=Ho.heavy.horizontal),t==="double"&&(n=Ho.double.horizontal),f.hex(o)(n.repeat(Math.max(0,e)))}function Ss(e,t,o){let n=Math.min(1,Math.max(0,e/t)),r=Math.round(n*o),s=o-r;return f.hex(p.success)(Fo.filled.repeat(r))+f.hex(p.textDim)(Fo.empty.repeat(s))}function Ge(e,t,o="#000000"){return f.bgHex(t).hex(o).bold(` ${e} `)}function bs(e){switch(e.toLowerCase()){case "easy":return Ge("Easy",p.success);case "medium":return Ge("Medium",p.warning);case "hard":return Ge("Hard",p.error);default:return Ge(e,p.textMuted)}}function Cs(e){switch(e){case "ac":return f.hex(p.success)(Y.check);case "notac":return f.hex(p.warning)("\u25CB");default:return f.hex(p.textDim)(" ")}}function C(e,t){return f.hex(p.textMuted)("[")+f.hex(p.primary)(e)+f.hex(p.textMuted)("] ")+f.hex(p.text)(t)}function Bo(e){return e.map(t=>C(t.key,t.label)).join(" ")}function nt(e,t,o){let n=Math.max(20,o),r=f.hex(p.primary).bold(` ${e} `),s=f.hex(p.textMuted)(A(t,Math.max(8,n-2)));return [$(r,n),$(s,n)]}function Me(e,t){let o=Math.max(10,t),n=f.hex(p.primary).bold(` ${e} `),r=Math.max(0,o-wt(n));return n+f.hex(p.textMuted)(j.horizontal.repeat(r))}function rt(e,t,o="normal"){let n=Math.max(20,t),r=o==="compact"?e.slice(0,3):e,s=Bo(r);return H([s],n).map(a=>$(a,n))}function st(e,t,o,n,r=.5){let s=Math.max(20,o),i=Math.max(1,n),a=Math.max(8,Math.floor(s*r)),l=Math.max(8,s-a-1),u=[...e],g=[...t],d=[];for(;u.length<i;)u.push("");for(;g.length<i;)g.push("");for(let m=0;m<i;m++){let b=ue(A(u[m]??"",a),a),_=ue(A(g[m]??"",l),l);d.push(b+f.hex(p.border)(j.vertical)+_);}return d}var Vl=["\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 ","\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D ","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],zl=["\u2566 \u2554\u2550\u2557\u2554\u2550\u2557\u2554\u2566\u2557\u2554\u2550\u2557\u2554\u2550\u2557\u2554\u2566\u2557\u2554\u2550\u2557","\u2551 \u2551\u2563 \u2551\u2563 \u2551 \u2551 \u2551 \u2551 \u2551\u2551\u2551\u2563 ","\u2569\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u2569 \u255A\u2550\u255D\u255A\u2550\u255D\u2550\u2569\u255D\u255A\u2550\u255D"];function it(e){return (e>=80?Vl:zl).map(o=>$(f.hex(p.primary)(o),e))}function H(e,t){let o=Math.max(1,t),n=[];for(let r of e){if(P(r).length<=o){n.push(r);continue}let i=r.split(" "),a="",l=0;for(let u of i){let g=P(u).length;if(g>o){l>0&&(n.push(a),a="",l=0);let m=u;for(;P(m).length>0;){let b=m.slice(0,o);n.push(b),m=m.slice(o);}continue}let d=a?1:0;l+g+d<=o?(a+=(a?" ":"")+u,l+=g+d):(n.push(a),a=u,l=g);}a&&n.push(a);}return n}function Yl(e){switch(e){case "status":case "testResult":case "submitResult":return 6;case "hint":case "submissions":case "snapshots":return 10;case "note":case "diff":return 12;default:return 0}}function Mt(e,t){let o=Math.max(10,e),s=Math.max(4,o-3-2);if(t==="none")return {bodyHeight:s,drawerHeight:0};let i=1,a=s>=14?8:5,l=Math.max(3,s-a-i),u=Math.max(3,Math.min(Yl(t),l));return {bodyHeight:Math.max(3,s-i-u),drawerHeight:u}}function eo(e){return [{problem:null,slug:e,detail:null,loading:true,error:null,scrollOffset:0,contentLines:[],testResult:null,submissionResult:null,isRunning:false,successMessage:null,activeHintIndex:null,isBookmarked:false,drawerMode:"none",focusRegion:"body",drawerScrollOffset:0,drawerData:{statusMessage:null},submissionsHistory:null,submissionsLoading:false,snapshotsList:null,snapshotCursor:0,noteContent:null,diffContent:null},c.fetchProblemDetail(e)]}function xe(e){return {...e,drawerMode:"none",focusRegion:"body",drawerScrollOffset:0,drawerData:{statusMessage:null}}}function ne(e,t,o=null){return t==="none"?xe(e):{...e,drawerMode:t,focusRegion:"drawer",drawerScrollOffset:0,drawerData:{statusMessage:o}}}function to(e,t,o,n){let r=Jl(t,o,n);switch(e.type){case "PROBLEM_FOCUS_TOGGLE":return t.drawerMode==="none"?[t,c.none()]:[{...t,focusRegion:t.focusRegion==="body"?"drawer":"body"},c.none()];case "PROBLEM_SCROLL_UP":return [{...t,scrollOffset:Math.max(0,t.scrollOffset-1)},c.none()];case "PROBLEM_SCROLL_DOWN":return [{...t,scrollOffset:Math.min(r,t.scrollOffset+1)},c.none()];case "PROBLEM_PAGE_UP":{let s=Math.max(3,Math.floor(Wo(o,t.drawerMode)*.8));return [{...t,scrollOffset:Math.max(0,t.scrollOffset-s)},c.none()]}case "PROBLEM_PAGE_DOWN":{let s=Math.max(3,Math.floor(Wo(o,t.drawerMode)*.8));return [{...t,scrollOffset:Math.min(r,t.scrollOffset+s)},c.none()]}case "PROBLEM_TOP":return [{...t,scrollOffset:0},c.none()];case "PROBLEM_BOTTOM":return [{...t,scrollOffset:r},c.none()];case "PROBLEM_DETAIL_LOADED":{let s=Ql(e.detail),i=de.has(e.detail.questionFrontendId);return [{...t,loading:false,detail:e.detail,contentLines:s,scrollOffset:0,isBookmarked:i,error:null,successMessage:null,drawerMode:"none",focusRegion:"body",drawerScrollOffset:0,drawerData:{statusMessage:null}},c.none()]}case "PROBLEM_DETAIL_ERROR":return [{...ne({...t,loading:false,error:e.error},"status",e.error)},c.none()];case "PROBLEM_PICK":return [t,c.pickProblem(t.slug)];case "PROBLEM_TEST":return [{...ne(t,"status","Running tests..."),isRunning:true,testResult:null,submissionResult:null,successMessage:null,error:null},c.testSolution(t.slug)];case "PROBLEM_SUBMIT":return [{...ne(t,"status","Submitting solution..."),isRunning:true,testResult:null,submissionResult:null,successMessage:null,error:null},c.submitSolution(t.slug)];case "PROBLEM_TEST_RESULT":return [{...ne(t,"testResult"),isRunning:false,testResult:e.result,submissionResult:null},c.none()];case "PROBLEM_SUBMIT_RESULT":return [{...ne(t,"submitResult"),isRunning:false,submissionResult:e.result,testResult:null},c.none()];case "PROBLEM_BOOKMARK":{if(!t.detail)return [t,c.none()];let s=t.detail.questionFrontendId;if(de.has(s)){de.remove(s);let a="Problem unbookmarked";return [{...ne(t,"status",a),isBookmarked:false,successMessage:a,error:null},c.none()]}de.add(s);let i="Problem bookmarked";return [{...ne(t,"status",i),isBookmarked:true,successMessage:i,error:null},c.none()]}case "PROBLEM_TOGGLE_HINT":return (t.detail?.hints||[]).length===0?[{...ne(t,"status","No hints available for this problem"),error:null,successMessage:null},c.none()]:t.drawerMode==="hint"?[xe(t),c.none()]:[{...ne(t,"hint"),activeHintIndex:t.activeHintIndex??0},c.none()];case "PROBLEM_NEXT_HINT":{let s=t.detail?.hints||[];if(s.length===0)return [t,c.none()];let i=t.activeHintIndex??0;return [{...t,activeHintIndex:Math.min(s.length-1,i+1),drawerScrollOffset:0},c.none()]}case "PROBLEM_PREV_HINT":{let s=t.activeHintIndex??0;return [{...t,activeHintIndex:Math.max(0,s-1),drawerScrollOffset:0},c.none()]}case "PROBLEM_HINT_SCROLL_UP":return [{...t,drawerScrollOffset:Math.max(0,t.drawerScrollOffset-1)},c.none()];case "PROBLEM_HINT_SCROLL_DOWN":return [{...t,drawerScrollOffset:Math.min(Xt(t,o,n),t.drawerScrollOffset+1)},c.none()];case "PROBLEM_NOTES":return t.detail?[t,c.openEditor(t.detail.questionFrontendId)]:[t,c.none()];case "PROBLEM_ACTION_ERROR":return [{...ne(t,"status",e.error),isRunning:false,error:e.error},c.none()];case "PROBLEM_ACTION_SUCCESS":return [{...ne(t,"status",e.message),isRunning:false,successMessage:e.message,error:null},c.none()];case "PROBLEM_CLOSE_RESULT":return [xe(t),c.none()];case "PROBLEM_SHOW_SUBMISSIONS":return t.drawerMode==="submissions"?[xe(t),c.none()]:[{...ne(t,"submissions"),submissionsLoading:true,submissionsHistory:null},c.fetchSubmissions(t.slug)];case "PROBLEM_SUBMISSIONS_LOADED":return [{...ne(t,"submissions"),submissionsLoading:false,submissionsHistory:e.submissions,error:null},c.none()];case "PROBLEM_SUBMISSIONS_ERROR":return [{...ne(t,"status",e.error),submissionsLoading:false,error:e.error},c.none()];case "PROBLEM_CLOSE_SUBMISSIONS":return [xe(t),c.none()];case "PROBLEM_SUBMISSIONS_SCROLL_UP":return [{...t,drawerScrollOffset:Math.max(0,t.drawerScrollOffset-1)},c.none()];case "PROBLEM_SUBMISSIONS_SCROLL_DOWN":return [{...t,drawerScrollOffset:Math.min(Xt(t,o,n),t.drawerScrollOffset+1)},c.none()];case "PROBLEM_SHOW_SNAPSHOTS":{if(t.drawerMode==="snapshots")return [xe(t),c.none()];let s=t.detail?.questionFrontendId||t.slug;return [{...ne(t,"snapshots"),snapshotsList:J.list(s),snapshotCursor:0},c.none()]}case "PROBLEM_CLOSE_SNAPSHOTS":return [xe(t),c.none()];case "PROBLEM_SNAPSHOT_UP":return !t.snapshotsList||t.snapshotsList.length===0?[t,c.none()]:[{...t,snapshotCursor:Math.max(0,t.snapshotCursor-1)},c.none()];case "PROBLEM_SNAPSHOT_DOWN":return !t.snapshotsList||t.snapshotsList.length===0?[t,c.none()]:[{...t,snapshotCursor:Math.min(t.snapshotsList.length-1,t.snapshotCursor+1)},c.none()];case "PROBLEM_VIEW_NOTE":return t.detail?[{...ne(t,"status","Loading note...")},c.loadNote(t.detail.questionFrontendId)]:[t,c.none()];case "PROBLEM_NOTE_LOADED":return [{...ne(t,"note"),noteContent:e.content,error:null},c.none()];case "PROBLEM_CLOSE_NOTE":return [xe(t),c.none()];case "PROBLEM_NOTE_SCROLL_UP":return [{...t,drawerScrollOffset:Math.max(0,t.drawerScrollOffset-1)},c.none()];case "PROBLEM_NOTE_SCROLL_DOWN":return [{...t,drawerScrollOffset:Math.min(Xt(t,o,n),t.drawerScrollOffset+1)},c.none()];case "PROBLEM_DIFF_SNAPSHOT":{if(!t.snapshotsList||t.snapshotsList.length===0)return [t,c.none()];let s=t.snapshotsList[t.snapshotCursor];return s?[t,c.diffSnapshot(t.slug,s.id.toString())]:[t,c.none()]}case "PROBLEM_DIFF_LOADED":return [{...ne(t,"diff"),diffContent:e.content,error:null},c.none()];case "PROBLEM_CLOSE_DIFF":return [xe(t),c.none()];case "PROBLEM_DIFF_SCROLL_UP":return [{...t,drawerScrollOffset:Math.max(0,t.drawerScrollOffset-1)},c.none()];case "PROBLEM_DIFF_SCROLL_DOWN":return [{...t,drawerScrollOffset:Math.min(Xt(t,o,n),t.drawerScrollOffset+1)},c.none()];case "PROBLEM_RESTORE_SNAPSHOT":{if(!t.snapshotsList||t.snapshotsList.length===0)return [t,c.none()];let s=t.snapshotsList[t.snapshotCursor];return s?[t,c.restoreSnapshot(t.slug,s.id.toString())]:[t,c.none()]}default:return [t,c.none()]}}function Ql(e){return go(e.content||"").split(`
|
|
245
|
+
`)}function Wo(e,t){let o=Math.max(6,e-4);return Mt(o,t).bodyHeight}function Jl(e,t,o){let n=Wo(t,e.drawerMode),r=Math.max(20,o-4),s=H(e.contentLines,r);return Math.max(0,s.length-n)}function Xt(e,t,o){if(e.drawerMode==="none"||e.drawerMode==="snapshots")return 0;let n=Math.max(6,t-4),r=Mt(n,e.drawerMode),s=Math.max(1,r.drawerHeight-2),i=Math.max(20,o-2),a=Xl(e,i);return Math.max(0,a.length-s)}function Xl(e,t){let o=Math.max(10,t-2);switch(e.drawerMode){case "hint":{let n=e.detail?.hints||[],r=e.activeHintIndex??0,s=n[r]??"",i=Es(s);return H([i||"No hint content"],o)}case "submissions":return e.submissionsLoading?["Loading submissions..."]:!e.submissionsHistory||e.submissionsHistory.length===0?["No submissions found for this problem.","Use [s] Submit after picking a solution."]:e.submissionsHistory.map(n=>{let r=Zt(n.statusDisplay||"-",10).padEnd(10),s=Zt(n.runtime||"-",8).padEnd(8),i=Zt(n.memory||"-",8).padEnd(8),a=Zt(n.lang||"-",8).padEnd(8);return `${r} ${s} ${i} ${a}`});case "note":return H(Zl(e.noteContent||"No notes found. Press e to edit."),o);case "diff":return (e.diffContent||"No diff available.").split(`
|
|
246
|
+
`).map(n=>Es(n));case "testResult":{let n=e.testResult;return n?n.compile_error?["Compile Error",...H([n.compile_error],o)]:n.runtime_error?["Runtime Error",...H([n.runtime_error],o)]:n.correct_answer?["All test cases passed"]:["Wrong answer"]:["No test result available."]}case "submitResult":{let n=e.submissionResult;if(!n)return ["No submission result available."];let r=[n.status_msg||"-",`Runtime: ${n.status_runtime||"-"}`,`Memory: ${n.status_memory||"-"}`];return n.runtime_error&&r.push(...H([n.runtime_error],o)),r}case "status":{let n=e.drawerData.statusMessage||e.successMessage||e.error||(e.isRunning?"Working...":"Ready");return H([n],o)}default:return []}}function Es(e){return P(e).replace(/\[green\]|\[red\]|\[grey\]/g,"").replace(/<\/?[^>]+(>|$)/g,"").replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/\s+/g," ").trim()}function Zt(e,t){return e.length<=t?e:t<=1?"\u2026":`${e.slice(0,t-1)}\u2026`}function Zl(e){let t=e.split(`
|
|
247
|
+
`),o=[];for(let n of t){let r=n.trim();if(!r){o.length>0&&o[o.length-1]!==""&&o.push("");continue}if(r.startsWith("<!--")&&r.endsWith("-->"))continue;let s=n.replace(/\*\*(.*?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\[(.*?)\]\((.*?)\)/g,"$1 ($2)");s.startsWith("## ")?s=`\u2022 ${s.slice(3)}`:s.startsWith("# ")&&(s=s.slice(2)),o.push(s);}for(;o.length>0&&o[o.length-1]==="";)o.pop();return o.length>0?o:["No notes found. Press e to edit."]}var tc=[{key:"lang",label:"Language"},{key:"workDir",label:"Work Dir"},{key:"editor",label:"Editor"},{key:"syncRepo",label:"Sync Repo"}];function jo(e,t,o){let n=[],r=Math.max(20,t),s=Math.max(8,o),i=e.selectedWorkspace?`Active: ${e.activeWorkspace} \u2022 Selected: ${e.selectedWorkspace}`:"Manage isolated problem-solving contexts";n.push(...nt(`${Y.folder} Workspaces`,i,r)),n.push(f.hex(p.textMuted)(j.horizontal.repeat(r)));let a=Math.max(3,s-n.length-3);if(r>=90)n.push(...st(ws(e,r),Ms(e,r),r,a,.43));else {let l=Math.max(3,Math.floor(a*.45)),u=Math.max(3,a-l-1),g=ws(e,r).slice(0,l);for(;g.length<l;)g.push("");let d=Ms(e,r).slice(0,u);for(;d.length<u;)d.push("");n.push(...g),n.push(f.hex(p.border)(j.horizontal.repeat(r))),n.push(...d);}for(;n.length<s-2;)n.push("");return n.push(f.hex(p.textMuted)(j.horizontal.repeat(r))),n.push(...oc(e,r)),n.slice(0,s).join(`
|
|
248
|
+
`)}function ws(e,t){let o=t>=90?Math.max(20,Math.floor(t*.43)):t,n=[];if(n.push(Me("Workspace List",o)),n.push(""),e.workspaces.length===0)return n.push(f.hex(p.warning)("No workspaces found.")),n;for(let r=0;r<e.workspaces.length;r++){let s=e.workspaces[r],i=r===e.cursor,a=s===e.activeWorkspace,l=i?f.hex(p.primary).bold("\u25B6"):" ",u=a?f.hex(p.success)("\u25CF"):f.hex(p.textMuted)("\u25CB"),g=A(s,Math.max(6,o-8)),d=` ${l} ${u} ${g}`;i&&e.paneFocus==="list"?n.push(f.bgHex(p.bgHighlight)(d.padEnd(Math.max(0,o-1)))):n.push(d);}return n.push(""),n.push(f.hex(p.textMuted)(`Count: ${e.workspaces.length}`)),n}function Ms(e,t){let o=t>=90?Math.max(20,t-Math.floor(t*.43)-1):t,n=[];if(n.push(Me("Properties",o)),n.push(""),!e.selectedWorkspace||!e.draftConfig)return n.push(f.hex(p.textMuted)("Select a workspace to view properties.")),n;n.push(f.hex(p.primary).bold(A(e.selectedWorkspace,o-2))),n.push(e.selectedWorkspace===e.activeWorkspace?f.hex(p.success)("Currently active"):f.hex(p.textMuted)("Not active")),n.push("");for(let r of tc){let s=e.selectedField===r.key,i=e.draftConfig[r.key]||"(empty)",a=A(i,Math.max(8,o-18)),l=s?f.hex(p.primary)("\u25B6"):" ",u=e.isDirty&&s?f.hex(p.warning)("*"):" ",g=`${l} ${r.label.padEnd(10)}: ${a} ${u}`;if(s&&e.paneFocus==="editor"){let d=e.isEditing?`${g}\u2588`:g;n.push(f.bgHex(p.bgHighlight)(d.padEnd(Math.max(0,o-1))));}else n.push(g);}return n.push(""),n.push(f.hex(p.textMuted)(e.isEditing?"Editing field: Enter=Save Esc=Cancel":"Press Enter to edit selected field")),n}function oc(e,t){if(e.showCreateInput)return [`Create workspace: ${A(e.newWorkspaceName,Math.max(5,t-20))}\u2588`,`${C("Enter","Create")} ${C("Esc","Cancel")}`];if(e.showDeleteConfirm){let o=e.workspaces[e.cursor]||"";return [f.bgRed.white(` Delete "${o}"? `),`${C("Enter","Delete")} ${C("Esc","Cancel")}`]}if(e.error){let o=H([`Error: ${e.error}`],Math.max(20,t-2));return [f.hex(p.error)(o[0]??e.error)]}if(e.success){let o=H([e.success],Math.max(20,t-2));return [f.hex(p.success)(o[0]??e.success)]}return rt([{key:"\u2191/\u2193",label:e.paneFocus==="list"?"Select workspace":"Select field"},{key:"Tab/h/l",label:"Switch pane"},{key:"Enter",label:e.paneFocus==="list"?"Switch/Edit":e.isEditing?"Save":"Edit"},{key:"c",label:"Create"},{key:"d",label:"Delete"},{key:"Esc",label:"Back/Cancel"}],t,t<90?"compact":"normal")}var _t=["lang","workDir","editor","syncRepo"];function nc(e){return {lang:e.lang??"",workDir:e.workDir??"",editor:e.editor??"",syncRepo:e.syncRepo??""}}function ks(e){return e?nc(T.getConfig(e)):null}function oo(e,t,o){let n=Math.max(0,Math.min(o,Math.max(0,t.length-1))),r=t[n]??null,s=ks(r);return {...e,workspaces:t,cursor:n,selectedWorkspace:r,selectedConfig:s,draftConfig:s?{...s}:null,isDirty:false,isEditing:false}}function Ts(){let e=T.list(),t=T.getActive(),o=Math.max(0,e.indexOf(t)),n=e[o]??null,r=ks(n);return [{workspaces:e,activeWorkspace:t,cursor:o,paneFocus:"list",selectedField:"lang",selectedWorkspace:n,selectedConfig:r,draftConfig:r?{...r}:null,isEditing:false,isDirty:false,showCreateInput:false,newWorkspaceName:"",showDeleteConfirm:false,error:null,success:null},c.none()]}function _s(e,t){if(!e.draftConfig)return e;let o=e.selectedField,n={...e.draftConfig,[o]:t(e.draftConfig[o])};return {...e,draftConfig:n,isDirty:true,error:null,success:null}}function Go(e,t){switch(e.type){case "WORKSPACE_UP":return t.isEditing?[t,c.none()]:[oo(t,t.workspaces,t.cursor-1),c.none()];case "WORKSPACE_DOWN":return t.isEditing?[t,c.none()]:[oo(t,t.workspaces,t.cursor+1),c.none()];case "WORKSPACE_SELECT":{if(t.isEditing||t.showCreateInput||t.showDeleteConfirm)return [t,c.none()];let o=t.workspaces[t.cursor];return o?o===t.activeWorkspace?[{...t,success:`Already on "${o}"`,error:null},c.none()]:T.setActive(o)?[{...t,activeWorkspace:o,success:`Switched to "${o}"`,error:null},c.switchWorkspace(o)]:[{...t,error:`Failed to switch to "${o}"`,success:null},c.none()]:[t,c.none()]}case "WORKSPACE_FOCUS_LIST":return [{...t,paneFocus:"list",isEditing:false,isDirty:false,error:null},c.none()];case "WORKSPACE_FOCUS_EDITOR":return [{...t,paneFocus:"editor",error:null},c.none()];case "WORKSPACE_TOGGLE_FOCUS":return [{...t,paneFocus:t.paneFocus==="list"?"editor":"list",isEditing:false,isDirty:false,error:null},c.none()];case "WORKSPACE_FIELD_UP":{if(t.paneFocus!=="editor"||t.isEditing)return [t,c.none()];let o=Math.max(0,_t.indexOf(t.selectedField)-1);return [{...t,selectedField:_t[o]},c.none()]}case "WORKSPACE_FIELD_DOWN":{if(t.paneFocus!=="editor"||t.isEditing)return [t,c.none()];let o=Math.min(_t.length-1,_t.indexOf(t.selectedField)+1);return [{...t,selectedField:_t[o]},c.none()]}case "WORKSPACE_EDIT_START":return t.paneFocus!=="editor"||!t.draftConfig?[t,c.none()]:[{...t,isEditing:true,error:null,success:null},c.none()];case "WORKSPACE_EDIT_INPUT":return t.isEditing?[_s(t,o=>o+e.char),c.none()]:[t,c.none()];case "WORKSPACE_EDIT_BACKSPACE":return t.isEditing?[_s(t,o=>o.slice(0,-1)),c.none()]:[t,c.none()];case "WORKSPACE_EDIT_CANCEL":return [{...t,draftConfig:t.selectedConfig?{...t.selectedConfig}:null,isEditing:false,isDirty:false,error:null},c.none()];case "WORKSPACE_EDIT_SAVE":{if(!t.isEditing||!t.selectedWorkspace||!t.draftConfig)return [t,c.none()];let o={lang:t.draftConfig.lang.trim(),workDir:t.draftConfig.workDir.trim(),editor:t.draftConfig.editor.trim(),syncRepo:t.draftConfig.syncRepo.trim()};return o.lang?o.workDir?(T.setConfig({lang:o.lang,workDir:o.workDir,editor:o.editor||void 0,syncRepo:o.syncRepo||void 0},t.selectedWorkspace),[{...t,selectedConfig:o,draftConfig:{...o},isEditing:false,isDirty:false,error:null,success:`Saved "${t.selectedWorkspace}" properties`},c.none()]):[{...t,error:"Working directory is required"},c.none()]:[{...t,error:"Language is required"},c.none()]}case "WORKSPACE_CREATE_START":return [{...t,showCreateInput:true,newWorkspaceName:"",error:null,success:null,paneFocus:"list"},c.none()];case "WORKSPACE_CREATE_INPUT":return t.showCreateInput?[{...t,newWorkspaceName:t.newWorkspaceName+e.char,error:null},c.none()]:[t,c.none()];case "WORKSPACE_CREATE_BACKSPACE":return t.showCreateInput?[{...t,newWorkspaceName:t.newWorkspaceName.slice(0,-1),error:null},c.none()]:[t,c.none()];case "WORKSPACE_CREATE_CANCEL":return [{...t,showCreateInput:false,newWorkspaceName:"",error:null},c.none()];case "WORKSPACE_CREATE_SUBMIT":{if(!t.showCreateInput)return [t,c.none()];let o=t.newWorkspaceName.trim();if(!o)return [{...t,error:"Name cannot be empty"},c.none()];if(T.exists(o))return [{...t,error:"Workspace already exists"},c.none()];if(!T.create(o,{workDir:"",lang:"typescript"}))return [{...t,error:"Failed to create workspace"},c.none()];let r=T.list();return [{...oo({...t,showCreateInput:false,newWorkspaceName:""},r,r.indexOf(o)),success:`Created workspace "${o}"`,paneFocus:"list"},c.createWorkspace(o)]}case "WORKSPACE_DELETE":{let o=t.workspaces[t.cursor];return o?o==="default"?[{...t,error:"Cannot delete default workspace"},c.none()]:[{...t,showDeleteConfirm:true,error:null,success:null},c.none()]:[t,c.none()]}case "WORKSPACE_DELETE_CANCEL":return [{...t,showDeleteConfirm:false,error:null},c.none()];case "WORKSPACE_DELETE_CONFIRM":{let o=t.workspaces[t.cursor];if(!o)return [t,c.none()];if(o==="default")return [{...t,error:"Cannot delete default workspace"},c.none()];if(!T.delete(o))return [{...t,error:`Failed to delete "${o}"`},c.none()];let r=T.list(),s=T.getActive();return [{...oo({...t,showDeleteConfirm:false,activeWorkspace:s},r,Math.min(t.cursor,Math.max(0,r.length-1))),success:`Deleted workspace "${o}"`},c.deleteWorkspace(o)]}default:return [t,c.none()]}}function Ls(e){let t=[],o=/^## v?([\d.]+)/gm,n=[...e.matchAll(o)];for(let r=0;r<n.length;r++){let s=n[r],i=`v${s[1]}`,a=s.index+s[0].length,l=r+1<n.length?n[r+1].index:e.length,u=e.slice(a,l).trim(),g=u.includes("\u26A0\uFE0F Breaking Change"),d=u.match(/> \*\*Release Date\*\*: (.*)/),m=d?d[1].trim():void 0;t.push({version:i,content:u,hasBreakingChanges:g,date:m});}return t}function Os(e,t){return e.loading||e.error?3:Ps(e.entries,t).length}function Ko(e,t,o){let n=[],s=f.hex(p.primary).bold(Y.code+" Changelog ")+f.hex(p.textMuted)("Latest updates and improvements");n.push(s),n.push(f.hex(p.textMuted)(j.horizontal.repeat(t))),n.push("");let i=Math.max(3,o-5);if(e.loading)n.push(""),n.push(" "+f.hex(p.primary)("\u22EF Loading release notes..."));else if(e.error)n.push(""),n.push(" "+f.red(Y.cross+" Error loading changelog:")),n.push(" "+f.red(e.error));else {let l=Ps(e.entries,t),u=Math.max(0,l.length-i),g=Math.min(e.scrollOffset,u);if(l.slice(g,g+i).forEach(m=>{n.push(" "+m);}),u>0&&n.length<o-2){let m=`${g+1}-${Math.min(g+i,l.length)} of ${l.length}`;n.push(" "+f.hex(p.textMuted)(m));}}for(;n.length<o-2;)n.push("");n.push(f.hex(p.textMuted)(j.horizontal.repeat(t)));let a=[C("j/k","Scroll"),C("Esc","Back")];return n.push(a.join(" ")),n.slice(0,o).join(`
|
|
249
|
+
`)}function sc(e,t){let o=[],n=` ${e.version} `,r=e.hasBreakingChanges?f.bgRed.white.bold(n)+f.red(" \u26A0\uFE0F BREAKING CHANGES"):f.bgHex(p.primary).black.bold(n);o.push(r),e.date&&o.push(f.gray(` \u{1F4C5} ${e.date}`)),o.push("");let s=e.content.split(`
|
|
250
|
+
`),i=false;for(let a of s)if(!(a.trim()===""&&!i)&&!(a.startsWith("> **Release Date**")||a.startsWith("> **Focus**"))){if(a.startsWith("### ")){let l=a.replace("### ","").trim();o.push("");let u="\u{1F4CC}";l.includes("Breaking")?u="\u26A0\uFE0F":l.includes("Feature")||l.includes("New")?u="\u{1F680}":(l.includes("Fix")||l.includes("Bug"))&&(u="\u{1F41B}"),o.push(f.bold.yellow(`${u} ${l}`)),i=true;continue}if(a.startsWith("#### ")){o.push(f.bold.white(" "+a.replace("#### ","").trim()));continue}if(a.startsWith("- ")){let l=a.replace("- ","").trim(),u=l.match(/^\*\*(.+?)\*\*:?\s*(.*)/),g="";u?g=f.cyan(`\u2022 ${f.bold(u[1])}`)+(u[2]?f.white(`: ${u[2]}`):""):g=f.white(`\u2022 ${l}`),o.push(...Rs(" "+g,t-3,5));continue}a.startsWith("---")||a.trim().length>0&&o.push(...Rs(" "+f.gray(a.trim()),t-3,3));}return o}function Rs(e,t,o){let n=Math.max(1,t);if(xs(e).length<=n)return [e];let r=e.split(" "),s=[],i="",a=" ".repeat(o);return r.forEach(l=>{xs(i+l).length+1>n?(s.push(i),i=a+l+" "):i+=l+" ";}),i&&s.push(i),s}function xs(e){return e.replace(/\x1B\[\d+m/g,"")}function Ps(e,t){let o=[],n=Math.max(20,t-4);return e.forEach(r=>{o.push(...sc(r,n)),o.push(""),o.push(f.hex(p.border)(j.horizontal.repeat(n))),o.push("");}),o}function $s(e){return [{entries:[],scrollOffset:0,loading:true,error:null},c.fetchChangelog()]}function qo(e,t,o,n){let r=Math.max(3,o-5),s=Math.max(0,Os(t,n)-r);switch(e.type){case "CHANGELOG_SCROLL_UP":return [{...t,scrollOffset:Math.max(0,t.scrollOffset-1)},c.none()];case "CHANGELOG_SCROLL_DOWN":return [{...t,scrollOffset:Math.min(s,t.scrollOffset+1)},c.none()];case "CHANGELOG_FETCH_START":return [{...t,loading:true,error:null},c.none()];case "CHANGELOG_FETCH_SUCCESS":let i=Ls(e.content);return [{...t,loading:false,entries:i,error:null,scrollOffset:0},c.none()];case "CHANGELOG_FETCH_ERROR":return [{...t,loading:false,error:e.error},c.none()];default:return [t,c.none()]}}function Vo(e,t,o){let n=[],r=[],s=it(t);if(r.push(...s),r.push(""),r.push($(f.hex(p.textMuted)("Please authenticate to access LeetCode features"),t)),r.push(""),r.push(""),e.step==="instructions"){let l=Math.max(28,Math.min(100,t-4)),u=[f.hex(p.warning).bold("How to Login:"),"","1. Open https://leetcode.com in your browser","2. Login to your account","3. Open DevTools (F12) \u2192 Application \u2192 Cookies \u2192 leetcode.com","4. Copy the values of "+f.bold.cyan("LEETCODE_SESSION")+" and "+f.bold.cyan("csrftoken"),"","Note: These credentials are stored locally on your machine."];he(u,l,{title:"Authentication Instructions",borderColor:p.primary,padding:1,borderStyle:"round"}).forEach(d=>r.push($(d,t))),r.push(""),r.push($(C("Enter","Continue to Login"),t));}else if(e.step==="input"||e.step==="verifying"||e.step==="error"){let l=Math.max(28,Math.min(100,t-4)),u=[],g=e.focusedField==="session",d=e.focusedField==="csrf",m=Math.max(12,l-20),b=z=>z.length>m?"..."+z.slice(-(m-3)):z,_=e.sessionToken?b(e.sessionToken):f.gray("Paste here..."),w=e.csrfToken?b(e.csrfToken):e.sessionToken?f.gray("Paste here..."):f.gray("Waiting..."),R=e.sessionToken?b(e.sessionToken):f.gray("(empty)"),G=e.csrfToken?b(e.csrfToken):f.gray("(empty)");u.push(f.bold("LEETCODE_SESSION:")),u.push(g?f.hex(p.primary)("> ")+_:" "+R+(e.sessionToken?f.green(" \u2714"):"")),u.push(""),u.push(f.bold("csrftoken:")),u.push(d?f.hex(p.primary)("> ")+w:" "+G+(e.csrfToken?f.green(" \u2714"):"")),u.push(""),e.error?u.push($(f.red(e.error),l-4)):e.step==="verifying"?u.push($(f.yellow("Verifying credentials..."),l-4)):u.push($(f.gray("Use Command+V to paste"),l-4)),he(u,l,{title:"Enter Credentials",borderColor:e.error?p.error:p.primary,padding:1}).forEach(z=>r.push($(z,t))),r.push(""),e.step==="input"&&r.push($(C("Enter",e.focusedField==="session"?"Next":"Login")+" "+C("Esc","Cancel"),t));}else e.step==="success"&&(r.push(""),r.push($(f.green.bold("\u2714 Login Successful!"),t)),r.push($("Redirecting...",t)));let i=r.length,a=Math.max(0,Math.floor((o-i)/2));for(let l=0;l<a;l++)n.push("");for(n.push(...r);n.length<o;)n.push("");return n.slice(0,o).join(`
|
|
251
|
+
`)}function zo(e,t){switch(e.type){case "LOGIN_SESSION_INPUT":return [{...t,sessionToken:e.value},c.none()];case "LOGIN_CSRF_INPUT":return [{...t,csrfToken:e.value},c.none()];case "LOGIN_SWITCH_FOCUS":return [{...t,focusedField:t.focusedField==="session"?"csrf":"session"},c.none()];case "LOGIN_SET_FOCUS":return [{...t,focusedField:e.field},c.none()];case "LOGIN_BACK":return [{...t,step:"instructions",focusedField:"session",error:null},c.none()];case "LOGIN_SUBMIT":return t.step==="instructions"?[{...t,step:"input",focusedField:"session"},c.none()]:!t.sessionToken||!t.csrfToken?[{...t,error:"Both fields are required"},c.none()]:[{...t,step:"verifying",error:null},c.login(t.sessionToken,t.csrfToken)];case "LOGIN_SUCCESS":return [{...t,step:"success"},c.none()];case "LOGIN_ERROR":return [{...t,step:"input",error:e.error},c.none()]}return [t,c.none()]}function vs(e){let{username:t,isConnected:o,width:n}=e,r=[],s=f.hex(p.primary).bold(`${Y.fire} LeetCode CLI`),i=o?f.hex(p.success)("\u25CF Connected"):f.hex(p.error)("\u25CB Offline"),a=t?f.hex(p.text)(`${Y.code} ${t}`):f.hex(p.textMuted)("Not logged in"),l=s,u=`${i} ${a}`,g=P(u).length,d=Math.max(1,n-g-1),m=H([l],d)[0]??l,b=P(m).length,_=n-b-g,w=_>0?" ".repeat(_):" ";return r.push(m+w+u),r.push(f.hex(p.textMuted)(j.horizontal.repeat(n))),r}function As(e){let{screen:t,hints:o,message:n,width:r}=e,s=[];s.push(f.hex(p.textMuted)(j.horizontal.repeat(r)));let i=Bo(o),a=f.bgHex(p.bgHighlight).hex(p.primary)(` ${t.toUpperCase()} `),l;if(n){let _=f.hex(p.warning)(n);l=i+" "+_;}else l=i;let u=P(a).length,g=Math.max(1,r-u-1);l=H([l],g)[0]??"";let d=P(l).length,m=r-d-u,b=m>0?" ".repeat(m):" ";return s.push(l+b+a),s}function Ds(e){switch(e){case "home":return [{key:"j/k",label:"Navigate"},{key:"\u21B5",label:"Select"},{key:"q",label:"Quit"},{key:"?",label:"Help"}];case "list":return [{key:"j/k",label:"Move"},{key:"/",label:"Search"},{key:"1-3",label:"Filter"},{key:"\u21B5",label:"Open"},{key:"Esc",label:"Back"}];case "problem":return [{key:"j/k",label:"Scroll"},{key:"p",label:"Pick"},{key:"t",label:"Test"},{key:"s",label:"Submit"},{key:"Esc",label:"Back"}];case "timer":return [{key:"Space",label:"Start/Pause"},{key:"r",label:"Reset"},{key:"Esc",label:"Back"}];case "help":return [{key:"j/k",label:"Scroll"},{key:"PgUp/PgDn",label:"Page"},{key:"?/Esc",label:"Close"}];case "workspace":return [{key:"Tab",label:"Switch Pane"},{key:"Enter",label:"Switch/Edit"},{key:"c/d",label:"Create/Delete"},{key:"Esc",label:"Back"}];case "config":return [{key:"Tab",label:"Switch Pane"},{key:"Enter",label:"Edit/Save"},{key:"Esc",label:"Back"}];default:return [{key:"Esc",label:"Back"},{key:"?",label:"Help"}]}}function Is(e,t,o){let n=[],r=Math.max(1,o),s=t>=80?6:3,i=Et.length+4,a=s+2+i+4,l=Math.max(0,Math.floor((r-a)/2));for(let w=0;w<l;w++)n.push("");let u=it(t);n.push(...u),n.push("");let g=f.hex(p.textMuted)("A modern command-line interface for LeetCode");n.push($(g,t)),n.push("");let d=Math.max(4,Math.min(100,t-2)),m=[];for(let w=0;w<Et.length;w++){let R=Et[w],G=w===e.menuIndex,K=G?f.hex(p.primary)(" \u25B6 "):" ",z=f.hex(p.primary)(`[${R.key}]`),Pt=G?f.hex(p.textBright).bold(R.label):f.hex(p.text)(R.label),$t=f.hex(p.textMuted)(` - ${R.description}`),He=`${K}${z} ${Pt}`,ui=P(He).length,pi=P($t).length;ui+pi<d-6&&(He+=$t);let gi=P(He),cn=Math.max(0,d-4-gi.length);He=He+(cn>0?" ".repeat(cn):""),G?m.push(f.bgHex(p.bgHighlight)(He)):m.push(He);}let b=he(m,d,"Menu");for(let w of b)n.push($(w,t));n.push("");let _=[f.hex(p.textMuted)(`${Y.arrow} Press `)+f.hex(p.primary)("j/k")+f.hex(p.textMuted)(" or ")+f.hex(p.primary)("\u2191/\u2193")+f.hex(p.textMuted)(" to navigate"),f.hex(p.textMuted)(`${Y.arrow} Press `)+f.hex(p.primary)("Enter")+f.hex(p.textMuted)(" or the highlighted key to select")];for(let w of _)n.push($(w,t));for(;n.length<r;)n.push("");return n.slice(0,r).join(`
|
|
252
|
+
`)}function Ns(e,t,o){let n=[],r=o;if(n.push(lc(e,t)),n.push(""),n.push(cc(e,t)),n.push(uc(e,t)),n.push(""),e.loading&&e.problems.length===0)return n.push(...fc(t,r-6)),n.join(`
|
|
253
|
+
`);if(e.error&&e.problems.length===0)return n.push(...mc(e.error,t,r-6)),n.join(`
|
|
254
|
+
`);if(e.problems.length===0)return n.push(...yc(t,r-6)),n.join(`
|
|
255
|
+
`);n.push(pc(t)),n.push(f.hex(p.textMuted)(j.horizontal.repeat(t)));let s=Math.max(3,r-9),i=e.problems.slice(e.scrollOffset,e.scrollOffset+s);for(let a=0;a<i.length;a++){let l=i[a],u=e.scrollOffset+a===e.cursor;n.push(gc(l,u,t));}for(let a=i.length;a<s;a++)n.push("");return n.push(f.hex(p.textMuted)(j.horizontal.repeat(t))),n.push(dc(e,t)),n.join(`
|
|
256
|
+
`)}function lc(e,t){let o=e.bookmarkFilter?"\u2605 Bookmarks":`${Y.folder} Problems`,n=f.hex(p.primary).bold(o),r=f.hex(p.textMuted)(`(${e.problems.length}${e.bookmarkFilter?" bookmarked":` of ${e.total}`})`),s=e.loadingMore?f.hex(p.primary)(" \u22EF Loading more..."):"",i=`${n} ${r}${s}`;if(t<60)return i;if(e.total>0){let a=e.problems.filter(b=>b.status==="ac").length,u=Ss(a,e.problems.length,20),g=f.hex(p.textMuted)(` ${a} solved`),d=u+g,m=t-P(i).length-P(d).length;return i+(m>0?" ".repeat(m):" ")+d}return i}function cc(e,t){let o=f.hex(p.textMuted)(`${Y.target} Search: `);if(e.searchMode){let n=e.searchBuffer||"",r=f.hex(p.primary)("\u258C"),s=Math.max(10,Math.min(30,t-P(o).length-4)),i=f.bgHex(p.bgHighlight).hex(p.textBright)(` ${n}${r} `.padEnd(s)),a=t>60?f.hex(p.textMuted)(" (Enter to search, Esc to cancel)"):"";return o+i+a}if(e.searchQuery){let n=f.hex(p.primary).underline(e.searchQuery),r=f.hex(p.textMuted)(" [c] to clear");return o+n+r}return o+f.hex(p.textDim)("Press / to search...")}function uc(e,t){let o=[];o.push(f.hex(p.textMuted)(`${Y.gear} Filters: `));let n=[{key:"1",value:"Easy",color:p.success},{key:"2",value:"Medium",color:p.warning},{key:"3",value:"Hard",color:p.error}];for(let i of n)e.difficultyFilter===i.value?o.push(Ge(i.value,i.color)):o.push(f.hex(p.textMuted)("[")+f.hex(p.textDim)(i.key)+f.hex(p.textMuted)("] ")+f.hex(p.textDim)(i.value)),o.push(" ");o.push(f.hex(p.textMuted)(" \u2502 "));let r=[{key:"s",value:"solved",label:"Solved",color:p.success},{key:"a",value:"attempted",label:"Tried",color:p.warning}];for(let i of r)e.statusFilter===i.value?o.push(Ge(i.label,i.color)):o.push(f.hex(p.textMuted)("[")+f.hex(p.textDim)(i.key)+f.hex(p.textMuted)("] ")+f.hex(p.textDim)(i.label)),o.push(" ");return (e.difficultyFilter||e.statusFilter||e.searchQuery||e.bookmarkFilter)&&(o.push(f.hex(p.textMuted)(" \u2502 ")),o.push(C("c","Clear All"))),H([o.join("")],Math.max(10,t-1))[0]??""}function pc(e){let t=Fs(e),o=Math.max(8,e-t.selector-t.status-t.id-t.difficulty-t.acceptance-t.premium-6),n=[" "+ue("",t.selector)+ue("",t.status)+ue("ID",t.id),ue("Title",o)];return t.difficulty>0&&n.push(ue("Diff",t.difficulty)),t.acceptance>0&&n.push(Uo("Acc %",t.acceptance)),t.premium>0&&n.push(" "+ue("",t.premium)),f.hex(p.textMuted)(n.join(""))}function gc(e,t,o){let n=Fs(o),r=Math.max(8,o-n.selector-n.status-n.id-n.difficulty-n.acceptance-n.premium-6),s=t?f.hex(p.primary).bold("\u25B6 "):" ",i=Cs(e.status),a=wt(i)<n.status?i+" ".repeat(n.status-wt(i)):i,l=f.hex(p.textMuted)(ue(e.questionFrontendId,n.id)),u=t?f.hex(p.textBright).bold(A(e.title,r)):f.hex(p.text)(A(e.title,r)),g=ue(u,r),d=e.difficulty==="Easy"?p.success:e.difficulty==="Medium"?p.warning:p.error,m=n.difficulty>0?f.hex(d)(ue(e.difficulty,n.difficulty)):"",b=n.acceptance>0?f.hex(p.textMuted)(Uo(`${Math.round(e.acRate)}%`,n.acceptance)):"",_=n.premium>0?e.isPaidOnly?f.hex(p.warning)("\u{1F48E}"):" ":"",w=" "+s+a+l+g+m+(n.acceptance>0?b:"")+(n.premium>0?" "+_:"");if(t){let R=P(w),G=o-R.length;return f.bgHex(p.bgHighlight)(w+(G>0?" ".repeat(G):""))}return w}function dc(e,t){let o=e.problems.length>0?`${e.cursor+1} of ${e.problems.length}`:"0 of 0",n=f.hex(p.textMuted)(`Position: ${o}`),r=e.problems.length<e.total?f.hex(p.textMuted)(` (${e.total-e.problems.length} more available)`):"",s=[C("j/k","Move"),C("g/G","Top/Bottom"),C("b","Bookmarks"),C("\u21B5","Open")],i=t<70?`${C("j/k","Move")} ${C("\u21B5","Open")}`:s.join(" "),a=t-P(n+r).length-P(i).length;return n+r+(a>0?" ".repeat(a):" ")+i}function Fs(e){return e>=78?Qt.tableColumns:e>=62?{...Qt.tableColumns,id:5,difficulty:8,acceptance:0,premium:0}:{...Qt.tableColumns,status:2,id:4,difficulty:0,acceptance:0,premium:0}}function fc(e,t){let o=[],n=Math.floor(t/2);for(let i=0;i<n-1;i++)o.push("");let r=f.hex(p.primary)("\u22EF"),s=f.hex(p.textMuted)(" Loading problems...");for(o.push(" "+r+s);o.length<t;)o.push("");return o}function mc(e,t,o){let n=[],r=Math.floor(o/2);for(let s=0;s<r-2;s++)n.push("");for(n.push(" "+f.hex(p.error)(`${Y.cross} Error: ${e}`)),n.push(""),n.push(" "+f.hex(p.textMuted)("Press R to retry"));n.length<o;)n.push("");return n}function yc(e,t){let o=[],n=Math.floor(t/2);for(let r=0;r<n-2;r++)o.push("");for(o.push(" "+f.hex(p.textMuted)("No problems found.")),o.push(""),o.push(" "+f.hex(p.textMuted)("Try adjusting your filters or search query."));o.length<t;)o.push("");return o}function Hs(e,t,o){let n=[],r=o,s=[$(`Solving: ${e.problemTitle}`,t-4),$(`Difficulty: ${e.difficulty}`,t-4)];n.push(...he(s,t,"Timer")),n.push("");let i=Math.floor(e.remainingSeconds/60),a=e.remainingSeconds%60,l=`${i.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`,u=hc(l,e.status),g=Math.max(...u.map(K=>P(K).length),0),d=Math.floor((t-g)/2),m=u.map(K=>" ".repeat(Math.max(0,d))+K),b=r-n.length-8,_=Math.max(0,Math.floor(b/2)-3);for(let K=0;K<_;K++)n.push("");n.push(...m);for(let K=0;K<_;K++)n.push("");let w="",R=p.textMuted;switch(e.status){case "running":w=" RUNNING ",R=p.success;break;case "paused":w=" PAUSED ",R=p.warning;break;case "idle":w=" READY ",R=p.primary;break;case "completed":w=" TIME UP! ",R=p.error;break}for(n.push(""),n.push($(f.bgHex(R).black.bold(w),t)),n.push("");n.length<r-3;)n.push("");let G="";return e.status==="running"?G=C("Space","Pause")+" "+C("R","Reset"):G=C("Space","Start")+" "+C("R","Reset"),G+=" "+C("Esc","Back"),n.push($(G,t)),n.join(`
|
|
257
|
+
`)}function hc(e,t){let o={0:["\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"],1:[" \u2588\u2588 "," \u2588\u2588 "," \u2588\u2588 "," \u2588\u2588 "," \u2588\u2588 "],2:["\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 ","\u2588\u2588\u2588\u2588\u2588\u2588"],3:["\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"],4:["\u2588\u2588 \u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588"," \u2588\u2588"],5:["\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 ","\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"],6:["\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 ","\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"],7:["\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588"," \u2588\u2588"," \u2588\u2588"," \u2588\u2588"],8:["\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"],9:["\u2588\u2588\u2588\u2588\u2588\u2588","\u2588\u2588 \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2588"],":":[" "," \u2588\u2588 "," "," \u2588\u2588 "," "]},n=["","","","",""],r=t==="running"?f.hex(p.success):t==="paused"?f.hex(p.warning):t==="completed"?f.hex(p.error):f.hex(p.primary);for(let s of e){let i=o[s]||o[0];for(let a=0;a<5;a++)n[a]+=r(i[a])+" ";}return n}var Us=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Bs(e,t){try{let o=JSON.parse(e),n=new Date,r=Math.min(52,Math.floor((t-10)/3)),s=[];for(let g=r-1;g>=0;g--){let d=new Date(n);d.setDate(d.getDate()-g*7-d.getDay());let m=0,b=0;for(let w=0;w<7;w++){let R=new Date(d);if(R.setDate(R.getDate()+w),R>n)break;let G=new Date(Date.UTC(R.getFullYear(),R.getMonth(),R.getDate())),K=Math.floor(G.getTime()/1e3).toString(),z=o[K]||0;m+=z,z>0&&b++;}let _=new Date(d);_.setDate(_.getDate()+6),s.push({start:`${Us[d.getMonth()]} ${d.getDate()}`,end:`${Us[_.getMonth()]} ${_.getDate()}`,count:m,days:b});}let i=[],a=s.reduce((g,d)=>g+d.count,0),l=s.reduce((g,d)=>g+d.days,0);i.push(f.bold(`\u{1F4C5} Activity (Last ${r} Weeks)`)),i.push(f.gray("\u2500".repeat(t)));let u=s.slice(-8);for(let g of u){let d=`${g.start} - ${g.end}`.padEnd(18),b=g.count>0?f.green("\u2588".repeat(Math.min(g.count,10))).padEnd(10):f.gray("\xB7").padEnd(10),_=g.count>0?`${g.count} subs`.padEnd(10):"".padEnd(10),w=g.days>0?`${g.days}d active`:"";i.push(` ${f.white(d)} ${b} ${f.cyan(_)} ${f.yellow(w)}`);}return i.push(f.gray(`Total: ${a} subs, ${l} days`)),i}catch{return [f.red("Error parsing calendar data")]}}function Ws(e,t){try{let o=JSON.parse(e),n=new Date,r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=[];for(let u=6;u>=0;u--){let g=new Date(n);g.setDate(g.getDate()-u);let d=new Date(Date.UTC(g.getFullYear(),g.getMonth(),g.getDate())),m=Math.floor(d.getTime()/1e3).toString();s.push({label:r[g.getDay()],count:o[m]||0});}let i=Math.max(...s.map(u=>u.count),1),a=5,l=[];l.push(f.bold("\u{1F4C8} Trend (Last 7 Days)"));for(let u=a;u>=1;u--){let g=` ${u===a?i.toString().padStart(2):" "} \u2502`;for(let d of s)Math.round(d.count/i*a)>=u?g+=f.green(" \u2588\u2588 "):g+=" ";l.push(g);}return l.push(` 0 \u2514${"\u2500\u2500\u2500\u2500".repeat(7)}`),l.push(` ${s.map(u=>u.label.padEnd(4)).join("")}`),l}catch{return [f.red("Error generating trend")]}}function Gs(e,t,o){let n=[],r=o;if(e.loading)return bc(t,r);if(e.error)return js(e.error,t,r);if(!e.stats||!e.skillStats)return js("No data available",t,r);n.push("");let s=[`User: ${f.bold(e.stats.username)} Rank: #${e.stats.ranking} Streak: ${e.stats.streak} \u{1F525}`];n.push(...he(s,t,"Profile")),n.push("");let i=r-7;if(i>8&&e.stats.submissionCalendar){let a=Ws(e.stats.submissionCalendar);n.push(...he(a,t,"Trend")),n.push(""),i-=a.length+2;}if(i>8&&e.stats.submissionCalendar){let a=Bs(e.stats.submissionCalendar,t-4);n.push(...he(a,t,"Activity")),n.push(""),i-=a.length+2;}if(i>5&&e.skillStats){let a=Sc(e,t-4);n.push(...he(a,t,"Top Skills"));}for(;n.length<r-1;)n.push("");return n.push($(C("Esc","Back")+" "+C("R","Refresh"),t)),n.join(`
|
|
258
|
+
`)}function Sc(e,t){let o=e.skillStats,r=[...o.advanced,...o.intermediate,...o.fundamental].sort((s,i)=>i.problemsSolved-s.problemsSolved).slice(0,10).map(s=>`${s.tagName} (${s.problemsSolved})`).join(" \u2022 ");return [A(r,t-4)]}function bc(e,t){let o=[],n=Math.floor(t/2);for(let r=0;r<n;r++)o.push("");for(o.push($(f.hex(p.primary)("Loading stats..."),e));o.length<t;)o.push("");return o.join(`
|
|
259
|
+
`)}function js(e,t,o){let n=[],r=Math.floor(o/2);for(let s=0;s<r;s++)n.push("");for(n.push($(f.hex(p.error)(`Error: ${e}`),t));n.length<o;)n.push("");return n.join(`
|
|
260
|
+
`)}var Cc={language:"Example: typescript, python3, cpp",editor:"Example: code, vim, nvim",workdir:"Example: /Users/name/leetcode",repo:"Example: https://github.com/user/leetcode.git"};function Vs(e,t,o){let n=Math.max(20,t),r=Math.max(8,o),s=[];s.push(...nt(`${Y.gear} Configuration`,"Workspace-local CLI settings",n)),s.push(f.hex(p.textMuted)(j.horizontal.repeat(n)));let i=Math.max(3,r-s.length-3);if(n>=90)s.push(...st(Ks(e,n),qs(e,n),n,i,.4));else {let a=Math.max(3,Math.floor(i*.4)),l=Math.max(3,i-a-1),u=Ks(e,n).slice(0,a);for(;u.length<a;)u.push("");let g=qs(e,n).slice(0,l);for(;g.length<l;)g.push("");s.push(...u),s.push(f.hex(p.border)(j.horizontal.repeat(n))),s.push(...g);}for(;s.length<r-2;)s.push("");return s.push(f.hex(p.textMuted)(j.horizontal.repeat(n))),s.push(...Ec(e,n)),s.slice(0,r).join(`
|
|
261
|
+
`)}function Ks(e,t){let o=t>=90?Math.max(20,Math.floor(t*.4)):t,n=[];n.push(Me("Options",o)),n.push("");for(let r=0;r<e.options.length;r++){let s=e.options[r],i=r===e.selectedOption,l=`${i?f.hex(p.primary)("\u25B6"):" "} ${A(s.label,Math.max(8,o-4))}`;i&&e.paneFocus==="list"?n.push(f.bgHex(p.bgHighlight)(l.padEnd(Math.max(0,o-1)))):n.push(l);}return n}function qs(e,t){let o=t>=90?Math.max(20,t-Math.floor(t*.4)-1):t,n=e.options[e.selectedOption],r=[];r.push(Me("Editor",o)),r.push(""),r.push(f.hex(p.primary).bold(n.label)),r.push(...H([f.hex(p.textMuted)(n.description)],Math.max(12,o-2))),r.push("");let i=`Value: ${(e.isEditing?`${e.draftValue}\u2588`:e.draftValue)||"(empty)"}`,a=A(i,Math.max(8,o-2));return e.paneFocus==="editor"?r.push(f.bgHex(p.bgHighlight)(a.padEnd(Math.max(0,o-1)))):r.push(a),r.push(f.hex(p.textMuted)(A(Cc[n.id]||"",o-2))),r.push(""),n.id==="language"||n.id==="workdir"?r.push(f.hex(p.textMuted)("Validation: required")):r.push(f.hex(p.textMuted)("Validation: optional")),e.validationError?r.push(f.hex(p.error)(A(e.validationError,o-2))):e.isDirty?r.push(f.hex(p.warning)("Unsaved changes")):r.push(f.hex(p.success)("No pending changes")),r}function Ec(e,t){return rt([{key:"\u2191/\u2193",label:(e.paneFocus==="list","Move option")},{key:"Tab/h/l",label:"Switch pane"},{key:"Enter",label:e.isEditing?"Save":"Edit"},{key:"Esc",label:e.isEditing?"Cancel edit":"Back"}],t,t<90?"compact":"normal")}function zs(e,t,o){let n=[],r=Math.max(30,t),s=Math.max(10,o);if(e.loading)return Jo("Loading problem details...",r,s,p.primary);if(e.error&&!e.detail)return Jo(`Error: ${e.error}`,r,s,p.error);if(!e.detail)return Jo("Problem detail not found",r,s,p.error);let i=f.bgHex(p.bgHighlight).hex(p.textMuted)(` ${e.detail.questionFrontendId} `),a=f.hex(p.textBright).bold(` ${e.detail.title} `),l=bs(e.detail.difficulty),u=e.isBookmarked?f.hex(p.warning)(" \u2605"):"",g=(e.detail.topicTags||[]).map(m=>f.hex(p.info)(`#${m.name}`)).join(" ");n.push($(`${i}${a}${l}${u}`,r)),n.push($(A(g,r),r)),n.push(f.hex(p.textMuted)(Jt(r)));let d=Mt(s,e.drawerMode);for(n.push(...wc(e,r,d.bodyHeight)),e.drawerMode!=="none"&&d.drawerHeight>0&&(n.push(f.hex(p.border)(Jt(r))),n.push(..._c(e,r,d.drawerHeight)));n.length<s-2;)n.push("");return n.push(f.hex(p.textMuted)(Jt(r))),n.push(...Mc(e,r)),n.slice(0,s).join(`
|
|
262
|
+
`)}function wc(e,t,o){let n=[],r=Math.max(12,t-4),s=H(e.contentLines,r),i=Math.max(0,s.length-o),a=Math.min(e.scrollOffset,i),l=s.slice(a,a+o);for(let u of l)n.push(` ${f.hex(p.text)(u)}`);for(;n.length<o;)n.push("");return n}function Mc(e,t){let o=t>=130?[C("p","Pick"),C("t","Test"),C("s","Submit"),C("h","Hint"),C("H","Subs"),C("V","Snaps"),C("b",e.isBookmarked?"Unbookmark":"Bookmark"),C("n","Note"),C("e","Edit")]:[C("p","Pick"),C("t","Test"),C("s","Submit"),C("h","Hint"),C("H","Subs"),C("V","Snaps"),C("n","Note")],n=e.drawerMode==="none"?[C("Esc","Back")]:[C("Tab",`Focus ${e.focusRegion==="body"?"Drawer":"Body"}`),C("Esc","Close Drawer")],r=[...o,...n].join(" ");return [$(A(r,Math.max(20,t-2)),t)]}function _c(e,t,o){let n=e.drawerMode;if(n==="snapshots")return kc(e,t,o);let r=Lc(e),s=Rc(n),i=Tc(e,n,t),a=Math.max(1,o-2),l=Math.max(0,i.length-a),u=Math.min(e.drawerScrollOffset,l),g=i.slice(u,u+a),d=[Me(e.focusRegion==="drawer"?`${r} \u2022 Focused`:r,t)];for(d.push(...g.map(m=>A(m,t)));d.length<o-1;)d.push("");return d.push(f.hex(p.textMuted)(A(s,t))),d.slice(0,o)}function kc(e,t,o){let n=e.focusRegion==="drawer"?"Snapshots \u2022 Focused":"Snapshots",r=[Me(n,t)];if(!e.snapshotsList||e.snapshotsList.length===0)r.push(f.hex(p.warning)("No snapshots saved.")),r.push(f.hex(p.textMuted)("Create snapshots from your solution workflow."));else {let s=Math.max(1,o-2),i=Math.floor(e.snapshotCursor/s)*s,a=e.snapshotsList.slice(i,i+s);for(let l=0;l<a.length;l++){let u=a[l],d=i+l===e.snapshotCursor,m=d?f.hex(p.primary)("\u25B6"):" ",b=A(u.name,20).padEnd(20),_=A(u.language,10).padEnd(10),w=`${m} ${String(u.id).padStart(3)} ${b} ${_} ${String(u.lines).padStart(4)}L`;r.push(d?f.bgHex(p.bgHighlight)(A(w,t).padEnd(Math.max(0,t-1))):w);}}for(;r.length<o-1;)r.push("");return r.push(f.hex(p.textMuted)(A(`${C("j/k","Move")} ${C("d/r","Diff/Restore")} ${C("V/Esc","Close")}`,t))),r.slice(0,o)}function Tc(e,t,o){let n=Math.max(10,o-2);switch(t){case "hint":{let r=e.detail?.hints||[],s=e.activeHintIndex??0,i=r[s]??"No hints available",a=Pc(i);return [f.hex(p.primary).bold(`Hint ${s+1}/${Math.max(1,r.length)}`),...H([a||"No hint content"],n)]}case "submissions":return e.submissionsLoading?[f.hex(p.primary)("Loading submissions...")]:!e.submissionsHistory||e.submissionsHistory.length===0?[f.hex(p.warning)("No submissions found for this problem."),f.hex(p.textMuted)("Use [s] Submit after picking a solution.")]:e.submissionsHistory.map(r=>{let s=r.statusDisplay==="Accepted"?p.success:p.error,i=f.hex(s)(A(r.statusDisplay,12).padEnd(12)),a=f.hex(p.cyan)(A(r.runtime||"-",8).padEnd(8)),l=f.hex(p.textMuted)(A(r.memory||"-",8).padEnd(8)),u=f.hex(p.info)(A(r.lang||"-",8).padEnd(8));return `${i} ${a} ${l} ${u}`});case "note":return H($c(e.noteContent||"No notes found. Press e to edit."),n);case "diff":return (e.diffContent||"No diff available.").split(`
|
|
263
|
+
`).map(s=>Oc(s));case "testResult":{let r=e.testResult;return r?r.compile_error?[f.hex(p.error).bold("Compile Error"),...H([r.compile_error],n)]:r.runtime_error?[f.hex(p.error).bold("Runtime Error"),...H([r.runtime_error],n)]:r.correct_answer?[f.hex(p.success).bold("All test cases passed")]:[f.hex(p.warning).bold("Wrong answer")]:["No test result available."]}case "submitResult":{let r=e.submissionResult;if(!r)return ["No submission result available."];let i=[r.status_msg==="Accepted"?f.hex(p.success).bold(r.status_msg):f.hex(p.error).bold(r.status_msg),f.hex(p.cyan)(`Runtime: ${r.status_runtime||"-"}`),f.hex(p.textMuted)(`Memory: ${r.status_memory||"-"}`)];return r.runtime_error&&i.push(...H([r.runtime_error],n)),i}case "status":{let r=e.drawerData.statusMessage||e.successMessage||e.error||(e.isRunning?"Working...":"Ready"),s=e.error?p.error:e.successMessage?p.success:e.isRunning?p.primary:p.textMuted;return H([r],n).map(i=>f.hex(s)(i))}default:return []}}function Lc(e){switch(e.drawerMode){case "hint":return "Hints";case "submissions":return "Submissions";case "snapshots":return "Snapshots";case "note":return "Notes";case "diff":return "Diff";case "testResult":return "Test Result";case "submitResult":return "Submission Result";case "status":return xc(e);default:return "Drawer"}}function Rc(e){switch(e){case "hint":return `${C("\u2190/\u2192","Prev/Next")} ${C("j/k","Scroll")} ${C("h/Esc","Close")}`;case "submissions":return `${C("j/k","Scroll")} ${C("H/Esc","Close")}`;case "snapshots":return `${C("j/k","Move")} ${C("d/r","Diff/Restore")} ${C("V/Esc","Close")}`;case "note":return `${C("j/k","Scroll")} ${C("e","Edit")} ${C("n/Esc","Close")}`;case "diff":return `${C("j/k","Scroll")} ${C("d/Esc","Close")}`;default:return `${C("Esc","Close")}`}}function xc(e){let o=(e.drawerData.statusMessage||e.successMessage||e.error||(e.isRunning?"Working...":"Ready")).toLowerCase();return o.includes("running tests")?"Testing":o.includes("submitting")?"Submitting":o.includes("bookmark")?"Bookmark":o.includes("error")?"Error":"Status"}function Oc(e){return e.startsWith("[green]")?f.green(e.slice(7)):e.startsWith("[red]")?f.red(e.slice(5)):e.startsWith("[grey]")?f.gray(e.slice(6)):e.startsWith("+")?f.green(e):e.startsWith("-")?f.red(e):e}function Pc(e){return P(e).replace(/<\/?[^>]+(>|$)/g,"").replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/\s+/g," ").trim()}function $c(e){let t=e.split(`
|
|
264
|
+
`),o=[];for(let n of t){let r=n.trim();if(!r){o.length>0&&o[o.length-1]!==""&&o.push("");continue}if(r.startsWith("<!--")&&r.endsWith("-->"))continue;let s=n.replace(/\*\*(.*?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\[(.*?)\]\((.*?)\)/g,"$1 ($2)");s.startsWith("## ")?s=`${f.hex(p.primary).bold("\u2022")} ${s.slice(3)}`:s.startsWith("# ")&&(s=f.hex(p.primary).bold(s.slice(2))),o.push(s);}for(;o.length>0&&o[o.length-1]==="";)o.pop();return o.length>0?o:["No notes found. Press e to edit."]}function Jo(e,t,o,n){let r=[],s=Math.max(0,Math.floor(o/2)-1);for(let i=0;i<s;i++)r.push("");for(r.push($(f.hex(n)(e),t));r.length<o;)r.push("");return r.join(`
|
|
265
|
+
`)}function Ys(e){let t=[],{terminalWidth:o,terminalHeight:n}=e;if(e.isCheckingAuth)return Ac(o,n);let r=vs({username:e.user?.username??"Guest",isConnected:e.user?.isLoggedIn??false,width:o});t.push(...r);let s=Math.max(1,n-4),i=vc(e,o,s);t.push(i);let a=e.screenState.screen==="problem"||e.screenState.screen==="help"?[]:Ds(e.screenState.screen),l=As({screen:e.screenState.screen,hints:a,message:e.globalError??void 0,width:o});return t.push(...l),Nc(t.join(`
|
|
266
|
+
`),o,n)}function vc(e,t,o){let{screenState:n}=e;switch(n.screen){case "home":return Is(n.model,t,o);case "list":return Ns(n.model,t,o);case "help":return Dc(n.model,t,o);case "login":return Vo(n.model,t,o);case "workspace":return jo(n.model,t,o);case "timer":return Hs(n.model,t,o);case "stats":return Gs(n.model,t,o);case "config":return Vs(n.model,t,o);case "problem":return zs(n.model,t,o);case "changelog":return Ko(n.model,t,o)}}function Ac(e,t){let o=[],n=Math.floor(t/2);for(let i=0;i<n-5;i++)o.push("");let r=it(e);o.push(...r),o.push("");let s=f.hex(p.primary)("\u22EF Checking authentication...");for(o.push($(s,e));o.length<t;)o.push("");return o.join(`
|
|
267
|
+
`)}function Dc(e,t,o){let n=[],r=Math.max(20,t),s=Math.max(8,o);n.push(...nt(`${Y.star} Keyboard Cheat Sheet`,"All shortcuts in one place",r)),n.push(f.hex(p.textMuted)(j.horizontal.repeat(r)));let i=r<90?"compact":"normal",a=rt([{key:"j/k",label:"Scroll"},{key:"PgUp/PgDn",label:"Page"},{key:"g/G",label:"Top/Bottom"},{key:"?/Esc",label:"Close"}],r,i).slice(0,1),l=1+a.length,u=Math.max(3,s-n.length-l),g=Qs(r),d=Math.max(0,g.length-u),m=Math.min(e.scrollOffset,d),b=g.slice(m,m+u);for(n.push(...b);n.length<s-l;)n.push("");return n.push(f.hex(p.textMuted)(j.horizontal.repeat(r))),n.push(...a),n.slice(0,s).join(`
|
|
268
|
+
`)}function Ic(){return [{section:"Global",items:[["?","Toggle help"],["Ctrl+C","Quit app"],["Esc","Back / close panel"]]},{section:"Navigation",items:[["j / \u2193","Move down"],["k / \u2191","Move up"],["g / G","Top / Bottom"],["PgUp/PgDn","Page jump"]]},{section:"Home",items:[["l","Problem list"],["d / r","Daily / Random"],["w / c","Workspace / Config"],["q","Quit"]]},{section:"List",items:[["/","Search"],["1/2/3","Difficulty filters"],["s / a / b","Status / Attempted / Bookmarks"],["Enter","Open problem"]]},{section:"Problem",items:[["p / t / s","Pick / Test / Submit"],["h / H / V","Hint / Subs / Snapshots"],["b / n / e","Bookmark / Note / Edit note"],["j / k","Scroll content/panel"]]},{section:"Workspace/Config",items:[["Tab / h / l","Switch pane"],["Enter","Switch or edit/save"],["c / d","Create / Delete workspace"],["Esc","Cancel edit or go back"]]}]}function Xo(e,t){let o=[],n=Math.max(20,t),r=Math.max(8,Math.min(14,Math.floor(n*.26))),s=Math.max(8,n-r-3);o.push(Me(e.section,t));for(let[i,a]of e.items){let l=H([a],s),u=f.hex(p.cyan)(ue(i,r));o.push(` ${u} ${f.hex(p.text)(l[0]??"")}`);for(let g=1;g<l.length;g++)o.push(` ${" ".repeat(r)} ${f.hex(p.textMuted)(l[g])}`);}return o}function Qs(e){let t=Ic();if(e<90){let i=[];for(let a of t)i.push(...Xo(a,e)),i.push("");return i}let o=[],n=.49,r=Math.max(8,Math.floor(e*n)),s=Math.max(8,e-r-1);for(let i=0;i<t.length;i+=2){let a=Xo(t[i],r),l=t[i+1]?Xo(t[i+1],s):[],u=Math.max(a.length,l.length);o.push(...st(a,l,e,u,n)),o.push("");}return o}function Js(e,t){let o=Math.max(20,e),n=Math.max(8,t),r=Math.max(3,n-5);return Math.max(0,Qs(o).length-r)}function Nc(e,t,o){let n=Math.max(1,t),r=Math.max(1,o),s=e.split(`
|
|
269
|
+
`),i=[];for(let a=0;a<s.length;a++){let l=s[a]??"";P(l).length>n?i.push(A(l,n)):i.push(l);}for(;i.length<r;)i.push("");return i.slice(0,r).join(`
|
|
270
|
+
`)}function Xs(e,t){switch(e.type){case "INIT":return [{...t,needsRender:true},c.checkAuth()];case "KEY_PRESS":{let{key:o}=e;if(o.ctrl&&o.name==="c")return [t,c.exit()];if(o.name==="q"&&t.screenState.screen==="home")return [t,c.exit()];if(o.name==="?")return t.screenState.screen==="help"?[{...t,...Zo(t),needsRender:true},c.none()]:[{...t,...fe(t,{screen:"help",model:{scrollOffset:0}}),needsRender:true},c.none()];if(o.name==="escape"&&t.screenState.screen!=="home"){if(t.screenState.screen==="config"&&t.screenState.model.isEditing)return no(t,e);if(t.screenState.screen==="problem"){let n=t.screenState.model;if(n.drawerMode!=="none"){let[r,s]=to({type:"PROBLEM_CLOSE_RESULT"},n,t.terminalHeight,t.terminalWidth);return [{...t,screenState:{screen:"problem",model:r},needsRender:true},s]}}if(t.screenState.screen==="workspace"){let n=t.screenState.model;if(n.showCreateInput||n.showDeleteConfirm||n.isEditing)return no(t,e)}return t.screenState.screen==="login"?no(t,e):[{...t,...Zo(t),needsRender:true},c.none()]}return no(t,e)}case "RESIZE":return [{...t,terminalWidth:e.width,terminalHeight:e.height,needsRender:true},c.none()];case "NAVIGATE":return [{...t,...fe(t,e.to),needsRender:true},c.none()];case "GO_BACK":return [{...t,...Zo(t),needsRender:true},c.none()];case "AUTH_CHECK_COMPLETE":return e.user?[{...t,isCheckingAuth:false,user:{username:e.user.username,isLoggedIn:true},needsRender:true},c.none()]:[{...t,isCheckingAuth:false,user:null,screenState:{screen:"login",model:{step:"instructions",sessionToken:"",csrfToken:"",focusedField:"session",error:null}},needsRender:true},c.none()];case "GLOBAL_ERROR":return [{...t,globalError:e.error,needsRender:true},c.none()];case "CLEAR_ERROR":return [{...t,globalError:null,needsRender:true},c.none()];case "FETCH_DAILY_SUCCESS":{let[o,n]=eo(e.slug);return [{...t,...fe(t,{screen:"problem",model:o}),needsRender:true},n]}case "FETCH_RANDOM_SUCCESS":{let[o,n]=eo(e.slug);return [{...t,...fe(t,{screen:"problem",model:o}),needsRender:true},n]}case "QUIT":return [t,c.exit()];case "LOGIN_SUCCESS":return [{...t,user:{username:e.username,isLoggedIn:true},screenState:{screen:"home",model:{menuIndex:0}},needsRender:true},c.none()];default:return ei(e,t)}}function fe(e,t){return {screenState:t,history:[...e.history,e.screenState],globalError:null}}function Zo(e){if(e.history.length===0)return {screenState:{screen:"home",model:{menuIndex:0}},globalError:null};let t=[...e.history];return {screenState:t.pop(),history:t,globalError:null}}function no(e,t){let{screenState:o}=e;switch(o.screen){case "home":return Zs(e,t);case "list":return Fc(e,t);case "problem":return Hc(e,t);case "timer":case "stats":case "config":return Bc(e,t);case "help":return Wc(e,t);case "workspace":return Zc(e,t);case "changelog":return eu(e,t);case "login":return tu(e,t);default:return [e,c.none()]}}function Zs(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,n=e.screenState.model;if(o.name==="l"){let[r,s]=vo();return [{...e,...fe(e,{screen:"list",model:r}),needsRender:true},s]}if(o.name==="d")return [e,c.fetchDaily()];if(o.name==="r")return [e,c.fetchRandom()];if(o.name==="b"){let[r,s]=vo();return [{...e,...fe(e,{screen:"list",model:{...r,bookmarkFilter:true}}),needsRender:true},s]}if(o.name==="t")return [{...e,...fe(e,{screen:"timer",model:{problemId:null,problemTitle:"Practice",difficulty:"Medium",remainingSeconds:2400,totalSeconds:2400,status:"idle",viewMode:"timer"}}),needsRender:true},c.none()];if(o.name==="s"){let[r,s]=ms();return [{...e,...fe(e,{screen:"stats",model:r}),needsRender:true},s]}if(o.name==="y")return [{...e,globalError:"Use CLI command: leet sync (requires terminal interaction)",needsRender:true},c.none()];if(o.name==="w"){let[r,s]=Ts();return [{...e,...fe(e,{screen:"workspace",model:r}),needsRender:true},s]}if(o.name==="c"){let[r,s]=hs();return [{...e,...fe(e,{screen:"config",model:r}),needsRender:true},s]}if(o.name==="?")return [{...e,...fe(e,{screen:"help",model:{scrollOffset:0}}),needsRender:true},c.none()];if(o.name==="v"){let[r,s]=$s();return [{...e,...fe(e,{screen:"changelog",model:r}),needsRender:true},s]}if(o.name==="L")return [e,c.logout()];if(o.name==="j"||o.name==="down"){let[r,s]=zt({type:"HOME_MENU_DOWN"},n);return [{...e,screenState:{screen:"home",model:r},needsRender:true},s]}if(o.name==="k"||o.name==="up"){let[r,s]=zt({type:"HOME_MENU_UP"},n);return [{...e,screenState:{screen:"home",model:r},needsRender:true},s]}if(o.name==="return"){let s=["l","d","r","b","t","s","y","w","c","v","L","?"][n.menuIndex];if(s)return Zs(e,{type:"KEY_PRESS",key:{name:s,sequence:s,ctrl:false,meta:false,shift:false}})}return [e,c.none()]}function Fc(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,n=e.screenState.model,r=null;if(n.searchMode)o.name==="escape"?r={type:"LIST_SEARCH_CANCEL"}:o.name==="return"?r={type:"LIST_SEARCH_SUBMIT"}:o.name==="backspace"?r={type:"LIST_SEARCH_BACKSPACE"}:o.sequence.length===1&&!o.ctrl&&!o.meta&&(r={type:"LIST_SEARCH_INPUT",char:o.sequence});else if(o.name==="j"||o.name==="down")r={type:"LIST_CURSOR_DOWN"};else if(o.name==="k"||o.name==="up")r={type:"LIST_CURSOR_UP"};else if(o.name==="g")r={type:"LIST_GO_TOP"};else if(o.name==="G")r={type:"LIST_GO_BOTTOM"};else if(o.name==="/")r={type:"LIST_SEARCH_START"};else if(o.name==="return"){let s=n.problems[n.cursor];if(s){let[i,a]=eo(s.titleSlug);return [{...e,...fe(e,{screen:"problem",model:i}),needsRender:true},a]}r={type:"LIST_SELECT"};}else o.name==="1"?r={type:"LIST_FILTER_DIFFICULTY",difficulty:n.difficultyFilter==="Easy"?null:"Easy"}:o.name==="2"?r={type:"LIST_FILTER_DIFFICULTY",difficulty:n.difficultyFilter==="Medium"?null:"Medium"}:o.name==="3"?r={type:"LIST_FILTER_DIFFICULTY",difficulty:n.difficultyFilter==="Hard"?null:"Hard"}:o.name==="s"?r={type:"LIST_FILTER_STATUS",status:n.statusFilter==="solved"?null:"solved"}:o.name==="a"?r={type:"LIST_FILTER_STATUS",status:n.statusFilter==="attempted"?null:"attempted"}:o.name==="b"?r={type:"LIST_FILTER_BOOKMARKS"}:o.name==="c"?r={type:"LIST_CLEAR_FILTERS"}:o.name==="R"&&(r={type:"LIST_REFRESH"});if(r){let[s,i]=Ao(r,n,e.terminalHeight);return [{...e,screenState:{screen:"list",model:s},needsRender:true},i]}return [e,c.none()]}function ei(e,t){let{screenState:o}=t,n=t.terminalHeight;switch(o.screen){case "list":{if(!jc(e))return [t,c.none()];let[r,s]=Ao(e,o.model,n);return [{...t,screenState:{screen:"list",model:r},needsRender:true},s]}case "home":{if(!Gc(e))return [t,c.none()];let[r,s]=zt(e,o.model);return [{...t,screenState:{screen:"home",model:r},needsRender:true},s]}case "timer":{if(!Kc(e))return [t,c.none()];let[r,s]=Yt(e,o.model);return [{...t,screenState:{screen:"timer",model:r},needsRender:true},s]}case "stats":{if(!qc(e))return [t,c.none()];let[r,s]=Do(e,o.model);return [{...t,screenState:{screen:"stats",model:r},needsRender:true},s]}case "config":{if(!Vc(e))return [t,c.none()];let[r,s]=No(e,o.model);return [{...t,screenState:{screen:"config",model:r},needsRender:true},s]}case "help":{if(!zc(e))return [t,c.none()];let r=o.model,s=Js(t.terminalWidth,t.terminalHeight-4),i=Math.max(3,Math.floor((t.terminalHeight-4)/2)),a=r.scrollOffset;switch(e.type){case "HELP_SCROLL_UP":a=Math.max(0,r.scrollOffset-1);break;case "HELP_SCROLL_DOWN":a=Math.min(s,r.scrollOffset+1);break;case "HELP_PAGE_UP":a=Math.max(0,r.scrollOffset-i);break;case "HELP_PAGE_DOWN":a=Math.min(s,r.scrollOffset+i);break;case "HELP_TOP":a=0;break;case "HELP_BOTTOM":a=s;break}return [{...t,screenState:{screen:"help",model:{scrollOffset:a}},needsRender:true},c.none()]}case "workspace":{if(!Qc(e))return [t,c.none()];let[r,s]=Go(e,o.model);return [{...t,screenState:{screen:"workspace",model:r},needsRender:true},s]}case "problem":{if(!Yc(e))return [t,c.none()];let[r,s]=to(e,o.model,n,t.terminalWidth);return [{...t,screenState:{...o,model:r},needsRender:true},s]}case "changelog":{if(!Jc(e))return [t,c.none()];let[r,s]=qo(e,o.model,n,t.terminalWidth);return [{...t,screenState:{screen:"changelog",model:r},needsRender:true},s]}case "login":{if(!Xc(e))return [t,c.none()];let[r,s]=zo(e,o.model);return [{...t,screenState:{screen:"login",model:r},needsRender:true},s]}default:return [t,c.none()]}}function Hc(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,n=e.screenState.model,r=null;if(!r&&n.drawerMode==="note"&&(o.name==="n"||o.name==="escape")&&(r={type:"PROBLEM_CLOSE_NOTE"}),!r&&n.drawerMode==="diff"&&(o.name==="d"||o.name==="escape")&&(r={type:"PROBLEM_CLOSE_DIFF"}),!r){let i=Uc(o.name);i&&(r=i);}!r&&o.name==="tab"&&n.drawerMode!=="none"&&(r={type:"PROBLEM_FOCUS_TOGGLE"}),!r&&n.drawerMode!=="none"&&o.name==="escape"&&(r={type:"PROBLEM_CLOSE_RESULT"}),!r&&n.drawerMode==="hint"&&(o.name==="left"?r={type:"PROBLEM_PREV_HINT"}:o.name==="right"&&(r={type:"PROBLEM_NEXT_HINT"})),!r&&n.drawerMode!=="none"&&n.focusRegion==="drawer"&&(n.drawerMode==="snapshots"?o.name==="j"||o.name==="down"?r={type:"PROBLEM_SNAPSHOT_DOWN"}:o.name==="k"||o.name==="up"?r={type:"PROBLEM_SNAPSHOT_UP"}:o.name==="d"?r={type:"PROBLEM_DIFF_SNAPSHOT"}:o.name==="r"&&(r={type:"PROBLEM_RESTORE_SNAPSHOT"}):n.drawerMode==="hint"?o.name==="j"||o.name==="down"?r={type:"PROBLEM_HINT_SCROLL_DOWN"}:(o.name==="k"||o.name==="up")&&(r={type:"PROBLEM_HINT_SCROLL_UP"}):n.drawerMode==="submissions"?o.name==="j"||o.name==="down"?r={type:"PROBLEM_SUBMISSIONS_SCROLL_DOWN"}:(o.name==="k"||o.name==="up")&&(r={type:"PROBLEM_SUBMISSIONS_SCROLL_UP"}):n.drawerMode==="note"?o.name==="j"||o.name==="down"?r={type:"PROBLEM_NOTE_SCROLL_DOWN"}:(o.name==="k"||o.name==="up")&&(r={type:"PROBLEM_NOTE_SCROLL_UP"}):n.drawerMode==="diff"&&(o.name==="j"||o.name==="down"?r={type:"PROBLEM_DIFF_SCROLL_DOWN"}:(o.name==="k"||o.name==="up")&&(r={type:"PROBLEM_DIFF_SCROLL_UP"})));let s=n.drawerMode==="none"||n.focusRegion==="body";if(!r&&s&&(o.name==="j"||o.name==="down"?r={type:"PROBLEM_SCROLL_DOWN"}:o.name==="k"||o.name==="up"?r={type:"PROBLEM_SCROLL_UP"}:o.name==="pagedown"?r={type:"PROBLEM_PAGE_DOWN"}:o.name==="pageup"?r={type:"PROBLEM_PAGE_UP"}:o.name==="g"?r={type:"PROBLEM_TOP"}:o.name==="G"&&(r={type:"PROBLEM_BOTTOM"})),r){let[i,a]=to(r,n,e.terminalHeight,e.terminalWidth);return [{...e,screenState:{screen:"problem",model:i},needsRender:true},a]}return [e,c.none()]}function Uc(e){return e==="p"?{type:"PROBLEM_PICK"}:e==="t"?{type:"PROBLEM_TEST"}:e==="s"?{type:"PROBLEM_SUBMIT"}:e==="b"?{type:"PROBLEM_BOOKMARK"}:e==="n"?{type:"PROBLEM_VIEW_NOTE"}:e==="e"?{type:"PROBLEM_NOTES"}:e==="h"?{type:"PROBLEM_TOGGLE_HINT"}:e==="H"||e==="S"?{type:"PROBLEM_SHOW_SUBMISSIONS"}:e==="v"||e==="V"||e==="w"?{type:"PROBLEM_SHOW_SNAPSHOTS"}:null}function Bc(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,{screenState:n}=e;if(n.screen==="timer"){let r=n.model;if(o.name==="space"){let[s,i]=Yt({type:r.status==="running"?"TIMER_PAUSE":"TIMER_START"},r);return [{...e,screenState:{...n,model:s},needsRender:true},i]}if(o.name==="r"){let[s,i]=Yt({type:"TIMER_RESET"},r);return [{...e,screenState:{...n,model:s},needsRender:true},i]}}if(n.screen==="config"){let r=n.model,s=null;if(o.name==="tab"||o.name==="h"||o.name==="l"?s={type:"CONFIG_TOGGLE_FOCUS"}:o.name==="left"?s={type:"CONFIG_FOCUS_LIST"}:o.name==="right"?s={type:"CONFIG_FOCUS_EDITOR"}:r.isEditing?o.name==="escape"?s={type:"CONFIG_EDIT_CANCEL"}:o.name==="return"||o.name==="enter"?s={type:"CONFIG_EDIT_SAVE"}:o.name==="backspace"?s={type:"CONFIG_EDIT_BACKSPACE"}:o.sequence.length===1&&!o.ctrl&&!o.meta&&(s={type:"CONFIG_EDIT_INPUT",char:o.sequence}):o.name==="j"||o.name==="down"?s={type:"CONFIG_OPTION_DOWN"}:o.name==="k"||o.name==="up"?s={type:"CONFIG_OPTION_UP"}:(o.name==="return"||o.name==="enter")&&(s={type:"CONFIG_EDIT_START"}),s){let[i,a]=No(s,r);return [{...e,screenState:{...n,model:i},needsRender:true},a]}}if(n.screen==="stats"){let r=n.model;if(o.name==="r"||o.name==="R"){let[s,i]=Do({type:"STATS_REFRESH"},r);return [{...e,screenState:{...n,model:s},needsRender:true},i]}}return [e,c.none()]}function Wc(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,n=null;return o.name==="j"||o.name==="down"?n={type:"HELP_SCROLL_DOWN"}:o.name==="k"||o.name==="up"?n={type:"HELP_SCROLL_UP"}:o.name==="pagedown"?n={type:"HELP_PAGE_DOWN"}:o.name==="pageup"?n={type:"HELP_PAGE_UP"}:o.name==="g"?n={type:"HELP_TOP"}:o.name==="G"&&(n={type:"HELP_BOTTOM"}),n?ei(n,e):[e,c.none()]}function jc(e){return e.type.startsWith("LIST_")}function Gc(e){return e.type.startsWith("HOME_")}function Kc(e){return e.type.startsWith("TIMER_")}function qc(e){return e.type.startsWith("STATS_")}function Vc(e){return e.type.startsWith("CONFIG_")}function zc(e){return e.type.startsWith("HELP_")}function Yc(e){return e.type.startsWith("PROBLEM_")}function Qc(e){return e.type.startsWith("WORKSPACE_")}function Jc(e){return e.type.startsWith("CHANGELOG_")}function Xc(e){return e.type.startsWith("LOGIN_")}function Zc(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,n=e.screenState.model,r=null;if(n.showCreateInput?o.name==="escape"?r={type:"WORKSPACE_CREATE_CANCEL"}:o.name==="return"||o.name==="enter"?r={type:"WORKSPACE_CREATE_SUBMIT"}:o.name==="backspace"?r={type:"WORKSPACE_CREATE_BACKSPACE"}:o.sequence.length===1&&!o.ctrl&&!o.meta&&(r={type:"WORKSPACE_CREATE_INPUT",char:o.sequence}):n.showDeleteConfirm?o.name==="y"||o.name==="return"||o.name==="enter"?r={type:"WORKSPACE_DELETE_CONFIRM"}:(o.name==="n"||o.name==="escape")&&(r={type:"WORKSPACE_DELETE_CANCEL"}):n.isEditing?o.name==="escape"?r={type:"WORKSPACE_EDIT_CANCEL"}:o.name==="return"||o.name==="enter"?r={type:"WORKSPACE_EDIT_SAVE"}:o.name==="backspace"?r={type:"WORKSPACE_EDIT_BACKSPACE"}:o.sequence.length===1&&!o.ctrl&&!o.meta&&(r={type:"WORKSPACE_EDIT_INPUT",char:o.sequence}):o.name==="tab"||o.name==="h"||o.name==="l"?r={type:"WORKSPACE_TOGGLE_FOCUS"}:o.name==="left"?r={type:"WORKSPACE_FOCUS_LIST"}:o.name==="right"?r={type:"WORKSPACE_FOCUS_EDITOR"}:n.paneFocus==="list"?o.name==="j"||o.name==="down"?r={type:"WORKSPACE_DOWN"}:o.name==="k"||o.name==="up"?r={type:"WORKSPACE_UP"}:o.name==="return"||o.name==="enter"?r={type:"WORKSPACE_SELECT"}:o.name==="c"?r={type:"WORKSPACE_CREATE_START"}:o.name==="d"&&(r={type:"WORKSPACE_DELETE"}):o.name==="j"||o.name==="down"?r={type:"WORKSPACE_FIELD_DOWN"}:o.name==="k"||o.name==="up"?r={type:"WORKSPACE_FIELD_UP"}:(o.name==="return"||o.name==="enter")&&(r={type:"WORKSPACE_EDIT_START"}),r){let[s,i]=Go(r,n);return [{...e,screenState:{screen:"workspace",model:s},needsRender:true},i]}return [e,c.none()]}function eu(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t;if(o.name==="k"||o.name==="up")return n(e,{type:"CHANGELOG_SCROLL_UP"});if(o.name==="j"||o.name==="down")return n(e,{type:"CHANGELOG_SCROLL_DOWN"});return [e,c.none()];function n(r,s){let i=r.screenState;if(i.screen!=="changelog")return [r,c.none()];let[a,l]=qo(s,i.model,r.terminalHeight,r.terminalWidth);return [{...r,screenState:{screen:"changelog",model:a},needsRender:true},l]}}function tu(e,t){if(t.type!=="KEY_PRESS")return [e,c.none()];let{key:o}=t,n=e.screenState.model;if(o.ctrl&&o.name==="c")return [e,c.exit()];if(n.step==="instructions"){if(o.name==="return"||o.name==="enter")return r(e,{type:"LOGIN_SUBMIT"});if(o.name==="escape")return [e,c.exit()]}else if(n.step==="input"||n.step==="error"){if(o.name==="escape")return r(e,{type:"LOGIN_BACK"});if(o.name==="tab"||o.name==="down"||o.name==="up")return r(e,{type:"LOGIN_SWITCH_FOCUS"});if(o.name==="return"||o.name==="enter"){if(n.focusedField==="session"){if(n.sessionToken.length>0)return r(e,{type:"LOGIN_SET_FOCUS",field:"csrf"})}else if(n.csrfToken.length>0&&n.sessionToken.length>0)return r(e,{type:"LOGIN_SUBMIT"})}else if(o.name==="backspace"){if(n.focusedField==="session"){if(n.sessionToken.length>0)return r(e,{type:"LOGIN_SESSION_INPUT",value:n.sessionToken.slice(0,-1)})}else if(n.csrfToken.length>0)return r(e,{type:"LOGIN_CSRF_INPUT",value:n.csrfToken.slice(0,-1)})}else if(!o.ctrl&&!o.meta)return n.focusedField==="session"?r(e,{type:"LOGIN_SESSION_INPUT",value:n.sessionToken+o.sequence}):r(e,{type:"LOGIN_CSRF_INPUT",value:n.csrfToken+o.sequence})}return [e,c.none()];function r(s,i){let[a,l]=zo(i,s.screenState.model);return [{...s,screenState:{screen:"login",model:a},needsRender:true},l]}}var ru="https://raw.githubusercontent.com/night-slayer18/leetcode-cli/main/docs/releases.md",Oe=null;function en(e,t){switch(e.type){case "CMD_NONE":return;case "CMD_BATCH":for(let o of e.commands)en(o,t);return;case "CMD_FETCH_STATS":lu(t);return;case "CMD_CHECK_AUTH":su(t);return;case "CMD_FETCH_PROBLEMS":iu(e.filters,e.append,t);return;case "CMD_FETCH_PROBLEM_DETAIL":au(e.slug,t);return;case "CMD_START_TIMER_SUBSCRIPTION":Oe&&clearInterval(Oe),Oe=setInterval(()=>{t({type:"TIMER_TICK"});},e.intervalMs);return;case "CMD_STOP_TIMER_SUBSCRIPTION":Oe&&(clearInterval(Oe),Oe=null);return;case "CMD_PICK_PROBLEM":uu(e.slug,t);return;case "CMD_TEST_SOLUTION":pu(e.slug,t);return;case "CMD_SUBMIT_SOLUTION":gu(e.slug,t);return;case "CMD_SAVE_CONFIG":cu(e.key,e.value);return;case "CMD_EXIT":ro();return;case "CMD_FETCH_DAILY":du(t);return;case "CMD_FETCH_RANDOM":fu(t);return;case "CMD_FETCH_SUBMISSIONS":Su(e.slug,t);return;case "CMD_LOAD_NOTE":mu(e.problemId,t);return;case "CMD_DIFF_SNAPSHOT":yu(e.slug,e.snapshotId,t);return;case "CMD_RESTORE_SNAPSHOT":hu(e.slug,e.snapshotId,t);return;case "CMD_FETCH_CHANGELOG":bu(t);return;case "CMD_LOGOUT":Cu(t);return;case "CMD_LOGIN":Eu(e.session,e.csrf,t);return;default:return}}async function su(e){let t=ae.get();if(!t){e({type:"AUTH_CHECK_COMPLETE",user:null});return}S.setCredentials(t);try{let o=await S.checkAuth();o.isSignedIn&&o.username?e({type:"AUTH_CHECK_COMPLETE",user:{username:o.username}}):e({type:"AUTH_CHECK_COMPLETE",user:null});}catch{e({type:"AUTH_CHECK_COMPLETE",user:null});}}async function iu(e,t,o){o({type:"LIST_FETCH_START"});try{let n=ae.get();n&&S.setCredentials(n);let r=await S.getProblems(e),s=r.problems.map(i=>({questionId:i.questionId,questionFrontendId:i.questionFrontendId,title:i.title,titleSlug:i.titleSlug,difficulty:i.difficulty,isPaidOnly:i.isPaidOnly,acRate:i.acRate,topicTags:i.topicTags,status:i.status}));o({type:"LIST_FETCH_SUCCESS",problems:s,total:r.total,append:t});}catch(n){o({type:"LIST_FETCH_ERROR",error:n instanceof Error?n.message:"Failed to fetch problems"});}}async function au(e,t){try{let o=await S.getProblem(e);t({type:"PROBLEM_DETAIL_LOADED",detail:o});}catch(o){t({type:"PROBLEM_DETAIL_ERROR",error:o instanceof Error?o.message:"Failed to fetch problem"});}}async function lu(e){e({type:"STATS_FETCH_START"});try{let t=ae.get();if(!t)throw new Error("You must be logged in to view stats");S.setCredentials(t);let o=await S.checkAuth();if(!o.isSignedIn||!o.username)throw new Error("Not logged in");let[n,r,s]=await Promise.all([S.getUserProfile(o.username),S.getSkillStats(o.username),S.getDailyChallenge()]);e({type:"STATS_FETCH_SUCCESS",stats:n,skills:r,daily:s});}catch(t){e({type:"STATS_FETCH_ERROR",error:t instanceof Error?t.message:"Failed to fetch statistics"});}}function cu(e,t){switch(e){case "language":M.setLanguage(t);break;case "editor":M.setEditor(t);break;case "workdir":M.setWorkDir(t);break;case "repo":M.setRepo(t);break}}async function tn(e){let t=M.getLanguage(),o=await S.getProblem(e),n=Qe(o.questionFrontendId,o.titleSlug,t),r=M.getWorkDir(),s=o.difficulty,i=o.topicTags.length>0?o.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",a=$e.join(r,s,i,n);try{return {code:await Pe.readFile(a,"utf-8"),lang:t,questionId:o.questionId}}catch{let u=$e.join(r,n);try{return {code:await Pe.readFile(u,"utf-8"),lang:t,questionId:o.questionId}}catch{throw new Error(`Could not read solution file at ${a}. Make sure you have picked the problem first.`)}}}async function uu(e,t){try{let o=await S.getProblem(e),n=M.getLanguage(),r=Be[n]??n,s=o.codeSnippets??[],i=Bt(s,r);if(!i)throw new Error(`No code template available for ${r}`);let a=Wt(o.questionFrontendId,o.titleSlug,o.title,o.difficulty,i.code,r,o.content??void 0),l=M.getWorkDir(),u=o.difficulty,g=o.topicTags.length>0?o.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",d=$e.join(l,u,g);try{await Pe.mkdir(d,{recursive:!0});}catch{}let m=Qe(o.questionFrontendId,o.titleSlug,r),b=$e.join(d,m);existsSync(b)?t({type:"PROBLEM_ACTION_SUCCESS",message:`File ready: ${m}`}):(await Pe.writeFile(b,a,"utf-8"),t({type:"PROBLEM_ACTION_SUCCESS",message:`Created ${m}`}));}catch(o){t({type:"PROBLEM_ACTION_ERROR",error:o instanceof Error?o.message:"Failed to pick problem"});}}async function pu(e,t){try{let{code:o,lang:n}=await tn(e),r=await S.getProblem(e),s=await S.testSolution(e,o,n,r.exampleTestcases,r.questionId);t({type:"PROBLEM_TEST_RESULT",result:s});}catch(o){t({type:"PROBLEM_ACTION_ERROR",error:o instanceof Error?o.message:"Test failed"});}}async function gu(e,t){try{let{code:o,lang:n}=await tn(e),r=await S.getProblem(e),s=await S.submitSolution(e,o,n,r.questionId);t({type:"PROBLEM_SUBMIT_RESULT",result:s});}catch(o){t({type:"PROBLEM_ACTION_ERROR",error:o instanceof Error?o.message:"Submit failed"});}}async function du(e){try{let t=await S.getDailyChallenge();if(t&&t.question&&t.question.titleSlug)e({type:"FETCH_DAILY_SUCCESS",slug:t.question.titleSlug});else throw new Error("No daily challenge found")}catch(t){e({type:"GLOBAL_ERROR",error:t instanceof Error?t.message:"Failed to fetch daily challenge"});}}async function fu(e){try{let t=await S.getRandomProblem();if(t)e({type:"FETCH_RANDOM_SUCCESS",slug:t});else throw new Error("No random problem found")}catch(t){e({type:"GLOBAL_ERROR",error:t instanceof Error?t.message:"Failed to fetch random problem"});}}async function mu(e,t){try{let o=$e.join(M.getWorkDir(),".notes"),n=$e.join(o,`${e}.md`);if(existsSync(n)){let r=await Pe.readFile(n,"utf-8");t({type:"PROBLEM_NOTE_LOADED",content:r});}else t({type:"PROBLEM_NOTE_LOADED",content:'No notes found. Press "n" again to create/edit.'});}catch{t({type:"PROBLEM_ACTION_ERROR",error:"Failed to load note"});}}async function yu(e,t,o){try{let{code:n}=await tn(e),s=(await S.getProblem(e)).questionFrontendId,i=J.get(s,t);if(!i)throw new Error("Snapshot not found");let a=J.getCode(s,i),l=diffLines(n,a),u="";l.forEach(g=>{let d=g.added?"[green]":g.removed?"[red]":"[grey]",m=g.added?"+ ":g.removed?"- ":" ";g.value.split(`
|
|
271
|
+
`).forEach(b=>{b&&(u+=`${d}${m}${b}
|
|
272
|
+
`);});}),o({type:"PROBLEM_DIFF_LOADED",content:u});}catch(n){o({type:"PROBLEM_ACTION_ERROR",error:n instanceof Error?n.message:"Diff failed"});}}async function hu(e,t,o){try{let n=await S.getProblem(e),r=n.questionFrontendId,s=J.get(r,t);if(!s)throw new Error("Snapshot not found");let i=J.getCode(r,s),a=M.getLanguage(),l=Qe(n.questionFrontendId,n.titleSlug,s.language||a),u=M.getWorkDir(),g=n.difficulty,d=n.topicTags.length>0?n.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",m=$e.join(u,g,d),b=$e.join(m,l);await Pe.writeFile(b,i,"utf-8"),o({type:"PROBLEM_ACTION_SUCCESS",message:`Restored snapshot '${s.name}'`});}catch{o({type:"PROBLEM_ACTION_ERROR",error:"Restore failed"});}}async function Su(e,t){try{let o=await S.getSubmissionList(e,20);t({type:"PROBLEM_SUBMISSIONS_LOADED",submissions:o});}catch(o){t({type:"PROBLEM_SUBMISSIONS_ERROR",error:o instanceof Error?o.message:"Failed to fetch submissions"});}}async function bu(e){e({type:"CHANGELOG_FETCH_START"});try{let t=await yi(ru).text();e({type:"CHANGELOG_FETCH_SUCCESS",content:t});}catch(t){e({type:"CHANGELOG_FETCH_ERROR",error:t.message||"Failed to fetch changelog"});}}function oi(){Oe&&(clearInterval(Oe),Oe=null);}function Cu(e){ae.clear(),e({type:"AUTH_CHECK_COMPLETE",user:null});}async function Eu(e,t,o){let n={session:e,csrfToken:t};S.setCredentials(n);try{let r=await S.checkAuth();r.isSignedIn&&r.username?(ae.set(n),o({type:"LOGIN_SUCCESS",username:r.username}),setTimeout(()=>{o({type:"AUTH_CHECK_COMPLETE",user:{username:r.username}});},1e3)):o({type:"LOGIN_ERROR",error:"Invalid credentials. Please check your session cookies."});}catch(r){o({type:"LOGIN_ERROR",error:r instanceof Error?r.message:"Login failed"});}}var ni={"\x1B[A":"up","\x1B[B":"down","\x1B[C":"right","\x1B[D":"left","\x1B[5~":"pageup","\x1B[6~":"pagedown","\x1B[H":"home","\x1B[F":"end","\x1B[2~":"insert","\x1B[3~":"delete","\x1B":"escape","\r":"return","\n":"return","\x7F":"backspace","\b":"backspace"," ":"space"," ":"tab"};function ri(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e),o=t.toString(),n=t.length===1&&t[0]<27,r=t.length===2&&t[0]===27,s;ni[o]?s=ni[o]:n&&t.length===1?s=String.fromCharCode(t[0]+96):r&&t.length===2?s=String.fromCharCode(t[1]):s=o;let i=/^[A-Z]$/.test(s);return {name:s,sequence:o,ctrl:n,meta:r,shift:i}}var wu="\x1B[?1049h",Mu="\x1B[?1049l",_u="\x1B[?25l",ku="\x1B[?25h";function on(){process.stdout.write(wu),process.stdout.write(_u);}function nn(){process.stdout.write(ku),process.stdout.write(Mu),process.stdout.write("\x1B[0m");}function rn(){process.stdin.isTTY&&process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8");}function sn(){process.stdin.isTTY&&process.stdin.setRawMode(false);}var Te,dt=false,Ke=true,an=null,gt=false,Tt=null,Lt=null,Rt=null;function ut(e){if(!dt)return;let t=Te.screenState.screen,[o,n]=Xs(e,Te);Te=o,t!==o.screenState.screen&&(Ke=true,io="",Fe=[]),n.type!=="CMD_NONE"&&(n.type==="CMD_OPEN_EDITOR"?(Lu(),jt(n.id,"edit",{silent:true}).catch(r=>{ut({type:"GLOBAL_ERROR",error:r instanceof Error?r.message:"Failed to open editor"});}).finally(()=>{Ru(),Ke=true,Fe=[],Te={...Te,needsRender:true},ut({type:"PROBLEM_VIEW_NOTE"}),si();})):en(n,ut)),Te.needsRender&&(si(),Te={...Te,needsRender:false});}var io="",Fe=[],ct="\x1B[0m";function si(){if(!dt)return;let e=Ys(Te);if(e===io)return;io=e;let t=e.split(`
|
|
273
|
+
`);if(Ke||Fe.length===0){stdout.write(ct),stdout.write(so.cursorTo(0,0)),stdout.write(so.eraseScreen),stdout.write(e),stdout.write(ct),Ke=false,Fe=t;return}let o=Math.max(Fe.length,t.length),n=[];for(let r=0;r<o;r++){let s=Fe[r]??"",i=t[r]??"";s!==i&&(n.push(ct),n.push(so.cursorTo(0,r)),n.push(so.eraseLine),i.length>0&&n.push(i),n.push(ct));}n.length>0&&stdout.write(n.join("")),Fe=t;}function ii(e){if(gt||!dt)return;let t=ri(e);ut({type:"KEY_PRESS",key:t});}var ln=false;function Tu(){ln||(ln=true,dt=false,gt=false,stdin.off("data",ii),Tt&&(stdout.off("resize",Tt),Tt=null),Lt&&(process.off("SIGINT",Lt),Lt=null),Rt&&(process.off("SIGTERM",Rt),Rt=null),oi(),stdout.write(ct),nn(),ao.show(),sn(),stdin.pause(),an?.(),an=null);}function Lu(){gt||(gt=true,stdout.write(ct),nn(),ao.show(),sn(),stdin.pause());}function Ru(){!dt||!gt||(gt=false,on(),ao.hide(),rn(),stdin.resume(),Ke=true);}async function ai(e){if(!stdin.isTTY||!stdout.isTTY)throw new Error("TUI requires an interactive terminal");let t=new Promise(o=>{an=o;});return Te=e,dt=true,ln=false,Ke=true,io="",Fe=[],on(),ao.hide(),rn(),stdin.on("data",ii),Tt=()=>{ut({type:"RESIZE",width:stdout.columns||80,height:stdout.rows||24}),Ke=true;},stdout.on("resize",Tt),ut({type:"INIT"}),Lt=()=>{ro();},Rt=()=>{ro();},process.on("SIGINT",Lt),process.on("SIGTERM",Rt),await t}function ro(){Tu();}async function li(e={}){let{username:t}=e,o=fs(t);await ai(o);}var N=new Command;N.configureHelp({sortSubcommands:true,subcommandTerm:e=>{let t=e.name(),o=e.alias(),n=o?`${t}|${o}`:t;return f.cyan(n.padEnd(16))},subcommandDescription:e=>f.white(e.description()),optionTerm:e=>f.yellow(e.flags),optionDescription:e=>f.white(e.description)});N.name("leetcode").usage("[command] [options]").description(f.bold.cyan("\u{1F525} A modern LeetCode CLI built with TypeScript")).version("2.3.0","-v, --version","Output the version number").helpOption("-h, --help","Display help for command").addHelpText("after",`
|
|
274
|
+
${f.yellow("Examples:")}
|
|
275
|
+
${f.cyan("$ leetcode login")} Login to LeetCode
|
|
276
|
+
${f.cyan("$ leetcode list -d easy")} List easy problems
|
|
277
|
+
${f.cyan("$ leetcode random -d medium")} Get random medium problem
|
|
278
|
+
${f.cyan("$ leetcode pick 1")} Start solving "Two Sum"
|
|
279
|
+
${f.cyan("$ leetcode test 1")} Test your solution
|
|
280
|
+
${f.cyan("$ leetcode submit 1")} Submit your solution
|
|
281
|
+
`);N.command("login").description("Login to LeetCode with browser cookies").addHelpText("after",`
|
|
282
|
+
${f.yellow("How to login:")}
|
|
283
|
+
1. Open ${f.cyan("https://leetcode.com")} in your browser
|
|
255
284
|
2. Login to your account
|
|
256
285
|
3. Open Developer Tools (F12) \u2192 Application \u2192 Cookies
|
|
257
|
-
4. Copy values of ${
|
|
286
|
+
4. Copy values of ${f.green("LEETCODE_SESSION")} and ${f.green("csrftoken")}
|
|
258
287
|
5. Paste when prompted by this command
|
|
259
|
-
`).action(
|
|
260
|
-
${
|
|
261
|
-
${
|
|
262
|
-
${
|
|
263
|
-
${
|
|
264
|
-
${
|
|
265
|
-
${
|
|
266
|
-
${
|
|
267
|
-
`).action(
|
|
268
|
-
${
|
|
269
|
-
${
|
|
270
|
-
${
|
|
271
|
-
${
|
|
272
|
-
`).action(
|
|
273
|
-
${
|
|
274
|
-
${
|
|
275
|
-
${
|
|
276
|
-
${
|
|
277
|
-
${
|
|
278
|
-
|
|
279
|
-
${
|
|
280
|
-
`).action(
|
|
281
|
-
${
|
|
282
|
-
${
|
|
283
|
-
${
|
|
284
|
-
`).action(
|
|
285
|
-
${
|
|
286
|
-
${
|
|
287
|
-
${
|
|
288
|
-
${
|
|
289
|
-
${
|
|
290
|
-
${
|
|
291
|
-
`).action(
|
|
292
|
-
${
|
|
293
|
-
${
|
|
294
|
-
${
|
|
295
|
-
${
|
|
296
|
-
${
|
|
297
|
-
${
|
|
298
|
-
|
|
299
|
-
${
|
|
300
|
-
`).action(async(e,
|
|
301
|
-
${
|
|
302
|
-
${
|
|
303
|
-
${
|
|
304
|
-
`).action(
|
|
305
|
-
${
|
|
306
|
-
${
|
|
307
|
-
${
|
|
308
|
-
${
|
|
309
|
-
${
|
|
310
|
-
${
|
|
311
|
-
${
|
|
312
|
-
|
|
313
|
-
${
|
|
314
|
-
`).action(
|
|
315
|
-
${
|
|
316
|
-
${
|
|
317
|
-
${
|
|
318
|
-
${
|
|
319
|
-
${
|
|
320
|
-
`).action(
|
|
321
|
-
${
|
|
322
|
-
${
|
|
323
|
-
${
|
|
324
|
-
${
|
|
325
|
-
${
|
|
326
|
-
`).action(
|
|
327
|
-
${
|
|
328
|
-
${
|
|
329
|
-
${
|
|
330
|
-
${
|
|
331
|
-
${
|
|
332
|
-
`).action(
|
|
333
|
-
${
|
|
334
|
-
${
|
|
288
|
+
`).action(Rn);N.command("logout").description("Clear stored credentials").action(xn);N.command("whoami").description("Check current login status").action(On);N.command("list").alias("l").description("List LeetCode problems").option("-d, --difficulty <level>","Filter by difficulty (easy/medium/hard)").option("-s, --status <status>","Filter by status (todo/solved/attempted)").option("-t, --tag <tags...>","Filter by topic tags").option("-q, --search <keywords>","Search by keywords").option("-n, --limit <number>","Number of problems to show","20").option("-p, --page <number>","Page number","1").addHelpText("after",`
|
|
289
|
+
${f.yellow("Examples:")}
|
|
290
|
+
${f.cyan("$ leetcode list")} List first 20 problems
|
|
291
|
+
${f.cyan("$ leetcode list -d easy")} List easy problems only
|
|
292
|
+
${f.cyan("$ leetcode list -s solved")} List your solved problems
|
|
293
|
+
${f.cyan("$ leetcode list -t array -t string")} Filter by multiple tags
|
|
294
|
+
${f.cyan('$ leetcode list -q "two sum"')} Search by keywords
|
|
295
|
+
${f.cyan("$ leetcode list -n 50 -p 2")} Show 50 problems, page 2
|
|
296
|
+
`).action(jn);N.command("show <id>").alias("s").description("Show problem description").addHelpText("after",`
|
|
297
|
+
${f.yellow("Examples:")}
|
|
298
|
+
${f.cyan("$ leetcode show 1")} Show by problem ID
|
|
299
|
+
${f.cyan("$ leetcode show two-sum")} Show by problem slug
|
|
300
|
+
${f.cyan("$ leetcode s 412")} Short alias
|
|
301
|
+
`).action(Nt);N.command("hint <id>").alias("h").description("Show hints for a problem").option("-a, --all","Show all hints at once").addHelpText("after",`
|
|
302
|
+
${f.yellow("Examples:")}
|
|
303
|
+
${f.cyan("$ leetcode hint 1")} Show hints for problem 1
|
|
304
|
+
${f.cyan("$ leetcode hint two-sum")} Show hints by slug
|
|
305
|
+
${f.cyan("$ leetcode hint 1 --all")} Show all hints at once
|
|
306
|
+
${f.cyan("$ leetcode h 412")} Short alias
|
|
307
|
+
|
|
308
|
+
${f.gray("Hints are revealed one at a time. Press Enter to see more.")}
|
|
309
|
+
`).action(Gn);N.command("daily").alias("d").description("Show today's daily challenge").addHelpText("after",`
|
|
310
|
+
${f.yellow("Examples:")}
|
|
311
|
+
${f.cyan("$ leetcode daily")} Show today's challenge
|
|
312
|
+
${f.cyan("$ leetcode d")} Short alias
|
|
313
|
+
`).action(dr);N.command("random").alias("r").description("Get a random problem").option("-d, --difficulty <level>","Filter by difficulty (easy/medium/hard)").option("-t, --tag <tag>","Filter by topic tag").option("--pick","Auto-generate solution file").option("--no-open","Do not open file in editor").addHelpText("after",`
|
|
314
|
+
${f.yellow("Examples:")}
|
|
315
|
+
${f.cyan("$ leetcode random")} Get any random problem
|
|
316
|
+
${f.cyan("$ leetcode random -d medium")} Random medium problem
|
|
317
|
+
${f.cyan("$ leetcode random -t array")} Random array problem
|
|
318
|
+
${f.cyan("$ leetcode random --pick")} Random + create file
|
|
319
|
+
${f.cyan("$ leetcode r -d easy --pick")} Random easy + file
|
|
320
|
+
`).action(fr);N.command("pick <id>").alias("p").description("Generate solution file for a problem").option("-l, --lang <language>","Programming language for the solution").option("--no-open","Do not open file in editor").addHelpText("after",`
|
|
321
|
+
${f.yellow("Examples:")}
|
|
322
|
+
${f.cyan("$ leetcode pick 1")} Pick by problem ID
|
|
323
|
+
${f.cyan("$ leetcode pick two-sum")} Pick by problem slug
|
|
324
|
+
${f.cyan("$ leetcode pick 1 -l python3")} Pick with specific language
|
|
325
|
+
${f.cyan("$ leetcode pick 1 --no-open")} Create file without opening
|
|
326
|
+
${f.cyan("$ leetcode p 412")} Short alias
|
|
327
|
+
|
|
328
|
+
${f.gray("Files are organized by: workDir/Difficulty/Category/")}
|
|
329
|
+
`).action(async(e,t)=>{await _e(e,t);});N.command("pick-batch <ids...>").description("Generate solution files for multiple problems").option("-l, --lang <language>","Programming language for the solutions").addHelpText("after",`
|
|
330
|
+
${f.yellow("Examples:")}
|
|
331
|
+
${f.cyan("$ leetcode pick-batch 1 2 3")} Pick problems 1, 2, and 3
|
|
332
|
+
${f.cyan("$ leetcode pick-batch 1 2 3 -l py")} Pick with Python
|
|
333
|
+
`).action(Zn);N.command("test <file>").alias("t").description("Test solution against sample test cases").option("-c, --testcase <testcase>","Custom test case").option("-V, --visualize","Visual output for data structures (arrays, trees, etc.)").addHelpText("after",`
|
|
334
|
+
${f.yellow("Examples:")}
|
|
335
|
+
${f.cyan("$ leetcode test 1")} Test by problem ID
|
|
336
|
+
${f.cyan("$ leetcode test two-sum")} Test by problem slug
|
|
337
|
+
${f.cyan("$ leetcode test ./path/to/file.py")} Test by file path
|
|
338
|
+
${f.cyan('$ leetcode test 1 -c "[1,2]\\n3"')} Test with custom case
|
|
339
|
+
${f.cyan("$ leetcode test 1 --visualize")} Visual mode for debugging
|
|
340
|
+
${f.cyan("$ leetcode t 412")} Short alias
|
|
341
|
+
|
|
342
|
+
${f.gray("Testcases use \\n to separate multiple inputs.")}
|
|
343
|
+
`).action(rr);N.command("submit <file>").alias("x").description("Submit solution to LeetCode").addHelpText("after",`
|
|
344
|
+
${f.yellow("Examples:")}
|
|
345
|
+
${f.cyan("$ leetcode submit 1")} Submit by problem ID
|
|
346
|
+
${f.cyan("$ leetcode submit two-sum")} Submit by problem slug
|
|
347
|
+
${f.cyan("$ leetcode submit ./path/to/file.py")} Submit by file path
|
|
348
|
+
${f.cyan("$ leetcode x 412")} Short alias
|
|
349
|
+
`).action(ar);N.command("diff <id>").description("Compare solution with past submissions").option("-s, --submission <id>","Compare with specific submission ID").option("-f, --file <path>","Compare with a local file").option("-u, --unified","Show unified diff (line-by-line changes)").addHelpText("after",`
|
|
350
|
+
${f.yellow("Examples:")}
|
|
351
|
+
${f.cyan("$ leetcode diff 1")} Compare with last accepted
|
|
352
|
+
${f.cyan("$ leetcode diff 1 -u")} Show unified diff
|
|
353
|
+
${f.cyan("$ leetcode diff 1 -s 12345")} Compare with specific submission
|
|
354
|
+
${f.cyan("$ leetcode diff 1 -f other.py")} Compare with local file
|
|
355
|
+
`).action(Qr);N.command("submissions <id>").description("View past submissions").option("-n, --limit <number>","Number of submissions to show","20").option("--last","Show details of the last accepted submission").option("--download","Download the last accepted submission code").addHelpText("after",`
|
|
356
|
+
${f.yellow("Examples:")}
|
|
357
|
+
${f.cyan("$ leetcode submissions 1")} View submissions for problem
|
|
358
|
+
${f.cyan("$ leetcode submissions 1 -n 5")} Show last 5 submissions
|
|
359
|
+
${f.cyan("$ leetcode submissions 1 --last")} Show last accepted submission
|
|
360
|
+
${f.cyan("$ leetcode submissions 1 --download")} Download last accepted code
|
|
361
|
+
`).action(hr);N.command("stat [username]").description("Show user statistics and analytics").option("-c, --calendar","Weekly activity summary (submissions & active days for last 12 weeks)").option("-s, --skills","Skill breakdown (problems solved grouped by topic tags)").option("-t, --trend","Daily trend chart (bar graph of submissions for last 7 days)").addHelpText("after",`
|
|
362
|
+
${f.yellow("Options Explained:")}
|
|
363
|
+
${f.cyan("-c, --calendar")} Shows a table of your weekly submissions and active days
|
|
335
364
|
for the past 12 weeks. Useful for tracking consistency.
|
|
336
365
|
|
|
337
|
-
${
|
|
366
|
+
${f.cyan("-s, --skills")} Shows how many problems you solved per topic tag,
|
|
338
367
|
grouped by difficulty (Fundamental/Intermediate/Advanced).
|
|
339
368
|
Helps identify your strong and weak areas.
|
|
340
369
|
|
|
341
|
-
${
|
|
370
|
+
${f.cyan("-t, --trend")} Shows a bar chart of daily submissions for the past week.
|
|
342
371
|
Visualizes your recent coding activity day by day.
|
|
343
372
|
|
|
344
|
-
${
|
|
345
|
-
${
|
|
346
|
-
${
|
|
347
|
-
${
|
|
348
|
-
${
|
|
349
|
-
${
|
|
350
|
-
`).action((e,
|
|
351
|
-
${
|
|
352
|
-
${
|
|
353
|
-
`).action(
|
|
354
|
-
${
|
|
355
|
-
${
|
|
356
|
-
${
|
|
357
|
-
${
|
|
358
|
-
${
|
|
359
|
-
|
|
360
|
-
${
|
|
361
|
-
${
|
|
362
|
-
${
|
|
363
|
-
${
|
|
364
|
-
`).action(
|
|
365
|
-
${
|
|
366
|
-
${
|
|
367
|
-
${
|
|
368
|
-
|
|
369
|
-
${
|
|
370
|
-
${
|
|
371
|
-
${
|
|
372
|
-
${
|
|
373
|
-
`).action(
|
|
374
|
-
${
|
|
375
|
-
${
|
|
376
|
-
`).action(
|
|
377
|
-
${
|
|
378
|
-
${
|
|
379
|
-
${
|
|
380
|
-
${
|
|
381
|
-
${
|
|
382
|
-
${
|
|
383
|
-
${
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
373
|
+
${f.yellow("Examples:")}
|
|
374
|
+
${f.cyan("$ leetcode stat")} Show basic stats (solved count, rank)
|
|
375
|
+
${f.cyan("$ leetcode stat lee215")} Show another user's stats
|
|
376
|
+
${f.cyan("$ leetcode stat -c")} Weekly activity table
|
|
377
|
+
${f.cyan("$ leetcode stat -s")} Topic-wise breakdown
|
|
378
|
+
${f.cyan("$ leetcode stat -t")} 7-day trend chart
|
|
379
|
+
`).action((e,t)=>gr(e,t));N.command("today").description("Show today's progress summary").addHelpText("after",`
|
|
380
|
+
${f.yellow("Examples:")}
|
|
381
|
+
${f.cyan("$ leetcode today")} Show streak, solved, and daily challenge
|
|
382
|
+
`).action(Mr);N.command("bookmark <action> [id]").description("Manage problem bookmarks").addHelpText("after",`
|
|
383
|
+
${f.yellow("Actions:")}
|
|
384
|
+
${f.cyan("add <id>")} Bookmark a problem
|
|
385
|
+
${f.cyan("remove <id>")} Remove a bookmark
|
|
386
|
+
${f.cyan("list")} List all bookmarks
|
|
387
|
+
${f.cyan("clear")} Clear all bookmarks
|
|
388
|
+
|
|
389
|
+
${f.yellow("Examples:")}
|
|
390
|
+
${f.cyan("$ leetcode bookmark add 1")} Bookmark problem 1
|
|
391
|
+
${f.cyan("$ leetcode bookmark remove 1")} Remove bookmark
|
|
392
|
+
${f.cyan("$ leetcode bookmark list")} List all bookmarks
|
|
393
|
+
`).action(Er);N.command("note <id> [action]").description("View or edit notes for a problem").addHelpText("after",`
|
|
394
|
+
${f.yellow("Actions:")}
|
|
395
|
+
${f.cyan("edit")} Open notes in editor (default)
|
|
396
|
+
${f.cyan("view")} Display notes in terminal
|
|
397
|
+
|
|
398
|
+
${f.yellow("Examples:")}
|
|
399
|
+
${f.cyan("$ leetcode note 1")} Edit notes for problem 1
|
|
400
|
+
${f.cyan("$ leetcode note 1 edit")} Edit notes (explicit)
|
|
401
|
+
${f.cyan("$ leetcode note 1 view")} View notes in terminal
|
|
402
|
+
`).action(jt);N.command("sync").description("Sync solutions to Git repository").addHelpText("after",`
|
|
403
|
+
${f.yellow("Examples:")}
|
|
404
|
+
${f.cyan("$ leetcode sync")} Sync all solutions to remote
|
|
405
|
+
`).action(_r);N.command("config").description("View or set configuration").option("-l, --lang <language>","Set default programming language").option("-e, --editor <editor>","Set editor command").option("-w, --workdir <path>","Set working directory for solutions").option("-r, --repo [url]","Set Git repository URL (omit value to clear)").option("-i, --interactive","Interactive configuration").addHelpText("after",`
|
|
406
|
+
${f.yellow("Examples:")}
|
|
407
|
+
${f.cyan("$ leetcode config")} View current config
|
|
408
|
+
${f.cyan("$ leetcode config -l python3")} Set language to Python
|
|
409
|
+
${f.cyan('$ leetcode config -e "code"')} Set editor to VS Code
|
|
410
|
+
${f.cyan("$ leetcode config -w ~/leetcode")} Set solutions folder
|
|
411
|
+
${f.cyan("$ leetcode config -r https://...")} Set git repository
|
|
412
|
+
${f.cyan("$ leetcode config --repo")} Clear git repository
|
|
413
|
+
${f.cyan("$ leetcode config -i")} Interactive setup
|
|
414
|
+
|
|
415
|
+
${f.gray("Supported languages: typescript, javascript, python3, java, cpp, c, csharp, go, rust, kotlin, swift")}
|
|
416
|
+
`).action(async e=>{e.interactive?await br():await Sr(e);});N.command("timer [id]").description("Start interview mode with timer").option("-m, --minutes <minutes>","Custom time limit in minutes").option("--stats","Show solve time statistics").option("--stop","Stop active timer").addHelpText("after",`
|
|
417
|
+
${f.yellow("How it works:")}
|
|
388
418
|
Start a problem with a countdown timer to simulate interview conditions.
|
|
389
419
|
Default time limits: Easy (20 min), Medium (40 min), Hard (60 min).
|
|
390
420
|
Your solve times are recorded when you submit successfully.
|
|
391
421
|
|
|
392
|
-
${
|
|
393
|
-
${
|
|
394
|
-
${
|
|
395
|
-
${
|
|
396
|
-
${
|
|
397
|
-
`).action((e,
|
|
398
|
-
${
|
|
399
|
-
${
|
|
400
|
-
${
|
|
401
|
-
${
|
|
402
|
-
${
|
|
403
|
-
${
|
|
404
|
-
${
|
|
405
|
-
|
|
406
|
-
${
|
|
407
|
-
${
|
|
408
|
-
${
|
|
409
|
-
${
|
|
410
|
-
${
|
|
411
|
-
`);
|
|
412
|
-
${
|
|
413
|
-
${
|
|
414
|
-
${
|
|
415
|
-
${
|
|
416
|
-
${
|
|
417
|
-
${
|
|
418
|
-
|
|
419
|
-
${
|
|
420
|
-
${
|
|
421
|
-
${
|
|
422
|
-
${
|
|
423
|
-
${
|
|
424
|
-
`);
|
|
425
|
-
${
|
|
426
|
-
${
|
|
427
|
-
${
|
|
428
|
-
${
|
|
429
|
-
`).action(
|
|
430
|
-
${
|
|
431
|
-
${
|
|
432
|
-
${
|
|
433
|
-
${
|
|
434
|
-
${
|
|
435
|
-
${
|
|
436
|
-
`).action((e,
|
|
422
|
+
${f.yellow("Examples:")}
|
|
423
|
+
${f.cyan("$ leetcode timer 1")} Start problem 1 with default time
|
|
424
|
+
${f.cyan("$ leetcode timer 1 -m 30")} Start with 30 minute limit
|
|
425
|
+
${f.cyan("$ leetcode timer --stats")} Show your solve time statistics
|
|
426
|
+
${f.cyan("$ leetcode timer --stop")} Stop active timer
|
|
427
|
+
`).action((e,t)=>kr(e,t));var xt=N.command("workspace").description("Manage workspaces for different contexts");xt.command("current").description("Show current workspace").action(Jr);xt.command("list").description("List all workspaces").action(Xr);xt.command("create <name>").description("Create a new workspace").option("-w, --workdir <path>","Set working directory for this workspace").action(Zr);xt.command("use <name>").description("Switch to a workspace").action(es);xt.command("delete <name>").description("Delete a workspace").action(ts);var ft=N.command("collab").description("Collaborative coding with a partner").addHelpText("after",`
|
|
428
|
+
${f.yellow("Subcommands:")}
|
|
429
|
+
${f.cyan("host <id>")} Create a room and get a code to share
|
|
430
|
+
${f.cyan("join <code>")} Join a room with the shared code
|
|
431
|
+
${f.cyan("sync")} Upload your solution to the room
|
|
432
|
+
${f.cyan("compare")} View both solutions side by side
|
|
433
|
+
${f.cyan("status")} Check room and sync status
|
|
434
|
+
${f.cyan("leave")} End the collaboration session
|
|
435
|
+
|
|
436
|
+
${f.yellow("Examples:")}
|
|
437
|
+
${f.gray("$ leetcode collab host 1")} Start a session for Two Sum
|
|
438
|
+
${f.gray("$ leetcode collab join ABC123")} Join your partner's session
|
|
439
|
+
${f.gray("$ leetcode collab sync")} Upload your code after solving
|
|
440
|
+
${f.gray("$ leetcode collab compare")} Compare solutions
|
|
441
|
+
`);ft.command("host <problemId>").description("Host a collaboration session").action(Rr);ft.command("join <roomCode>").description("Join a collaboration session").action(xr);ft.command("sync").description("Sync your code with partner").action(Or);ft.command("compare").description("Compare your solution with partner").action(Pr);ft.command("leave").description("Leave the collaboration session").action($r);ft.command("status").description("Show collaboration status").action(vr);var Ot=N.command("snapshot").description("Save and restore solution versions").addHelpText("after",`
|
|
442
|
+
${f.yellow("Subcommands:")}
|
|
443
|
+
${f.cyan("save <id> [name]")} Save current solution as a snapshot
|
|
444
|
+
${f.cyan("list <id>")} List all snapshots for a problem
|
|
445
|
+
${f.cyan("restore <id> <snapshot>")} Restore a snapshot
|
|
446
|
+
${f.cyan("diff <id> <s1> <s2>")} Compare two snapshots
|
|
447
|
+
${f.cyan("delete <id> <snapshot>")} Delete a snapshot
|
|
448
|
+
|
|
449
|
+
${f.yellow("Examples:")}
|
|
450
|
+
${f.gray('$ leetcode snapshot save 1 "brute-force"')} Save current solution
|
|
451
|
+
${f.gray("$ leetcode snapshot list 1")} List snapshots
|
|
452
|
+
${f.gray("$ leetcode snapshot restore 1 2")} Restore snapshot #2
|
|
453
|
+
${f.gray("$ leetcode snapshot diff 1 1 2")} Compare snapshots
|
|
454
|
+
`);Ot.command("save <id> [name]").description("Save current solution as a snapshot").action(Wr);Ot.command("list <id>").description("List all snapshots for a problem").action(jr);Ot.command("restore <id> <snapshot>").description("Restore a snapshot").action(Gr);Ot.command("diff <id> <snap1> <snap2>").description("Compare two snapshots").action(Kr);Ot.command("delete <id> <snapshot>").description("Delete a snapshot").action(qr);N.command("update").description("Check for CLI updates").option("--check-only","Only check for updates, do not show update instructions").option("-f, --force","Force check even if recently checked").addHelpText("after",`
|
|
455
|
+
${f.yellow("Examples:")}
|
|
456
|
+
${f.cyan("$ leetcode update")} Check for updates
|
|
457
|
+
${f.cyan("$ leetcode update --force")} Force re-check npm registry
|
|
458
|
+
${f.cyan("$ leetcode update --check-only")} Just check, minimal output
|
|
459
|
+
`).action(cs);N.command("changelog [version]").description("View release notes and changelog").option("--latest","Show only the latest version").option("--breaking","Show only versions with breaking changes").option("-a, --all","Show all versions (default: only newer than installed)").addHelpText("after",`
|
|
460
|
+
${f.yellow("Examples:")}
|
|
461
|
+
${f.cyan("$ leetcode changelog")} Show what's new since your version
|
|
462
|
+
${f.cyan("$ leetcode changelog --all")} View full changelog
|
|
463
|
+
${f.cyan("$ leetcode changelog 2.0.0")} Show specific version
|
|
464
|
+
${f.cyan("$ leetcode changelog --latest")} Show latest version only
|
|
465
|
+
${f.cyan("$ leetcode changelog --breaking")} Filter to breaking changes
|
|
466
|
+
`).action((e,t)=>ds(e,t));N.showHelpAfterError("(add --help for additional information)");var Ou=process.argv.length>2&&!["update","changelog","--version","-v","--help","-h"].includes(process.argv[2]);Ou&&us().catch(()=>{});var ci=process.argv.slice(2);ci.length===0&&process.stdout.isTTY?li({username:""}).catch(e=>{console.error("Failed to launch TUI:",e.message),process.exit(1);}):ci.length===0?(console.log(),console.log(f.bold.cyan(" \u{1F525} LeetCode CLI")),console.log(f.gray(" A modern command-line interface for LeetCode")),console.log(),N.outputHelp()):N.parse();
|