@night-slayer18/leetcode-cli 2.1.0 → 2.2.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/README.md +12 -0
- package/dist/index.js +78 -67
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -74,6 +74,7 @@ leetcode submit 1
|
|
|
74
74
|
| `today` | Show daily progress & challenge |
|
|
75
75
|
| `list` | List problems with filters |
|
|
76
76
|
| `show <id>` | Display problem description |
|
|
77
|
+
| `hint <id>` | Show hints for a problem |
|
|
77
78
|
| `pick <id>` | Generate solution file |
|
|
78
79
|
| `pick-batch <ids>` | Pick multiple problems |
|
|
79
80
|
| `bookmark <action>` | Manage problem bookmarks |
|
|
@@ -122,6 +123,17 @@ leetcode show 1
|
|
|
122
123
|
leetcode show two-sum
|
|
123
124
|
```
|
|
124
125
|
|
|
126
|
+
### Get Hints
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
# Show hints one at a time (press Enter for next)
|
|
130
|
+
leetcode hint 1
|
|
131
|
+
leetcode hint two-sum
|
|
132
|
+
|
|
133
|
+
# Show all hints at once
|
|
134
|
+
leetcode hint 1 --all
|
|
135
|
+
```
|
|
136
|
+
|
|
125
137
|
### Pick Problem
|
|
126
138
|
|
|
127
139
|
```bash
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {Command}from'commander';import l from'chalk';import
|
|
2
|
+
import {Command}from'commander';import l from'chalk';import to from'inquirer';import je from'ora';import kn from'got';import {z}from'zod';import vn from'conf';import {homedir}from'os';import {join,dirname,basename,extname,resolve,sep}from'path';import We from'cli-table3';import {mkdir,writeFile,readFile,readdir}from'fs/promises';import {existsSync,writeFileSync,readFileSync,unlinkSync,mkdirSync}from'fs';import {execSync,spawn}from'child_process';import Hn from'open';import {createClient}from'@supabase/supabase-js';import {diffLines}from'diff';import {fileURLToPath}from'url';var wn=z.object({name:z.string(),slug:z.string()}),Sn=z.object({name:z.string(),slug:z.string()}),$n=z.object({lang:z.string(),langSlug:z.string(),code:z.string()}),xe=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(wn),status:z.enum(["ac","notac"]).nullable()}),co=xe.extend({content:z.string().nullable(),codeSnippets:z.array($n).nullable(),sampleTestCase:z.string(),exampleTestcases:z.string(),hints:z.array(z.string()),companyTags:z.array(Sn).nullable(),stats:z.string()}),go=z.object({date:z.string(),link:z.string(),question:xe}),mo=z.object({id:z.string(),statusDisplay:z.string(),lang:z.string(),runtime:z.string(),timestamp:z.string(),memory:z.string()}),uo=z.object({code:z.string(),lang:z.object({name:z.string()})}),po=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()}),fo=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()}),yo=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()})}),ho=z.object({isSignedIn:z.boolean(),username:z.string().nullable()});var bo=`
|
|
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 eo from'inquirer';im
|
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
|
-
`,
|
|
27
|
+
`,wo=`
|
|
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 eo from'inquirer';im
|
|
|
54
54
|
status
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
|
-
`,
|
|
57
|
+
`,So=`
|
|
58
58
|
query globalData {
|
|
59
59
|
userStatus {
|
|
60
60
|
isSignedIn
|
|
61
61
|
username
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
|
-
|
|
64
|
+
`,$o=`
|
|
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 eo from'inquirer';im
|
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
|
-
|
|
85
|
+
`,ko=`
|
|
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 eo from'inquirer';im
|
|
|
104
104
|
}
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
|
-
`,
|
|
107
|
+
`,vo=`
|
|
108
108
|
query questionOfToday {
|
|
109
109
|
activeDailyCodingChallengeQuestion {
|
|
110
110
|
date
|
|
@@ -125,7 +125,7 @@ import {Command}from'commander';import l from'chalk';import eo from'inquirer';im
|
|
|
125
125
|
}
|
|
126
126
|
}
|
|
127
127
|
}
|
|
128
|
-
`,
|
|
128
|
+
`,Co=`
|
|
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 eo from'inquirer';im
|
|
|
142
142
|
}
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
|
-
`,
|
|
145
|
+
`,Po=`
|
|
146
146
|
query randomQuestion($categorySlug: String, $filters: QuestionListFilterInput) {
|
|
147
147
|
randomQuestion(categorySlug: $categorySlug, filters: $filters) {
|
|
148
148
|
titleSlug
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
|
-
`,
|
|
151
|
+
`,To=`
|
|
152
152
|
query submissionDetails($submissionId: Int!) {
|
|
153
153
|
submissionDetails(submissionId: $submissionId) {
|
|
154
154
|
code
|
|
@@ -157,44 +157,47 @@ import {Command}from'commander';import l from'chalk';import eo 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 ${o} problems`));}function
|
|
160
|
+
`;var Le="https://leetcode.com",Oe=class{client;credentials=null;constructor(){this.client=kn.extend({prefixUrl:Le,headers:{"Content-Type":"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",Origin:Le,Referer:`${Le}/`},timeout:{request:3e4},retry:{limit:2}});}setCredentials(o){this.credentials=o,this.client=this.client.extend({headers:{Cookie:`LEETCODE_SESSION=${o.session}; csrftoken=${o.csrfToken}`,"X-CSRFToken":o.csrfToken}});}getCredentials(){return this.credentials}async graphql(o,t={}){let n=await this.client.post("graphql",{json:{query:o,variables:t}}).json();if(n.errors?.length)throw new Error(`GraphQL Error: ${n.errors[0].message}`);return n.data}async checkAuth(){let o=await this.graphql(So);return ho.parse(o.userStatus)}async getProblems(o={}){let t={categorySlug:"",limit:o.limit??50,skip:o.skip??0,filters:{}};o.difficulty&&(t.filters.difficulty=o.difficulty),o.status&&(t.filters.status=o.status),o.tags?.length&&(t.filters.tags=o.tags),o.searchKeywords&&(t.filters.searchKeywords=o.searchKeywords);let n=await this.graphql(bo,t),r=z.array(xe).parse(n.problemsetQuestionList.questions);return {total:n.problemsetQuestionList.total,problems:r}}async getProblem(o){let t=await this.graphql(wo,{titleSlug:o});return co.parse(t.question)}async getProblemById(o){let{problems:t}=await this.getProblems({searchKeywords:o,limit:10}),n=t.find(r=>r.questionFrontendId===o);if(!n)throw new Error(`Problem #${o} not found`);return this.getProblem(n.titleSlug)}async getDailyChallenge(){let o=await this.graphql(vo);return go.parse(o.activeDailyCodingChallengeQuestion)}async getRandomProblem(o={}){let t={categorySlug:"",filters:{}};o.difficulty&&(t.filters.difficulty=o.difficulty),o.tags?.length&&(t.filters.tags=o.tags);let n=await this.graphql(Po,t);return z.object({titleSlug:z.string()}).parse(n.randomQuestion).titleSlug}async getUserProfile(o){let n=(await this.graphql($o,{username:o})).matchedUser,r=yo.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(o){return (await this.graphql(ko,{username:o})).matchedUser.tagProblemCounts}async getSubmissionList(o,t=20,n=0){let r=await this.graphql(Co,{questionSlug:o,limit:t,offset:n});return z.array(mo).parse(r.questionSubmissionList.submissions)}async getSubmissionDetails(o){let t=await this.graphql(To,{submissionId:o});return uo.parse(t.submissionDetails)}async testSolution(o,t,n,r,s){let i=await this.client.post(`problems/${o}/interpret_solution/`,{json:{data_input:r,lang:n,typed_code:t,question_id:s}}).json();return this.pollSubmission(i.interpret_id,"interpret",po)}async submitSolution(o,t,n,r){let s=await this.client.post(`problems/${o}/submit/`,{json:{lang:n,typed_code:t,question_id:r}}).json();return this.pollSubmission(s.submission_id.toString(),"submission",fo)}async pollSubmission(o,t,n){let r=`submissions/detail/${o}/check/`,s=12,i=500,a=3e3;for(let g=0;g<s;g++){try{let p=await this.client.get(r).json();if(p.state==="SUCCESS"||p.state==="FAILURE")return n.parse(p)}catch(p){if(g===s-1){let b=t==="interpret"?"Test":"Submission";throw new Error(`${b} check failed: ${p instanceof Error?p.message:"Network error"}`)}}let u=Math.min(i*Math.pow(2,g),a);await new Promise(p=>setTimeout(p,u));}let c=t==="interpret"?"Test":"Submission";throw new Error(`${c} timeout: Result not available after 30 seconds`)}},h=new Oe;var ge=new vn({configName:"credentials",cwd:join(homedir(),".leetcode"),defaults:{}}),X={get(){let e=ge.get("session"),o=ge.get("csrfToken");return !e||!o?null:{session:e,csrfToken:o}},set(e){ge.set("session",e.session),ge.set("csrfToken",e.csrfToken);},clear(){ge.clear();},getPath(){return ge.path}};async function xo(){console.log(),console.log(l.cyan("LeetCode CLI Login")),console.log(l.gray("\u2500".repeat(40))),console.log(),console.log(l.yellow("To login, you need to provide your LeetCode session cookies.")),console.log(l.gray("1. Open https://leetcode.com in your browser")),console.log(l.gray("2. Login to your account")),console.log(l.gray("3. Open DevTools (F12) \u2192 Application \u2192 Cookies \u2192 leetcode.com")),console.log(l.gray("4. Copy the values of LEETCODE_SESSION and csrftoken")),console.log();let e=await to.prompt([{type:"password",name:"session",message:"LEETCODE_SESSION:",mask:"*",validate:n=>n.length>0||"Session token is required"},{type:"password",name:"csrfToken",message:"csrftoken:",mask:"*",validate:n=>n.length>0||"CSRF token is required"}]),o={session:e.session.trim(),csrfToken:e.csrfToken.trim()},t=je("Verifying credentials...").start();try{h.setCredentials(o);let{isSignedIn:n,username:r}=await h.checkAuth();if(!n||!r){t.fail("Invalid credentials"),console.log(l.red("Please check your session cookies and try again."));return}X.set(o),t.succeed(`Logged in as ${l.green(r)}`),console.log(),console.log(l.gray(`Credentials saved to ${X.getPath()}`));}catch(n){t.fail("Authentication failed"),n instanceof Error&&console.log(l.red(n.message));}}async function Eo(){X.clear(),console.log(l.green("\u2713 Logged out successfully"));}async function Lo(){let e=X.get();if(!e){console.log(l.yellow('Not logged in. Run "leetcode login" to authenticate.'));return}let o=je("Checking session...").start();try{h.setCredentials(e);let{isSignedIn:t,username:n}=await h.checkAuth();if(!t||!n){o.fail("Session expired"),console.log(l.yellow('Please run "leetcode login" to re-authenticate.'));return}o.succeed(`Logged in as ${l.green(n)}`);}catch(t){o.fail("Failed to check session"),t instanceof Error&&console.log(l.red(t.message));}}async function $(){let e=X.get();if(!e)return console.log(l.yellow("\u26A0\uFE0F Please login first: leetcode login")),{authorized:false};try{h.setCredentials(e);let{isSignedIn:o,username:t}=await h.checkAuth();return o?{authorized:!0,username:t??void 0}:(console.log(l.yellow("\u26A0\uFE0F Session expired. Please run: leetcode login")),{authorized:!1})}catch{return console.log(l.yellow("\u26A0\uFE0F Session validation failed. Please run: leetcode login")),{authorized:false}}}var Dn={"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 xn(e){for(let o of e){let t=Dn[o.name];if(t)return t}return null}function Ao(e){try{return JSON.parse(e)}catch{return e}}function oe(e){return Array.isArray(e)&&e.length>0&&Array.isArray(e[0])}function Ro(e,o){if(!Array.isArray(e)||e.length===0)return String(e);let t=Math.max(...e.map(i=>String(i).length),1),n=Math.max(t,3),r=e.map((i,a)=>`[${a}]`.padStart(n).padEnd(n)).join(" "),s=e.map((i,a)=>{let c=String(i).padStart(n).padEnd(n);return o&&Array.isArray(o)&&o[a]!==i?l.red.bold(c):c}).join(" ");return `${l.gray(r)}
|
|
161
|
+
${s}`}function Fo(e,o){return Array.isArray(e)?e.length===0?l.gray("(empty)"):e.map((n,r)=>{let s=String(n);return o&&Array.isArray(o)&&(r>=o.length||o[r]!==n)?l.red.bold(s):s}).join(l.gray(" \u2192 ")):String(e)}function _o(e){if(!Array.isArray(e)||e.length===0)return l.gray("(empty tree)");let o=[],t=Math.floor(Math.log2(e.length))+1,n=Math.pow(2,t)*3;function r(s,i,a,c){if(i>e.length-1)return;let g=[],u=[],p=Math.floor(n/Math.pow(2,s+1));for(let b=i;b<=a&&b<e.length;b++){let C=e[b],I=C===null?" ":String(C);g.push(I.padStart(p).padEnd(p));let R=2*b+1,q=2*b+2,ee=R<e.length&&e[R]!==null,ie=q<e.length&&e[q]!==null;if(ee||ie){let V="";ee?V+="/":V+=" ",V+=" ",ie?V+="\\":V+=" ",u.push(V.padStart(p).padEnd(p));}}g.length>0&&(o.push(g.join("")),u.length>0&&s<t-1&&o.push(u.join("")));}for(let s=0;s<t;s++){let i=Math.pow(2,s)-1,a=Math.pow(2,s+1)-2;r(s,i,a);}return o.join(`
|
|
162
|
+
`)}function Ae(e,o){if(!oe(e)||e.length===0)return String(e);let t=e.length,n=e[0].length,r=3,s=[],i=" "+e[0].map((a,c)=>String(c).padStart(r).padEnd(r)).join(" ");s.push(l.gray(i)),s.push(" \u250C"+Array(n).fill("\u2500\u2500\u2500").join("\u252C")+"\u2510");for(let a=0;a<t;a++){let c=e[a].map((g,u)=>{let p=String(g).padStart(2);return o&&oe(o)&&o[a]&&o[a][u]!==g?l.red.bold(p):p}).join(" \u2502 ");s.push(l.gray(` ${a} `)+`\u2502 ${c} \u2502`),a<t-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 No(e){return oe(e)?e.map((t,n)=>{let r=Array.isArray(t)?t.join(", "):String(t);return ` ${l.cyan(String(n))} \u2192 [${r}]`}).join(`
|
|
164
|
+
`):String(e)}function Io(e,o,t){let n=Ao(e),r=Ao(o),s=e===o,i=xn(t),a,c;if(oe(n)){let g=oe(r)?r:void 0;return a=Ae(n,g),c=oe(r)?Ae(r):String(o),{outputVis:a,expectedVis:c,matches:s}}if(i===null)return {outputVis:String(e),expectedVis:String(o),matches:s,unsupported:true};switch(i){case "linkedlist":a=Fo(n,r),c=Fo(r);break;case "tree":a=_o(n),c=_o(r);break;case "graph":a=No(n),c=No(r);break;case "matrix":let g=oe(r)?r:void 0;a=Ae(n,g),c=oe(r)?Ae(r):String(o);break;case "array":case "string":Array.isArray(n)?(a=Ro(n,r),c=Array.isArray(r)?Ro(r):String(o)):(a=s?String(e):l.red.bold(String(e)),c=String(o));break}return {outputVis:a,expectedVis:c,matches:s}}function Uo(e,o){let t=new We({head:[l.cyan("ID"),l.cyan("Title"),l.cyan("Difficulty"),l.cyan("Rate"),l.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}`),t.push([n.questionFrontendId,r.length>42?r.slice(0,39)+"...":r,Re(n.difficulty),`${n.acRate.toFixed(1)}%`,En(n.status)]);}console.log(t.toString()),console.log(l.gray(`
|
|
165
|
+
Showing ${e.length} of ${o} problems`));}function jo(e){console.log();let o=e.isPaidOnly?"\u{1F512} ":"";if(console.log(l.bold.cyan(` ${e.questionFrontendId}. ${o}${e.title}`)),console.log(` ${Re(e.difficulty)}`),console.log(l.gray(` https://leetcode.com/problems/${e.titleSlug}/`)),console.log(),e.isPaidOnly&&(console.log(l.yellow(" \u26A0\uFE0F Premium Problem")),console.log(l.gray(" This problem requires a LeetCode Premium subscription.")),console.log(l.gray(" Visit the URL above to view on LeetCode.")),console.log()),e.topicTags.length){let n=e.topicTags.map(r=>l.bgBlue.white(` ${r.name} `)).join(" ");console.log(` ${n}`),console.log();}console.log(l.gray("\u2500".repeat(60))),console.log();let t=e.content;if(!t){console.log(l.yellow(" \u{1F512} Premium Content")),console.log(l.gray(" Problem description is not available directly.")),console.log(l.gray(" Please visit the URL above to view on LeetCode.")),console.log();return}t=t.replace(/<sup>(.*?)<\/sup>/gi,"^$1"),t=t.replace(/<strong class="example">Example (\d+):<\/strong>/gi,"\xA7EXAMPLE\xA7$1\xA7"),t=t.replace(/Input:/gi,"\xA7INPUT\xA7"),t=t.replace(/Output:/gi,"\xA7OUTPUT\xA7"),t=t.replace(/Explanation:/gi,"\xA7EXPLAIN\xA7"),t=t.replace(/<strong>Constraints:<\/strong>/gi,"\xA7CONSTRAINTS\xA7"),t=t.replace(/Constraints:/gi,"\xA7CONSTRAINTS\xA7"),t=t.replace(/<strong>Follow-up:/gi,"\xA7FOLLOWUP\xA7"),t=t.replace(/Follow-up:/gi,"\xA7FOLLOWUP\xA7"),t=t.replace(/<li>/gi," \u2022 "),t=t.replace(/<\/li>/gi,`
|
|
166
166
|
`),t=t.replace(/<\/p>/gi,`
|
|
167
167
|
|
|
168
168
|
`),t=t.replace(/<br\s*\/?>/gi,`
|
|
169
|
-
`),t=t.replace(/<[^>]+>/g,""),t=t.replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'").replace(/≤/g,"\u2264").replace(/≥/g,"\u2265").replace(/&#(\d+);/g,(n,
|
|
169
|
+
`),t=t.replace(/<[^>]+>/g,""),t=t.replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'").replace(/≤/g,"\u2264").replace(/≥/g,"\u2265").replace(/&#(\d+);/g,(n,r)=>String.fromCharCode(parseInt(r,10))),t=t.replace(/\n{3,}/g,`
|
|
170
170
|
|
|
171
|
-
`).trim(),t=t.replace(/§EXAMPLE§(\d+)§/g,(n,
|
|
171
|
+
`).trim(),t=t.replace(/§EXAMPLE§(\d+)§/g,(n,r)=>l.green.bold(`\u{1F4CC} Example ${r}:`)),t=t.replace(/§INPUT§/g,l.yellow("Input:")),t=t.replace(/§OUTPUT§/g,l.yellow("Output:")),t=t.replace(/§EXPLAIN§/g,l.gray("Explanation:")),t=t.replace(/§CONSTRAINTS§/g,l.cyan.bold(`
|
|
172
172
|
\u{1F4CB} Constraints:`)),t=t.replace(/§FOLLOWUP§/g,l.magenta.bold(`
|
|
173
|
-
\u{1F4A1} Follow-up:`)),console.log(t),console.log();}function
|
|
173
|
+
\u{1F4A1} Follow-up:`)),console.log(t),console.log();}function Mo(e,o){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));return}e.correct_answer?console.log(l.green.bold("\u2713 All test cases passed!")):console.log(l.yellow.bold("\u2717 Some test cases failed"));let t=e.code_answer??[],n=e.expected_code_answer??[];if(o&&t.length>0){console.log(),console.log(l.gray.bold("\u2500".repeat(50)));let s=t.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:c}=s[i],{outputVis:g,expectedVis:u,matches:p,unsupported:b}=Io(a,c,o);console.log(),console.log(l.gray(`Test Case ${i+1}:`)),b&&(console.log(l.yellow(" \u26A0 No visualization available for this problem type")),console.log(l.gray(` Tags: ${o.map(C=>C.name).join(", ")}`))),console.log(),console.log(l.cyan(" Your Output:")),g.split(`
|
|
174
174
|
`).forEach(C=>console.log(` ${C}`)),console.log(),console.log(l.cyan(" Expected:")),u.split(`
|
|
175
|
-
`).forEach(C=>console.log(` ${C}`)),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
|
|
176
|
-
Page ${
|
|
175
|
+
`).forEach(C=>console.log(` ${C}`)),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 s of t)console.log(l.white(` ${s}`));console.log(),console.log(l.gray("Expected Output:"));for(let s of n)console.log(l.white(` ${s}`));}let r=(e.std_output_list??[]).filter(s=>s);if(r.length>0){console.log(),console.log(l.gray("Stdout:"));for(let s of r)console.log(l.gray(` ${s}`));}}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,r,s){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([Re(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")(r.toString()),l.gray("days")),console.log(l.gray("\u{1F4C5} Total active days:"),l.white(s.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(Re(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 Re(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 En(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",r=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,r]);}console.log(o.toString());}async function Wo(e){let{authorized:o}=await $();if(!o)return;let t=je("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 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),s*r<i&&console.log(l.gray(`
|
|
176
|
+
Page ${s} of ${Math.ceil(i/r)}. Use --page to navigate.`));}catch(n){t.fail("Failed to fetch problems"),n instanceof Error&&console.log(l.red(n.message));}}async function Fe(e){let{authorized:o}=await $();if(!o)return;let t=je("Fetching problem...").start();try{let n;if(/^\d+$/.test(e)?n=await h.getProblemById(e):n=await h.getProblem(e),!n){t.fail(`Problem "${e}" not found`);return}t.stop(),jo(n);}catch(n){t.fail("Failed to fetch problem"),n instanceof Error&&console.log(l.red(n.message));}}async function Vo(e,o){let{authorized:t}=await $();if(!t)return;let n=je("Fetching problem hints...").start();try{let r;if(/^\d+$/.test(e)?r=await h.getProblemById(e):r=await h.getProblem(e),!r){n.fail(`Problem "${e}" not found`);return}n.stop(),console.log(),console.log(l.bold.cyan(`${r.questionFrontendId}. ${r.title}`)),console.log();let s=r.hints||[];if(s.length===0){console.log(l.yellow("\u26A0 No hints available for this problem.")),console.log(l.gray("Try working through the problem description and examples first!"));return}o.all?s.forEach((i,a)=>{zo(i,a+1,s.length);}):await Nn(s);}catch(r){n.fail("Failed to fetch problem hints"),r instanceof Error&&console.log(l.red(r.message));}}function zo(e,o,t){let n=_n(e);console.log(l.bold.yellow(`\u{1F4A1} Hint ${o}/${t}`)),console.log(l.white(n)),console.log();}function _n(e){return e.replace(/<code>/g,l.cyan("`")).replace(/<\/code>/g,l.cyan("`")).replace(/<b>/g,l.bold("")).replace(/<\/b>/g,"").replace(/<i>/g,l.italic("")).replace(/<\/i>/g,"").replace(/<br\s*\/?>/g,`
|
|
177
|
+
`).replace(/<p>/g,"").replace(/<\/p>/g,`
|
|
178
|
+
`).replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/ /g," ").replace(/"/g,'"').trim()}async function Nn(e){let t=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),n=r=>new Promise(s=>{if(r>=e.length){console.log(l.green("\u2713 All hints revealed! Good luck solving the problem!")),t.close(),s();return}zo(e[r],r+1,e.length),r<e.length-1?t.question(l.gray(`Press Enter for next hint (${e.length-r-1} remaining), or 'q' to quit: `),i=>{i.toLowerCase()==="q"?(console.log(l.gray(`
|
|
179
|
+
Good luck! You can always run this command again for more hints.`)),t.close(),s()):s(n(r+1));}):(console.log(l.green("\u2713 All hints revealed! Good luck solving the problem!")),t.close(),s());});await n(0);}var Qe=join(homedir(),".leetcode"),Ge=join(Qe,"workspaces.json"),_e=join(Qe,"workspaces");function Ie(e){existsSync(e)||mkdirSync(e,{recursive:true});}function ae(){return existsSync(Ge)?JSON.parse(readFileSync(Ge,"utf-8")):{active:"default",workspaces:[]}}function Ne(e){Ie(Qe),writeFileSync(Ge,JSON.stringify(e,null,2));}var k={ensureInitialized(){let e=ae();e.workspaces.length===0&&(this.create("default",{workDir:join(homedir(),"leetcode"),lang:"typescript"}),e.workspaces=["default"],e.active="default",Ne(e));},getActive(){return this.ensureInitialized(),ae().active},setActive(e){let o=ae();return o.workspaces.includes(e)?(o.active=e,Ne(o),true):false},list(){return this.ensureInitialized(),ae().workspaces},exists(e){return this.ensureInitialized(),ae().workspaces.includes(e)},create(e,o){let t=ae();if(t.workspaces.includes(e))return false;let n=join(_e,e);Ie(n),Ie(join(n,"snapshots"));let r=join(n,"config.json");return writeFileSync(r,JSON.stringify(o,null,2)),writeFileSync(join(n,"timer.json"),JSON.stringify({solveTimes:{},activeTimer:null},null,2)),writeFileSync(join(n,"collab.json"),JSON.stringify({session:null},null,2)),t.workspaces.push(e),Ne(t),true},delete(e){if(e==="default")return false;let o=ae();return o.workspaces.includes(e)?(o.workspaces=o.workspaces.filter(t=>t!==e),o.active===e&&(o.active="default"),Ne(o),true):false},getWorkspaceDir(e){let o=e??this.getActive();return join(_e,o)},getConfig(e){let o=e??this.getActive(),t=join(_e,o,"config.json");return existsSync(t)?JSON.parse(readFileSync(t,"utf-8")):{workDir:join(homedir(),"leetcode"),lang:"typescript"}},setConfig(e,o){let t=o??this.getActive(),n=join(_e,t);Ie(n);let s={...this.getConfig(t),...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 w={getConfig(){let e=k.getConfig();return {language:e.lang,editor:e.editor,workDir:e.workDir,repo:e.syncRepo}},setLanguage(e){k.setConfig({lang:e});},setEditor(e){k.setConfig({editor:e});},setWorkDir(e){k.setConfig({workDir:e});},setRepo(e){k.setConfig({syncRepo:e});},deleteRepo(){let e=k.getConfig();delete e.syncRepo,k.setConfig(e);},getLanguage(){return k.getConfig().lang},getEditor(){return k.getConfig().editor},getWorkDir(){return k.getConfig().workDir},getRepo(){return k.getConfig().syncRepo},getPath(){return join(k.getWorkspaceDir(),"config.json")},getActiveWorkspace(){return k.getActive()}};var me={typescript:"ts",javascript:"js",python3:"py",java:"java",cpp:"cpp",c:"c",csharp:"cs",go:"go",rust:"rs",kotlin:"kt",swift:"swift"},$e={typescript:"typescript",javascript:"javascript",python3:"python3",python:"python3",java:"java","c++":"cpp",cpp:"cpp",c:"c","c#":"csharp",csharp:"csharp",go:"go",golang:"go",rust:"rust",kotlin:"kotlin",swift:"swift"};function Go(e,o){let t=e.find(n=>$e[n.langSlug.toLowerCase()]===o);return t||(e[0]??null)}function Yo(e,o,t,n,r,s,i){let a=jn(s);return `${qn(a,e,t,n,o,i)}
|
|
177
180
|
|
|
178
|
-
${
|
|
179
|
-
`}function
|
|
181
|
+
${r}
|
|
182
|
+
`}function jn(e){return e==="python3"?{single:"#",blockStart:'"""',blockEnd:'"""',linePrefix:""}:{single:"//",blockStart:"/*",blockEnd:"*/",linePrefix:" * "}}function Mn(e){let o=e;return o=o.replace(/<sup>(.*?)<\/sup>/gi,"^$1"),o=o.replace(/<strong class="example">Example (\d+):<\/strong>/gi,`
|
|
180
183
|
Example $1:`),o=o.replace(/<li>/gi,"\u2022 "),o=o.replace(/<\/li>/gi,`
|
|
181
184
|
`),o=o.replace(/<\/p>/gi,`
|
|
182
185
|
|
|
183
186
|
`),o=o.replace(/<br\s*\/?>/gi,`
|
|
184
187
|
`),o=o.replace(/<[^>]+>/g,""),o=o.replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'").replace(/≤/g,"<=").replace(/≥/g,">=").replace(/&#(\d+);/g,(t,n)=>String.fromCharCode(parseInt(n,10))),o=o.replace(/\n{3,}/g,`
|
|
185
188
|
|
|
186
|
-
`).trim(),o}function
|
|
189
|
+
`).trim(),o}function qn(e,o,t,n,r,s){let i=e.linePrefix,a=[e.blockStart,`${i}${o}. ${t}`,`${i}Difficulty: ${n}`,`${i}https://leetcode.com/problems/${r}/`];if(s){a.push(`${i}`),a.push(`${i}${"\u2500".repeat(50)}`),a.push(`${i}`);let g=Mn(s).split(`
|
|
187
190
|
`);for(let u of g)if(u.length>70){let p=u.split(" "),b="";for(let C of p)(b+" "+C).length>70?(a.push(`${i}${b.trim()}`),b=C):b+=" "+C;b.trim()&&a.push(`${i}${b.trim()}`);}else a.push(`${i}${u}`);}return a.push(e.blockEnd),a.join(`
|
|
188
|
-
`)}function
|
|
189
|
-
// 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(
|
|
190
|
-
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
|
|
191
|
-
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=Ie({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=ae(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 C=await h.submitSolution(c,p,u,b.questionId);if(s.stop(),Mo(C),C.status_msg==="Accepted"){let I=B.getActiveTimer();if(I&&I.problemId===a){let R=B.stopTimer();if(R){B.recordSolveTime(a,b.title,b.difficulty,R.durationSeconds,I.durationMinutes);let q=Math.floor(R.durationSeconds/60),Z=R.durationSeconds%60,re=`${q}m ${Z}s`,H=R.durationSeconds<=I.durationMinutes*60;console.log(),console.log(l.bold("\u23F1\uFE0F Timer Result:")),console.log(` Solved in ${H?l.green(re):l.yellow(re)} (limit: ${I.durationMinutes}m)`),console.log(H?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 it=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function at(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 C=new Date(Date.UTC(b.getFullYear(),b.getMonth(),b.getDate())),I=Math.floor(C.getTime()/1e3).toString(),R=o[I]||0;c+=R,R>0&&g++;}let u=new Date(a);u.setDate(u.getDate()+6),n.push({start:`${it[a.getMonth()]} ${a.getDate()}`,end:`${it[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 lt(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 ct(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 gt(e,o={}){let{authorized:t,username:n}=await v();if(!t)return;let s=Ie("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){qo(i.username,i.realName,i.ranking,i.acSubmissionNum,i.streak,i.totalActiveDays);return}if(o.calendar&&(i.submissionCalendar?at(i.submissionCalendar):console.log(l.yellow("Calendar data not available."))),o.trend&&(i.submissionCalendar?ct(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(),lt(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 mt(){let{authorized:e}=await v();if(!e)return;let o=Ie("Fetching daily challenge...").start();try{let t=await h.getDailyChallenge();o.stop(),Oo(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 dt(e){let{authorized:o}=await v();if(!o)return;let t=Ie("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 Y(s,{open:e.open??!0}):(await Ae(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 ft(e,o){let{authorized:t}=await v();if(!t)return;let n=Ie("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:")),We([c])):console.log(l.yellow("No accepted submissions found in recent history."));}else We(a);if(o.download){let c=Ie("Downloading submission...").start(),g=a.find(gn=>gn.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(),C=s.difficulty,I=s.topicTags.length>0?s.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",R=join(b,C,I);existsSync(R)||await mkdir(R,{recursive:!0});let q=p.lang.name,Z=we[q]??"txt",re=ge[Z]??q,H=`${s.questionFrontendId}.${s.titleSlug}.submission-${g.id}.${re}`,ao=join(R,H);await writeFile(ao,p.code,"utf-8"),c.succeed(`Downloaded to ${l.green(H)}`),console.log(l.gray(`Path: ${ao}`));}}catch(s){n.fail("Failed to fetch submissions"),s instanceof Error&&console.log(l.red(s.message));}}var Xe=["typescript","javascript","python3","java","cpp","c","csharp","go","rust","kotlin","swift"];async function yt(e){if(!e.lang&&!e.editor&&!e.workdir){bt();return}if(e.lang){let o=e.lang.toLowerCase();if(!Xe.includes(o)){console.log(l.red(`Unsupported language: ${e.lang}`)),console.log(l.gray(`Supported: ${Xe.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 ht(){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 eo.prompt([{type:"list",name:"language",message:"Default programming language:",choices:Xe,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")),bt();}function bt(){let e=w.getConfig(),o=K.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 te=new fn({projectName:"leetcode-cli-bookmarks",defaults:{bookmarks:[]}}),ue={add(e){let o=te.get("bookmarks");return o.includes(e)?false:(te.set("bookmarks",[...o,e]),true)},remove(e){let o=te.get("bookmarks");return o.includes(e)?(te.set("bookmarks",o.filter(t=>t!==e)),true):false},list(){return te.get("bookmarks")},has(e){return te.get("bookmarks").includes(e)},count(){return te.get("bookmarks").length},clear(){te.set("bookmarks",[]);}};async function wt(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(!oe(o)){console.log(l.red(`Invalid problem ID: ${o}`)),console.log(l.gray("Problem ID must be a positive integer"));return}ue.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}ue.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 as();break;case "clear":let n=ue.count();n===0?console.log(l.yellow("No bookmarks to clear")):(ue.clear(),console.log(l.green(`\u2713 Cleared ${n} bookmark${n!==1?"s":""}`)));break}}async function as(){let e=ue.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 v();if(o){let t=Ie({text:"Fetching problem details...",spinner:"dots"}).start();try{let n=new Oe({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,ls(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 ls(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 $t(e,o){if(!oe(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 ds(s,e):await us(s,e);}async function ds(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 us(e,o){if(!existsSync(e)){let t=await ps(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 Se(e);}async function ps(e){let o=`# Problem ${e} Notes
|
|
191
|
+
`)}function Qo(e,o,t){let n=me[t];return `${e}.${o}.${n}`}var Vn=["vim","nvim","vi","nano","emacs","micro","helix"],zn=["code","code-insiders","cursor","codium","vscodium"];async function ke(e,o){let t=w.getEditor()??process.env.EDITOR??"code",n=w.getWorkDir();if(Vn.includes(t)){console.log(),console.log(l.gray(`Open with: ${t} ${e}`));return}try{if(zn.includes(t)){spawn(t,["-r",n,"-g",e],{detached:!0,stdio:"ignore"}).unref();return}await Hn(e,{app:{name:t}});}catch{}}async function Q(e,o){let{authorized:t}=await $();if(!t)return false;let n=je({text:"Fetching problem details...",spinner:"dots"}).start();try{let r;if(/^\d+$/.test(e)?r=await h.getProblemById(e):r=await h.getProblem(e),!r)return n.fail(`Problem "${e}" not found`),!1;n.text="Generating solution file...";let s=o.lang?.toLowerCase()??w.getLanguage(),i=$e[s]??s,a=r.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 - ${r.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(r.questionFrontendId,r.titleSlug,r.title,r.difficulty,g,i,r.content??void 0),p=w.getWorkDir(),b=r.difficulty,C=r.topicTags.length>0?r.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",I=join(p,b,C);existsSync(I)||await mkdir(I,{recursive:!0});let R=Qo(r.questionFrontendId,r.titleSlug,i),q=join(I,R);return existsSync(q)?(n.warn(`File already exists: ${R}`),console.log(l.gray(`Path: ${q}`)),o.open!==!1&&await ke(q),!0):(await writeFile(q,u,"utf-8"),n.succeed(`Created ${l.green(R)}`),console.log(l.gray(`Path: ${q}`)),console.log(),console.log(l.cyan(`${r.questionFrontendId}. ${r.title}`)),console.log(l.gray(`Difficulty: ${r.difficulty} | Category: ${C}`)),o.open!==!1&&await ke(q),!0)}catch(r){if(n.fail("Failed to fetch problem"),r instanceof Error)if(r.message.includes("expected object, received null"))console.log(l.red(`Problem "${e}" not found`));else try{let s=JSON.parse(r.message);Array.isArray(s)?console.log(l.red("API Response Validation Failed")):console.log(l.red(r.message));}catch{console.log(l.red(r.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,r=0;for(let s of e)await Q(s,{...o,open:false})?n++:r++,console.log();console.log(l.gray("\u2500".repeat(50))),console.log(l.bold(`Done! ${l.green(`${n} succeeded`)}${r>0?`, ${l.red(`${r} 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 r of n){if(r.name.startsWith("."))continue;let s=join(e,r.name);if(r.isDirectory()){let i=await H(s,o,t+1);if(i)return i}else if(r.name.startsWith(`${o}.`)){let i=r.name.split(".").pop()?.toLowerCase();if(i&&i in Qn)return s}}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 r of n){let s=join(e,r.name);if(r.isDirectory()){let i=await ve(s,o,t+1);if(i)return i}else if(r.name===o)return s}return null}var Qn={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 Ue(e){return !e.includes("/")&&!e.includes("\\")&&e.includes(".")}function de(e,o){let t=resolve(e),n=resolve(o),r=n.endsWith(sep)?n:n+sep;return t===n||t.startsWith(r)}async function st(e,o){let{authorized:t}=await $();if(!t)return;let n=e,r=w.getWorkDir();if(te(e)){let i=await H(r,e);if(!i){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.gray(`Looking in: ${r}`)),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(Ue(e)){let i=await ve(r,e);if(!i){console.log(l.red(`File not found: ${e}`)),console.log(l.gray(`Looking in: ${r}`));return}n=i,console.log(l.gray(`Found: ${n}`));}if(!existsSync(n)){console.log(l.red(`File not found: ${n}`));return}if(!de(n,r)){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: ${r}`)),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 s=je({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(l.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(l.gray("Example: 1.two-sum.ts"));return}let[,c,g]=a,u=i.split(".").pop(),p=le(u);if(!p){s.fail(`Unsupported file extension: .${u}`);return}let b=await readFile(n,"utf-8");s.text="Fetching problem details...";let C=await h.getProblem(g),I=o.testcase??C.exampleTestcases??C.sampleTestCase;s.text="Running tests...";let R=await h.testSolution(g,b,p,I,C.questionId);s.stop(),Mo(R,o.visualize?C.topicTags:void 0);}catch(i){s.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 r=ce();r.activeTimer={problemId:e,title:o,difficulty:t,startedAt:new Date().toISOString(),durationMinutes:n},Je(r);},getActiveTimer(){return ce().activeTimer},stopTimer(){let e=ce(),o=e.activeTimer;if(!o)return null;let t=new Date(o.startedAt),r=Math.floor((new Date().getTime()-t.getTime())/1e3);return e.activeTimer=null,Je(e),{durationSeconds:r}},recordSolveTime(e,o,t,n,r){let s=ce();s.solveTimes[e]||(s.solveTimes[e]=[]),s.solveTimes[e].push({problemId:e,title:o,difficulty:t,solvedAt:new Date().toISOString(),durationSeconds:n,timerMinutes:r}),Je(s);},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 r of n)t+=r.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 s=await H(n,e);if(!s){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=s,console.log(l.gray(`Found: ${t}`));}else if(Ue(e)){let s=await ve(n,e);if(!s){console.log(l.red(`File not found: ${e}`)),console.log(l.gray(`Looking in: ${n}`));return}t=s,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 r=je({text:"Reading solution file...",spinner:"dots"}).start();try{let s=basename(t),i=s.match(/^(\d+)\.([^.]+)\./);if(!i){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[,a,c]=i,g=s.split(".").pop(),u=le(g);if(!u){r.fail(`Unsupported file extension: .${g}`);return}let p=await readFile(t,"utf-8");r.text="Fetching problem details...";let b=await h.getProblem(c);r.text="Submitting solution...";let C=await h.submitSolution(c,p,u,b.questionId);if(r.stop(),qo(C),C.status_msg==="Accepted"){let I=G.getActiveTimer();if(I&&I.problemId===a){let R=G.stopTimer();if(R){G.recordSolveTime(a,b.title,b.difficulty,R.durationSeconds,I.durationMinutes);let q=Math.floor(R.durationSeconds/60),ee=R.durationSeconds%60,ie=`${q}m ${ee}s`,V=R.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(s){r.fail("Submission failed"),s instanceof Error&&console.log(l.red(s.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 C=new Date(Date.UTC(b.getFullYear(),b.getMonth(),b.getDate())),I=Math.floor(C.getTime()/1e3).toString(),R=o[I]||0;c+=R,R>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 r=n.reduce((i,a)=>i+a.count,0),s=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(r+" submissions")}, ${l.yellow.bold(s+" 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=(r,s,i)=>{if(s.length===0)return;console.log(),console.log(i.bold(` ${r}`));let a=[...s].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"],r=[];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();r.push({label:n[g.getDay()],count:o[p]||0});}let s=Math.max(...r.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?s.toString().padStart(2):" "} \u2502`;for(let u of r)Math.round(u.count/s*i)>=c?g+=l.green(" \u2588\u2588 "):g+=" ";console.log(g);}console.log(` 0 \u2514${"\u2500\u2500\u2500\u2500".repeat(7)}`),console.log(` ${r.map(c=>c.label.padEnd(4)).join("")}`),console.log(l.gray(` ${r.map(c=>c.count.toString().padEnd(4)).join("")}`));let a=r.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 r=je("Fetching statistics...").start();try{let s=e||n;if(!s){r.fail("No username found");return}let i=await h.getUserProfile(s);if(r.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){r.start("Fetching skill stats...");let a=await h.getSkillStats(s);r.stop(),mt(a.fundamental,a.intermediate,a.advanced);}}catch(s){r.fail("Failed to fetch statistics"),s instanceof Error&&console.log(l.red(s.message));}}async function pt(){let{authorized:e}=await $();if(!e)return;let o=je("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=je("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 r=await h.getRandomProblem(n);t.succeed("Found random problem!"),console.log(),e.pick?await Q(r,{open:e.open??!0}):(await Fe(r),console.log(l.gray("Run following to start solving:")),console.log(l.cyan(` leetcode pick ${r}`)));}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=je("Fetching problem info...").start();try{let r;if(/^\d+$/.test(e)?r=await h.getProblemById(e):r=await h.getProblem(e),!r){n.fail(`Problem "${e}" not found`);return}let s=r.titleSlug;n.text="Fetching submissions...";let i=o.limit?parseInt(o.limit,10):20,a=await h.getSubmissionList(s,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=je("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(),C=r.difficulty,I=r.topicTags.length>0?r.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",R=join(b,C,I);existsSync(R)||await mkdir(R,{recursive:!0});let q=p.lang.name,ee=$e[q]??"txt",ie=me[ee]??q,V=`${r.questionFrontendId}.${r.titleSlug}.submission-${g.id}.${ie}`,lo=join(R,V);await writeFile(lo,p.code,"utf-8"),c.succeed(`Downloaded to ${l.green(V)}`),console.log(l.gray(`Path: ${lo}`));}}catch(r){n.fail("Failed to fetch submissions"),r instanceof Error&&console.log(l.red(r.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 br();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 br(){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=je({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 r of e)try{let s=await h.getProblemById(r);s?n.push([s.questionFrontendId,s.title.length>42?s.title.slice(0,39)+"...":s.title,wr(s.difficulty),s.status==="ac"?l.green("\u2713"):l.gray("-")]):n.push([r,l.gray("(not found)"),"-","-"]);}catch{n.push([r,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 wr(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"),r=join(n,`${e}.md`);existsSync(n)||await mkdir(n,{recursive:true}),t==="view"?await vr(r,e):await Cr(r,e);}async function vr(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 Cr(e,o){if(!existsSync(e)){let t=await Pr(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 Pr(e){let o=`# Problem ${e} Notes
|
|
192
195
|
|
|
193
|
-
`,{authorized:t}=await
|
|
196
|
+
`,{authorized:t}=await $();if(t)try{let n=await h.getProblemById(e);n&&(o=`# ${e}. ${n.title}
|
|
194
197
|
|
|
195
198
|
`,o+=`**Difficulty:** ${n.difficulty}
|
|
196
199
|
`,o+=`**URL:** https://leetcode.com/problems/${n.titleSlug}/
|
|
197
|
-
`,n.topicTags.length>0&&(o+=`**Topics:** ${n.topicTags.map(
|
|
200
|
+
`,n.topicTags.length>0&&(o+=`**Topics:** ${n.topicTags.map(r=>r.name).join(", ")}
|
|
198
201
|
`),o+=`
|
|
199
202
|
---
|
|
200
203
|
|
|
@@ -223,22 +226,22 @@ For security reasons, you can only submit files from within your workspace.`)),c
|
|
|
223
226
|
|
|
224
227
|
<!-- What did you learn from this problem? -->
|
|
225
228
|
|
|
226
|
-
`}async function
|
|
227
|
-
Please create a new repository on your Git provider and copy the URL.`));let{url:
|
|
228
|
-
`).length,
|
|
229
|
-
`).length} lines from ${n}`))):o.fail(
|
|
230
|
-
`);for(let c=0;c<i.length;c++){let g=String(c+1).padStart(3," ");console.log(`${l.gray(g)} ${i[c]}`);}console.log(),console.log(l.bold.blue(`\u25B8 ${
|
|
231
|
-
`);for(let c=0;c<a.length;c++){let g=String(c+1).padStart(3," ");console.log(`${l.gray(g)} ${a[c]}`);}console.log(),console.log(l.gray("\u2500".repeat(60))),console.log(l.gray(`Your code: ${i.length} lines | Partner: ${a.length} lines`)),console.log();}async function
|
|
232
|
-
`).length,createdAt:new Date().toISOString()};return
|
|
233
|
-
`).filter(b=>b!=="");if(u.added){c+=p.length;for(let b of p)console.log(l.green("+ "+b));}else if(u.removed){g+=p.length;for(let b of p)console.log(l.red("- "+b));}else if(p.length<=4)for(let b of p)console.log(l.gray(" "+b));else console.log(l.gray(" "+p[0])),console.log(l.gray(" "+p[1])),console.log(l.gray(` ... (${p.length-4} more lines)`)),console.log(l.gray(" "+p[p.length-2])),console.log(l.gray(" "+p[p.length-1]));}console.log(),console.log(l.gray("\u2500".repeat(50))),console.log(`${l.green("+"+c+" added")} ${l.gray("\xB7")} ${l.red("-"+g+" removed")} ${l.gray("\xB7")} ${l.gray(n.lines+" \u2192 "+
|
|
234
|
-
`),n=t.length;console.log(),console.log(l.bold.cyan(`=== ${o} (${n} lines) ===`)),console.log(l.gray("\u2500".repeat(60))),t.forEach((s
|
|
235
|
-
`).length,
|
|
229
|
+
`}async function Pt(){let{authorized:e,username:o}=await $();if(!e||!o)return;let t=je({text:"Fetching your progress...",spinner:"dots"}).start();try{let[n,r]=await Promise.all([h.getUserProfile(o),h.getDailyChallenge()]);t.stop(),console.log(),console.log(l.bold.cyan("\u{1F4CA} Today's Summary"),l.gray(`- ${o}`)),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(l.yellow(`\u{1F525} Current Streak: ${n.streak} day${n.streak!==1?"s":""}`)),console.log(l.gray(` Total Active Days: ${n.totalActiveDays}`)),console.log();let s=n.acSubmissionNum.find(u=>u.difficulty==="All"),i=n.acSubmissionNum.find(u=>u.difficulty==="Easy"),a=n.acSubmissionNum.find(u=>u.difficulty==="Medium"),c=n.acSubmissionNum.find(u=>u.difficulty==="Hard");console.log(l.white("\u{1F4C8} Problems Solved:")),console.log(` ${l.green("Easy")}: ${i?.count??0} | ${l.yellow("Medium")}: ${a?.count??0} | ${l.red("Hard")}: ${c?.count??0}`),console.log(` ${l.bold("Total")}: ${s?.count??0}`),console.log(),console.log(l.bold.yellow("\u{1F3AF} Today's Challenge:")),console.log(` ${r.question.questionFrontendId}. ${r.question.title}`),console.log(` ${Dr(r.question.difficulty)}`);let g=r.question.status;console.log(g==="ac"?l.green(" \u2713 Completed!"):g==="notac"?l.yellow(" \u25CB Attempted"):l.gray(" - Not started")),console.log(),console.log(l.gray(` leetcode pick ${r.question.questionFrontendId} # Start working on it`));}catch(n){t.fail("Failed to fetch progress"),n instanceof Error&&console.log(l.red(n.message));}}function Dr(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 Er(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-").replace(/--+/g,"-")}function Lr(e){let o=/^https:\/\/[\w.-]+\/[\w./-]+$/,t=/^git@[\w.-]+:[\w./-]+$/;return o.test(e)||t.test(e)}function Ar(e){return `'${e.replace(/'/g,"'\\''")}'`}function Rr(){try{return execSync("git --version",{stdio:"ignore"}),!0}catch{return false}}function Fr(e){try{return execSync("git rev-parse --is-inside-work-tree",{cwd:e,stdio:"ignore"}),!0}catch{return false}}function _r(){try{return execSync("gh --version",{stdio:"ignore"}),!0}catch{return false}}function Tt(e){try{return execSync("git config --get remote.origin.url",{cwd:e,encoding:"utf-8"}).trim()}catch{return null}}async function Nr(e){let{init:o}=await to.prompt([{type:"confirm",name:"init",message:"Work directory is not a git repository. Initialize?",default:true}]);if(!o)return console.log(l.yellow("Skipping basic git initialization.")),false;let t=je("Initializing git repository...").start();try{return execSync("git init",{cwd:e}),t.succeed("Initialized git repository"),!0}catch(n){throw t.fail("Failed to initialize git repository"),n}}async function Ir(e){let o=je(),t=w.getRepo();if(!t){if(_r()){let{createGh:r}=await to.prompt([{type:"confirm",name:"createGh",message:"Create a new private GitHub repository?",default:true}]);if(r){o.start("Creating GitHub repository...");try{let s=e.split("/").pop()||"leetcode-solutions",i=Er(s);return execSync(`gh repo create ${i} --private --source=. --remote=origin`,{cwd:e}),o.succeed("Created and linked GitHub repository"),t=Tt(e)||"",t&&w.setRepo(t),t}catch(s){o.fail("Failed to create GitHub repository"),console.log(l.red(s));}}}if(!t){console.log(l.yellow(`
|
|
230
|
+
Please create a new repository on your Git provider and copy the URL.`));let{url:r}=await to.prompt([{type:"input",name:"url",message:"Enter remote repository URL:",validate:s=>s.length>0?true:"URL cannot be empty"}]);t=r;}}if(t&&!Lr(t))return console.log(l.red("Invalid repository URL format.")),console.log(l.gray("Expected: https://github.com/user/repo or git@github.com:user/repo")),"";if(t&&w.setRepo(t),!Tt(e)&&t)try{execSync(`git remote add origin ${t}`,{cwd:e}),console.log(l.green("\u2713 Added remote origin"));}catch{console.log(l.red("Failed to add remote origin"));}return t||""}async function Dt(){let e=w.getWorkDir();if(!existsSync(e)){console.log(l.red(`Work directory does not exist: ${e}`));return}if(!Rr()){console.log(l.red("Git is not installed. Please install Git to use command."));return}if(!Fr(e)&&!await Nr(e))return;await Ir(e);let o=je("Syncing solutions...").start();try{let t=execSync("git status --porcelain",{cwd:e,encoding:"utf-8"});if(!t){o.info("No changes to sync");return}execSync("git add .",{cwd:e});let r=t.trim().split(`
|
|
231
|
+
`).length,s=new Date().toISOString().replace("T"," ").substring(0,19),i=`Sync: ${r} solutions - ${s}`;execSync(`git commit -m ${Ar(i)}`,{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(t){o.fail("Sync failed"),t.message&&console.log(l.red(t.message));}}var jr={Easy:20,Medium:40,Hard:60};function fe(e){if(e<60)return `${e}s`;if(e<3600){let o=Math.floor(e/60),t=e%60;return t>0?`${o}m ${t}s`:`${o}m`}else {let o=Math.floor(e/3600),t=Math.floor(e%3600/60);return t>0?`${o}h ${t}m`:`${o}h`}}async function xt(e,o){if(o.stats){await qr(e);return}if(o.stop){await Mr();return}if(!e){console.log(l.yellow("Please provide a problem ID to start the timer.")),console.log(l.gray("Usage: leetcode timer <id>")),console.log(l.gray(" leetcode timer --stats")),console.log(l.gray(" leetcode timer --stop"));return}let{authorized:t}=await $();if(!t)return;let n=G.getActiveTimer();if(n){let s=new Date(n.startedAt),i=Math.floor((Date.now()-s.getTime())/1e3);console.log(l.yellow("\u26A0\uFE0F You have an active timer running:")),console.log(l.white(` Problem: ${n.title}`)),console.log(l.white(` Elapsed: ${fe(i)}`)),console.log(),console.log(l.gray("Use `leetcode timer --stop` to stop it first."));return}let r=je("Fetching problem...").start();try{let s;if(/^\d+$/.test(e)?s=await h.getProblemById(e):s=await h.getProblem(e),!s){r.fail(`Problem "${e}" not found`);return}r.stop();let i=o.minutes??jr[s.difficulty]??30;G.startTimer(s.questionFrontendId,s.title,s.difficulty,i),console.log(),console.log(l.bold.cyan("\u23F1\uFE0F Interview Mode Started!")),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(l.white(`Problem: ${s.questionFrontendId}. ${s.title}`)),console.log(l.white(`Difficulty: ${l.bold(s.difficulty)}`)),console.log(l.white(`Time Limit: ${l.bold.yellow(i+" minutes")}`)),console.log(),console.log(l.gray("\u2500".repeat(50))),console.log(l.green("\u2713 Timer is running in background")),console.log(l.gray(" When you submit successfully, your time will be recorded.")),console.log(l.gray(" Use `leetcode timer --stop` to cancel.")),console.log(),await Q(e,{open:!0});}catch(s){r.fail("Failed to start timer"),s instanceof Error&&console.log(l.red(s.message));}}async function Mr(){let e=G.stopTimer();if(!e){console.log(l.yellow("No active timer to stop."));return}console.log(l.green("\u23F1\uFE0F Timer stopped.")),console.log(l.gray(`Elapsed time: ${fe(e.durationSeconds)}`)),console.log(l.gray("(Time not recorded since problem was not submitted)"));}async function qr(e){if(e&&/^\d+$/.test(e)){let o=G.getSolveTimes(e);if(o.length===0){console.log(l.yellow(`No solve times recorded for problem ${e}`));return}console.log(),console.log(l.bold(`\u23F1\uFE0F Solve Times for Problem ${e}`)),console.log(l.gray("\u2500".repeat(40)));for(let t of o){let n=new Date(t.solvedAt).toLocaleDateString(),r=fe(t.durationSeconds),s=t.timerMinutes,i=t.durationSeconds<=s*60;console.log(` ${n} ${i?l.green(r):l.red(r)} (limit: ${s}m)`);}}else {let o=G.getStats(),t=G.getAllSolveTimes();console.log(),console.log(l.bold("\u23F1\uFE0F Timer Statistics")),console.log(l.gray("\u2500".repeat(40))),console.log(),console.log(` Problems timed: ${l.cyan(o.totalProblems)}`),console.log(` Total time: ${l.cyan(fe(o.totalTime))}`),console.log(` Average time: ${l.cyan(fe(o.avgTime))}`),console.log();let n=[];for(let[r,s]of Object.entries(t))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(l.bold(" Recent Solves:"));for(let r of n.slice(0,5)){let s=new Date(r.date).toLocaleDateString();console.log(l.gray(` ${s} `)+l.white(`${r.problemId}. ${r.title.substring(0,25)}`)+l.gray(" ")+l.cyan(fe(r.duration)));}}console.log();}}var Hr="https://abagrmwdpvnfyuqizyym.supabase.co",Wr="sb_publishable_indrKu8VJmASdyLp7w8Hog_OyqT17cV",re=createClient(Hr,Wr);function ro(){return k.getCollabPath()}function Yr(){let e=ro();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{session:null}}function Qr(e){let o=ro(),t=dirname(o);existsSync(t)||mkdirSync(t,{recursive:true}),writeFileSync(o,JSON.stringify(e,null,2));}var Z={getSession(){return Yr().session},setSession(e){Qr({session:e});},getPath(){return ro()}};function Jr(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",o="";for(let t=0;t<6;t++)o+=e.charAt(Math.floor(Math.random()*e.length));return o}var Y={getSession(){return Z.getSession()},async createRoom(e,o){let t=Jr(),{error:n}=await re.from("collab_rooms").insert({room_code:t,problem_id:e,host_username:o,host_code:"",guest_username:null,guest_code:null});return n?{error:n.message}:(Z.setSession({roomCode:t,problemId:e,isHost:true,username:o}),{roomCode:t})},async joinRoom(e,o){let{data:t,error:n}=await re.from("collab_rooms").select("*").eq("room_code",e.toUpperCase()).single();if(n||!t)return {error:"Room not found"};let{error:r}=await re.from("collab_rooms").update({guest_username:o}).eq("room_code",e.toUpperCase());return r?{error:r.message}:(Z.setSession({roomCode:e.toUpperCase(),problemId:t.problem_id,isHost:false,username:o}),{problemId:t.problem_id})},async syncCode(e){let o=Z.getSession();if(!o)return {success:false,error:"No active session"};let t=o.isHost?"host_code":"guest_code",{error:n}=await re.from("collab_rooms").update({[t]:e}).eq("room_code",o.roomCode);return n?{success:false,error:n.message}:{success:true}},async getPartnerCode(){let e=Z.getSession();if(!e)return {error:"No active session"};let{data:o,error:t}=await re.from("collab_rooms").select("*").eq("room_code",e.roomCode).single();return t||!o?{error:"Room not found"}:e.isHost?{code:o.guest_code||"",username:o.guest_username||"Partner"}:{code:o.host_code||"",username:o.host_username||"Host"}},async getRoomStatus(){let e=Z.getSession();if(!e)return {error:"No active session"};let{data:o,error:t}=await re.from("collab_rooms").select("*").eq("room_code",e.roomCode).single();return t||!o?{error:"Room not found"}:{host:o.host_username,guest:o.guest_username,hasHostCode:!!o.host_code,hasGuestCode:!!o.guest_code}},async leaveRoom(){let e=Z.getSession();e&&e.isHost&&await re.from("collab_rooms").delete().eq("room_code",e.roomCode),Z.setSession(null);}};async function At(e){let{authorized:o,username:t}=await $();if(!o||!t)return;let n=je("Creating collaboration room...").start();try{let r=await Y.createRoom(e,t);if("error"in r){n.fail(r.error);return}n.succeed("Room created!"),console.log(),console.log(l.bold.cyan("\u{1F465} Collaborative Coding Session")),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(l.white(`Room Code: ${l.bold.green(r.roomCode)}`)),console.log(l.white(`Problem: ${e}`)),console.log(),console.log(l.gray("Share this code with your partner:")),console.log(l.yellow(` leetcode collab join ${r.roomCode}`)),console.log(),console.log(l.gray("\u2500".repeat(50))),console.log(l.gray("After solving, sync and compare:")),console.log(l.gray(" leetcode collab sync - Upload your solution")),console.log(l.gray(" leetcode collab compare - See both solutions")),console.log(l.gray(" leetcode collab status - Check room status")),console.log(l.gray(" leetcode collab leave - End session")),console.log(),await Q(e,{open:!0});}catch(r){n.fail("Failed to create room"),r instanceof Error&&console.log(l.red(r.message));}}async function Rt(e){let{authorized:o,username:t}=await $();if(!o||!t)return;let n=je(`Joining room ${e}...`).start();try{let r=await Y.joinRoom(e.toUpperCase(),t);if("error"in r){n.fail(r.error);return}n.succeed("Joined room!"),console.log(),console.log(l.bold.cyan("\u{1F465} Collaborative Coding Session")),console.log(l.gray("\u2500".repeat(50))),console.log(),console.log(l.white(`Room Code: ${l.bold.green(e.toUpperCase())}`)),console.log(l.white(`Problem: ${r.problemId}`)),console.log(),console.log(l.gray("\u2500".repeat(50))),console.log(l.gray("After solving, sync and compare:")),console.log(l.gray(" leetcode collab sync - Upload your solution")),console.log(l.gray(" leetcode collab compare - See both solutions")),console.log(l.gray(" leetcode collab status - Check room status")),console.log(l.gray(" leetcode collab leave - End session")),console.log(),await Q(r.problemId,{open:!0});}catch(r){n.fail("Failed to join room"),r instanceof Error&&console.log(l.red(r.message));}}async function Ft(){let e=Y.getSession();if(!e){console.log(l.yellow("No active collaboration session.")),console.log(l.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` first."));return}let o=je("Syncing your code...").start(),t=w.getWorkDir(),n=await H(t,e.problemId);if(!n){o.fail(`No solution file found for problem ${e.problemId}`);return}let r=await readFile(n,"utf-8"),s=await Y.syncCode(r);s.success?(o.succeed("Code synced successfully!"),console.log(l.gray(`Uploaded ${r.split(`
|
|
232
|
+
`).length} lines from ${n}`))):o.fail(s.error||"Sync failed");}async function _t(){let e=Y.getSession();if(!e){console.log(l.yellow("No active collaboration session.")),console.log(l.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` first."));return}let o=je("Fetching solutions...").start(),t=w.getWorkDir(),n=await H(t,e.problemId);if(!n){o.fail(`No solution file found for problem ${e.problemId}`);return}let r=await readFile(n,"utf-8"),s=await Y.getPartnerCode();if("error"in s){o.fail(s.error);return}if(o.stop(),!s.code){console.log(l.yellow("Partner has not synced their code yet.")),console.log(l.gray("Ask them to run `leetcode collab sync`."));return}console.log(),console.log(l.bold.cyan("\u{1F4CA} Solution Comparison")),console.log(l.gray("\u2500".repeat(60))),console.log(),console.log(l.bold.green(`\u25B8 Your Solution (${e.username})`)),console.log(l.gray("\u2500".repeat(60)));let i=r.split(`
|
|
233
|
+
`);for(let c=0;c<i.length;c++){let g=String(c+1).padStart(3," ");console.log(`${l.gray(g)} ${i[c]}`);}console.log(),console.log(l.bold.blue(`\u25B8 ${s.username}'s Solution`)),console.log(l.gray("\u2500".repeat(60)));let a=s.code.split(`
|
|
234
|
+
`);for(let c=0;c<a.length;c++){let g=String(c+1).padStart(3," ");console.log(`${l.gray(g)} ${a[c]}`);}console.log(),console.log(l.gray("\u2500".repeat(60))),console.log(l.gray(`Your code: ${i.length} lines | Partner: ${a.length} lines`)),console.log();}async function Nt(){if(!Y.getSession()){console.log(l.yellow("No active collaboration session."));return}await Y.leaveRoom(),console.log(l.green("\u2713 Left the collaboration session."));}async function It(){let e=Y.getSession();if(!e){console.log(l.yellow("No active collaboration session.")),console.log(l.gray("Use `leetcode collab host <id>` or `leetcode collab join <code>` to start."));return}let o=await Y.getRoomStatus();if("error"in o){console.log(l.red(o.error));return}console.log(),console.log(l.bold.cyan("\u{1F465} Collaboration Status")),console.log(l.gray("\u2500".repeat(40))),console.log(` Room: ${l.green(e.roomCode)}`),console.log(` Problem: ${e.problemId}`),console.log(` Role: ${e.isHost?"Host":"Guest"}`),console.log(),console.log(l.bold(" Participants:")),console.log(` Host: ${o.host} ${o.hasHostCode?l.green("\u2713 synced"):l.gray("pending")}`),console.log(` Guest: ${o.guest||l.gray("(waiting...)")} ${o.hasGuestCode?l.green("\u2713 synced"):l.gray("pending")}`),console.log();}function Zr(){return k.getSnapshotsDir()}function qt(e){return join(Zr(),e)}function Ot(e){return join(qt(e),"meta.json")}function Me(e){return join(qt(e),"files")}function Ht(e){let o=Me(e);existsSync(o)||mkdirSync(o,{recursive:true});}function Ce(e){let o=Ot(e);return existsSync(o)?JSON.parse(readFileSync(o,"utf-8")):{problemId:e,problemTitle:"",snapshots:[]}}function Ut(e,o){Ht(e),writeFileSync(Ot(e),JSON.stringify(o,null,2));}var W={save(e,o,t,n,r){Ht(e);let s=Ce(e);o&&(s.problemTitle=o);let i=s.snapshots.length>0?Math.max(...s.snapshots.map(C=>C.id))+1:1,a=r||`snapshot-${i}`,c=s.snapshots.find(C=>C.name===a);if(c)return {error:`Snapshot with name "${a}" already exists (ID: ${c.id})`};let g=me[n]||n,u=`${i}_${a}.${g}`,p=join(Me(e),u);writeFileSync(p,t,"utf-8");let b={id:i,name:a,fileName:u,language:n,lines:t.split(`
|
|
235
|
+
`).length,createdAt:new Date().toISOString()};return s.snapshots.push(b),Ut(e,s),b},list(e){return Ce(e).snapshots},getMeta(e){return Ce(e)},get(e,o){let t=Ce(e),n=t.snapshots.find(s=>s.id===parseInt(o,10));return n||t.snapshots.find(s=>s.name===o)||null},getCode(e,o){let t=join(Me(e),o.fileName);if(!existsSync(t))throw new Error(`Snapshot file not found: ${o.fileName}`);return readFileSync(t,"utf-8")},delete(e,o){let t=Ce(e),n=this.get(e,o);if(!n)return false;let r=join(Me(e),n.fileName);return existsSync(r)&&unlinkSync(r),t.snapshots=t.snapshots.filter(s=>s.id!==n.id),Ut(e,t),true},hasSnapshots(e){return this.list(e).length>0}};function ns(e){let o=new Date(e),n=new Date().getTime()-o.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 zt(e,o){let t=w.getWorkDir();try{let n=await H(t,e);if(!n){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.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=le(s)||s,c=basename(n).match(/^\d+\.(.+)\.\w+$/),g=c?c[1]:"",u=W.save(e,g,r,i,o);if("error"in u){console.log(l.red("\u2717 "+u.error));return}let p=u;console.log(l.green("\u2713 Snapshot saved!")),console.log(),console.log(` ID: ${l.cyan(p.id)}`),console.log(` Name: ${l.white(p.name)}`),console.log(` Lines: ${l.gray(p.lines)}`),console.log(` File: ${l.gray(n)}`);}catch(n){console.log(l.red("Failed to save snapshot")),n instanceof Error&&console.log(l.gray(n.message));}}async function Bt(e){let o=W.list(e);if(o.length===0){console.log(l.yellow(`No snapshots found for problem ${e}`)),console.log(l.gray("Use `leetcode snapshot save "+e+"` to create one."));return}let t=W.getMeta(e);console.log(),console.log(l.bold(`\u{1F4F8} Snapshots for Problem ${e}`)),t.problemTitle&&console.log(l.gray(` ${t.problemTitle}`)),console.log(l.gray("\u2500".repeat(50))),console.log();for(let n of o){let r=ns(n.createdAt);console.log(` ${l.cyan(n.id.toString().padStart(2))}. ${l.white(n.name.padEnd(25))} ${l.gray(n.lines+" lines")} ${l.gray("\xB7")} ${l.gray(r)}`);}console.log(),console.log(l.gray("Commands:")),console.log(l.gray(` restore: leetcode snapshot restore ${e} <id|name>`)),console.log(l.gray(` diff: leetcode snapshot diff ${e} <id1> <id2>`)),console.log(l.gray(` delete: leetcode snapshot delete ${e} <id|name>`));}async function Gt(e,o){let t=w.getWorkDir();try{let n=W.get(e,o);if(!n){console.log(l.red(`Snapshot "${o}" not found for problem ${e}`)),console.log(l.gray("Run `leetcode snapshot list "+e+"` to see available snapshots."));return}let r=await H(t,e);if(!r){console.log(l.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),c=le(a)||a;W.save(e,"",s,c,i);let g=W.getCode(e,n);await writeFile(r,g,"utf-8"),console.log(l.green("\u2713 Snapshot restored!")),console.log(),console.log(` Restored: ${l.cyan(n.name)} (${n.lines} lines)`),console.log(` File: ${l.gray(r)}`),console.log(` Backup: ${l.gray(i)}`);}catch(n){console.log(l.red("Failed to restore snapshot")),n instanceof Error&&console.log(l.gray(n.message));}}async function Yt(e,o,t){try{let n=W.get(e,o),r=W.get(e,t);if(!n){console.log(l.red(`Snapshot "${o}" not found`));return}if(!r){console.log(l.red(`Snapshot "${t}" not found`));return}let s=W.getCode(e,n),i=W.getCode(e,r);console.log(),console.log(l.bold(`\u{1F4CA} Diff: ${n.name} \u2192 ${r.name}`)),console.log(l.gray("\u2500".repeat(50))),console.log();let a=diffLines(s,i),c=0,g=0;for(let u of a){let p=u.value.split(`
|
|
236
|
+
`).filter(b=>b!=="");if(u.added){c+=p.length;for(let b of p)console.log(l.green("+ "+b));}else if(u.removed){g+=p.length;for(let b of p)console.log(l.red("- "+b));}else if(p.length<=4)for(let b of p)console.log(l.gray(" "+b));else console.log(l.gray(" "+p[0])),console.log(l.gray(" "+p[1])),console.log(l.gray(` ... (${p.length-4} more lines)`)),console.log(l.gray(" "+p[p.length-2])),console.log(l.gray(" "+p[p.length-1]));}console.log(),console.log(l.gray("\u2500".repeat(50))),console.log(`${l.green("+"+c+" added")} ${l.gray("\xB7")} ${l.red("-"+g+" removed")} ${l.gray("\xB7")} ${l.gray(n.lines+" \u2192 "+r.lines+" lines")}`);}catch(n){console.log(l.red("Failed to diff snapshots")),n instanceof Error&&console.log(l.gray(n.message));}}async function Qt(e,o){let t=W.get(e,o);if(!t){console.log(l.red(`Snapshot "${o}" not found for problem ${e}`));return}let n=W.delete(e,o);console.log(n?l.green(`\u2713 Deleted snapshot: ${t.name}`):l.red("Failed to delete snapshot"));}function Kt(e,o){let t=e.split(`
|
|
237
|
+
`),n=t.length;console.log(),console.log(l.bold.cyan(`=== ${o} (${n} lines) ===`)),console.log(l.gray("\u2500".repeat(60))),t.forEach((r,s)=>{let i=(s+1).toString().padStart(3);console.log(l.gray(i+" \u2502 ")+r);});}function is(e,o,t,n){let r=e.split(`
|
|
238
|
+
`).length,s=o.split(`
|
|
236
239
|
`).length;console.log(),console.log(l.bold(`\u{1F4CA} Unified Diff: ${t} \u2192 ${n}`)),console.log(l.gray("\u2500".repeat(60))),console.log();let i=diffLines(e,o),a=0,c=0;for(let g of i){let u=g.value.split(`
|
|
237
|
-
`).filter(p=>p!=="");if(g.added){a+=u.length;for(let p of u)console.log(l.green("+ "+p));}else if(g.removed){c+=u.length;for(let p of u)console.log(l.red("- "+p));}else if(u.length<=6)for(let p of u)console.log(l.gray(" "+p));else console.log(l.gray(" "+u[0])),console.log(l.gray(" "+u[1])),console.log(l.dim(` ... (${u.length-4} unchanged lines)`)),console.log(l.gray(" "+u[u.length-2])),console.log(l.gray(" "+u[u.length-1]));}console.log(),console.log(l.gray("\u2500".repeat(60))),console.log(`${l.green("+"+a+" added")} ${l.gray("\xB7")} ${l.red("-"+c+" removed")} ${l.gray("\xB7")} ${l.gray(
|
|
238
|
-
`).filter(u=>u!=="");c.added?i+=g.length:c.removed&&(a+=g.length);}console.log(),console.log(l.gray("\u2500".repeat(60))),console.log(`${l.bold("Summary:")} ${l.green("+"+i+" added")} ${l.gray("\xB7")} ${l.red("-"+a+" removed")}`),console.log(l.gray("Tip: Use --unified for line-by-line diff"));}}async function
|
|
239
|
-
For security reasons, you can only diff files from within your workspace.`));return}let p=await readFile(o.file,"utf-8");
|
|
240
|
-
`)))):(console.log(),console.log(l.green("\u2713")+` You're on the latest version (${l.cyan(o)})`),console.log());}async function
|
|
241
|
-
`),
|
|
240
|
+
`).filter(p=>p!=="");if(g.added){a+=u.length;for(let p of u)console.log(l.green("+ "+p));}else if(g.removed){c+=u.length;for(let p of u)console.log(l.red("- "+p));}else if(u.length<=6)for(let p of u)console.log(l.gray(" "+p));else console.log(l.gray(" "+u[0])),console.log(l.gray(" "+u[1])),console.log(l.dim(` ... (${u.length-4} unchanged lines)`)),console.log(l.gray(" "+u[u.length-2])),console.log(l.gray(" "+u[u.length-1]));}console.log(),console.log(l.gray("\u2500".repeat(60))),console.log(`${l.green("+"+a+" added")} ${l.gray("\xB7")} ${l.red("-"+c+" removed")} ${l.gray("\xB7")} ${l.gray(r+" \u2192 "+s+" lines")}`);}function so(e,o,t,n,r){if(r)is(e,o,t,n);else {Kt(e,t),Kt(o,n);let s=diffLines(e,o),i=0,a=0;for(let c of s){let g=c.value.split(`
|
|
241
|
+
`).filter(u=>u!=="");c.added?i+=g.length:c.removed&&(a+=g.length);}console.log(),console.log(l.gray("\u2500".repeat(60))),console.log(`${l.bold("Summary:")} ${l.green("+"+i+" added")} ${l.gray("\xB7")} ${l.red("-"+a+" removed")}`),console.log(l.gray("Tip: Use --unified for line-by-line diff"));}}async function Zt(e,o){let{authorized:t}=await $();if(!t)return;let n=w.getWorkDir(),r=je("Finding solution file...").start();try{let s=await H(n,e);if(!s){r.fail(`No solution file found for problem ${e}`),console.log(l.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...",o.file){if(r.stop(),!existsSync(o.file)){console.log(l.red(`File not found: ${o.file}`));return}if(!de(o.file,n)){console.log(l.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(l.gray(`File: ${o.file}`)),console.log(l.gray(`Workspace: ${n}`)),console.log(l.yellow(`
|
|
242
|
+
For security reasons, you can only diff files from within your workspace.`));return}let p=await readFile(o.file,"utf-8");so(i,p,"Your Solution",o.file,o.unified??!1);return}let a=await h.getProblemById(e);if(!a){r.fail(`Problem ${e} not found`);return}if(o.submission){let p=parseInt(o.submission,10),b=await h.getSubmissionDetails(p);r.stop(),so(i,b.code,"Your Solution",`Submission #${p}`,o.unified??!1);return}let g=(await h.getSubmissionList(a.titleSlug,50)).find(p=>p.statusDisplay==="Accepted");if(!g){r.fail("No accepted submissions found for this problem"),console.log(l.gray("Tip: Use --file to compare with a local file instead"));return}let u=await h.getSubmissionDetails(parseInt(g.id,10));r.stop(),so(i,u.code,"Your Solution","Last Accepted",o.unified??!1);}catch(s){r.fail("Failed to diff"),s instanceof Error&&console.log(l.red(s.message));}}async function en(){let e=k.getActive(),o=k.getConfig(e);console.log(),console.log(l.bold.cyan(`\u{1F4C1} Active Workspace: ${e}`)),console.log(l.gray("\u2500".repeat(40))),console.log(` workDir: ${l.white(o.workDir)}`),console.log(` lang: ${l.white(o.lang)}`),o.editor&&console.log(` editor: ${l.white(o.editor)}`),o.syncRepo&&console.log(` syncRepo: ${l.white(o.syncRepo)}`),console.log();}async function on(){let e=k.list(),o=k.getActive();console.log(),console.log(l.bold("Workspaces:")),console.log();for(let t of e){let n=k.getConfig(t),r=t===o?l.green("\u25B8 "):" ",s=t===o?l.green.bold(t):t;console.log(`${r}${s}`),console.log(` ${l.gray(n.workDir)}`);}console.log();}async function tn(e,o){if(k.exists(e)){console.log(l.red(`Workspace "${e}" already exists`));return}let t=o.workdir??join(homedir(),"leetcode",e),n={workDir:t,lang:"typescript"};k.create(e,n)?(console.log(l.green(`\u2713 Created workspace "${e}"`)),console.log(` workDir: ${l.gray(t)}`),console.log(),console.log(l.gray(`Switch to it: leetcode workspace use ${e}`))):console.log(l.red("Failed to create workspace"));}async function nn(e){if(!k.exists(e)){console.log(l.red(`Workspace "${e}" not found`)),console.log(l.gray("Use `leetcode workspace list` to see available workspaces"));return}if(k.setActive(e)){let t=k.getConfig(e);console.log(l.green(`\u2713 Switched to workspace "${e}"`)),console.log(` workDir: ${l.gray(t.workDir)}`);}else console.log(l.red("Failed to switch workspace"));}async function rn(e){if(e==="default"){console.log(l.red("Cannot delete the default workspace"));return}if(!k.exists(e)){console.log(l.red(`Workspace "${e}" not found`));return}let{confirmed:o}=await to.prompt([{type:"confirm",name:"confirmed",message:`Delete workspace "${e}"? (files in workDir will NOT be deleted)`,default:false}]);if(!o){console.log(l.gray("Cancelled"));return}let t=k.delete(e);console.log(t?l.green(`\u2713 Deleted workspace "${e}"`):l.red("Failed to delete workspace"));}var io=join(homedir(),".leetcode"),Pe=join(io,"version-cache.json"),fs=1440*60*1e3;function ys(){existsSync(io)||mkdirSync(io,{recursive:true});}function sn(){if(existsSync(Pe))try{return JSON.parse(readFileSync(Pe,"utf-8"))}catch{return null}return null}function hs(e){ys(),writeFileSync(Pe,JSON.stringify(e,null,2));}var se={shouldCheck(){let e=sn();return e?Date.now()-e.lastCheck>fs:true},getCached(){return sn()},updateCache(e,o){hs({lastCheck:Date.now(),latestVersion:e,hasBreakingChanges:o});},clearCache(){existsSync(Pe)&&unlinkSync(Pe);}};function he(e,o){let t=e.replace("v","").split(".").map(Number),n=o.replace("v","").split(".").map(Number);for(let r=0;r<3;r++){let s=t[r]||0,i=n[r]||0;if(s>i)return true;if(s<i)return false}return false}function ln(e,o){let t=parseInt(e.replace("v","").split(".")[0])||0;return (parseInt(o.replace("v","").split(".")[0])||0)>t}var vs=fileURLToPath(import.meta.url),gn=dirname(vs),Cs="https://registry.npmjs.org/@night-slayer18/leetcode-cli/latest",Ps="@night-slayer18/leetcode-cli";function be(){let e=[join(gn,"../package.json"),join(gn,"../../package.json")];for(let o of e)try{let t=JSON.parse(readFileSync(o,"utf-8"));if(t.version)return t.version}catch{continue}throw new Error("Could not read package.json version. Ensure you are running from a valid installation.")}async function dn(){let o=(await kn(Cs,{timeout:{request:1e4},retry:{limit:2}}).json()).version,t=be(),n=ln(t,o);return {version:o,hasBreakingChanges:n}}function Ts(e,o,t){console.log();let n=60,r="\u256D"+"\u2500".repeat(n-2)+"\u256E",s="\u2570"+"\u2500".repeat(n-2)+"\u256F";console.log(l.cyan(r));let i=` \u{1F680} Update available: ${l.gray(e)} \u2192 ${l.green(o)}`;if(console.log(l.cyan("\u2502")+i.padEnd(n+18)+l.cyan("\u2502")),t){console.log(l.cyan("\u2502")+"".padEnd(n-2)+l.cyan("\u2502"));let c=` ${l.yellow("\u26A0\uFE0F This update contains breaking changes!")}`;console.log(l.cyan("\u2502")+c.padEnd(n+20)+l.cyan("\u2502"));let g=` ${l.gray("Run:")} leetcode changelog ${l.gray("to review changes")}`;console.log(l.cyan("\u2502")+g.padEnd(n+16)+l.cyan("\u2502"));}console.log(l.cyan("\u2502")+"".padEnd(n-2)+l.cyan("\u2502"));let a=` ${l.gray("Run:")} npm update -g ${Ps}`;console.log(l.cyan("\u2502")+a.padEnd(n+8)+l.cyan("\u2502")),console.log(l.cyan(s)),console.log();}async function un(e){let o=be();e.force&&se.clearCache();let t=se.getCached(),n,r;if(t&&!se.shouldCheck()&&!e.force)n=t.latestVersion,r=t.hasBreakingChanges;else {let s=je("Checking for updates...").start();try{let i=await dn();n=i.version,r=i.hasBreakingChanges,se.updateCache(n,r),s.stop();}catch(i){s.fail("Failed to check for updates"),process.env.DEBUG&&console.log(l.gray(` Debug: ${i instanceof Error?i.message:String(i)}`)),console.log(l.gray(" Could not reach npm registry. Check your internet connection."));return}}he(o,n)?(Ts(o,n,r),e.checkOnly||r&&(console.log(l.yellow("\u{1F4A1} Tip: Review the changelog before updating to check for breaking changes.")),console.log(l.gray(` Run: leetcode changelog
|
|
243
|
+
`)))):(console.log(),console.log(l.green("\u2713")+` You're on the latest version (${l.cyan(o)})`),console.log());}async function pn(){if(!se.shouldCheck()){let e=se.getCached();e&&he(be(),e.latestVersion)&&mn(be(),e.latestVersion,e.hasBreakingChanges);return}try{let e=await dn();se.updateCache(e.version,e.hasBreakingChanges),he(be(),e.version)&&mn(be(),e.version,e.hasBreakingChanges);}catch{}}function mn(e,o,t){console.log(),t?(console.log(l.yellow(`\u26A0\uFE0F Update ${e} \u2192 ${o} available (breaking changes!)`)),console.log(l.gray(" Run: leetcode changelog && leetcode update"))):(console.log(l.cyan(`\u{1F680} Update available: ${e} \u2192 ${o}`)),console.log(l.gray(" Run: leetcode update"))),console.log();}var Rs=fileURLToPath(import.meta.url),yn=dirname(Rs),Fs="https://raw.githubusercontent.com/night-slayer18/leetcode-cli/main/docs/releases.md";function _s(){let e=[join(yn,"../package.json"),join(yn,"../../package.json")];for(let o of e)try{let t=JSON.parse(readFileSync(o,"utf-8"));if(t.version)return t.version}catch{continue}throw new Error("Could not read package.json version. Ensure you are running from a valid installation.")}async function Ns(){return await kn(Fs,{timeout:{request:1e4},retry:{limit:2}}).text()}function Is(e){let o=[],t=/^## v?([\d.]+)/gm,n=[...e.matchAll(t)];for(let r=0;r<n.length;r++){let s=n[r],i=`v${s[1]}`,a=s.index+s[0].length,c=r+1<n.length?n[r+1].index:e.length,g=e.slice(a,c).trim(),u=g.includes("\u26A0\uFE0F Breaking Change");o.push({version:i,content:g,hasBreakingChanges:u});}return o}function Us(e,o,t){let n=t?l.bgRed.white.bold(` ${e} `)+l.red(" \u26A0\uFE0F BREAKING CHANGES"):l.bgCyan.black.bold(` ${e} `);console.log(n),console.log();let r=o.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(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}`));}s=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=je("Fetching changelog...").start();try{let n=await Ns();t.stop();let r=Is(n);if(r.length===0){console.log(l.yellow("No release entries found."));return}let s=_s(),i=r;if(e){let a=e.startsWith("v")?e:`v${e}`;if(i=r.filter(c=>c.version===a),i.length===0){console.log(l.red(`Version ${e} not found in changelog.`)),console.log(l.gray("Available versions: "+r.map(c=>c.version).join(", ")));return}}else if(o.latest)i=r.slice(0,1);else if(o.breaking){if(i=r.filter(a=>a.hasBreakingChanges),i.length===0){console.log(l.green("\u2713 No breaking changes in any release."));return}}else if(o.all)i=r;else {if(i=r.filter(a=>he(a.version,s)),i.length===0){console.log(l.green(`\u2713 You're on the latest version (${s})`)),console.log(l.gray("Use --all to see the full changelog."));return}console.log(l.gray(`Showing changes since your version (${s})`)),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)Us(a.version,a.content,a.hasBreakingChanges),console.log(l.gray("\u2500".repeat(60))),console.log();if(!e&&!o.latest){let a=r.filter(c=>c.hasBreakingChanges).length;console.log(l.gray(`Showing ${i.length} of ${r.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 P=new Command;P.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)});P.name("leetcode").usage("[command] [options]").description(l.bold.cyan("\u{1F525} A modern LeetCode CLI built with TypeScript")).version("2.2.0","-v, --version","Output the version number").helpOption("-h, --help","Display help for command").addHelpText("after",`
|
|
242
245
|
${l.yellow("Examples:")}
|
|
243
246
|
${l.cyan("$ leetcode login")} Login to LeetCode
|
|
244
247
|
${l.cyan("$ leetcode list -d easy")} List easy problems
|
|
@@ -246,14 +249,14 @@ ${l.yellow("Examples:")}
|
|
|
246
249
|
${l.cyan("$ leetcode pick 1")} Start solving "Two Sum"
|
|
247
250
|
${l.cyan("$ leetcode test 1")} Test your solution
|
|
248
251
|
${l.cyan("$ leetcode submit 1")} Submit your solution
|
|
249
|
-
`);
|
|
252
|
+
`);P.command("login").description("Login to LeetCode with browser cookies").addHelpText("after",`
|
|
250
253
|
${l.yellow("How to login:")}
|
|
251
254
|
1. Open ${l.cyan("https://leetcode.com")} in your browser
|
|
252
255
|
2. Login to your account
|
|
253
256
|
3. Open Developer Tools (F12) \u2192 Application \u2192 Cookies
|
|
254
257
|
4. Copy values of ${l.green("LEETCODE_SESSION")} and ${l.green("csrftoken")}
|
|
255
258
|
5. Paste when prompted by this command
|
|
256
|
-
`).action(
|
|
259
|
+
`).action(xo);P.command("logout").description("Clear stored credentials").action(Eo);P.command("whoami").description("Check current login status").action(Lo);P.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",`
|
|
257
260
|
${l.yellow("Examples:")}
|
|
258
261
|
${l.cyan("$ leetcode list")} List first 20 problems
|
|
259
262
|
${l.cyan("$ leetcode list -d easy")} List easy problems only
|
|
@@ -261,23 +264,31 @@ ${l.yellow("Examples:")}
|
|
|
261
264
|
${l.cyan("$ leetcode list -t array -t string")} Filter by multiple tags
|
|
262
265
|
${l.cyan('$ leetcode list -q "two sum"')} Search by keywords
|
|
263
266
|
${l.cyan("$ leetcode list -n 50 -p 2")} Show 50 problems, page 2
|
|
264
|
-
`).action(Wo);
|
|
267
|
+
`).action(Wo);P.command("show <id>").alias("s").description("Show problem description").addHelpText("after",`
|
|
265
268
|
${l.yellow("Examples:")}
|
|
266
269
|
${l.cyan("$ leetcode show 1")} Show by problem ID
|
|
267
270
|
${l.cyan("$ leetcode show two-sum")} Show by problem slug
|
|
268
271
|
${l.cyan("$ leetcode s 412")} Short alias
|
|
269
|
-
`).action(
|
|
272
|
+
`).action(Fe);P.command("hint <id>").alias("h").description("Show hints for a problem").option("-a, --all","Show all hints at once").addHelpText("after",`
|
|
273
|
+
${l.yellow("Examples:")}
|
|
274
|
+
${l.cyan("$ leetcode hint 1")} Show hints for problem 1
|
|
275
|
+
${l.cyan("$ leetcode hint two-sum")} Show hints by slug
|
|
276
|
+
${l.cyan("$ leetcode hint 1 --all")} Show all hints at once
|
|
277
|
+
${l.cyan("$ leetcode h 412")} Short alias
|
|
278
|
+
|
|
279
|
+
${l.gray("Hints are revealed one at a time. Press Enter to see more.")}
|
|
280
|
+
`).action(Vo);P.command("daily").alias("d").description("Show today's daily challenge").addHelpText("after",`
|
|
270
281
|
${l.yellow("Examples:")}
|
|
271
282
|
${l.cyan("$ leetcode daily")} Show today's challenge
|
|
272
283
|
${l.cyan("$ leetcode d")} Short alias
|
|
273
|
-
`).action(
|
|
284
|
+
`).action(pt);P.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",`
|
|
274
285
|
${l.yellow("Examples:")}
|
|
275
286
|
${l.cyan("$ leetcode random")} Get any random problem
|
|
276
287
|
${l.cyan("$ leetcode random -d medium")} Random medium problem
|
|
277
288
|
${l.cyan("$ leetcode random -t array")} Random array problem
|
|
278
289
|
${l.cyan("$ leetcode random --pick")} Random + create file
|
|
279
290
|
${l.cyan("$ leetcode r -d easy --pick")} Random easy + file
|
|
280
|
-
`).action(
|
|
291
|
+
`).action(ft);P.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",`
|
|
281
292
|
${l.yellow("Examples:")}
|
|
282
293
|
${l.cyan("$ leetcode pick 1")} Pick by problem ID
|
|
283
294
|
${l.cyan("$ leetcode pick two-sum")} Pick by problem slug
|
|
@@ -286,11 +297,11 @@ ${l.yellow("Examples:")}
|
|
|
286
297
|
${l.cyan("$ leetcode p 412")} Short alias
|
|
287
298
|
|
|
288
299
|
${l.gray("Files are organized by: workDir/Difficulty/Category/")}
|
|
289
|
-
`).action(async(e,o)=>{await
|
|
300
|
+
`).action(async(e,o)=>{await Q(e,o);});P.command("pick-batch <ids...>").description("Generate solution files for multiple problems").option("-l, --lang <language>","Programming language for the solutions").addHelpText("after",`
|
|
290
301
|
${l.yellow("Examples:")}
|
|
291
302
|
${l.cyan("$ leetcode pick-batch 1 2 3")} Pick problems 1, 2, and 3
|
|
292
303
|
${l.cyan("$ leetcode pick-batch 1 2 3 -l py")} Pick with Python
|
|
293
|
-
`).action(
|
|
304
|
+
`).action(Xo);P.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",`
|
|
294
305
|
${l.yellow("Examples:")}
|
|
295
306
|
${l.cyan("$ leetcode test 1")} Test by problem ID
|
|
296
307
|
${l.cyan("$ leetcode test two-sum")} Test by problem slug
|
|
@@ -300,25 +311,25 @@ ${l.yellow("Examples:")}
|
|
|
300
311
|
${l.cyan("$ leetcode t 412")} Short alias
|
|
301
312
|
|
|
302
313
|
${l.gray("Testcases use \\n to separate multiple inputs.")}
|
|
303
|
-
`).action(
|
|
314
|
+
`).action(st);P.command("submit <file>").alias("x").description("Submit solution to LeetCode").addHelpText("after",`
|
|
304
315
|
${l.yellow("Examples:")}
|
|
305
316
|
${l.cyan("$ leetcode submit 1")} Submit by problem ID
|
|
306
317
|
${l.cyan("$ leetcode submit two-sum")} Submit by problem slug
|
|
307
318
|
${l.cyan("$ leetcode submit ./path/to/file.py")} Submit by file path
|
|
308
319
|
${l.cyan("$ leetcode x 412")} Short alias
|
|
309
|
-
`).action(
|
|
320
|
+
`).action(lt);P.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",`
|
|
310
321
|
${l.yellow("Examples:")}
|
|
311
322
|
${l.cyan("$ leetcode diff 1")} Compare with last accepted
|
|
312
323
|
${l.cyan("$ leetcode diff 1 -u")} Show unified diff
|
|
313
324
|
${l.cyan("$ leetcode diff 1 -s 12345")} Compare with specific submission
|
|
314
325
|
${l.cyan("$ leetcode diff 1 -f other.py")} Compare with local file
|
|
315
|
-
`).action(
|
|
326
|
+
`).action(Zt);P.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",`
|
|
316
327
|
${l.yellow("Examples:")}
|
|
317
328
|
${l.cyan("$ leetcode submissions 1")} View submissions for problem
|
|
318
329
|
${l.cyan("$ leetcode submissions 1 -n 5")} Show last 5 submissions
|
|
319
330
|
${l.cyan("$ leetcode submissions 1 --last")} Show last accepted submission
|
|
320
331
|
${l.cyan("$ leetcode submissions 1 --download")} Download last accepted code
|
|
321
|
-
`).action(
|
|
332
|
+
`).action(bt);P.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",`
|
|
322
333
|
${l.yellow("Options Explained:")}
|
|
323
334
|
${l.cyan("-c, --calendar")} Shows a table of your weekly submissions and active days
|
|
324
335
|
for the past 12 weeks. Useful for tracking consistency.
|
|
@@ -336,10 +347,10 @@ ${l.yellow("Examples:")}
|
|
|
336
347
|
${l.cyan("$ leetcode stat -c")} Weekly activity table
|
|
337
348
|
${l.cyan("$ leetcode stat -s")} Topic-wise breakdown
|
|
338
349
|
${l.cyan("$ leetcode stat -t")} 7-day trend chart
|
|
339
|
-
`).action((e,o)=>
|
|
350
|
+
`).action((e,o)=>ut(e,o));P.command("today").description("Show today's progress summary").addHelpText("after",`
|
|
340
351
|
${l.yellow("Examples:")}
|
|
341
352
|
${l.cyan("$ leetcode today")} Show streak, solved, and daily challenge
|
|
342
|
-
`).action(
|
|
353
|
+
`).action(Pt);P.command("bookmark <action> [id]").description("Manage problem bookmarks").addHelpText("after",`
|
|
343
354
|
${l.yellow("Actions:")}
|
|
344
355
|
${l.cyan("add <id>")} Bookmark a problem
|
|
345
356
|
${l.cyan("remove <id>")} Remove a bookmark
|
|
@@ -350,7 +361,7 @@ ${l.yellow("Examples:")}
|
|
|
350
361
|
${l.cyan("$ leetcode bookmark add 1")} Bookmark problem 1
|
|
351
362
|
${l.cyan("$ leetcode bookmark remove 1")} Remove bookmark
|
|
352
363
|
${l.cyan("$ leetcode bookmark list")} List all bookmarks
|
|
353
|
-
`).action(
|
|
364
|
+
`).action(kt);P.command("note <id> [action]").description("View or edit notes for a problem").addHelpText("after",`
|
|
354
365
|
${l.yellow("Actions:")}
|
|
355
366
|
${l.cyan("edit")} Open notes in editor (default)
|
|
356
367
|
${l.cyan("view")} Display notes in terminal
|
|
@@ -359,10 +370,10 @@ ${l.yellow("Examples:")}
|
|
|
359
370
|
${l.cyan("$ leetcode note 1")} Edit notes for problem 1
|
|
360
371
|
${l.cyan("$ leetcode note 1 edit")} Edit notes (explicit)
|
|
361
372
|
${l.cyan("$ leetcode note 1 view")} View notes in terminal
|
|
362
|
-
`).action(
|
|
373
|
+
`).action(Ct);P.command("sync").description("Sync solutions to Git repository").addHelpText("after",`
|
|
363
374
|
${l.yellow("Examples:")}
|
|
364
375
|
${l.cyan("$ leetcode sync")} Sync all solutions to remote
|
|
365
|
-
`).action(
|
|
376
|
+
`).action(Dt);P.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").option("-i, --interactive","Interactive configuration").addHelpText("after",`
|
|
366
377
|
${l.yellow("Examples:")}
|
|
367
378
|
${l.cyan("$ leetcode config")} View current config
|
|
368
379
|
${l.cyan("$ leetcode config -l python3")} Set language to Python
|
|
@@ -372,7 +383,7 @@ ${l.yellow("Examples:")}
|
|
|
372
383
|
${l.cyan("$ leetcode config -i")} Interactive setup
|
|
373
384
|
|
|
374
385
|
${l.gray("Supported languages: typescript, javascript, python3, java, cpp, c, csharp, go, rust, kotlin, swift")}
|
|
375
|
-
`).action(async e=>{e.interactive?await
|
|
386
|
+
`).action(async e=>{e.interactive?await St():await wt(e);});P.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",`
|
|
376
387
|
${l.yellow("How it works:")}
|
|
377
388
|
Start a problem with a countdown timer to simulate interview conditions.
|
|
378
389
|
Default time limits: Easy (20 min), Medium (40 min), Hard (60 min).
|
|
@@ -383,7 +394,7 @@ ${l.yellow("Examples:")}
|
|
|
383
394
|
${l.cyan("$ leetcode timer 1 -m 30")} Start with 30 minute limit
|
|
384
395
|
${l.cyan("$ leetcode timer --stats")} Show your solve time statistics
|
|
385
396
|
${l.cyan("$ leetcode timer --stop")} Stop active timer
|
|
386
|
-
`).action((e,o)=>
|
|
397
|
+
`).action((e,o)=>xt(e,o));var Te=P.command("workspace").description("Manage workspaces for different contexts");Te.command("current").description("Show current workspace").action(en);Te.command("list").description("List all workspaces").action(on);Te.command("create <name>").description("Create a new workspace").option("-w, --workdir <path>","Set working directory for this workspace").action(tn);Te.command("use <name>").description("Switch to a workspace").action(nn);Te.command("delete <name>").description("Delete a workspace").action(rn);var we=P.command("collab").description("Collaborative coding with a partner").addHelpText("after",`
|
|
387
398
|
${l.yellow("Subcommands:")}
|
|
388
399
|
${l.cyan("host <id>")} Create a room and get a code to share
|
|
389
400
|
${l.cyan("join <code>")} Join a room with the shared code
|
|
@@ -397,7 +408,7 @@ ${l.yellow("Examples:")}
|
|
|
397
408
|
${l.gray("$ leetcode collab join ABC123")} Join your partner's session
|
|
398
409
|
${l.gray("$ leetcode collab sync")} Upload your code after solving
|
|
399
410
|
${l.gray("$ leetcode collab compare")} Compare solutions
|
|
400
|
-
`);
|
|
411
|
+
`);we.command("host <problemId>").description("Host a collaboration session").action(At);we.command("join <roomCode>").description("Join a collaboration session").action(Rt);we.command("sync").description("Sync your code with partner").action(Ft);we.command("compare").description("Compare your solution with partner").action(_t);we.command("leave").description("Leave the collaboration session").action(Nt);we.command("status").description("Show collaboration status").action(It);var De=P.command("snapshot").description("Save and restore solution versions").addHelpText("after",`
|
|
401
412
|
${l.yellow("Subcommands:")}
|
|
402
413
|
${l.cyan("save <id> [name]")} Save current solution as a snapshot
|
|
403
414
|
${l.cyan("list <id>")} List all snapshots for a problem
|
|
@@ -410,16 +421,16 @@ ${l.yellow("Examples:")}
|
|
|
410
421
|
${l.gray("$ leetcode snapshot list 1")} List snapshots
|
|
411
422
|
${l.gray("$ leetcode snapshot restore 1 2")} Restore snapshot #2
|
|
412
423
|
${l.gray("$ leetcode snapshot diff 1 1 2")} Compare snapshots
|
|
413
|
-
`);
|
|
424
|
+
`);De.command("save <id> [name]").description("Save current solution as a snapshot").action(zt);De.command("list <id>").description("List all snapshots for a problem").action(Bt);De.command("restore <id> <snapshot>").description("Restore a snapshot").action(Gt);De.command("diff <id> <snap1> <snap2>").description("Compare two snapshots").action(Yt);De.command("delete <id> <snapshot>").description("Delete a snapshot").action(Qt);P.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",`
|
|
414
425
|
${l.yellow("Examples:")}
|
|
415
426
|
${l.cyan("$ leetcode update")} Check for updates
|
|
416
427
|
${l.cyan("$ leetcode update --force")} Force re-check npm registry
|
|
417
428
|
${l.cyan("$ leetcode update --check-only")} Just check, minimal output
|
|
418
|
-
`).action(
|
|
429
|
+
`).action(un);P.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",`
|
|
419
430
|
${l.yellow("Examples:")}
|
|
420
431
|
${l.cyan("$ leetcode changelog")} Show what's new since your version
|
|
421
432
|
${l.cyan("$ leetcode changelog --all")} View full changelog
|
|
422
433
|
${l.cyan("$ leetcode changelog 2.0.0")} Show specific version
|
|
423
434
|
${l.cyan("$ leetcode changelog --latest")} Show latest version only
|
|
424
435
|
${l.cyan("$ leetcode changelog --breaking")} Filter to breaking changes
|
|
425
|
-
`).action((e,o)=>
|
|
436
|
+
`).action((e,o)=>hn(e,o));P.showHelpAfterError("(add --help for additional information)");var Ms=process.argv.length>2&&!["update","changelog","--version","-v","--help","-h"].includes(process.argv[2]);Ms&&pn().catch(()=>{});P.parse();process.argv.slice(2).length||(console.log(),console.log(l.bold.cyan(" \u{1F525} LeetCode CLI")),console.log(l.gray(" A modern command-line interface for LeetCode")),console.log(),P.outputHelp());
|