@night-slayer18/leetcode-cli 2.2.2 → 2.4.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 +98 -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 $o from'inquirer';import Vt from'ora';import xi from'got';import {z}from'zod';import Ri from'conf';import {homedir}from'os';import*as $e from'path';import $e__default,{join,dirname,basename,extname,resolve,sep}from'path';import mo from'cli-table3';import Di from'striptags';import*as Oe from'fs/promises';import {mkdir,writeFile,readFile,readdir}from'fs/promises';import {existsSync,writeFileSync,readFileSync,unlinkSync,mkdirSync}from'fs';import {execSync,execFileSync,spawn}from'child_process';import ea from'open';import {createClient}from'@supabase/supabase-js';import {diffLines}from'diff';import {fileURLToPath}from'url';import {stdin,stdout}from'process';import lo from'ansi-escapes';import uo from'cli-cursor';var ki=z.object({name:z.string(),slug:z.string()}),Ti=z.object({name:z.string(),slug:z.string()}),Li=z.object({lang:z.string(),langSlug:z.string(),code:z.string()}),$t=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(ki),status:z.enum(["ac","notac"]).nullable()}),yn=$t.extend({content:z.string().nullable(),codeSnippets:z.array(Li).nullable(),sampleTestCase:z.string(),exampleTestcases:z.string(),hints:z.array(z.string()),companyTags:z.array(Ti).nullable(),stats:z.string()}),hn=z.object({date:z.string(),link:z.string(),question:$t}),Sn=z.object({id:z.string(),statusDisplay:z.string(),lang:z.string(),runtime:z.string(),timestamp:z.string(),memory:z.string()}),bn=z.object({code:z.string(),lang:z.object({name:z.string()})}),Cn=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()}),En=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()}),wn=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()})}),Mn=z.object({isSignedIn:z.boolean(),username:z.string().nullable()});var _n=`
|
|
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
|
+
`,kn=`
|
|
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
|
+
`,Tn=`
|
|
58
58
|
query globalData {
|
|
59
59
|
userStatus {
|
|
60
60
|
isSignedIn
|
|
61
61
|
username
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
|
-
|
|
64
|
+
`,Ln=`
|
|
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
|
+
`,xn=`
|
|
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
|
+
`,Rn=`
|
|
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
|
+
`,Pn=`
|
|
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
|
+
`,On=`
|
|
146
146
|
query randomQuestion($categorySlug: String, $filters: QuestionListFilterInput) {
|
|
147
147
|
randomQuestion(categorySlug: $categorySlug, filters: $filters) {
|
|
148
148
|
titleSlug
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
|
-
|
|
151
|
+
`,$n=`
|
|
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 po="https://leetcode.com",go=class{client;credentials=null;constructor(){this.client=xi.extend({prefixUrl:po,headers:{"Content-Type":"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",Origin:po,Referer:`${po}/`},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(Tn);return Mn.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(_n,o),r=z.array($t).parse(n.problemsetQuestionList.questions);return {total:n.problemsetQuestionList.total,problems:r}}async getProblem(t){let o=await this.graphql(kn,{titleSlug:t});return yn.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(Rn);return hn.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(On,o);return z.object({titleSlug:z.string()}).parse(n.randomQuestion).titleSlug}async getUserProfile(t){let n=(await this.graphql(Ln,{username:t})).matchedUser,r=wn.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(xn,{username:t})).matchedUser.tagProblemCounts}async getSubmissionList(t,o=20,n=0){let r=await this.graphql(Pn,{questionSlug:t,limit:o,offset:n});return z.array(Sn).parse(r.questionSubmissionList.submissions)}async getSubmissionDetails(t){let o=await this.graphql($n,{submissionId:t});return bn.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",Cn)}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",En)}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 go;var qe=new Ri({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 An(){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 $o.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=Vt("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 Dn(){ae.clear(),console.log(f.green("\u2713 Logged out successfully"));}async function In(){let e=ae.get();if(!e){console.log(f.yellow('Not logged in. Run "leetcode login" to authenticate.'));return}let t=Vt("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 vi={"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 Ai(e){for(let t of e){let o=vi[t.name];if(o)return o}return null}function Nn(e){try{return JSON.parse(e)}catch{return e}}function ve(e){return Array.isArray(e)&&e.length>0&&Array.isArray(e[0])}function Fn(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 Hn(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 Un(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],M=b===null?" ":String(b);u.push(M.padStart(d).padEnd(d));let E=2*m+1,x=2*m+2,G=E<e.length&&e[E]!==null,q=x<e.length&&e[x]!==null;if(G||q){let z="";G?z+="/":z+=" ",z+=" ",q?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 At(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 Bn(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 Wn(e,t,o){let n=Nn(e),r=Nn(t),s=e===t,i=Ai(o),a,l;if(ve(n)){let u=ve(r)?r:void 0;return a=At(n,u),l=ve(r)?At(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=Hn(n,r),l=Hn(r);break;case "tree":a=Un(n),l=Un(r);break;case "graph":a=Bn(n),l=Bn(r);break;case "matrix":let u=ve(r)?r:void 0;a=At(n,u),l=ve(r)?At(r):String(t);break;case "array":case "string":Array.isArray(n)?(a=Fn(n,r),l=Array.isArray(r)?Fn(r):String(t)):(a=s?String(e):f.red.bold(String(e)),l=String(t));break}return {outputVis:a,expectedVis:l,matches:s}}function jn(e,t){let o=new mo({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,Dt(n.difficulty),`${n.acRate.toFixed(1)}%`,Ii(n.status)]);}console.log(o.toString()),console.log(f.gray(`
|
|
165
|
+
Showing ${e.length} of ${t} problems`));}function Gn(e){console.log();let t=e.isPaidOnly?"\u{1F512} ":"";if(console.log(f.bold.cyan(` ${e.questionFrontendId}. ${t}${e.title}`)),console.log(` ${Dt(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(yo(o)),console.log();}function yo(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=Di(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 qn(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}=Wn(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 Kn(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 Vn(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 mo({head:[f.cyan("Difficulty"),f.cyan("Solved")],style:{head:[],border:[]}});for(let l of n)l.difficulty!=="All"&&i.push([Dt(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 zn(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(Dt(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 Dt(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 Ii(e){switch(e){case "ac":return f.green("\u2713");case "notac":return f.yellow("\u25CB");default:return f.gray("-")}}function ho(e){let t=new mo({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 Yn(e){let{authorized:t}=await v();if(!t)return;let o=Vt("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}jn(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 It(e){let{authorized:t}=await v();if(!t)return;let o=Vt("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(),Gn(n);}catch(n){o.fail("Failed to fetch problem"),n instanceof Error&&console.log(f.red(n.message));}}async function Qn(e,t){let{authorized:o}=await v();if(!o)return;let n=Vt("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)=>{Jn(i,a+1,s.length);}):await ji(s);}catch(r){n.fail("Failed to fetch problem hints"),r instanceof Error&&console.log(f.red(r.message));}}function Jn(e,t,o){let n=Wi(e);console.log(f.bold.yellow(`\u{1F4A1} Hint ${t}/${o}`)),console.log(f.white(n)),console.log();}function Wi(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 (Di(t)??"").replace(/</g,"<").replace(/>/g,">").replace(/ /g," ").replace(/"/g,'"').replace(/&/g,"&").trim()}async function ji(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}Jn(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 Nt(e){return !e.includes("/")&&!e.includes("\\")&&e.includes(".")}var Gi=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/,qi=/^[a-zA-Z0-9][a-zA-Z0-9 _-]{0,63}$/;function Ke(e){return Gi.test(e.trim())}function er(e){return qi.test(e.trim())}function Ve(e,t){let o=resolve(e),n=resolve(t),r=n.endsWith(sep)?n:n+sep;return o===n||o.startsWith(r)}var wo=join(homedir(),".leetcode"),Co=join(wo,"workspaces.json"),Ft=join(wo,"workspaces");function Ht(e){existsSync(e)||mkdirSync(e,{recursive:true});}function Ue(){return existsSync(Co)?JSON.parse(readFileSync(Co,"utf-8")):{active:"default",workspaces:[]}}function ft(e){Ht(wo),writeFileSync(Co,JSON.stringify(e,null,2));}function Te(e){let t=e.trim();return Ke(t)?t:null}var T={ensureInitialized(){let e=Ue(),t=e.workspaces.map(r=>Te(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",ft(e);return}let n=Te(e.active);!n||!e.workspaces.includes(n)?(e.active=e.workspaces[0],o=true):n!==e.active&&(e.active=n,o=true),o&&ft(e);},getActive(){return this.ensureInitialized(),Ue().active},setActive(e){let t=Te(e);if(!t)return false;let o=Ue();return o.workspaces.includes(t)?(o.active=t,ft(o),true):false},list(){return this.ensureInitialized(),Ue().workspaces},exists(e){let t=Te(e);return t?(this.ensureInitialized(),Ue().workspaces.includes(t)):false},create(e,t){let o=Te(e);if(!o)return false;let n=Ue();if(n.workspaces.includes(o))return false;let r=join(Ft,o);Ht(r),Ht(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),ft(n),true},delete(e){let t=Te(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"),ft(o),true):false},getWorkspaceDir(e){let t=e?Te(e)||"default":this.getActive();return join(Ft,t)},getConfig(e){let t=e?Te(e)||"default":this.getActive(),o=join(Ft,t,"config.json");return existsSync(o)?JSON.parse(readFileSync(o,"utf-8")):{workDir:join(homedir(),"leetcode"),lang:"typescript"}},setConfig(e,t){let o=t?Te(t)||"default":this.getActive(),n=join(Ft,o);Ht(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 _={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 Ut=["typescript","javascript","python3","java","cpp","c","csharp","go","rust","kotlin","swift","sql"],Mo={typescript:"typescript",ts:"typescript",javascript:"javascript",js:"javascript",python3:"python3",python:"python3",py:"python3",java:"java","c++":"cpp",cpp:"cpp",c:"c","c#":"csharp",csharp:"csharp",cs:"csharp",go:"go",golang:"go",rust:"rust",rs:"rust",kotlin:"kotlin",kt:"kotlin",swift:"swift",sql:"sql",mysql:"sql",mssql:"sql",postgresql:"sql",postgres:"sql",oracle:"sql"},zi={typescript:"typescript",javascript:"javascript",python3:"python3",java:"java",cpp:"cpp",c:"c",csharp:"csharp",go:"golang",rust:"rust",kotlin:"kotlin",swift:"swift",sql:"mysql"},Yi={sql:"mysql",mysql:"mysql",mssql:"mssql","ms sql":"mssql",postgresql:"postgresql",postgres:"postgresql",oracle:"oracle"};function nr(e){return e.trim().toLowerCase()}function or(e){let t=nr(e).replace(/[-_]+/g," ");return Yi[t]??null}function Be(e){return Mo[nr(e)]??null}function rr(e){return Be(e)}function Qi(e){if(!e||e.length===0)return "mysql";let t=new Set;for(let o of e){let n=or(o.langSlug);if(n){t.add(n);continue}let r=or(o.lang);r&&t.add(r);}return t.has("mysql")?"mysql":t.has("mssql")?"mssql":t.has("postgresql")?"postgresql":t.has("oracle")?"oracle":"mysql"}function Bt(e,t){return e==="sql"?Qi(t):zi[e]}function sr(){return Ut.join(", ")}var ze={typescript:"ts",javascript:"js",python3:"py",java:"java",cpp:"cpp",c:"c",csharp:"cs",go:"go",rust:"rs",kotlin:"kt",swift:"swift",sql:"sql"},ir={...Mo};function Wt(e,t){let o=e.find(n=>rr(n.langSlug)===t);return o||(e[0]??null)}function jt(e,t){let o=ar(e);return `${o.single} Premium Problem - ${t}
|
|
180
|
+
${o.single} Solution stub not available - visit LeetCode to view`}function Gt(e,t,o,n,r,s,i){let a=ar(s);return `${Zi(a,e,o,n,t,i)}
|
|
181
|
+
|
|
182
|
+
${r}
|
|
183
|
+
`}function ar(e){switch(e){case "python3":return {single:"#",blockStart:'"""',blockEnd:'"""',linePrefix:""};case "sql":return {single:"--",blockStart:"/*",blockEnd:"*/",linePrefix:" * "};default:return {single:"//",blockStart:"/*",blockEnd:"*/",linePrefix:" * "}}}function Xi(e){let t=e;return t=t.replace(/<sup>(.*?)<\/sup>/gi,"^$1"),t=t.replace(/<strong class="example">Example (\d+):<\/strong>/gi,`
|
|
184
|
+
Example $1:`),t=t.replace(/<li>/gi,"\u2022 "),t=t.replace(/<\/li>/gi,`
|
|
166
185
|
`),t=t.replace(/<\/p>/gi,`
|
|
167
186
|
|
|
168
187
|
`),t=t.replace(/<br\s*\/?>/gi,`
|
|
169
|
-
`),t=
|
|
170
|
-
|
|
171
|
-
`).trim(),t
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
`).
|
|
175
|
-
`).forEach(x=>console.log(` ${x}`)),console.log(),console.log(p?l.green(" \u2713 Match"):l.red(" \u2717 Mismatch"));}console.log(l.gray.bold("\u2500".repeat(50)));}else {console.log(),console.log(l.gray("Your Output:"));for(let r of t)console.log(l.white(` ${r}`));console.log(),console.log(l.gray("Expected Output:"));for(let r of n)console.log(l.white(` ${r}`));}let s=(e.std_output_list??[]).filter(r=>r);if(s.length>0){console.log(),console.log(l.gray("Stdout:"));for(let r of s)console.log(l.gray(` ${r}`));}}function qo(e){if(console.log(),e.compile_error){console.log(l.red.bold("\u274C Compile Error")),console.log(l.red(e.compile_error));return}if(e.runtime_error){console.log(l.red.bold("\u274C Runtime Error")),console.log(l.red(e.runtime_error)),e.last_testcase&&console.log(l.gray("Last testcase:"),e.last_testcase);return}e.status_msg==="Accepted"?(console.log(l.green.bold("\u2713 Accepted!")),console.log(),console.log(l.gray("Runtime:"),l.white(e.status_runtime),l.gray(`(beats ${e.runtime_percentile?.toFixed(1)??"N/A"}%)`)),console.log(l.gray("Memory:"),l.white(e.status_memory),l.gray(`(beats ${e.memory_percentile?.toFixed(1)??"N/A"}%)`))):(console.log(l.red.bold(`\u274C ${e.status_msg}`)),console.log(),console.log(l.gray(`Passed ${e.total_correct}/${e.total_testcases} testcases`)),e.code_output&&console.log(l.gray("Your Output:"),e.code_output),e.expected_output&&console.log(l.gray("Expected:"),e.expected_output),e.last_testcase&&console.log(l.gray("Failed testcase:"),e.last_testcase));}function Oo(e,o,t,n,s,r){console.log(),console.log(l.bold.white(`\u{1F464} ${e}`)+(o?l.gray(` (${o})`):"")),console.log(l.gray(`Ranking: #${t.toLocaleString()}`)),console.log();let i=new We({head:[l.cyan("Difficulty"),l.cyan("Solved")],style:{head:[],border:[]}});for(let c of n)c.difficulty!=="All"&&i.push([Ae(c.difficulty),c.count.toString()]);let a=n.find(c=>c.difficulty==="All")?.count??0;i.push([l.white.bold("Total"),l.white.bold(a.toString())]),console.log(i.toString()),console.log(),console.log(l.gray("\u{1F525} Current streak:"),l.hex("#FFA500")(s.toString()),l.gray("days")),console.log(l.gray("\u{1F4C5} Total active days:"),l.white(r.toString()));}function Ho(e,o){if(console.log(),console.log(l.bold.yellow("\u{1F3AF} Daily Challenge"),l.gray(`(${e})`)),console.log(),console.log(l.white(`${o.questionFrontendId}. ${o.title}`)),console.log(Ae(o.difficulty)),console.log(l.gray(`https://leetcode.com/problems/${o.titleSlug}/`)),o.topicTags.length){console.log();let t=o.topicTags.map(n=>l.blue(n.name)).join(" ");console.log(l.gray("Tags:"),t);}}function Ae(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}}function Ln(e){switch(e){case "ac":return l.green("\u2713");case "notac":return l.yellow("\u25CB");default:return l.gray("-")}}function Ve(e){let o=new We({head:[l.cyan("ID"),l.cyan("Status"),l.cyan("Lang"),l.cyan("Runtime"),l.cyan("Memory"),l.cyan("Date")],colWidths:[12,18,15,12,12,25],style:{head:[],border:[]}});for(let t of e){let n=t.statusDisplay==="Accepted",s=new Date(parseInt(t.timestamp)*1e3).toLocaleString();o.push([t.id,n?l.green(t.statusDisplay):l.red(t.statusDisplay),t.lang,t.runtime,t.memory,s]);}console.log(o.toString());}async function Wo(e){let{authorized:o}=await $();if(!o)return;let t=Ue("Fetching problems...").start();try{let n={},s=parseInt(e.limit??"20",10),r=parseInt(e.page??"1",10);if(n.limit=s,n.skip=(r-1)*s,e.difficulty){let c={easy:"EASY",e:"EASY",medium:"MEDIUM",m:"MEDIUM",hard:"HARD",h:"HARD"};n.difficulty=c[e.difficulty.toLowerCase()];}if(e.status){let c={todo:"NOT_STARTED",solved:"AC",ac:"AC",attempted:"TRIED",tried:"TRIED"};n.status=c[e.status.toLowerCase()];}e.tag?.length&&(n.tags=e.tag),e.search&&(n.searchKeywords=e.search);let{total:i,problems:a}=await h.getProblems(n);if(t.stop(),a.length===0){console.log(l.yellow("No problems found matching your criteria."));return}Uo(a,i),r*s<i&&console.log(l.gray(`
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
${
|
|
182
|
-
`
|
|
183
|
-
Example $1:`),o=o.replace(/<li>/gi,"\u2022 "),o=o.replace(/<\/li>/gi,`
|
|
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+=`
|
|
188
|
+
`),t=Di(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,`
|
|
189
|
+
|
|
190
|
+
`).trim(),t}function Zi(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=Xi(s).split(`
|
|
191
|
+
`);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(`
|
|
192
|
+
`)}function Ye(e,t,o){let n=ze[o];return `${e}.${t}.${n}`}var ta=["vim","nvim","vi","nano","emacs","micro","helix"],oa=["code","code-insiders","cursor","codium","vscodium"];async function yt(e,t){let o=_.getEditor()??process.env.EDITOR??"code",n=_.getWorkDir();if(ta.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(oa.includes(o)){spawn(o,["-r",n,"-g",e],{detached:!0,stdio:"ignore"}).unref();return}await ea(e,{app:{name:o}});}catch{throw new Error(`Failed to open editor '${o}'. Make sure it is installed and in your PATH.`)}}async function Me(e,t){let{authorized:o}=await v();if(!o)return false;let n=Vt({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??_.getLanguage(),i=Be(s);if(!i)return n.fail(`Unsupported language: ${s}`),!1;let a=r.codeSnippets??[],l=Wt(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=jt(i,r.title);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=Gt(r.questionFrontendId,r.titleSlug,r.title,r.difficulty,u,i,r.content??void 0),d=_.getWorkDir(),m=r.difficulty,b=r.topicTags.length>0?r.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",M=join(d,m,b);existsSync(M)||await mkdir(M,{recursive:!0});let E=Ye(r.questionFrontendId,r.titleSlug,i),x=join(M,E);return existsSync(x)?(n.warn(`File already exists: ${E}`),console.log(f.gray(`Path: ${x}`)),t.open!==!1&&await yt(x),!0):(await writeFile(x,g,"utf-8"),n.succeed(`Created ${f.green(E)}`),console.log(f.gray(`Path: ${x}`)),console.log(),console.log(f.cyan(`${r.questionFrontendId}. ${r.title}`)),console.log(f.gray(`Difficulty: ${r.difficulty} | Category: ${b}`)),t.open!==!1&&await yt(x),!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 pr(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 Me(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 mr=5;async function ge(e,t,o=0){if(!existsSync(e)||o>=mr)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 _o)return s}}return null}async function ht(e,t,o=0){if(!existsSync(e)||o>=mr)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 ht(s,t,o+1);if(i)return i}else if(r.name===t)return s}return null}var _o={ts:"typescript",js:"javascript",py:"python3",java:"java",cpp:"cpp",c:"c",cs:"csharp",go:"go",rs:"rust",kt:"kotlin",swift:"swift",sql:"sql"};function ko(e){let t=e.split(".").pop()?.toLowerCase();return t?_o[t]??null:null}function qt(e,t){let o=_o[e.toLowerCase()];return o?Bt(o,t):null}async function yr(e,t){let{authorized:o}=await v();if(!o)return;let n=e,r=_.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(Nt(e)){let i=await ht(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(!Ve(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=Vt({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=await readFile(n,"utf-8");s.text="Fetching problem details...";let d=await S.getProblem(l),m=qt(u,d.codeSnippets);if(!m){s.fail(`Unsupported file extension: .${u}`);return}let b=t.testcase??d.exampleTestcases??d.sampleTestCase;s.text="Running tests...";let M=await S.testSolution(l,g,m,b,d.questionId);s.stop(),qn(M,t.visualize?d.topicTags:void 0);}catch(i){s.fail("Test failed"),n.toLowerCase().endsWith(".sql")&&console.log(f.yellow("SQL interpret mode may be unavailable for this problem on LeetCode. Try `leetcode submit <file>`.")),i instanceof Error&&console.log(f.red(i.message));}}function Sr(){return T.getTimerPath()}function We(){let e=Sr();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{solveTimes:{},activeTimer:null}}function To(e){let t=Sr(),o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true}),writeFileSync(t,JSON.stringify(e,null,2));}var be={startTimer(e,t,o,n){let r=We();r.activeTimer={problemId:e,title:t,difficulty:o,startedAt:new Date().toISOString(),durationMinutes:n},To(r);},getActiveTimer(){return We().activeTimer},stopTimer(){let e=We(),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,To(e),{durationSeconds:r}},recordSolveTime(e,t,o,n,r){let s=We();s.solveTimes[e]||(s.solveTimes[e]=[]),s.solveTimes[e].push({problemId:e,title:t,difficulty:o,solvedAt:new Date().toISOString(),durationSeconds:n,timerMinutes:r}),To(s);},getSolveTimes(e){return We().solveTimes[e]??[]},getAllSolveTimes(){return We().solveTimes??{}},getStats(){let e=We().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 br(e){let{authorized:t}=await v();if(!t)return;let o=e,n=_.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(Nt(e)){let s=await ht(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(!Ve(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=Vt({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=await readFile(o,"utf-8");r.text="Fetching problem details...";let d=await S.getProblem(l),m=qt(u,d.codeSnippets);if(!m){r.fail(`Unsupported file extension: .${u}`);return}r.text="Submitting solution...";let b=await S.submitSolution(l,g,m,d.questionId);if(r.stop(),Kn(b),b.status_msg==="Accepted"){let M=be.getActiveTimer();if(M&&M.problemId===a){let E=be.stopTimer();if(E){be.recordSolveTime(a,d.title,d.difficulty,E.durationSeconds,M.durationMinutes);let x=Math.floor(E.durationSeconds/60),G=E.durationSeconds%60,q=`${x}m ${G}s`,z=E.durationSeconds<=M.durationMinutes*60;console.log(),console.log(f.bold("\u23F1\uFE0F Timer Result:")),console.log(` Solved in ${z?f.green(q):f.yellow(q)} (limit: ${M.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 Cr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Er(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())),M=Math.floor(b.getTime()/1e3).toString(),E=t[M]||0;l+=E,E>0&&u++;}let g=new Date(a);g.setDate(g.getDate()+6),n.push({start:`${Cr[a.getMonth()]} ${a.getDate()}`,end:`${Cr[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 wr(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 Mr(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 _r(e,t={}){let{authorized:o,username:n}=await v();if(!o)return;let r=Vt("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){Vn(i.username,i.realName,i.ranking,i.acSubmissionNum,i.streak,i.totalActiveDays);return}if(t.calendar&&(i.submissionCalendar?Er(i.submissionCalendar):console.log(f.yellow("Calendar data not available."))),t.trend&&(i.submissionCalendar?Mr(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(),wr(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 kr(){let{authorized:e}=await v();if(!e)return;let t=Vt("Fetching daily challenge...").start();try{let o=await S.getDailyChallenge();t.stop(),zn(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 Tr(e){let{authorized:t}=await v();if(!t)return;let o=Vt("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 Me(r,{open:e.open??!0}):(await It(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 Rr(e,t){let{authorized:o}=await v();if(!o)return;let n=Vt("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:")),ho([l])):console.log(f.yellow("No accepted submissions found in recent history."));}else ho(a);if(t.download){let l=Vt("Downloading submission...").start(),u=a.find(Ot=>Ot.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=_.getWorkDir(),b=r.difficulty,M=r.topicTags.length>0?r.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",E=join(m,b,M);existsSync(E)||await mkdir(E,{recursive:!0});let x=d.lang.name.toLowerCase(),G=ir[x]??"txt",q=ze[G]??x,z=`${r.questionFrontendId}.${r.titleSlug}.submission-${u.id}.${q}`,Pt=join(E,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));}}async function Pr(e){let t=e.repo!==void 0;if(!e.lang&&!e.editor&&!e.workdir&&!t){$r();return}if(e.lang){let o=Be(e.lang);if(!o){console.log(f.red(`Unsupported language: ${e.lang}`)),console.log(f.gray(`Supported: ${Ut.join(", ")}`));return}_.setLanguage(o),console.log(f.green(`\u2713 Default language set to ${o}`));}e.editor&&(_.setEditor(e.editor),console.log(f.green(`\u2713 Editor set to ${e.editor}`))),e.workdir&&(_.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()===""?(_.deleteRepo(),console.log(f.green("\u2713 Repository URL cleared"))):typeof e.repo=="string"&&(_.setRepo(e.repo),console.log(f.green(`\u2713 Repository URL set to ${e.repo}`))));}async function Or(){let e=_.getConfig(),t=_.getActiveWorkspace();console.log(),console.log(f.bold.cyan(`\u{1F4C1} Configuring workspace: ${t}`)),console.log(f.gray("\u2500".repeat(40)));let o=await $o.prompt([{type:"list",name:"language",message:"Default programming language:",choices:Ut,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}]);_.setLanguage(o.language),_.setEditor(o.editor),_.setWorkDir(o.workDir),o.repo?_.setRepo(o.repo):_.deleteRepo(),console.log(),console.log(f.green("\u2713 Configuration saved")),$r();}function $r(){let e=_.getConfig(),t=ae.get(),o=_.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:"),_.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 Ri({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 vr(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 xa();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 xa(){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=Vt({text:"Fetching problem details...",spinner:"dots"}).start();try{let n=new mo({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,Ra(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 Ra(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 Kt(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(_.getWorkDir(),".notes"),s=join(r,`${e}.md`);existsSync(r)||await mkdir(r,{recursive:true}),n==="view"?await va(s,e):await Aa(s,e,o);}async function va(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 Aa(e,t,o={}){if(!existsSync(e)){let n=await Da(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 yt(e);}async function Da(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 Dr(){let{authorized:e,username:t}=await v();if(!e||!t)return;let o=Vt({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(` ${Na(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 Na(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 Ua(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-").replace(/--+/g,"-")}function Ba(e){let t=/^https:\/\/[\w.-]+\/[\w./-]+$/,o=/^git@[\w.-]+:[\w./-]+$/;return t.test(e)||o.test(e)}function Wa(){try{return execSync("git --version",{stdio:"ignore"}),!0}catch{return false}}function ja(e){try{return execSync("git rev-parse --is-inside-work-tree",{cwd:e,stdio:"ignore"}),!0}catch{return false}}function Ga(){try{return execSync("gh --version",{stdio:"ignore"}),!0}catch{return false}}function vo(e){try{return execSync("git config --get remote.origin.url",{cwd:e,encoding:"utf-8"}).trim()}catch{return null}}async function qa(e){let{init:t}=await $o.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=Vt("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 Ka(e){let t=Vt(),o=_.getRepo();if(!o){if(Ga()){let{createGh:r}=await $o.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=Ua(s);return execFileSync("gh",["repo","create",i,"--private","--source=.","--remote=origin"],{cwd:e}),t.succeed("Created and linked GitHub repository"),o=vo(e)||"",o&&_.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 $o.prompt([{type:"input",name:"url",message:"Enter remote repository URL:",validate:s=>s.length>0?true:"URL cannot be empty"}]);o=r;}}if(o&&!Ba(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&&_.setRepo(o),!vo(e)&&o)try{execFileSync("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 Ir(){let e=_.getWorkDir();if(!existsSync(e)){console.log(f.red(`Work directory does not exist: ${e}`));return}if(!Wa()){console.log(f.red("Git is not installed. Please install Git to use command."));return}if(!ja(e)&&!await qa(e))return;if(!await Ka(e)&&!vo(e)){console.log(f.red("No valid remote repository configured. Sync aborted."));return}let o=Vt("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}`;execFileSync("git",["commit","-m",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 za={Easy:20,Medium:40,Hard:60};function Je(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 Nr(e,t){if(t.stats){await Qa(e);return}if(t.stop){await Ya();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=be.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: ${Je(i)}`)),console.log(),console.log(f.gray("Use `leetcode timer --stop` to stop it first."));return}let r=Vt("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??za[s.difficulty]??30;be.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 Me(e,{open:!0});}catch(s){r.fail("Failed to start timer"),s instanceof Error&&console.log(f.red(s.message));}}async function Ya(){let e=be.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: ${Je(e.durationSeconds)}`)),console.log(f.gray("(Time not recorded since problem was not submitted)"));}async function Qa(e){if(e&&/^\d+$/.test(e)){let t=be.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=Je(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=be.getStats(),o=be.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(Je(t.totalTime))}`),console.log(` Average time: ${f.cyan(Je(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(Je(r.duration)));}}console.log();}}var Xa="https://abagrmwdpvnfyuqizyym.supabase.co",Za="sb_publishable_indrKu8VJmASdyLp7w8Hog_OyqT17cV",Ie=createClient(Xa,Za);function Do(){return T.getCollabPath()}function rl(){let e=Do();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{session:null}}function sl(e){let t=Do(),o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true}),writeFileSync(t,JSON.stringify(e,null,2));}var xe={getSession(){return rl().session},setSession(e){sl({session:e});},getPath(){return Do()}};function il(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let o=0;o<6;o++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}var Ee={getSession(){return xe.getSession()},async createRoom(e,t){let o=il(),{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}:(xe.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}:(xe.setSession({roomCode:e.toUpperCase(),problemId:o.problem_id,isHost:false,username:t}),{problemId:o.problem_id})},async syncCode(e){let t=xe.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=xe.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=xe.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=xe.getSession();e&&e.isHost&&await Ie.from("collab_rooms").delete().eq("room_code",e.roomCode),xe.setSession(null);}};async function Ur(e){let{authorized:t,username:o}=await v();if(!t||!o)return;let n=Vt("Creating collaboration room...").start();try{let r=await Ee.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 Me(e,{open:!0});}catch(r){n.fail("Failed to create room"),r instanceof Error&&console.log(f.red(r.message));}}async function Br(e){let{authorized:t,username:o}=await v();if(!t||!o)return;let n=Vt(`Joining room ${e}...`).start();try{let r=await Ee.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 Me(r.problemId,{open:!0});}catch(r){n.fail("Failed to join room"),r instanceof Error&&console.log(f.red(r.message));}}async function Wr(){let e=Ee.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=Vt("Syncing your code...").start();try{let o=_.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 Ee.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 jr(){let e=Ee.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=Vt("Fetching solutions...").start();try{let o=_.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 Ee.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 Gr(){if(!Ee.getSession()){console.log(f.yellow("No active collaboration session."));return}await Ee.leaveRoom(),console.log(f.green("\u2713 Left the collaboration session."));}async function qr(){let e=Ee.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 Ee.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 cl(){return T.getSnapshotsDir()}function Yr(e){return join(cl(),e)}function Qr(e){return join(Yr(e),"meta.json")}function zt(e){return join(Yr(e),"files")}function Jr(e){let t=zt(e);existsSync(t)||mkdirSync(t,{recursive:true});}function St(e){let t=Qr(e);return existsSync(t)?JSON.parse(readFileSync(t,"utf-8")):{problemId:e,problemTitle:"",snapshots:[]}}function Kr(e,t){Jr(e),writeFileSync(Qr(e),JSON.stringify(t,null,2));}var J={save(e,t,o,n,r){Jr(e);let s=St(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(!er(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=ze[n]||n,g=`${i}_${a}.${u}`,d=join(zt(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),Kr(e,s),m},list(e){return St(e).snapshots},getMeta(e){return St(e)},get(e,t){let o=St(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(zt(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=St(e),n=this.get(e,t);if(!n)return false;let r=join(zt(e),n.fileName);return existsSync(r)&&unlinkSync(r),o.snapshots=o.snapshots.filter(s=>s.id!==n.id),Kr(e,o),true},hasSnapshots(e){return this.list(e).length>0}};function dl(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 es(e,t){let o=_.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=ko(n)||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 ts(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=dl(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 os(e,t){let o=_.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=ko(r)||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 ns(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 rs(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 is(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 yl(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 Io(e,t,o,n,r){if(r)yl(e,t,o,n);else {is(e,o),is(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 ls(e,t){let{authorized:o}=await v();if(!o)return;let n=_.getWorkDir(),r=Vt("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(!Ve(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");Io(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(),Io(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(),Io(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 cs(){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 us(){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 ps(e,t){let o=e.trim();if(!Ke(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 gs(e){let t=e.trim();if(!Ke(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 ds(e){let t=e.trim();if(!Ke(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 $o.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 No=join(homedir(),".leetcode"),bt=join(No,"version-cache.json"),kl=1440*60*1e3;function Tl(){existsSync(No)||mkdirSync(No,{recursive:true});}function fs(){if(existsSync(bt))try{return JSON.parse(readFileSync(bt,"utf-8"))}catch{return null}return null}function Ll(e){Tl(),writeFileSync(bt,JSON.stringify(e,null,2));}var Ne={shouldCheck(){let e=fs();return e?Date.now()-e.lastCheck>kl:true},getCached(){return fs()},updateCache(e,t){Ll({lastCheck:Date.now(),latestVersion:e,hasBreakingChanges:t});},clearCache(){if(existsSync(bt))try{unlinkSync(bt);}catch{}}};function Ze(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 ys(e,t){let o=parseInt(e.replace("v","").split(".")[0])||0;return (parseInt(t.replace("v","").split(".")[0])||0)>o}var vl=fileURLToPath(import.meta.url),Ss=dirname(vl),Al="https://registry.npmjs.org/@night-slayer18/leetcode-cli/latest",Dl="@night-slayer18/leetcode-cli";function et(){let e=[join(Ss,"../package.json"),join(Ss,"../../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 Cs(){let t=(await xi(Al,{timeout:{request:1e4},retry:{limit:2}}).json()).version,o=et(),n=ys(o,t);return {version:t,hasBreakingChanges:n}}function Il(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 ${Dl}`;console.log(f.cyan("\u2502")+a.padEnd(n+8)+f.cyan("\u2502")),console.log(f.cyan(s)),console.log();}async function Es(e){let t=et();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=Vt("Checking for updates...").start();try{let i=await Cs();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}}Ze(n,t)?(Il(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 ws(){if(!Ne.shouldCheck()){let e=Ne.getCached();e&&Ze(e.latestVersion,et())&&bs(et(),e.latestVersion,e.hasBreakingChanges);return}try{let e=await Cs();Ne.updateCache(e.version,e.hasBreakingChanges),Ze(e.version,et())&&bs(et(),e.version,e.hasBreakingChanges);}catch{}}function bs(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 Wl=fileURLToPath(import.meta.url),_s=dirname(Wl),jl="https://raw.githubusercontent.com/night-slayer18/leetcode-cli/main/docs/releases.md";function Gl(){let e=[join(_s,"../package.json"),join(_s,"../../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 ql(){return await xi(jl,{timeout:{request:1e4},retry:{limit:2}}).text()}function Kl(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 Vl(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 ks(e,t={}){let o=Vt("Fetching changelog...").start();try{let n=await ql();o.stop();let r=Kl(n);if(r.length===0){console.log(f.yellow("No release entries found."));return}let s=Gl(),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=>Ze(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)Vl(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 Ts(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 Qt=50;function zl(){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 Ho(){let e=zl(),t={limit:Qt,skip:0};return [e,c.fetchProblems(t,false)]}function Uo(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=tt(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=tt({...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=tt({...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=tt({...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=tt({...t},0);return [{...t,bookmarkFilter:r,loading:true,cursor:0,scrollOffset:0},c.fetchProblems(s,false)]}case "LIST_CLEAR_FILTERS":{let r={limit:Qt,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=tt(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 tt(e,t){let o={limit:Qt,skip:t*Qt};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 Ct=[{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 Jt(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(Ct.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 Xt(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 Xl(){return {loading:true,error:null,stats:null,dailyChallenge:null,skillStats:null}}function Ls(){return [Xl(),c.fetchStats()]}function Bo(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 ec(e){return [{id:"language",label:"Default Language",description:"Language for new solutions (example: typescript, python3, sql)",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 Wo(e){return e.options[e.selectedOption]}function tc(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 oc(){let e=_.getConfig(),t=ec(e);return {selectedOption:0,options:t,paneFocus:"list",isEditing:false,draftValue:t[0]?.value??"",validationError:null,isDirty:false,config:e}}function Rs(){return [oc(),c.none()]}function xs(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 jo(e,t){switch(e.type){case "CONFIG_OPTION_UP":return t.isEditing?[t,c.none()]:[xs(t,t.selectedOption-1),c.none()];case "CONFIG_OPTION_DOWN":return t.isEditing?[t,c.none()]:[xs(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=Wo(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=Wo(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=Wo(t),n=tc(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"},Zt={tableColumns:{selector:2,status:3,id:6,difficulty:10,acceptance:8,premium:2}};var Go={filled:"\u2588",empty:"\u2591"};var rc=/\x1B\[[0-9;]*[a-zA-Z]/g;function O(e){return e.replace(rc,"")}function Et(e){return O(e).length}function A(e,t){if(t<=0)return "";if(t===1)return "\u2026";if(Et(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=O(e),n=t-o.length;return n>0?e+" ".repeat(n):e}function Ko(e,t){let o=O(e),n=t-o.length;return n>0?" ".repeat(n)+e:e}function $(e,t){if(t<=0)return "";let n=O(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 qo={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 ye(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=qo[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 M=f.hex(s).bold(` ${r} `),E=O(M).length;b+=f.hex(s)(l.horizontal),b+=M,b+=f.hex(s)(l.horizontal.repeat(Math.max(0,d-E-1)));}else b+=f.hex(s)(l.horizontal.repeat(d));b+=f.hex(s)(l.topRight||l.roundTopRight),u.push(b);for(let M=0;M<i;M++)u.push(f.hex(s)(l.vertical)+" ".repeat(d)+f.hex(s)(l.vertical));for(let M of e){let E=O(M),x=M;E.length>m&&(x=A(M,m));let G=m-O(x).length,q=" ".repeat(i)+x+" ".repeat(G)+" ".repeat(i);u.push(f.hex(s)(l.vertical)+q+f.hex(s)(l.vertical));}for(let M=0;M<i;M++)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 eo(e,t="light",o=p.textMuted){let n=j.horizontal;return t==="heavy"&&(n=qo.heavy.horizontal),t==="double"&&(n=qo.double.horizontal),f.hex(o)(n.repeat(Math.max(0,e)))}function Ps(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)(Go.filled.repeat(r))+f.hex(p.textDim)(Go.empty.repeat(s))}function je(e,t,o="#000000"){return f.bgHex(t).hex(o).bold(` ${e} `)}function Os(e){switch(e.toLowerCase()){case "easy":return je("Easy",p.success);case "medium":return je("Medium",p.warning);case "hard":return je("Hard",p.error);default:return je(e,p.textMuted)}}function $s(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 Vo(e){return e.map(t=>C(t.key,t.label)).join(" ")}function ot(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 we(e,t){let o=Math.max(10,t),n=f.hex(p.primary).bold(` ${e} `),r=Math.max(0,o-Et(n));return n+f.hex(p.textMuted)(j.horizontal.repeat(r))}function nt(e,t,o="normal"){let n=Math.max(20,t),r=o==="compact"?e.slice(0,3):e,s=Vo(r);return H([s],n).map(a=>$(a,n))}function rt(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),M=ue(A(g[m]??"",l),l);d.push(b+f.hex(p.border)(j.vertical)+M);}return d}var sc=["\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"],ic=["\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 st(e){return (e>=80?sc:ic).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(O(r).length<=o){n.push(r);continue}let i=r.split(" "),a="",l=0;for(let u of i){let g=O(u).length;if(g>o){l>0&&(n.push(a),a="",l=0);let m=u;for(;O(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 ac(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 wt(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(ac(t),l));return {bodyHeight:Math.max(3,s-i-u),drawerHeight:u}}function no(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 Re(e){return {...e,drawerMode:"none",focusRegion:"body",drawerScrollOffset:0,drawerData:{statusMessage:null}}}function ne(e,t,o=null){return t==="none"?Re(e):{...e,drawerMode:t,focusRegion:"drawer",drawerScrollOffset:0,drawerData:{statusMessage:o}}}function ro(e,t,o,n){let r=cc(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(zo(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(zo(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=lc(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"?[Re(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(to(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 [Re(t),c.none()];case "PROBLEM_SHOW_SUBMISSIONS":return t.drawerMode==="submissions"?[Re(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 [Re(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(to(t,o,n),t.drawerScrollOffset+1)},c.none()];case "PROBLEM_SHOW_SNAPSHOTS":{if(t.drawerMode==="snapshots")return [Re(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 [Re(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 [Re(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(to(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 [Re(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(to(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 lc(e){return yo(e.content||"").split(`
|
|
245
|
+
`)}function zo(e,t){let o=Math.max(6,e-4);return wt(o,t).bodyHeight}function cc(e,t,o){let n=zo(t,e.drawerMode),r=Math.max(20,o-4),s=H(e.contentLines,r);return Math.max(0,s.length-n)}function to(e,t,o){if(e.drawerMode==="none"||e.drawerMode==="snapshots")return 0;let n=Math.max(6,t-4),r=wt(n,e.drawerMode),s=Math.max(1,r.drawerHeight-2),i=Math.max(20,o-2),a=uc(e,i);return Math.max(0,a.length-s)}function uc(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=vs(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=oo(n.statusDisplay||"-",10).padEnd(10),s=oo(n.runtime||"-",8).padEnd(8),i=oo(n.memory||"-",8).padEnd(8),a=oo(n.lang||"-",8).padEnd(8);return `${r} ${s} ${i} ${a}`});case "note":return H(pc(e.noteContent||"No notes found. Press e to edit."),o);case "diff":return (e.diffContent||"No diff available.").split(`
|
|
246
|
+
`).map(n=>vs(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 vs(e){return O(e).replace(/\[green\]|\[red\]|\[grey\]/g,"").replace(/<\/?[^>]+(>|$)/g,"").replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/\s+/g," ").trim()}function oo(e,t){return e.length<=t?e:t<=1?"\u2026":`${e.slice(0,t-1)}\u2026`}function pc(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 dc=[{key:"lang",label:"Language"},{key:"workDir",label:"Work Dir"},{key:"editor",label:"Editor"},{key:"syncRepo",label:"Sync Repo"}];function Yo(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(...ot(`${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(...rt(As(e,r),Ds(e,r),r,a,.43));else {let l=Math.max(3,Math.floor(a*.45)),u=Math.max(3,a-l-1),g=As(e,r).slice(0,l);for(;g.length<l;)g.push("");let d=Ds(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(...fc(e,r)),n.slice(0,s).join(`
|
|
248
|
+
`)}function As(e,t){let o=t>=90?Math.max(20,Math.floor(t*.43)):t,n=[];if(n.push(we("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 Ds(e,t){let o=t>=90?Math.max(20,t-Math.floor(t*.43)-1):t,n=[];if(n.push(we("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 dc){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 fc(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 nt([{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 Mt=["lang","workDir","editor","syncRepo"];function mc(e){return {lang:e.lang??"",workDir:e.workDir??"",editor:e.editor??"",syncRepo:e.syncRepo??""}}function Ns(e){return e?mc(T.getConfig(e)):null}function so(e,t,o){let n=Math.max(0,Math.min(o,Math.max(0,t.length-1))),r=t[n]??null,s=Ns(r);return {...e,workspaces:t,cursor:n,selectedWorkspace:r,selectedConfig:s,draftConfig:s?{...s}:null,isDirty:false,isEditing:false}}function Fs(){let e=T.list(),t=T.getActive(),o=Math.max(0,e.indexOf(t)),n=e[o]??null,r=Ns(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 Is(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 Qo(e,t){switch(e.type){case "WORKSPACE_UP":return t.isEditing?[t,c.none()]:[so(t,t.workspaces,t.cursor-1),c.none()];case "WORKSPACE_DOWN":return t.isEditing?[t,c.none()]:[so(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,Mt.indexOf(t.selectedField)-1);return [{...t,selectedField:Mt[o]},c.none()]}case "WORKSPACE_FIELD_DOWN":{if(t.paneFocus!=="editor"||t.isEditing)return [t,c.none()];let o=Math.min(Mt.length-1,Mt.indexOf(t.selectedField)+1);return [{...t,selectedField:Mt[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?[Is(t,o=>o+e.char),c.none()]:[t,c.none()];case "WORKSPACE_EDIT_BACKSPACE":return t.isEditing?[Is(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 [{...so({...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 [{...so({...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 Hs(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 Ws(e,t){return e.loading||e.error?3:js(e.entries,t).length}function Jo(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=js(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 hc(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(...Us(" "+g,t-3,5));continue}a.startsWith("---")||a.trim().length>0&&o.push(...Us(" "+f.gray(a.trim()),t-3,3));}return o}function Us(e,t,o){let n=Math.max(1,t);if(Bs(e).length<=n)return [e];let r=e.split(" "),s=[],i="",a=" ".repeat(o);return r.forEach(l=>{Bs(i+l).length+1>n?(s.push(i),i=a+l+" "):i+=l+" ";}),i&&s.push(i),s}function Bs(e){return e.replace(/\x1B\[\d+m/g,"")}function js(e,t){let o=[],n=Math.max(20,t-4);return e.forEach(r=>{o.push(...hc(r,n)),o.push(""),o.push(f.hex(p.border)(j.horizontal.repeat(n))),o.push("");}),o}function Gs(e){return [{entries:[],scrollOffset:0,loading:true,error:null},c.fetchChangelog()]}function Xo(e,t,o,n){let r=Math.max(3,o-5),s=Math.max(0,Ws(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=Hs(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 Zo(e,t,o){let n=[],r=[],s=st(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."];ye(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,M=e.sessionToken?b(e.sessionToken):f.gray("Paste here..."),E=e.csrfToken?b(e.csrfToken):e.sessionToken?f.gray("Paste here..."):f.gray("Waiting..."),x=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)("> ")+M:" "+x+(e.sessionToken?f.green(" \u2714"):"")),u.push(""),u.push(f.bold("csrftoken:")),u.push(d?f.hex(p.primary)("> ")+E:" "+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)),ye(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 en(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 qs(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=O(u).length,d=Math.max(1,n-g-1),m=H([l],d)[0]??l,b=O(m).length,M=n-b-g,E=M>0?" ".repeat(M):" ";return r.push(m+E+u),r.push(f.hex(p.textMuted)(j.horizontal.repeat(n))),r}function Ks(e){let{screen:t,hints:o,message:n,width:r}=e,s=[];s.push(f.hex(p.textMuted)(j.horizontal.repeat(r)));let i=Vo(o),a=f.bgHex(p.bgHighlight).hex(p.primary)(` ${t.toUpperCase()} `),l;if(n){let M=f.hex(p.warning)(n);l=i+" "+M;}else l=i;let u=O(a).length,g=Math.max(1,r-u-1);l=H([l],g)[0]??"";let d=O(l).length,m=r-d-u,b=m>0?" ".repeat(m):" ";return s.push(l+b+a),s}function Vs(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 zs(e,t,o){let n=[],r=Math.max(1,o),s=t>=80?6:3,i=Ct.length+4,a=s+2+i+4,l=Math.max(0,Math.floor((r-a)/2));for(let E=0;E<l;E++)n.push("");let u=st(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 E=0;E<Ct.length;E++){let x=Ct[E],G=E===e.menuIndex,q=G?f.hex(p.primary)(" \u25B6 "):" ",z=f.hex(p.primary)(`[${x.key}]`),Pt=G?f.hex(p.textBright).bold(x.label):f.hex(p.text)(x.label),Ot=f.hex(p.textMuted)(` - ${x.description}`),He=`${q}${z} ${Pt}`,wi=O(He).length,Mi=O(Ot).length;wi+Mi<d-6&&(He+=Ot);let _i=O(He),mn=Math.max(0,d-4-_i.length);He=He+(mn>0?" ".repeat(mn):""),G?m.push(f.bgHex(p.bgHighlight)(He)):m.push(He);}let b=ye(m,d,"Menu");for(let E of b)n.push($(E,t));n.push("");let M=[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 E of M)n.push($(E,t));for(;n.length<r;)n.push("");return n.slice(0,r).join(`
|
|
252
|
+
`)}function Ys(e,t,o){let n=[],r=o;if(n.push(Cc(e,t)),n.push(""),n.push(Ec(e,t)),n.push(wc(e,t)),n.push(""),e.loading&&e.problems.length===0)return n.push(...Tc(t,r-6)),n.join(`
|
|
253
|
+
`);if(e.error&&e.problems.length===0)return n.push(...Lc(e.error,t,r-6)),n.join(`
|
|
254
|
+
`);if(e.problems.length===0)return n.push(...xc(t,r-6)),n.join(`
|
|
255
|
+
`);n.push(Mc(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(_c(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(kc(e,t)),n.join(`
|
|
256
|
+
`)}function Cc(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=Ps(a,e.problems.length,20),g=f.hex(p.textMuted)(` ${a} solved`),d=u+g,m=t-O(i).length-O(d).length;return i+(m>0?" ".repeat(m):" ")+d}return i}function Ec(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-O(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 wc(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(je(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(je(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 Mc(e){let t=Qs(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(Ko("Acc %",t.acceptance)),t.premium>0&&n.push(" "+ue("",t.premium)),f.hex(p.textMuted)(n.join(""))}function _c(e,t,o){let n=Qs(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=$s(e.status),a=Et(i)<n.status?i+" ".repeat(n.status-Et(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)(Ko(`${Math.round(e.acRate)}%`,n.acceptance)):"",M=n.premium>0?e.isPaidOnly?f.hex(p.warning)("\u{1F48E}"):" ":"",E=" "+s+a+l+g+m+(n.acceptance>0?b:"")+(n.premium>0?" "+M:"");if(t){let x=O(E),G=o-x.length;return f.bgHex(p.bgHighlight)(E+(G>0?" ".repeat(G):""))}return E}function kc(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-O(n+r).length-O(i).length;return n+r+(a>0?" ".repeat(a):" ")+i}function Qs(e){return e>=78?Zt.tableColumns:e>=62?{...Zt.tableColumns,id:5,difficulty:8,acceptance:0,premium:0}:{...Zt.tableColumns,status:2,id:4,difficulty:0,acceptance:0,premium:0}}function Tc(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 Lc(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 xc(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 Js(e,t,o){let n=[],r=o,s=[$(`Solving: ${e.problemTitle}`,t-4),$(`Difficulty: ${e.difficulty}`,t-4)];n.push(...ye(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=Rc(l,e.status),g=Math.max(...u.map(q=>O(q).length),0),d=Math.floor((t-g)/2),m=u.map(q=>" ".repeat(Math.max(0,d))+q),b=r-n.length-8,M=Math.max(0,Math.floor(b/2)-3);for(let q=0;q<M;q++)n.push("");n.push(...m);for(let q=0;q<M;q++)n.push("");let E="",x=p.textMuted;switch(e.status){case "running":E=" RUNNING ",x=p.success;break;case "paused":E=" PAUSED ",x=p.warning;break;case "idle":E=" READY ",x=p.primary;break;case "completed":E=" TIME UP! ",x=p.error;break}for(n.push(""),n.push($(f.bgHex(x).black.bold(E),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 Rc(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 Xs=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Zs(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 E=0;E<7;E++){let x=new Date(d);if(x.setDate(x.getDate()+E),x>n)break;let G=new Date(Date.UTC(x.getFullYear(),x.getMonth(),x.getDate())),q=Math.floor(G.getTime()/1e3).toString(),z=o[q]||0;m+=z,z>0&&b++;}let M=new Date(d);M.setDate(M.getDate()+6),s.push({start:`${Xs[d.getMonth()]} ${d.getDate()}`,end:`${Xs[M.getMonth()]} ${M.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),M=g.count>0?`${g.count} subs`.padEnd(10):"".padEnd(10),E=g.days>0?`${g.days}d active`:"";i.push(` ${f.white(d)} ${b} ${f.cyan(M)} ${f.yellow(E)}`);}return i.push(f.gray(`Total: ${a} subs, ${l} days`)),i}catch{return [f.red("Error parsing calendar data")]}}function ei(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 oi(e,t,o){let n=[],r=o;if(e.loading)return Oc(t,r);if(e.error)return ti(e.error,t,r);if(!e.stats||!e.skillStats)return ti("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(...ye(s,t,"Profile")),n.push("");let i=r-7;if(i>8&&e.stats.submissionCalendar){let a=ei(e.stats.submissionCalendar);n.push(...ye(a,t,"Trend")),n.push(""),i-=a.length+2;}if(i>8&&e.stats.submissionCalendar){let a=Zs(e.stats.submissionCalendar,t-4);n.push(...ye(a,t,"Activity")),n.push(""),i-=a.length+2;}if(i>5&&e.skillStats){let a=Pc(e,t-4);n.push(...ye(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 Pc(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 Oc(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 ti(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 $c={language:"Example: typescript, python3, cpp, sql",editor:"Example: code, vim, nvim",workdir:"Example: /Users/name/leetcode",repo:"Example: https://github.com/user/leetcode.git"};function si(e,t,o){let n=Math.max(20,t),r=Math.max(8,o),s=[];s.push(...ot(`${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(...rt(ni(e,n),ri(e,n),n,i,.4));else {let a=Math.max(3,Math.floor(i*.4)),l=Math.max(3,i-a-1),u=ni(e,n).slice(0,a);for(;u.length<a;)u.push("");let g=ri(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(...vc(e,n)),s.slice(0,r).join(`
|
|
261
|
+
`)}function ni(e,t){let o=t>=90?Math.max(20,Math.floor(t*.4)):t,n=[];n.push(we("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 ri(e,t){let o=t>=90?Math.max(20,t-Math.floor(t*.4)-1):t,n=e.options[e.selectedOption],r=[];r.push(we("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($c[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 vc(e,t){return nt([{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 ii(e,t,o){let n=[],r=Math.max(30,t),s=Math.max(10,o);if(e.loading)return nn("Loading problem details...",r,s,p.primary);if(e.error&&!e.detail)return nn(`Error: ${e.error}`,r,s,p.error);if(!e.detail)return nn("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=Os(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)(eo(r)));let d=wt(s,e.drawerMode);for(n.push(...Ac(e,r,d.bodyHeight)),e.drawerMode!=="none"&&d.drawerHeight>0&&(n.push(f.hex(p.border)(eo(r))),n.push(...Ic(e,r,d.drawerHeight)));n.length<s-2;)n.push("");return n.push(f.hex(p.textMuted)(eo(r))),n.push(...Dc(e,r)),n.slice(0,s).join(`
|
|
262
|
+
`)}function Ac(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 Dc(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 Ic(e,t,o){let n=e.drawerMode;if(n==="snapshots")return Nc(e,t,o);let r=Hc(e),s=Uc(n),i=Fc(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=[we(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 Nc(e,t,o){let n=e.focusRegion==="drawer"?"Snapshots \u2022 Focused":"Snapshots",r=[we(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),M=A(u.language,10).padEnd(10),E=`${m} ${String(u.id).padStart(3)} ${b} ${M} ${String(u.lines).padStart(4)}L`;r.push(d?f.bgHex(p.bgHighlight)(A(E,t).padEnd(Math.max(0,t-1))):E);}}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 Fc(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=jc(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(Gc(e.noteContent||"No notes found. Press e to edit."),n);case "diff":return (e.diffContent||"No diff available.").split(`
|
|
263
|
+
`).map(s=>Wc(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 Hc(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 Bc(e);default:return "Drawer"}}function Uc(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 Bc(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 Wc(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 jc(e){return O(e).replace(/<\/?[^>]+(>|$)/g,"").replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/\s+/g," ").trim()}function Gc(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 nn(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 ai(e){let t=[],{terminalWidth:o,terminalHeight:n}=e;if(e.isCheckingAuth)return Kc(o,n);let r=qs({username:e.user?.username??"Guest",isConnected:e.user?.isLoggedIn??false,width:o});t.push(...r);let s=Math.max(1,n-4),i=qc(e,o,s);t.push(i);let a=e.screenState.screen==="problem"||e.screenState.screen==="help"?[]:Vs(e.screenState.screen),l=Ks({screen:e.screenState.screen,hints:a,message:e.globalError??void 0,width:o});return t.push(...l),Yc(t.join(`
|
|
266
|
+
`),o,n)}function qc(e,t,o){let{screenState:n}=e;switch(n.screen){case "home":return zs(n.model,t,o);case "list":return Ys(n.model,t,o);case "help":return Vc(n.model,t,o);case "login":return Zo(n.model,t,o);case "workspace":return Yo(n.model,t,o);case "timer":return Js(n.model,t,o);case "stats":return oi(n.model,t,o);case "config":return si(n.model,t,o);case "problem":return ii(n.model,t,o);case "changelog":return Jo(n.model,t,o)}}function Kc(e,t){let o=[],n=Math.floor(t/2);for(let i=0;i<n-5;i++)o.push("");let r=st(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 Vc(e,t,o){let n=[],r=Math.max(20,t),s=Math.max(8,o);n.push(...ot(`${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=nt([{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=li(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 zc(){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 rn(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(we(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 li(e){let t=zc();if(e<90){let i=[];for(let a of t)i.push(...rn(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=rn(t[i],r),l=t[i+1]?rn(t[i+1],s):[],u=Math.max(a.length,l.length);o.push(...rt(a,l,e,u,n)),o.push("");}return o}function ci(e,t){let o=Math.max(20,e),n=Math.max(8,t),r=Math.max(3,n-5);return Math.max(0,li(o).length-r)}function Yc(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]??"";O(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 ui(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,...sn(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 io(t,e);if(t.screenState.screen==="problem"){let n=t.screenState.model;if(n.drawerMode!=="none"){let[r,s]=ro({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 io(t,e)}return t.screenState.screen==="login"?io(t,e):[{...t,...sn(t),needsRender:true},c.none()]}return io(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,...sn(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]=no(e.slug);return [{...t,...fe(t,{screen:"problem",model:o}),needsRender:true},n]}case "FETCH_RANDOM_SUCCESS":{let[o,n]=no(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 gi(e,t)}}function fe(e,t){return {screenState:t,history:[...e.history,e.screenState],globalError:null}}function sn(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 io(e,t){let{screenState:o}=e;switch(o.screen){case "home":return pi(e,t);case "list":return Qc(e,t);case "problem":return Jc(e,t);case "timer":case "stats":case "config":return Zc(e,t);case "help":return eu(e,t);case "workspace":return pu(e,t);case "changelog":return gu(e,t);case "login":return du(e,t);default:return [e,c.none()]}}function pi(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]=Ho();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]=Ho();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]=Ls();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]=Fs();return [{...e,...fe(e,{screen:"workspace",model:r}),needsRender:true},s]}if(o.name==="c"){let[r,s]=Rs();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]=Gs();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]=Jt({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]=Jt({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 pi(e,{type:"KEY_PRESS",key:{name:s,sequence:s,ctrl:false,meta:false,shift:false}})}return [e,c.none()]}function Qc(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]=no(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]=Uo(r,n,e.terminalHeight);return [{...e,screenState:{screen:"list",model:s},needsRender:true},i]}return [e,c.none()]}function gi(e,t){let{screenState:o}=t,n=t.terminalHeight;switch(o.screen){case "list":{if(!tu(e))return [t,c.none()];let[r,s]=Uo(e,o.model,n);return [{...t,screenState:{screen:"list",model:r},needsRender:true},s]}case "home":{if(!ou(e))return [t,c.none()];let[r,s]=Jt(e,o.model);return [{...t,screenState:{screen:"home",model:r},needsRender:true},s]}case "timer":{if(!nu(e))return [t,c.none()];let[r,s]=Xt(e,o.model);return [{...t,screenState:{screen:"timer",model:r},needsRender:true},s]}case "stats":{if(!ru(e))return [t,c.none()];let[r,s]=Bo(e,o.model);return [{...t,screenState:{screen:"stats",model:r},needsRender:true},s]}case "config":{if(!su(e))return [t,c.none()];let[r,s]=jo(e,o.model);return [{...t,screenState:{screen:"config",model:r},needsRender:true},s]}case "help":{if(!iu(e))return [t,c.none()];let r=o.model,s=ci(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(!lu(e))return [t,c.none()];let[r,s]=Qo(e,o.model);return [{...t,screenState:{screen:"workspace",model:r},needsRender:true},s]}case "problem":{if(!au(e))return [t,c.none()];let[r,s]=ro(e,o.model,n,t.terminalWidth);return [{...t,screenState:{...o,model:r},needsRender:true},s]}case "changelog":{if(!cu(e))return [t,c.none()];let[r,s]=Xo(e,o.model,n,t.terminalWidth);return [{...t,screenState:{screen:"changelog",model:r},needsRender:true},s]}case "login":{if(!uu(e))return [t,c.none()];let[r,s]=en(e,o.model);return [{...t,screenState:{screen:"login",model:r},needsRender:true},s]}default:return [t,c.none()]}}function Jc(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=Xc(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]=ro(r,n,e.terminalHeight,e.terminalWidth);return [{...e,screenState:{screen:"problem",model:i},needsRender:true},a]}return [e,c.none()]}function Xc(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 Zc(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]=Xt({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]=Xt({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]=jo(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]=Bo({type:"STATS_REFRESH"},r);return [{...e,screenState:{...n,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,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?gi(n,e):[e,c.none()]}function tu(e){return e.type.startsWith("LIST_")}function ou(e){return e.type.startsWith("HOME_")}function nu(e){return e.type.startsWith("TIMER_")}function ru(e){return e.type.startsWith("STATS_")}function su(e){return e.type.startsWith("CONFIG_")}function iu(e){return e.type.startsWith("HELP_")}function au(e){return e.type.startsWith("PROBLEM_")}function lu(e){return e.type.startsWith("WORKSPACE_")}function cu(e){return e.type.startsWith("CHANGELOG_")}function uu(e){return e.type.startsWith("LOGIN_")}function pu(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]=Qo(r,n);return [{...e,screenState:{screen:"workspace",model:s},needsRender:true},i]}return [e,c.none()]}function gu(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]=Xo(s,i.model,r.terminalHeight,r.terminalWidth);return [{...r,screenState:{screen:"changelog",model:a},needsRender:true},l]}}function du(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]=en(i,s.screenState.model);return [{...s,screenState:{screen:"login",model:a},needsRender:true},l]}}var yu="https://raw.githubusercontent.com/night-slayer18/leetcode-cli/main/docs/releases.md",Pe=null;function an(e,t){switch(e.type){case "CMD_NONE":return;case "CMD_BATCH":for(let o of e.commands)an(o,t);return;case "CMD_FETCH_STATS":Cu(t);return;case "CMD_CHECK_AUTH":hu(t);return;case "CMD_FETCH_PROBLEMS":Su(e.filters,e.append,t);return;case "CMD_FETCH_PROBLEM_DETAIL":bu(e.slug,t);return;case "CMD_START_TIMER_SUBSCRIPTION":Pe&&clearInterval(Pe),Pe=setInterval(()=>{t({type:"TIMER_TICK"});},e.intervalMs);return;case "CMD_STOP_TIMER_SUBSCRIPTION":Pe&&(clearInterval(Pe),Pe=null);return;case "CMD_PICK_PROBLEM":wu(e.slug,t);return;case "CMD_TEST_SOLUTION":Mu(e.slug,t);return;case "CMD_SUBMIT_SOLUTION":_u(e.slug,t);return;case "CMD_SAVE_CONFIG":Eu(e.key,e.value);return;case "CMD_EXIT":ao();return;case "CMD_FETCH_DAILY":ku(t);return;case "CMD_FETCH_RANDOM":Tu(t);return;case "CMD_FETCH_SUBMISSIONS":Pu(e.slug,t);return;case "CMD_LOAD_NOTE":Lu(e.problemId,t);return;case "CMD_DIFF_SNAPSHOT":xu(e.slug,e.snapshotId,t);return;case "CMD_RESTORE_SNAPSHOT":Ru(e.slug,e.snapshotId,t);return;case "CMD_FETCH_CHANGELOG":Ou(t);return;case "CMD_LOGOUT":$u(t);return;case "CMD_LOGIN":vu(e.session,e.csrf,t);return;default:return}}async function hu(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 Su(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 bu(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 Cu(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 Eu(e,t){switch(e){case "language":_.setLanguage(t);break;case "editor":_.setEditor(t);break;case "workdir":_.setWorkDir(t);break;case "repo":_.setRepo(t);break}}async function ln(e){let t=_.getLanguage(),o=await S.getProblem(e),n=Bt(t,o.codeSnippets),r=Ye(o.questionFrontendId,o.titleSlug,t),s=_.getWorkDir(),i=o.difficulty,a=o.topicTags.length>0?o.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",l=$e.join(s,i,a,r);try{return {code:await Oe.readFile(l,"utf-8"),lang:n,questionId:o.questionId}}catch{let g=$e.join(s,r);try{return {code:await Oe.readFile(g,"utf-8"),lang:n,questionId:o.questionId}}catch{throw new Error(`Could not read solution file at ${l}. Make sure you have picked the problem first.`)}}}async function wu(e,t){try{let o=await S.getProblem(e),n=_.getLanguage(),r=Be(n);if(!r)throw new Error(`Unsupported language: ${n}`);let s=o.codeSnippets??[],i=Wt(s,r);if(s.length>0&&!i)throw new Error(`No code template available for ${r}`);let a=i?i.code:jt(r,o.title),l=Gt(o.questionFrontendId,o.titleSlug,o.title,o.difficulty,a,r,o.content??void 0),u=_.getWorkDir(),g=o.difficulty,d=o.topicTags.length>0?o.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",m=$e.join(u,g,d);try{await Oe.mkdir(m,{recursive:!0});}catch{}let b=Ye(o.questionFrontendId,o.titleSlug,r),M=$e.join(m,b);existsSync(M)?t({type:"PROBLEM_ACTION_SUCCESS",message:`File ready: ${b}`}):(await Oe.writeFile(M,l,"utf-8"),t({type:"PROBLEM_ACTION_SUCCESS",message:`Created ${b}`}));}catch(o){t({type:"PROBLEM_ACTION_ERROR",error:o instanceof Error?o.message:"Failed to pick problem"});}}async function Mu(e,t){try{let{code:o,lang:n}=await ln(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 _u(e,t){try{let{code:o,lang:n}=await ln(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 ku(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 Tu(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 Lu(e,t){try{let o=$e.join(_.getWorkDir(),".notes"),n=$e.join(o,`${e}.md`);if(existsSync(n)){let r=await Oe.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 xu(e,t,o){try{let{code:n}=await ln(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 Ru(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=_.getLanguage(),l=Ye(n.questionFrontendId,n.titleSlug,s.language||a),u=_.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 Oe.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 Pu(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 Ou(e){e({type:"CHANGELOG_FETCH_START"});try{let t=await xi(yu).text();e({type:"CHANGELOG_FETCH_SUCCESS",content:t});}catch(t){e({type:"CHANGELOG_FETCH_ERROR",error:t.message||"Failed to fetch changelog"});}}function fi(){Pe&&(clearInterval(Pe),Pe=null);}function $u(e){ae.clear(),e({type:"AUTH_CHECK_COMPLETE",user:null});}async function vu(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 mi={"\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 yi(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;mi[o]?s=mi[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 Au="\x1B[?1049h",Du="\x1B[?1049l",Iu="\x1B[?25l",Nu="\x1B[?25h";function cn(){process.stdout.write(Au),process.stdout.write(Iu);}function un(){process.stdout.write(Nu),process.stdout.write(Du),process.stdout.write("\x1B[0m");}function pn(){process.stdin.isTTY&&process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8");}function gn(){process.stdin.isTTY&&process.stdin.setRawMode(false);}var ke,gt=false,Ge=true,dn=null,pt=false,kt=null,Tt=null,Lt=null;function ct(e){if(!gt)return;let t=ke.screenState.screen,[o,n]=ui(e,ke);ke=o,t!==o.screenState.screen&&(Ge=true,co="",Fe=[]),n.type!=="CMD_NONE"&&(n.type==="CMD_OPEN_EDITOR"?(Hu(),Kt(n.id,"edit",{silent:true}).catch(r=>{ct({type:"GLOBAL_ERROR",error:r instanceof Error?r.message:"Failed to open editor"});}).finally(()=>{Uu(),Ge=true,Fe=[],ke={...ke,needsRender:true},ct({type:"PROBLEM_VIEW_NOTE"}),hi();})):an(n,ct)),ke.needsRender&&(hi(),ke={...ke,needsRender:false});}var co="",Fe=[],lt="\x1B[0m";function hi(){if(!gt)return;let e=ai(ke);if(e===co)return;co=e;let t=e.split(`
|
|
273
|
+
`);if(Ge||Fe.length===0){stdout.write(lt),stdout.write(lo.cursorTo(0,0)),stdout.write(lo.eraseScreen),stdout.write(e),stdout.write(lt),Ge=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(lt),n.push(lo.cursorTo(0,r)),n.push(lo.eraseLine),i.length>0&&n.push(i),n.push(lt));}n.length>0&&stdout.write(n.join("")),Fe=t;}function Si(e){if(pt||!gt)return;let t=yi(e);ct({type:"KEY_PRESS",key:t});}var fn=false;function Fu(){fn||(fn=true,gt=false,pt=false,stdin.off("data",Si),kt&&(stdout.off("resize",kt),kt=null),Tt&&(process.off("SIGINT",Tt),Tt=null),Lt&&(process.off("SIGTERM",Lt),Lt=null),fi(),stdout.write(lt),un(),uo.show(),gn(),stdin.pause(),dn?.(),dn=null);}function Hu(){pt||(pt=true,stdout.write(lt),un(),uo.show(),gn(),stdin.pause());}function Uu(){!gt||!pt||(pt=false,cn(),uo.hide(),pn(),stdin.resume(),Ge=true);}async function bi(e){if(!stdin.isTTY||!stdout.isTTY)throw new Error("TUI requires an interactive terminal");let t=new Promise(o=>{dn=o;});return ke=e,gt=true,fn=false,Ge=true,co="",Fe=[],cn(),uo.hide(),pn(),stdin.on("data",Si),kt=()=>{ct({type:"RESIZE",width:stdout.columns||80,height:stdout.rows||24}),Ge=true;},stdout.on("resize",kt),ct({type:"INIT"}),Tt=()=>{ao();},Lt=()=>{ao();},process.on("SIGINT",Tt),process.on("SIGTERM",Lt),await t}function ao(){Fu();}async function Ci(e={}){let{username:t}=e,o=Ts(t);await bi(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.4.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(An);N.command("logout").description("Clear stored credentials").action(Dn);N.command("whoami").description("Check current login status").action(In);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(Yn);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(It);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(Qn);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(kr);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(Tr);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 Me(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(pr);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(yr);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(br);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(ls);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(Rr);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)=>_r(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(Dr);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(vr);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(Kt);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(Ir);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: ${sr()}`)}
|
|
416
|
+
`).action(async e=>{e.interactive?await Or():await Pr(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)=>Nr(e,t));var xt=N.command("workspace").description("Manage workspaces for different contexts");xt.command("current").description("Show current workspace").action(cs);xt.command("list").description("List all workspaces").action(us);xt.command("create <name>").description("Create a new workspace").option("-w, --workdir <path>","Set working directory for this workspace").action(ps);xt.command("use <name>").description("Switch to a workspace").action(gs);xt.command("delete <name>").description("Delete a workspace").action(ds);var dt=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
|
+
`);dt.command("host <problemId>").description("Host a collaboration session").action(Ur);dt.command("join <roomCode>").description("Join a collaboration session").action(Br);dt.command("sync").description("Sync your code with partner").action(Wr);dt.command("compare").description("Compare your solution with partner").action(jr);dt.command("leave").description("Leave the collaboration session").action(Gr);dt.command("status").description("Show collaboration status").action(qr);var Rt=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
|
+
`);Rt.command("save <id> [name]").description("Save current solution as a snapshot").action(es);Rt.command("list <id>").description("List all snapshots for a problem").action(ts);Rt.command("restore <id> <snapshot>").description("Restore a snapshot").action(os);Rt.command("diff <id> <snap1> <snap2>").description("Compare two snapshots").action(ns);Rt.command("delete <id> <snapshot>").description("Delete a snapshot").action(rs);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(Es);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)=>ks(e,t));N.showHelpAfterError("(add --help for additional information)");var Wu=process.argv.length>2&&!["update","changelog","--version","-v","--help","-h"].includes(process.argv[2]);Wu&&ws().catch(()=>{});var Ei=process.argv.slice(2);Ei.length===0&&process.stdout.isTTY?Ci({username:""}).catch(e=>{console.error("Failed to launch TUI:",e.message),process.exit(1);}):Ei.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();
|