@night-slayer18/leetcode-cli 2.1.0 → 2.1.1

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.
Files changed (2) hide show
  1. package/dist/index.js +33 -33
  2. package/package.json +1 -1
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 eo from'inquirer';import Ie from'ora';import pn from'got';import {z}from'zod';import fn from'conf';import {homedir}from'os';import {join,dirname,basename,extname,resolve,sep}from'path';import Oe 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 An from'open';import {createClient}from'@supabase/supabase-js';import {diffLines}from'diff';import {fileURLToPath}from'url';var mn=z.object({name:z.string(),slug:z.string()}),dn=z.object({name:z.string(),slug:z.string()}),un=z.object({lang:z.string(),langSlug:z.string(),code:z.string()}),Te=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(mn),status:z.enum(["ac","notac"]).nullable()}),lo=Te.extend({content:z.string().nullable(),codeSnippets:z.array(un).nullable(),sampleTestCase:z.string(),exampleTestcases:z.string(),hints:z.array(z.string()),companyTags:z.array(dn).nullable(),stats:z.string()}),co=z.object({date:z.string(),link:z.string(),question:Te}),go=z.object({id:z.string(),statusDisplay:z.string(),lang:z.string(),runtime:z.string(),timestamp:z.string(),memory:z.string()}),mo=z.object({code:z.string(),lang:z.object({name:z.string()})}),uo=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()}),po=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()}),fo=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()})}),yo=z.object({isSignedIn:z.boolean(),username:z.string().nullable()});var ho=`
2
+ import {Command}from'commander';import l from'chalk';import oo from'inquirer';import Ue from'ora';import wn from'got';import {z}from'zod';import Sn 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 In from'open';import {createClient}from'@supabase/supabase-js';import {diffLines}from'diff';import {fileURLToPath}from'url';var yn=z.object({name:z.string(),slug:z.string()}),hn=z.object({name:z.string(),slug:z.string()}),bn=z.object({lang:z.string(),langSlug:z.string(),code:z.string()}),De=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(yn),status:z.enum(["ac","notac"]).nullable()}),lo=De.extend({content:z.string().nullable(),codeSnippets:z.array(bn).nullable(),sampleTestCase:z.string(),exampleTestcases:z.string(),hints:z.array(z.string()),companyTags:z.array(hn).nullable(),stats:z.string()}),co=z.object({date:z.string(),link:z.string(),question:De}),go=z.object({id:z.string(),statusDisplay:z.string(),lang:z.string(),runtime:z.string(),timestamp:z.string(),memory:z.string()}),mo=z.object({code:z.string(),lang:z.object({name:z.string()})}),uo=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()}),po=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()}),fo=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()})}),yo=z.object({isSignedIn:z.boolean(),username:z.string().nullable()});var ho=`
3
3
  query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) {
4
4
  problemsetQuestionList: questionList(
5
5
  categorySlug: $categorySlug
@@ -157,12 +157,12 @@ import {Command}from'commander';import l from'chalk';import eo from'inquirer';im
157
157
  }
158
158
  }
159
159
  }
160
- `;var xe="https://leetcode.com",Me=class{client;credentials=null;constructor(){this.client=pn.extend({prefixUrl:xe,headers:{"Content-Type":"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",Origin:xe,Referer:`${xe}/`},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(wo);return yo.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(ho,t),s=z.array(Te).parse(n.problemsetQuestionList.questions);return {total:n.problemsetQuestionList.total,problems:s}}async getProblem(o){let t=await this.graphql(bo,{titleSlug:o});return lo.parse(t.question)}async getProblemById(o){let{problems:t}=await this.getProblems({searchKeywords:o,limit:10}),n=t.find(s=>s.questionFrontendId===o);if(!n)throw new Error(`Problem #${o} not found`);return this.getProblem(n.titleSlug)}async getDailyChallenge(){let o=await this.graphql(ko);return co.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(Co,t);return z.object({titleSlug:z.string()}).parse(n.randomQuestion).titleSlug}async getUserProfile(o){let n=(await this.graphql(So,{username:o})).matchedUser,s=fo.parse(n);return {username:s.username,realName:s.profile.realName,ranking:s.profile.ranking,acSubmissionNum:s.submitStatsGlobal.acSubmissionNum,streak:s.userCalendar.streak,totalActiveDays:s.userCalendar.totalActiveDays,submissionCalendar:n.userCalendar.submissionCalendar}}async getSkillStats(o){return (await this.graphql($o,{username:o})).matchedUser.tagProblemCounts}async getSubmissionList(o,t=20,n=0){let s=await this.graphql(vo,{questionSlug:o,limit:t,offset:n});return z.array(go).parse(s.questionSubmissionList.submissions)}async getSubmissionDetails(o){let t=await this.graphql(Po,{submissionId:o});return mo.parse(t.submissionDetails)}async testSolution(o,t,n,s,r){let i=await this.client.post(`problems/${o}/interpret_solution/`,{json:{data_input:s,lang:n,typed_code:t,question_id:r}}).json();return this.pollSubmission(i.interpret_id,"interpret",uo)}async submitSolution(o,t,n,s){let r=await this.client.post(`problems/${o}/submit/`,{json:{lang:n,typed_code:t,question_id:s}}).json();return this.pollSubmission(r.submission_id.toString(),"submission",po)}async pollSubmission(o,t,n){let s=`submissions/detail/${o}/check/`,r=30,i=1e3;for(let a=0;a<r;a++){let c=await this.client.get(s).json();if(c.state==="SUCCESS"||c.state==="FAILURE")return n.parse(c);await new Promise(g=>setTimeout(g,i));}throw new Error("Submission timeout: Result not available after 30 seconds")}},h=new Me;var ce=new fn({configName:"credentials",cwd:join(homedir(),".leetcode"),defaults:{}}),K={get(){let e=ce.get("session"),o=ce.get("csrfToken");return !e||!o?null:{session:e,csrfToken:o}},set(e){ce.set("session",e.session),ce.set("csrfToken",e.csrfToken);},clear(){ce.clear();},getPath(){return ce.path}};async function Do(){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 eo.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=Ie("Verifying credentials...").start();try{h.setCredentials(o);let{isSignedIn:n,username:s}=await h.checkAuth();if(!n||!s){t.fail("Invalid credentials"),console.log(l.red("Please check your session cookies and try again."));return}K.set(o),t.succeed(`Logged in as ${l.green(s)}`),console.log(),console.log(l.gray(`Credentials saved to ${K.getPath()}`));}catch(n){t.fail("Authentication failed"),n instanceof Error&&console.log(l.red(n.message));}}async function xo(){K.clear(),console.log(l.green("\u2713 Logged out successfully"));}async function Eo(){let e=K.get();if(!e){console.log(l.yellow('Not logged in. Run "leetcode login" to authenticate.'));return}let o=Ie("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 v(){let e=K.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 wn={"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 Sn(e){for(let o of e){let t=wn[o.name];if(t)return t}return null}function Lo(e){try{return JSON.parse(e)}catch{return e}}function ee(e){return Array.isArray(e)&&e.length>0&&Array.isArray(e[0])}function Ao(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),s=e.map((i,a)=>`[${a}]`.padStart(n).padEnd(n)).join(" "),r=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(s)}
160
+ `;var Ee="https://leetcode.com",qe=class{client;credentials=null;constructor(){this.client=wn.extend({prefixUrl:Ee,headers:{"Content-Type":"application/json","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",Origin:Ee,Referer:`${Ee}/`},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(wo);return yo.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(ho,t),s=z.array(De).parse(n.problemsetQuestionList.questions);return {total:n.problemsetQuestionList.total,problems:s}}async getProblem(o){let t=await this.graphql(bo,{titleSlug:o});return lo.parse(t.question)}async getProblemById(o){let{problems:t}=await this.getProblems({searchKeywords:o,limit:10}),n=t.find(s=>s.questionFrontendId===o);if(!n)throw new Error(`Problem #${o} not found`);return this.getProblem(n.titleSlug)}async getDailyChallenge(){let o=await this.graphql(ko);return co.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(Co,t);return z.object({titleSlug:z.string()}).parse(n.randomQuestion).titleSlug}async getUserProfile(o){let n=(await this.graphql(So,{username:o})).matchedUser,s=fo.parse(n);return {username:s.username,realName:s.profile.realName,ranking:s.profile.ranking,acSubmissionNum:s.submitStatsGlobal.acSubmissionNum,streak:s.userCalendar.streak,totalActiveDays:s.userCalendar.totalActiveDays,submissionCalendar:n.userCalendar.submissionCalendar}}async getSkillStats(o){return (await this.graphql($o,{username:o})).matchedUser.tagProblemCounts}async getSubmissionList(o,t=20,n=0){let s=await this.graphql(vo,{questionSlug:o,limit:t,offset:n});return z.array(go).parse(s.questionSubmissionList.submissions)}async getSubmissionDetails(o){let t=await this.graphql(Po,{submissionId:o});return mo.parse(t.submissionDetails)}async testSolution(o,t,n,s,r){let i=await this.client.post(`problems/${o}/interpret_solution/`,{json:{data_input:s,lang:n,typed_code:t,question_id:r}}).json();return this.pollSubmission(i.interpret_id,"interpret",uo)}async submitSolution(o,t,n,s){let r=await this.client.post(`problems/${o}/submit/`,{json:{lang:n,typed_code:t,question_id:s}}).json();return this.pollSubmission(r.submission_id.toString(),"submission",po)}async pollSubmission(o,t,n){let s=`submissions/detail/${o}/check/`,r=30,i=1e3;for(let a=0;a<r;a++){let c=await this.client.get(s).json();if(c.state==="SUCCESS"||c.state==="FAILURE")return n.parse(c);await new Promise(g=>setTimeout(g,i));}throw new Error("Submission timeout: Result not available after 30 seconds")}},h=new qe;var ce=new Sn({configName:"credentials",cwd:join(homedir(),".leetcode"),defaults:{}}),K={get(){let e=ce.get("session"),o=ce.get("csrfToken");return !e||!o?null:{session:e,csrfToken:o}},set(e){ce.set("session",e.session),ce.set("csrfToken",e.csrfToken);},clear(){ce.clear();},getPath(){return ce.path}};async function Do(){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 oo.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=Ue("Verifying credentials...").start();try{h.setCredentials(o);let{isSignedIn:n,username:s}=await h.checkAuth();if(!n||!s){t.fail("Invalid credentials"),console.log(l.red("Please check your session cookies and try again."));return}K.set(o),t.succeed(`Logged in as ${l.green(s)}`),console.log(),console.log(l.gray(`Credentials saved to ${K.getPath()}`));}catch(n){t.fail("Authentication failed"),n instanceof Error&&console.log(l.red(n.message));}}async function xo(){K.clear(),console.log(l.green("\u2713 Logged out successfully"));}async function Eo(){let e=K.get();if(!e){console.log(l.yellow('Not logged in. Run "leetcode login" to authenticate.'));return}let o=Ue("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 v(){let e=K.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 Cn={"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 Pn(e){for(let o of e){let t=Cn[o.name];if(t)return t}return null}function Lo(e){try{return JSON.parse(e)}catch{return e}}function ee(e){return Array.isArray(e)&&e.length>0&&Array.isArray(e[0])}function Ao(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),s=e.map((i,a)=>`[${a}]`.padStart(n).padEnd(n)).join(" "),r=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(s)}
161
161
  ${r}`}function Ro(e,o){return Array.isArray(e)?e.length===0?l.gray("(empty)"):e.map((n,s)=>{let r=String(n);return o&&Array.isArray(o)&&(s>=o.length||o[s]!==n)?l.red.bold(r):r}).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 s(r,i,a,c){if(i>e.length-1)return;let g=[],u=[],p=Math.floor(n/Math.pow(2,r+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,Z=R<e.length&&e[R]!==null,re=q<e.length&&e[q]!==null;if(Z||re){let H="";Z?H+="/":H+=" ",H+=" ",re?H+="\\":H+=" ",u.push(H.padStart(p).padEnd(p));}}g.length>0&&(o.push(g.join("")),u.length>0&&r<t-1&&o.push(u.join("")));}for(let r=0;r<t;r++){let i=Math.pow(2,r)-1,a=Math.pow(2,r+1)-2;s(r,i,a);}return o.join(`
162
- `)}function Ee(e,o){if(!ee(e)||e.length===0)return String(e);let t=e.length,n=e[0].length,s=3,r=[],i=" "+e[0].map((a,c)=>String(c).padStart(s).padEnd(s)).join(" ");r.push(l.gray(i)),r.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&&ee(o)&&o[a]&&o[a][u]!==g?l.red.bold(p):p}).join(" \u2502 ");r.push(l.gray(` ${a} `)+`\u2502 ${c} \u2502`),a<t-1?r.push(" \u251C"+Array(n).fill("\u2500\u2500\u2500").join("\u253C")+"\u2524"):r.push(" \u2514"+Array(n).fill("\u2500\u2500\u2500").join("\u2534")+"\u2518");}return r.join(`
162
+ `)}function Le(e,o){if(!ee(e)||e.length===0)return String(e);let t=e.length,n=e[0].length,s=3,r=[],i=" "+e[0].map((a,c)=>String(c).padStart(s).padEnd(s)).join(" ");r.push(l.gray(i)),r.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&&ee(o)&&o[a]&&o[a][u]!==g?l.red.bold(p):p}).join(" \u2502 ");r.push(l.gray(` ${a} `)+`\u2502 ${c} \u2502`),a<t-1?r.push(" \u251C"+Array(n).fill("\u2500\u2500\u2500").join("\u253C")+"\u2524"):r.push(" \u2514"+Array(n).fill("\u2500\u2500\u2500").join("\u2534")+"\u2518");}return r.join(`
163
163
  `)}function Fo(e){return ee(e)?e.map((t,n)=>{let s=Array.isArray(t)?t.join(", "):String(t);return ` ${l.cyan(String(n))} \u2192 [${s}]`}).join(`
164
- `):String(e)}function No(e,o,t){let n=Lo(e),s=Lo(o),r=e===o,i=Sn(t),a,c;if(ee(n)){let g=ee(s)?s:void 0;return a=Ee(n,g),c=ee(s)?Ee(s):String(o),{outputVis:a,expectedVis:c,matches:r}}if(i===null)return {outputVis:String(e),expectedVis:String(o),matches:r,unsupported:true};switch(i){case "linkedlist":a=Ro(n,s),c=Ro(s);break;case "tree":a=_o(n),c=_o(s);break;case "graph":a=Fo(n),c=Fo(s);break;case "matrix":let g=ee(s)?s:void 0;a=Ee(n,g),c=ee(s)?Ee(s):String(o);break;case "array":case "string":Array.isArray(n)?(a=Ao(n,s),c=Array.isArray(s)?Ao(s):String(o)):(a=r?String(e):l.red.bold(String(e)),c=String(o));break}return {outputVis:a,expectedVis:c,matches:r}}function Io(e,o){let t=new Oe({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 s=n.title;n.isPaidOnly&&(s=`\u{1F512} ${s}`),t.push([n.questionFrontendId,s.length>42?s.slice(0,39)+"...":s,Le(n.difficulty),`${n.acRate.toFixed(1)}%`,$n(n.status)]);}console.log(t.toString()),console.log(l.gray(`
165
- Showing ${e.length} of ${o} problems`));}function Uo(e){console.log();let o=e.isPaidOnly?"\u{1F512} ":"";if(console.log(l.bold.cyan(` ${e.questionFrontendId}. ${o}${e.title}`)),console.log(` ${Le(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(s=>l.bgBlue.white(` ${s.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,`
164
+ `):String(e)}function No(e,o,t){let n=Lo(e),s=Lo(o),r=e===o,i=Pn(t),a,c;if(ee(n)){let g=ee(s)?s:void 0;return a=Le(n,g),c=ee(s)?Le(s):String(o),{outputVis:a,expectedVis:c,matches:r}}if(i===null)return {outputVis:String(e),expectedVis:String(o),matches:r,unsupported:true};switch(i){case "linkedlist":a=Ro(n,s),c=Ro(s);break;case "tree":a=_o(n),c=_o(s);break;case "graph":a=Fo(n),c=Fo(s);break;case "matrix":let g=ee(s)?s:void 0;a=Le(n,g),c=ee(s)?Le(s):String(o);break;case "array":case "string":Array.isArray(n)?(a=Ao(n,s),c=Array.isArray(s)?Ao(s):String(o)):(a=r?String(e):l.red.bold(String(e)),c=String(o));break}return {outputVis:a,expectedVis:c,matches:r}}function Io(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 s=n.title;n.isPaidOnly&&(s=`\u{1F512} ${s}`),t.push([n.questionFrontendId,s.length>42?s.slice(0,39)+"...":s,Ae(n.difficulty),`${n.acRate.toFixed(1)}%`,Tn(n.status)]);}console.log(t.toString()),console.log(l.gray(`
165
+ Showing ${e.length} of ${o} problems`));}function Uo(e){console.log();let o=e.isPaidOnly?"\u{1F512} ":"";if(console.log(l.bold.cyan(` ${e.questionFrontendId}. ${o}${e.title}`)),console.log(` ${Ae(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(s=>l.bgBlue.white(` ${s.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,`
@@ -172,23 +172,23 @@ Showing ${e.length} of ${o} problems`));}function Uo(e){console.log();let o=e.is
172
172
  \u{1F4CB} Constraints:`)),t=t.replace(/§FOLLOWUP§/g,l.magenta.bold(`
173
173
  \u{1F4A1} Follow-up:`)),console.log(t),console.log();}function jo(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 r=t.map((i,a)=>({out:i,exp:n[a]??""})).filter(({out:i,exp:a})=>i!==""||a!=="");for(let i=0;i<r.length;i++){let{out:a,exp:c}=r[i],{outputVis:g,expectedVis:u,matches:p,unsupported:b}=No(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 r of t)console.log(l.white(` ${r}`));console.log(),console.log(l.gray("Expected Output:"));for(let r of n)console.log(l.white(` ${r}`));}let s=(e.std_output_list??[]).filter(r=>r);if(s.length>0){console.log(),console.log(l.gray("Stdout:"));for(let r of s)console.log(l.gray(` ${r}`));}}function Mo(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 qo(e,o,t,n,s,r){console.log(),console.log(l.bold.white(`\u{1F464} ${e}`)+(o?l.gray(` (${o})`):"")),console.log(l.gray(`Ranking: #${t.toLocaleString()}`)),console.log();let i=new Oe({head:[l.cyan("Difficulty"),l.cyan("Solved")],style:{head:[],border:[]}});for(let c of n)c.difficulty!=="All"&&i.push([Le(c.difficulty),c.count.toString()]);let a=n.find(c=>c.difficulty==="All")?.count??0;i.push([l.white.bold("Total"),l.white.bold(a.toString())]),console.log(i.toString()),console.log(),console.log(l.gray("\u{1F525} Current streak:"),l.hex("#FFA500")(s.toString()),l.gray("days")),console.log(l.gray("\u{1F4C5} Total active days:"),l.white(r.toString()));}function Oo(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(Le(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 Le(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 $n(e){switch(e){case "ac":return l.green("\u2713");case "notac":return l.yellow("\u25CB");default:return l.gray("-")}}function We(e){let o=new Oe({head:[l.cyan("ID"),l.cyan("Status"),l.cyan("Lang"),l.cyan("Runtime"),l.cyan("Memory"),l.cyan("Date")],colWidths:[12,18,15,12,12,25],style:{head:[],border:[]}});for(let t of e){let n=t.statusDisplay==="Accepted",s=new Date(parseInt(t.timestamp)*1e3).toLocaleString();o.push([t.id,n?l.green(t.statusDisplay):l.red(t.statusDisplay),t.lang,t.runtime,t.memory,s]);}console.log(o.toString());}async function Wo(e){let{authorized:o}=await v();if(!o)return;let t=Ie("Fetching problems...").start();try{let n={},s=parseInt(e.limit??"20",10),r=parseInt(e.page??"1",10);if(n.limit=s,n.skip=(r-1)*s,e.difficulty){let c={easy:"EASY",e:"EASY",medium:"MEDIUM",m:"MEDIUM",hard:"HARD",h:"HARD"};n.difficulty=c[e.difficulty.toLowerCase()];}if(e.status){let c={todo:"NOT_STARTED",solved:"AC",ac:"AC",attempted:"TRIED",tried:"TRIED"};n.status=c[e.status.toLowerCase()];}e.tag?.length&&(n.tags=e.tag),e.search&&(n.searchKeywords=e.search);let{total:i,problems:a}=await h.getProblems(n);if(t.stop(),a.length===0){console.log(l.yellow("No problems found matching your criteria."));return}Io(a,i),r*s<i&&console.log(l.gray(`
176
- Page ${r} of ${Math.ceil(i/s)}. Use --page to navigate.`));}catch(n){t.fail("Failed to fetch problems"),n instanceof Error&&console.log(l.red(n.message));}}async function Ae(e){let{authorized:o}=await v();if(!o)return;let t=Ie("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(),Uo(n);}catch(n){t.fail("Failed to fetch problem"),n instanceof Error&&console.log(l.red(n.message));}}var Ge=join(homedir(),".leetcode"),ze=join(Ge,"workspaces.json"),Re=join(Ge,"workspaces");function Fe(e){existsSync(e)||mkdirSync(e,{recursive:true});}function ie(){return existsSync(ze)?JSON.parse(readFileSync(ze,"utf-8")):{active:"default",workspaces:[]}}function _e(e){Fe(Ge),writeFileSync(ze,JSON.stringify(e,null,2));}var $={ensureInitialized(){let e=ie();e.workspaces.length===0&&(this.create("default",{workDir:join(homedir(),"leetcode"),lang:"typescript"}),e.workspaces=["default"],e.active="default",_e(e));},getActive(){return this.ensureInitialized(),ie().active},setActive(e){let o=ie();return o.workspaces.includes(e)?(o.active=e,_e(o),true):false},list(){return this.ensureInitialized(),ie().workspaces},exists(e){return this.ensureInitialized(),ie().workspaces.includes(e)},create(e,o){let t=ie();if(t.workspaces.includes(e))return false;let n=join(Re,e);Fe(n),Fe(join(n,"snapshots"));let s=join(n,"config.json");return writeFileSync(s,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),_e(t),true},delete(e){if(e==="default")return false;let o=ie();return o.workspaces.includes(e)?(o.workspaces=o.workspaces.filter(t=>t!==e),o.active===e&&(o.active="default"),_e(o),true):false},getWorkspaceDir(e){let o=e??this.getActive();return join(Re,o)},getConfig(e){let o=e??this.getActive(),t=join(Re,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(Re,t);Fe(n);let r={...this.getConfig(t),...e};writeFileSync(join(n,"config.json"),JSON.stringify(r,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=$.getConfig();return {language:e.lang,editor:e.editor,workDir:e.workDir,repo:e.syncRepo}},setLanguage(e){$.setConfig({lang:e});},setEditor(e){$.setConfig({editor:e});},setWorkDir(e){$.setConfig({workDir:e});},setRepo(e){$.setConfig({syncRepo:e});},deleteRepo(){let e=$.getConfig();delete e.syncRepo,$.setConfig(e);},getLanguage(){return $.getConfig().lang},getEditor(){return $.getConfig().editor},getWorkDir(){return $.getConfig().workDir},getRepo(){return $.getConfig().syncRepo},getPath(){return join($.getWorkspaceDir(),"config.json")},getActiveWorkspace(){return $.getActive()}};var ge={typescript:"ts",javascript:"js",python3:"py",java:"java",cpp:"cpp",c:"c",csharp:"cs",go:"go",rust:"rs",kotlin:"kt",swift:"swift"},we={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 Vo(e,o){let t=e.find(n=>we[n.langSlug.toLowerCase()]===o);return t||(e[0]??null)}function zo(e,o,t,n,s,r,i){let a=Dn(r);return `${En(a,e,t,n,o,i)}
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 r of t)console.log(l.white(` ${r}`));console.log(),console.log(l.gray("Expected Output:"));for(let r of n)console.log(l.white(` ${r}`));}let s=(e.std_output_list??[]).filter(r=>r);if(s.length>0){console.log(),console.log(l.gray("Stdout:"));for(let r of s)console.log(l.gray(` ${r}`));}}function Mo(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 qo(e,o,t,n,s,r){console.log(),console.log(l.bold.white(`\u{1F464} ${e}`)+(o?l.gray(` (${o})`):"")),console.log(l.gray(`Ranking: #${t.toLocaleString()}`)),console.log();let i=new We({head:[l.cyan("Difficulty"),l.cyan("Solved")],style:{head:[],border:[]}});for(let c of n)c.difficulty!=="All"&&i.push([Ae(c.difficulty),c.count.toString()]);let a=n.find(c=>c.difficulty==="All")?.count??0;i.push([l.white.bold("Total"),l.white.bold(a.toString())]),console.log(i.toString()),console.log(),console.log(l.gray("\u{1F525} Current streak:"),l.hex("#FFA500")(s.toString()),l.gray("days")),console.log(l.gray("\u{1F4C5} Total active days:"),l.white(r.toString()));}function Oo(e,o){if(console.log(),console.log(l.bold.yellow("\u{1F3AF} Daily Challenge"),l.gray(`(${e})`)),console.log(),console.log(l.white(`${o.questionFrontendId}. ${o.title}`)),console.log(Ae(o.difficulty)),console.log(l.gray(`https://leetcode.com/problems/${o.titleSlug}/`)),o.topicTags.length){console.log();let t=o.topicTags.map(n=>l.blue(n.name)).join(" ");console.log(l.gray("Tags:"),t);}}function Ae(e){switch(e.toLowerCase()){case "easy":return l.green(e);case "medium":return l.yellow(e);case "hard":return l.red(e);default:return e}}function Tn(e){switch(e){case "ac":return l.green("\u2713");case "notac":return l.yellow("\u25CB");default:return l.gray("-")}}function He(e){let o=new We({head:[l.cyan("ID"),l.cyan("Status"),l.cyan("Lang"),l.cyan("Runtime"),l.cyan("Memory"),l.cyan("Date")],colWidths:[12,18,15,12,12,25],style:{head:[],border:[]}});for(let t of e){let n=t.statusDisplay==="Accepted",s=new Date(parseInt(t.timestamp)*1e3).toLocaleString();o.push([t.id,n?l.green(t.statusDisplay):l.red(t.statusDisplay),t.lang,t.runtime,t.memory,s]);}console.log(o.toString());}async function Wo(e){let{authorized:o}=await v();if(!o)return;let t=Ue("Fetching problems...").start();try{let n={},s=parseInt(e.limit??"20",10),r=parseInt(e.page??"1",10);if(n.limit=s,n.skip=(r-1)*s,e.difficulty){let c={easy:"EASY",e:"EASY",medium:"MEDIUM",m:"MEDIUM",hard:"HARD",h:"HARD"};n.difficulty=c[e.difficulty.toLowerCase()];}if(e.status){let c={todo:"NOT_STARTED",solved:"AC",ac:"AC",attempted:"TRIED",tried:"TRIED"};n.status=c[e.status.toLowerCase()];}e.tag?.length&&(n.tags=e.tag),e.search&&(n.searchKeywords=e.search);let{total:i,problems:a}=await h.getProblems(n);if(t.stop(),a.length===0){console.log(l.yellow("No problems found matching your criteria."));return}Io(a,i),r*s<i&&console.log(l.gray(`
176
+ Page ${r} of ${Math.ceil(i/s)}. Use --page to navigate.`));}catch(n){t.fail("Failed to fetch problems"),n instanceof Error&&console.log(l.red(n.message));}}async function Re(e){let{authorized:o}=await v();if(!o)return;let t=Ue("Fetching problem...").start();try{let n;if(/^\d+$/.test(e)?n=await h.getProblemById(e):n=await h.getProblem(e),!n){t.fail(`Problem "${e}" not found`);return}t.stop(),Uo(n);}catch(n){t.fail("Failed to fetch problem"),n instanceof Error&&console.log(l.red(n.message));}}var Ye=join(homedir(),".leetcode"),Be=join(Ye,"workspaces.json"),_e=join(Ye,"workspaces");function Ne(e){existsSync(e)||mkdirSync(e,{recursive:true});}function ie(){return existsSync(Be)?JSON.parse(readFileSync(Be,"utf-8")):{active:"default",workspaces:[]}}function Fe(e){Ne(Ye),writeFileSync(Be,JSON.stringify(e,null,2));}var $={ensureInitialized(){let e=ie();e.workspaces.length===0&&(this.create("default",{workDir:join(homedir(),"leetcode"),lang:"typescript"}),e.workspaces=["default"],e.active="default",Fe(e));},getActive(){return this.ensureInitialized(),ie().active},setActive(e){let o=ie();return o.workspaces.includes(e)?(o.active=e,Fe(o),true):false},list(){return this.ensureInitialized(),ie().workspaces},exists(e){return this.ensureInitialized(),ie().workspaces.includes(e)},create(e,o){let t=ie();if(t.workspaces.includes(e))return false;let n=join(_e,e);Ne(n),Ne(join(n,"snapshots"));let s=join(n,"config.json");return writeFileSync(s,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),Fe(t),true},delete(e){if(e==="default")return false;let o=ie();return o.workspaces.includes(e)?(o.workspaces=o.workspaces.filter(t=>t!==e),o.active===e&&(o.active="default"),Fe(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);Ne(n);let r={...this.getConfig(t),...e};writeFileSync(join(n,"config.json"),JSON.stringify(r,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=$.getConfig();return {language:e.lang,editor:e.editor,workDir:e.workDir,repo:e.syncRepo}},setLanguage(e){$.setConfig({lang:e});},setEditor(e){$.setConfig({editor:e});},setWorkDir(e){$.setConfig({workDir:e});},setRepo(e){$.setConfig({syncRepo:e});},deleteRepo(){let e=$.getConfig();delete e.syncRepo,$.setConfig(e);},getLanguage(){return $.getConfig().lang},getEditor(){return $.getConfig().editor},getWorkDir(){return $.getConfig().workDir},getRepo(){return $.getConfig().syncRepo},getPath(){return join($.getWorkspaceDir(),"config.json")},getActiveWorkspace(){return $.getActive()}};var ge={typescript:"ts",javascript:"js",python3:"py",java:"java",cpp:"cpp",c:"c",csharp:"cs",go:"go",rust:"rs",kotlin:"kt",swift:"swift"},Se={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 Vo(e,o){let t=e.find(n=>Se[n.langSlug.toLowerCase()]===o);return t||(e[0]??null)}function zo(e,o,t,n,s,r,i){let a=Rn(r);return `${Fn(a,e,t,n,o,i)}
177
177
 
178
178
  ${s}
179
- `}function Dn(e){return e==="python3"?{single:"#",blockStart:'"""',blockEnd:'"""',linePrefix:""}:{single:"//",blockStart:"/*",blockEnd:"*/",linePrefix:" * "}}function xn(e){let o=e;return o=o.replace(/<sup>(.*?)<\/sup>/gi,"^$1"),o=o.replace(/<strong class="example">Example (\d+):<\/strong>/gi,`
179
+ `}function Rn(e){return e==="python3"?{single:"#",blockStart:'"""',blockEnd:'"""',linePrefix:""}:{single:"//",blockStart:"/*",blockEnd:"*/",linePrefix:" * "}}function _n(e){let o=e;return o=o.replace(/<sup>(.*?)<\/sup>/gi,"^$1"),o=o.replace(/<strong class="example">Example (\d+):<\/strong>/gi,`
180
180
  Example $1:`),o=o.replace(/<li>/gi,"\u2022 "),o=o.replace(/<\/li>/gi,`
181
181
  `),o=o.replace(/<\/p>/gi,`
182
182
 
183
183
  `),o=o.replace(/<br\s*\/?>/gi,`
184
184
  `),o=o.replace(/<[^>]+>/g,""),o=o.replace(/&nbsp;/g," ").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&le;/g,"<=").replace(/&ge;/g,">=").replace(/&#(\d+);/g,(t,n)=>String.fromCharCode(parseInt(n,10))),o=o.replace(/\n{3,}/g,`
185
185
 
186
- `).trim(),o}function En(e,o,t,n,s,r){let i=e.linePrefix,a=[e.blockStart,`${i}${o}. ${t}`,`${i}Difficulty: ${n}`,`${i}https://leetcode.com/problems/${s}/`];if(r){a.push(`${i}`),a.push(`${i}${"\u2500".repeat(50)}`),a.push(`${i}`);let g=xn(r).split(`
186
+ `).trim(),o}function Fn(e,o,t,n,s,r){let i=e.linePrefix,a=[e.blockStart,`${i}${o}. ${t}`,`${i}Difficulty: ${n}`,`${i}https://leetcode.com/problems/${s}/`];if(r){a.push(`${i}`),a.push(`${i}${"\u2500".repeat(50)}`),a.push(`${i}`);let g=_n(r).split(`
187
187
  `);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 Bo(e,o,t){let n=ge[t];return `${e}.${o}.${n}`}var _n=["vim","nvim","vi","nano","emacs","micro","helix"],Fn=["code","code-insiders","cursor","codium","vscodium"];async function Se(e,o){let t=w.getEditor()??process.env.EDITOR??"code",n=w.getWorkDir();if(_n.includes(t)){console.log(),console.log(l.gray(`Open with: ${t} ${e}`));return}try{if(Fn.includes(t)){spawn(t,["-r",n,"-g",e],{detached:!0,stdio:"ignore"}).unref();return}await An(e,{app:{name:t}});}catch{}}async function Y(e,o){let{authorized:t}=await v();if(!t)return false;let n=Ie({text:"Fetching problem details...",spinner:"dots"}).start();try{let s;if(/^\d+$/.test(e)?s=await h.getProblemById(e):s=await h.getProblem(e),!s)return n.fail(`Problem "${e}" not found`),!1;n.text="Generating solution file...";let r=o.lang?.toLowerCase()??w.getLanguage(),i=we[r]??r,a=s.codeSnippets??[],c=Vo(a,i),g;if(a.length===0)n.warn(l.yellow("Premium Problem (No code snippets available)")),console.log(l.gray("Generating placeholder file with problem info...")),g=`// \u{1F512} Premium Problem - ${s.title}
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(Z=>Z.langSlug).join(", ")}`)),!1;let u=zo(s.questionFrontendId,s.titleSlug,s.title,s.difficulty,g,i,s.content??void 0),p=w.getWorkDir(),b=s.difficulty,C=s.topicTags.length>0?s.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",I=join(p,b,C);existsSync(I)||await mkdir(I,{recursive:!0});let R=Bo(s.questionFrontendId,s.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 Se(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(`${s.questionFrontendId}. ${s.title}`)),console.log(l.gray(`Difficulty: ${s.difficulty} | Category: ${C}`)),o.open!==!1&&await Se(q),!0)}catch(s){if(n.fail("Failed to fetch problem"),s instanceof Error)if(s.message.includes("expected object, received null"))console.log(l.red(`Problem "${e}" not found`));else try{let r=JSON.parse(s.message);Array.isArray(r)?console.log(l.red("API Response Validation Failed")):console.log(l.red(s.message));}catch{console.log(l.red(s.message));}return false}}async function Jo(e,o){if(e.length===0){console.log(l.yellow("Please provide at least one problem ID"));return}let{authorized:t}=await v();if(!t)return;console.log(l.cyan(`\u{1F4E6} Picking ${e.length} problem${e.length!==1?"s":""}...`)),console.log(),console.log();let n=0,s=0;for(let r of e)await Y(r,{...o,open:false})?n++:s++,console.log();console.log(l.gray("\u2500".repeat(50))),console.log(l.bold(`Done! ${l.green(`${n} succeeded`)}${s>0?`, ${l.red(`${s} failed`)}`:""}`));}var Zo=5;async function O(e,o,t=0){if(!existsSync(e)||t>=Zo)return null;let n=await readdir(e,{withFileTypes:true});for(let s of n){if(s.name.startsWith("."))continue;let r=join(e,s.name);if(s.isDirectory()){let i=await O(r,o,t+1);if(i)return i}else if(s.name.startsWith(`${o}.`)){let i=s.name.split(".").pop()?.toLowerCase();if(i&&i in jn)return r}}return null}async function $e(e,o,t=0){if(!existsSync(e)||t>=Zo)return null;let n=await readdir(e,{withFileTypes:true});for(let s of n){let r=join(e,s.name);if(s.isDirectory()){let i=await $e(r,o,t+1);if(i)return i}else if(s.name===o)return r}return null}var jn={ts:"typescript",js:"javascript",py:"python3",java:"java",cpp:"cpp",c:"c",cs:"csharp",go:"go",rs:"rust",kt:"kotlin",swift:"swift"};function ae(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 oe(e){return /^\d+$/.test(e)}function Ne(e){return !e.includes("/")&&!e.includes("\\")&&e.includes(".")}function me(e,o){let t=resolve(e),n=resolve(o),s=n.endsWith(sep)?n:n+sep;return t===n||t.startsWith(s)}async function tt(e,o){let{authorized:t}=await v();if(!t)return;let n=e,s=w.getWorkDir();if(oe(e)){let i=await O(s,e);if(!i){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.gray(`Looking in: ${s}`)),console.log(l.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}n=i,console.log(l.gray(`Found: ${n}`));}else if(Ne(e)){let i=await $e(s,e);if(!i){console.log(l.red(`File not found: ${e}`)),console.log(l.gray(`Looking in: ${s}`));return}n=i,console.log(l.gray(`Found: ${n}`));}if(!existsSync(n)){console.log(l.red(`File not found: ${n}`));return}if(!me(n,s)){console.log(l.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(l.gray(`File: ${n}`)),console.log(l.gray(`Workspace: ${s}`)),console.log(l.yellow(`
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 r=Ie({text:"Reading solution file...",spinner:"dots"}).start();try{let i=basename(n),a=i.match(/^(\d+)\.([^.]+)\./);if(!a){r.fail("Invalid filename format"),console.log(l.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(l.gray("Example: 1.two-sum.ts"));return}let[,c,g]=a,u=i.split(".").pop(),p=ae(u);if(!p){r.fail(`Unsupported file extension: .${u}`);return}let b=await readFile(n,"utf-8");r.text="Fetching problem details...";let C=await h.getProblem(g),I=o.testcase??C.exampleTestcases??C.sampleTestCase;r.text="Running tests...";let R=await h.testSolution(g,b,p,I,C.questionId);r.stop(),jo(R,o.visualize?C.topicTags:void 0);}catch(i){r.fail("Test failed"),i instanceof Error&&console.log(l.red(i.message));}}function st(){return $.getTimerPath()}function le(){let e=st();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{solveTimes:{},activeTimer:null}}function Ye(e){let o=st(),t=dirname(o);existsSync(t)||mkdirSync(t,{recursive:true}),writeFileSync(o,JSON.stringify(e,null,2));}var B={startTimer(e,o,t,n){let s=le();s.activeTimer={problemId:e,title:o,difficulty:t,startedAt:new Date().toISOString(),durationMinutes:n},Ye(s);},getActiveTimer(){return le().activeTimer},stopTimer(){let e=le(),o=e.activeTimer;if(!o)return null;let t=new Date(o.startedAt),s=Math.floor((new Date().getTime()-t.getTime())/1e3);return e.activeTimer=null,Ye(e),{durationSeconds:s}},recordSolveTime(e,o,t,n,s){let r=le();r.solveTimes[e]||(r.solveTimes[e]=[]),r.solveTimes[e].push({problemId:e,title:o,difficulty:t,solvedAt:new Date().toISOString(),durationSeconds:n,timerMinutes:s}),Ye(r);},getSolveTimes(e){return le().solveTimes[e]??[]},getAllSolveTimes(){return le().solveTimes??{}},getStats(){let e=le().solveTimes??{},o=0,t=0;for(let n of Object.values(e)){o+=n.length;for(let s of n)t+=s.durationSeconds;}return {totalProblems:o,totalTime:t,avgTime:o>0?Math.floor(t/o):0}}};async function rt(e){let{authorized:o}=await v();if(!o)return;let t=e,n=w.getWorkDir();if(oe(e)){let r=await O(n,e);if(!r){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.gray(`Looking in: ${n}`)),console.log(l.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}t=r,console.log(l.gray(`Found: ${t}`));}else if(Ne(e)){let r=await $e(n,e);if(!r){console.log(l.red(`File not found: ${e}`)),console.log(l.gray(`Looking in: ${n}`));return}t=r,console.log(l.gray(`Found: ${t}`));}if(!existsSync(t)){console.log(l.red(`File not found: ${t}`));return}if(!me(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(`
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
188
+ `)}function Bo(e,o,t){let n=ge[t];return `${e}.${o}.${n}`}var jn=["vim","nvim","vi","nano","emacs","micro","helix"],Mn=["code","code-insiders","cursor","codium","vscodium"];async function $e(e,o){let t=w.getEditor()??process.env.EDITOR??"code",n=w.getWorkDir();if(jn.includes(t)){console.log(),console.log(l.gray(`Open with: ${t} ${e}`));return}try{if(Mn.includes(t)){spawn(t,["-r",n,"-g",e],{detached:!0,stdio:"ignore"}).unref();return}await In(e,{app:{name:t}});}catch{}}async function Y(e,o){let{authorized:t}=await v();if(!t)return false;let n=Ue({text:"Fetching problem details...",spinner:"dots"}).start();try{let s;if(/^\d+$/.test(e)?s=await h.getProblemById(e):s=await h.getProblem(e),!s)return n.fail(`Problem "${e}" not found`),!1;n.text="Generating solution file...";let r=o.lang?.toLowerCase()??w.getLanguage(),i=Se[r]??r,a=s.codeSnippets??[],c=Vo(a,i),g;if(a.length===0)n.warn(l.yellow("Premium Problem (No code snippets available)")),console.log(l.gray("Generating placeholder file with problem info...")),g=`// \u{1F512} Premium Problem - ${s.title}
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(Z=>Z.langSlug).join(", ")}`)),!1;let u=zo(s.questionFrontendId,s.titleSlug,s.title,s.difficulty,g,i,s.content??void 0),p=w.getWorkDir(),b=s.difficulty,C=s.topicTags.length>0?s.topicTags[0].name.replace(/[^\w\s-]/g,"").trim():"Uncategorized",I=join(p,b,C);existsSync(I)||await mkdir(I,{recursive:!0});let R=Bo(s.questionFrontendId,s.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 $e(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(`${s.questionFrontendId}. ${s.title}`)),console.log(l.gray(`Difficulty: ${s.difficulty} | Category: ${C}`)),o.open!==!1&&await $e(q),!0)}catch(s){if(n.fail("Failed to fetch problem"),s instanceof Error)if(s.message.includes("expected object, received null"))console.log(l.red(`Problem "${e}" not found`));else try{let r=JSON.parse(s.message);Array.isArray(r)?console.log(l.red("API Response Validation Failed")):console.log(l.red(s.message));}catch{console.log(l.red(s.message));}return false}}async function Qo(e,o){if(e.length===0){console.log(l.yellow("Please provide at least one problem ID"));return}let{authorized:t}=await v();if(!t)return;console.log(l.cyan(`\u{1F4E6} Picking ${e.length} problem${e.length!==1?"s":""}...`)),console.log(),console.log();let n=0,s=0;for(let r of e)await Y(r,{...o,open:false})?n++:s++,console.log();console.log(l.gray("\u2500".repeat(50))),console.log(l.bold(`Done! ${l.green(`${n} succeeded`)}${s>0?`, ${l.red(`${s} failed`)}`:""}`));}var Zo=5;async function O(e,o,t=0){if(!existsSync(e)||t>=Zo)return null;let n=await readdir(e,{withFileTypes:true});for(let s of n){if(s.name.startsWith("."))continue;let r=join(e,s.name);if(s.isDirectory()){let i=await O(r,o,t+1);if(i)return i}else if(s.name.startsWith(`${o}.`)){let i=s.name.split(".").pop()?.toLowerCase();if(i&&i in Hn)return r}}return null}async function ke(e,o,t=0){if(!existsSync(e)||t>=Zo)return null;let n=await readdir(e,{withFileTypes:true});for(let s of n){let r=join(e,s.name);if(s.isDirectory()){let i=await ke(r,o,t+1);if(i)return i}else if(s.name===o)return r}return null}var Hn={ts:"typescript",js:"javascript",py:"python3",java:"java",cpp:"cpp",c:"c",cs:"csharp",go:"go",rs:"rust",kt:"kotlin",swift:"swift"};function ae(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 oe(e){return /^\d+$/.test(e)}function Ie(e){return !e.includes("/")&&!e.includes("\\")&&e.includes(".")}function me(e,o){let t=resolve(e),n=resolve(o),s=n.endsWith(sep)?n:n+sep;return t===n||t.startsWith(s)}async function tt(e,o){let{authorized:t}=await v();if(!t)return;let n=e,s=w.getWorkDir();if(oe(e)){let i=await O(s,e);if(!i){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.gray(`Looking in: ${s}`)),console.log(l.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}n=i,console.log(l.gray(`Found: ${n}`));}else if(Ie(e)){let i=await ke(s,e);if(!i){console.log(l.red(`File not found: ${e}`)),console.log(l.gray(`Looking in: ${s}`));return}n=i,console.log(l.gray(`Found: ${n}`));}if(!existsSync(n)){console.log(l.red(`File not found: ${n}`));return}if(!me(n,s)){console.log(l.red("\u26A0\uFE0F Security Error: File path is outside the configured workspace")),console.log(l.gray(`File: ${n}`)),console.log(l.gray(`Workspace: ${s}`)),console.log(l.yellow(`
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 r=Ue({text:"Reading solution file...",spinner:"dots"}).start();try{let i=basename(n),a=i.match(/^(\d+)\.([^.]+)\./);if(!a){r.fail("Invalid filename format"),console.log(l.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(l.gray("Example: 1.two-sum.ts"));return}let[,c,g]=a,u=i.split(".").pop(),p=ae(u);if(!p){r.fail(`Unsupported file extension: .${u}`);return}let b=await readFile(n,"utf-8");r.text="Fetching problem details...";let C=await h.getProblem(g),I=o.testcase??C.exampleTestcases??C.sampleTestCase;r.text="Running tests...";let R=await h.testSolution(g,b,p,I,C.questionId);r.stop(),jo(R,o.visualize?C.topicTags:void 0);}catch(i){r.fail("Test failed"),i instanceof Error&&console.log(l.red(i.message));}}function st(){return $.getTimerPath()}function le(){let e=st();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{solveTimes:{},activeTimer:null}}function Qe(e){let o=st(),t=dirname(o);existsSync(t)||mkdirSync(t,{recursive:true}),writeFileSync(o,JSON.stringify(e,null,2));}var B={startTimer(e,o,t,n){let s=le();s.activeTimer={problemId:e,title:o,difficulty:t,startedAt:new Date().toISOString(),durationMinutes:n},Qe(s);},getActiveTimer(){return le().activeTimer},stopTimer(){let e=le(),o=e.activeTimer;if(!o)return null;let t=new Date(o.startedAt),s=Math.floor((new Date().getTime()-t.getTime())/1e3);return e.activeTimer=null,Qe(e),{durationSeconds:s}},recordSolveTime(e,o,t,n,s){let r=le();r.solveTimes[e]||(r.solveTimes[e]=[]),r.solveTimes[e].push({problemId:e,title:o,difficulty:t,solvedAt:new Date().toISOString(),durationSeconds:n,timerMinutes:s}),Qe(r);},getSolveTimes(e){return le().solveTimes[e]??[]},getAllSolveTimes(){return le().solveTimes??{}},getStats(){let e=le().solveTimes??{},o=0,t=0;for(let n of Object.values(e)){o+=n.length;for(let s of n)t+=s.durationSeconds;}return {totalProblems:o,totalTime:t,avgTime:o>0?Math.floor(t/o):0}}};async function rt(e){let{authorized:o}=await v();if(!o)return;let t=e,n=w.getWorkDir();if(oe(e)){let r=await O(n,e);if(!r){console.log(l.red(`No solution file found for problem ${e}`)),console.log(l.gray(`Looking in: ${n}`)),console.log(l.gray(`Run "leetcode pick ${e}" first to create a solution file.`));return}t=r,console.log(l.gray(`Found: ${t}`));}else if(Ie(e)){let r=await ke(n,e);if(!r){console.log(l.red(`File not found: ${e}`)),console.log(l.gray(`Looking in: ${n}`));return}t=r,console.log(l.gray(`Found: ${t}`));}if(!existsSync(t)){console.log(l.red(`File not found: ${t}`));return}if(!me(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(`
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=Ue({text:"Reading solution file...",spinner:"dots"}).start();try{let r=basename(t),i=r.match(/^(\d+)\.([^.]+)\./);if(!i){s.fail("Invalid filename format"),console.log(l.gray("Expected format: {id}.{title-slug}.{ext}")),console.log(l.gray("Example: 1.two-sum.ts"));return}let[,a,c]=i,g=r.split(".").pop(),u=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=Ue("Fetching statistics...").start();try{let r=e||n;if(!r){s.fail("No username found");return}let i=await h.getUserProfile(r);if(s.stop(),!o.calendar&&!o.skills&&!o.trend){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=Ue("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=Ue("Fetching random problem...").start();try{let n={};if(e.difficulty){let i={easy:"EASY",e:"EASY",medium:"MEDIUM",m:"MEDIUM",hard:"HARD",h:"HARD"}[e.difficulty.toLowerCase()];if(i)n.difficulty=i;else {t.fail(`Invalid difficulty: ${e.difficulty}`);return}}e.tag&&(n.tags=[e.tag]);let s=await h.getRandomProblem(n);t.succeed("Found random problem!"),console.log(),e.pick?await Y(s,{open:e.open??!0}):(await Re(s),console.log(l.gray("Run following to start solving:")),console.log(l.cyan(` leetcode pick ${s}`)));}catch(n){t.fail("Failed to fetch random problem"),n instanceof Error&&console.log(l.red(n.message));}}async function ft(e,o){let{authorized:t}=await v();if(!t)return;let n=Ue("Fetching problem info...").start();try{let s;if(/^\d+$/.test(e)?s=await h.getProblemById(e):s=await h.getProblem(e),!s){n.fail(`Problem "${e}" not found`);return}let r=s.titleSlug;n.text="Fetching submissions...";let i=o.limit?parseInt(o.limit,10):20,a=await h.getSubmissionList(r,i);if(n.stop(),a.length===0){console.log(l.yellow("No submissions found."));return}if(o.last){let c=a.find(g=>g.statusDisplay==="Accepted");c?(console.log(l.bold("Last Accepted Submission:")),He([c])):console.log(l.yellow("No accepted submissions found in recent history."));}else He(a);if(o.download){let c=Ue("Downloading submission...").start(),g=a.find(fn=>fn.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=Se[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 Ze=["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(!Ze.includes(o)){console.log(l.red(`Unsupported language: ${e.lang}`)),console.log(l.gray(`Supported: ${Ze.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 oo.prompt([{type:"list",name:"language",message:"Default programming language:",choices:Ze,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 Sn({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 ds();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 ds(){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=Ue({text:"Fetching problem details...",spinner:"dots"}).start();try{let n=new We({head:[l.cyan("ID"),l.cyan("Title"),l.cyan("Difficulty"),l.cyan("Status")],colWidths:[8,45,12,10],style:{head:[],border:[]}});for(let s of e)try{let r=await h.getProblemById(s);r?n.push([r.questionFrontendId,r.title.length>42?r.title.slice(0,39)+"...":r.title,us(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 us(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 hs(s,e):await bs(s,e);}async function hs(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 bs(e,o){if(!existsSync(e)){let t=await ws(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 $e(e);}async function ws(e){let o=`# Problem ${e} Notes
192
192
 
193
193
  `,{authorized:t}=await v();if(t)try{let n=await h.getProblemById(e);n&&(o=`# ${e}. ${n.title}
194
194
 
@@ -223,22 +223,22 @@ For security reasons, you can only submit files from within your workspace.`)),c
223
223
 
224
224
  <!-- What did you learn from this problem? -->
225
225
 
226
- `}async function kt(){let{authorized:e,username:o}=await v();if(!e||!o)return;let t=Ie({text:"Fetching your progress...",spinner:"dots"}).start();try{let[n,s]=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 r=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")}: ${r?.count??0}`),console.log(),console.log(l.bold.yellow("\u{1F3AF} Today's Challenge:")),console.log(` ${s.question.questionFrontendId}. ${s.question.title}`),console.log(` ${ys(s.question.difficulty)}`);let g=s.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 ${s.question.questionFrontendId} # Start working on it`));}catch(n){t.fail("Failed to fetch progress"),n instanceof Error&&console.log(l.red(n.message));}}function ys(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 bs(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-").replace(/--+/g,"-")}function ws(e){let o=/^https:\/\/[\w.-]+\/[\w./-]+$/,t=/^git@[\w.-]+:[\w./-]+$/;return o.test(e)||t.test(e)}function Ss(e){return `'${e.replace(/'/g,"'\\''")}'`}function $s(){try{return execSync("git --version",{stdio:"ignore"}),!0}catch{return false}}function ks(e){try{return execSync("git rev-parse --is-inside-work-tree",{cwd:e,stdio:"ignore"}),!0}catch{return false}}function vs(){try{return execSync("gh --version",{stdio:"ignore"}),!0}catch{return false}}function vt(e){try{return execSync("git config --get remote.origin.url",{cwd:e,encoding:"utf-8"}).trim()}catch{return null}}async function Cs(e){let{init:o}=await eo.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=Ie("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 Ps(e){let o=Ie(),t=w.getRepo();if(!t){if(vs()){let{createGh:s}=await eo.prompt([{type:"confirm",name:"createGh",message:"Create a new private GitHub repository?",default:true}]);if(s){o.start("Creating GitHub repository...");try{let r=e.split("/").pop()||"leetcode-solutions",i=bs(r);return execSync(`gh repo create ${i} --private --source=. --remote=origin`,{cwd:e}),o.succeed("Created and linked GitHub repository"),t=vt(e)||"",t&&w.setRepo(t),t}catch(r){o.fail("Failed to create GitHub repository"),console.log(l.red(r));}}}if(!t){console.log(l.yellow(`
227
- Please create a new repository on your Git provider and copy the URL.`));let{url:s}=await eo.prompt([{type:"input",name:"url",message:"Enter remote repository URL:",validate:r=>r.length>0?true:"URL cannot be empty"}]);t=s;}}if(t&&!ws(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),!vt(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 Ct(){let e=w.getWorkDir();if(!existsSync(e)){console.log(l.red(`Work directory does not exist: ${e}`));return}if(!$s()){console.log(l.red("Git is not installed. Please install Git to use command."));return}if(!ks(e)&&!await Cs(e))return;await Ps(e);let o=Ie("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 s=t.trim().split(`
228
- `).length,r=new Date().toISOString().replace("T"," ").substring(0,19),i=`Sync: ${s} solutions - ${r}`;execSync(`git commit -m ${Ss(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 Ds={Easy:20,Medium:40,Hard:60};function pe(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 Pt(e,o){if(o.stats){await Es(e);return}if(o.stop){await xs();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 v();if(!t)return;let n=B.getActiveTimer();if(n){let r=new Date(n.startedAt),i=Math.floor((Date.now()-r.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: ${pe(i)}`)),console.log(),console.log(l.gray("Use `leetcode timer --stop` to stop it first."));return}let s=Ie("Fetching problem...").start();try{let r;if(/^\d+$/.test(e)?r=await h.getProblemById(e):r=await h.getProblem(e),!r){s.fail(`Problem "${e}" not found`);return}s.stop();let i=o.minutes??Ds[r.difficulty]??30;B.startTimer(r.questionFrontendId,r.title,r.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: ${r.questionFrontendId}. ${r.title}`)),console.log(l.white(`Difficulty: ${l.bold(r.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 Y(e,{open:!0});}catch(r){s.fail("Failed to start timer"),r instanceof Error&&console.log(l.red(r.message));}}async function xs(){let e=B.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: ${pe(e.durationSeconds)}`)),console.log(l.gray("(Time not recorded since problem was not submitted)"));}async function Es(e){if(e&&/^\d+$/.test(e)){let o=B.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(),s=pe(t.durationSeconds),r=t.timerMinutes,i=t.durationSeconds<=r*60;console.log(` ${n} ${i?l.green(s):l.red(s)} (limit: ${r}m)`);}}else {let o=B.getStats(),t=B.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(pe(o.totalTime))}`),console.log(` Average time: ${l.cyan(pe(o.avgTime))}`),console.log();let n=[];for(let[s,r]of Object.entries(t))for(let i of r)n.push({problemId:s,title:i.title,duration:i.durationSeconds,date:i.solvedAt});if(n.length>0){n.sort((s,r)=>new Date(r.date).getTime()-new Date(s.date).getTime()),console.log(l.bold(" Recent Solves:"));for(let s of n.slice(0,5)){let r=new Date(s.date).toLocaleDateString();console.log(l.gray(` ${r} `)+l.white(`${s.problemId}. ${s.title.substring(0,25)}`)+l.gray(" ")+l.cyan(pe(s.duration)));}}console.log();}}var As="https://abagrmwdpvnfyuqizyym.supabase.co",Rs="sb_publishable_indrKu8VJmASdyLp7w8Hog_OyqT17cV",ne=createClient(As,Rs);function to(){return $.getCollabPath()}function Us(){let e=to();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{session:null}}function js(e){let o=to(),t=dirname(o);existsSync(t)||mkdirSync(t,{recursive:true}),writeFileSync(o,JSON.stringify(e,null,2));}var X={getSession(){return Us().session},setSession(e){js({session:e});},getPath(){return to()}};function Ms(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",o="";for(let t=0;t<6;t++)o+=e.charAt(Math.floor(Math.random()*e.length));return o}var G={getSession(){return X.getSession()},async createRoom(e,o){let t=Ms(),{error:n}=await ne.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}:(X.setSession({roomCode:t,problemId:e,isHost:true,username:o}),{roomCode:t})},async joinRoom(e,o){let{data:t,error:n}=await ne.from("collab_rooms").select("*").eq("room_code",e.toUpperCase()).single();if(n||!t)return {error:"Room not found"};let{error:s}=await ne.from("collab_rooms").update({guest_username:o}).eq("room_code",e.toUpperCase());return s?{error:s.message}:(X.setSession({roomCode:e.toUpperCase(),problemId:t.problem_id,isHost:false,username:o}),{problemId:t.problem_id})},async syncCode(e){let o=X.getSession();if(!o)return {success:false,error:"No active session"};let t=o.isHost?"host_code":"guest_code",{error:n}=await ne.from("collab_rooms").update({[t]:e}).eq("room_code",o.roomCode);return n?{success:false,error:n.message}:{success:true}},async getPartnerCode(){let e=X.getSession();if(!e)return {error:"No active session"};let{data:o,error:t}=await ne.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=X.getSession();if(!e)return {error:"No active session"};let{data:o,error:t}=await ne.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=X.getSession();e&&e.isHost&&await ne.from("collab_rooms").delete().eq("room_code",e.roomCode),X.setSession(null);}};async function xt(e){let{authorized:o,username:t}=await v();if(!o||!t)return;let n=Ie("Creating collaboration room...").start();try{let s=await G.createRoom(e,t);if("error"in s){n.fail(s.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(s.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 ${s.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 Y(e,{open:!0});}catch(s){n.fail("Failed to create room"),s instanceof Error&&console.log(l.red(s.message));}}async function Et(e){let{authorized:o,username:t}=await v();if(!o||!t)return;let n=Ie(`Joining room ${e}...`).start();try{let s=await G.joinRoom(e.toUpperCase(),t);if("error"in s){n.fail(s.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: ${s.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 Y(s.problemId,{open:!0});}catch(s){n.fail("Failed to join room"),s instanceof Error&&console.log(l.red(s.message));}}async function Lt(){let e=G.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=Ie("Syncing your code...").start(),t=w.getWorkDir(),n=await O(t,e.problemId);if(!n){o.fail(`No solution file found for problem ${e.problemId}`);return}let s=await readFile(n,"utf-8"),r=await G.syncCode(s);r.success?(o.succeed("Code synced successfully!"),console.log(l.gray(`Uploaded ${s.split(`
229
- `).length} lines from ${n}`))):o.fail(r.error||"Sync failed");}async function At(){let e=G.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=Ie("Fetching solutions...").start(),t=w.getWorkDir(),n=await O(t,e.problemId);if(!n){o.fail(`No solution file found for problem ${e.problemId}`);return}let s=await readFile(n,"utf-8"),r=await G.getPartnerCode();if("error"in r){o.fail(r.error);return}if(o.stop(),!r.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=s.split(`
226
+ `}async function kt(){let{authorized:e,username:o}=await v();if(!e||!o)return;let t=Ue({text:"Fetching your progress...",spinner:"dots"}).start();try{let[n,s]=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 r=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")}: ${r?.count??0}`),console.log(),console.log(l.bold.yellow("\u{1F3AF} Today's Challenge:")),console.log(` ${s.question.questionFrontendId}. ${s.question.title}`),console.log(` ${$s(s.question.difficulty)}`);let g=s.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 ${s.question.questionFrontendId} # Start working on it`));}catch(n){t.fail("Failed to fetch progress"),n instanceof Error&&console.log(l.red(n.message));}}function $s(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 vs(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-").replace(/--+/g,"-")}function Cs(e){let o=/^https:\/\/[\w.-]+\/[\w./-]+$/,t=/^git@[\w.-]+:[\w./-]+$/;return o.test(e)||t.test(e)}function Ps(e){return `'${e.replace(/'/g,"'\\''")}'`}function Ts(){try{return execSync("git --version",{stdio:"ignore"}),!0}catch{return false}}function Ds(e){try{return execSync("git rev-parse --is-inside-work-tree",{cwd:e,stdio:"ignore"}),!0}catch{return false}}function xs(){try{return execSync("gh --version",{stdio:"ignore"}),!0}catch{return false}}function vt(e){try{return execSync("git config --get remote.origin.url",{cwd:e,encoding:"utf-8"}).trim()}catch{return null}}async function Es(e){let{init:o}=await oo.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=Ue("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 Ls(e){let o=Ue(),t=w.getRepo();if(!t){if(xs()){let{createGh:s}=await oo.prompt([{type:"confirm",name:"createGh",message:"Create a new private GitHub repository?",default:true}]);if(s){o.start("Creating GitHub repository...");try{let r=e.split("/").pop()||"leetcode-solutions",i=vs(r);return execSync(`gh repo create ${i} --private --source=. --remote=origin`,{cwd:e}),o.succeed("Created and linked GitHub repository"),t=vt(e)||"",t&&w.setRepo(t),t}catch(r){o.fail("Failed to create GitHub repository"),console.log(l.red(r));}}}if(!t){console.log(l.yellow(`
227
+ Please create a new repository on your Git provider and copy the URL.`));let{url:s}=await oo.prompt([{type:"input",name:"url",message:"Enter remote repository URL:",validate:r=>r.length>0?true:"URL cannot be empty"}]);t=s;}}if(t&&!Cs(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),!vt(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 Ct(){let e=w.getWorkDir();if(!existsSync(e)){console.log(l.red(`Work directory does not exist: ${e}`));return}if(!Ts()){console.log(l.red("Git is not installed. Please install Git to use command."));return}if(!Ds(e)&&!await Es(e))return;await Ls(e);let o=Ue("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 s=t.trim().split(`
228
+ `).length,r=new Date().toISOString().replace("T"," ").substring(0,19),i=`Sync: ${s} solutions - ${r}`;execSync(`git commit -m ${Ps(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 Rs={Easy:20,Medium:40,Hard:60};function pe(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 Pt(e,o){if(o.stats){await Fs(e);return}if(o.stop){await _s();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 v();if(!t)return;let n=B.getActiveTimer();if(n){let r=new Date(n.startedAt),i=Math.floor((Date.now()-r.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: ${pe(i)}`)),console.log(),console.log(l.gray("Use `leetcode timer --stop` to stop it first."));return}let s=Ue("Fetching problem...").start();try{let r;if(/^\d+$/.test(e)?r=await h.getProblemById(e):r=await h.getProblem(e),!r){s.fail(`Problem "${e}" not found`);return}s.stop();let i=o.minutes??Rs[r.difficulty]??30;B.startTimer(r.questionFrontendId,r.title,r.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: ${r.questionFrontendId}. ${r.title}`)),console.log(l.white(`Difficulty: ${l.bold(r.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 Y(e,{open:!0});}catch(r){s.fail("Failed to start timer"),r instanceof Error&&console.log(l.red(r.message));}}async function _s(){let e=B.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: ${pe(e.durationSeconds)}`)),console.log(l.gray("(Time not recorded since problem was not submitted)"));}async function Fs(e){if(e&&/^\d+$/.test(e)){let o=B.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(),s=pe(t.durationSeconds),r=t.timerMinutes,i=t.durationSeconds<=r*60;console.log(` ${n} ${i?l.green(s):l.red(s)} (limit: ${r}m)`);}}else {let o=B.getStats(),t=B.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(pe(o.totalTime))}`),console.log(` Average time: ${l.cyan(pe(o.avgTime))}`),console.log();let n=[];for(let[s,r]of Object.entries(t))for(let i of r)n.push({problemId:s,title:i.title,duration:i.durationSeconds,date:i.solvedAt});if(n.length>0){n.sort((s,r)=>new Date(r.date).getTime()-new Date(s.date).getTime()),console.log(l.bold(" Recent Solves:"));for(let s of n.slice(0,5)){let r=new Date(s.date).toLocaleDateString();console.log(l.gray(` ${r} `)+l.white(`${s.problemId}. ${s.title.substring(0,25)}`)+l.gray(" ")+l.cyan(pe(s.duration)));}}console.log();}}var Is="https://abagrmwdpvnfyuqizyym.supabase.co",Us="sb_publishable_indrKu8VJmASdyLp7w8Hog_OyqT17cV",ne=createClient(Is,Us);function no(){return $.getCollabPath()}function Ws(){let e=no();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{session:null}}function Hs(e){let o=no(),t=dirname(o);existsSync(t)||mkdirSync(t,{recursive:true}),writeFileSync(o,JSON.stringify(e,null,2));}var X={getSession(){return Ws().session},setSession(e){Hs({session:e});},getPath(){return no()}};function Vs(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",o="";for(let t=0;t<6;t++)o+=e.charAt(Math.floor(Math.random()*e.length));return o}var G={getSession(){return X.getSession()},async createRoom(e,o){let t=Vs(),{error:n}=await ne.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}:(X.setSession({roomCode:t,problemId:e,isHost:true,username:o}),{roomCode:t})},async joinRoom(e,o){let{data:t,error:n}=await ne.from("collab_rooms").select("*").eq("room_code",e.toUpperCase()).single();if(n||!t)return {error:"Room not found"};let{error:s}=await ne.from("collab_rooms").update({guest_username:o}).eq("room_code",e.toUpperCase());return s?{error:s.message}:(X.setSession({roomCode:e.toUpperCase(),problemId:t.problem_id,isHost:false,username:o}),{problemId:t.problem_id})},async syncCode(e){let o=X.getSession();if(!o)return {success:false,error:"No active session"};let t=o.isHost?"host_code":"guest_code",{error:n}=await ne.from("collab_rooms").update({[t]:e}).eq("room_code",o.roomCode);return n?{success:false,error:n.message}:{success:true}},async getPartnerCode(){let e=X.getSession();if(!e)return {error:"No active session"};let{data:o,error:t}=await ne.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=X.getSession();if(!e)return {error:"No active session"};let{data:o,error:t}=await ne.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=X.getSession();e&&e.isHost&&await ne.from("collab_rooms").delete().eq("room_code",e.roomCode),X.setSession(null);}};async function xt(e){let{authorized:o,username:t}=await v();if(!o||!t)return;let n=Ue("Creating collaboration room...").start();try{let s=await G.createRoom(e,t);if("error"in s){n.fail(s.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(s.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 ${s.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 Y(e,{open:!0});}catch(s){n.fail("Failed to create room"),s instanceof Error&&console.log(l.red(s.message));}}async function Et(e){let{authorized:o,username:t}=await v();if(!o||!t)return;let n=Ue(`Joining room ${e}...`).start();try{let s=await G.joinRoom(e.toUpperCase(),t);if("error"in s){n.fail(s.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: ${s.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 Y(s.problemId,{open:!0});}catch(s){n.fail("Failed to join room"),s instanceof Error&&console.log(l.red(s.message));}}async function Lt(){let e=G.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=Ue("Syncing your code...").start(),t=w.getWorkDir(),n=await O(t,e.problemId);if(!n){o.fail(`No solution file found for problem ${e.problemId}`);return}let s=await readFile(n,"utf-8"),r=await G.syncCode(s);r.success?(o.succeed("Code synced successfully!"),console.log(l.gray(`Uploaded ${s.split(`
229
+ `).length} lines from ${n}`))):o.fail(r.error||"Sync failed");}async function At(){let e=G.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=Ue("Fetching solutions...").start(),t=w.getWorkDir(),n=await O(t,e.problemId);if(!n){o.fail(`No solution file found for problem ${e.problemId}`);return}let s=await readFile(n,"utf-8"),r=await G.getPartnerCode();if("error"in r){o.fail(r.error);return}if(o.stop(),!r.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=s.split(`
230
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 ${r.username}'s Solution`)),console.log(l.gray("\u2500".repeat(60)));let a=r.code.split(`
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 Rt(){if(!G.getSession()){console.log(l.yellow("No active collaboration session."));return}await G.leaveRoom(),console.log(l.green("\u2713 Left the collaboration session."));}async function _t(){let e=G.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 G.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 Ws(){return $.getSnapshotsDir()}function Ut(e){return join(Ws(),e)}function jt(e){return join(Ut(e),"meta.json")}function Ue(e){return join(Ut(e),"files")}function Mt(e){let o=Ue(e);existsSync(o)||mkdirSync(o,{recursive:true});}function ke(e){let o=jt(e);return existsSync(o)?JSON.parse(readFileSync(o,"utf-8")):{problemId:e,problemTitle:"",snapshots:[]}}function Ft(e,o){Mt(e),writeFileSync(jt(e),JSON.stringify(o,null,2));}var W={save(e,o,t,n,s){Mt(e);let r=ke(e);o&&(r.problemTitle=o);let i=r.snapshots.length>0?Math.max(...r.snapshots.map(C=>C.id))+1:1,a=s||`snapshot-${i}`,c=r.snapshots.find(C=>C.name===a);if(c)return {error:`Snapshot with name "${a}" already exists (ID: ${c.id})`};let g=ge[n]||n,u=`${i}_${a}.${g}`,p=join(Ue(e),u);writeFileSync(p,t,"utf-8");let b={id:i,name:a,fileName:u,language:n,lines:t.split(`
232
- `).length,createdAt:new Date().toISOString()};return r.snapshots.push(b),Ft(e,r),b},list(e){return ke(e).snapshots},getMeta(e){return ke(e)},get(e,o){let t=ke(e),n=t.snapshots.find(r=>r.id===parseInt(o,10));return n||t.snapshots.find(r=>r.name===o)||null},getCode(e,o){let t=join(Ue(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=ke(e),n=this.get(e,o);if(!n)return false;let s=join(Ue(e),n.fileName);return existsSync(s)&&unlinkSync(s),t.snapshots=t.snapshots.filter(r=>r.id!==n.id),Ft(e,t),true},hasSnapshots(e){return this.list(e).length>0}};function Bs(e){let o=new Date(e),n=new Date().getTime()-o.getTime(),s=Math.floor(n/6e4),r=Math.floor(s/60),i=Math.floor(r/24);return s<1?"just now":s<60?`${s}m ago`:r<24?`${r}h ago`:`${i}d ago`}async function Wt(e,o){let t=w.getWorkDir();try{let n=await O(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 s=await readFile(n,"utf-8"),r=extname(n).slice(1),i=ae(r)||r,c=basename(n).match(/^\d+\.(.+)\.\w+$/),g=c?c[1]:"",u=W.save(e,g,s,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 Ht(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 s=Bs(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(s)}`);}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 Vt(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 s=await O(t,e);if(!s){console.log(l.red(`No solution file found for problem ${e}`));return}let r=await readFile(s,"utf-8"),i=`backup-before-restore-${Date.now()}`,a=extname(s).slice(1),c=ae(a)||a;W.save(e,"",r,c,i);let g=W.getCode(e,n);await writeFile(s,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(s)}`),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 zt(e,o,t){try{let n=W.get(e,o),s=W.get(e,t);if(!n){console.log(l.red(`Snapshot "${o}" not found`));return}if(!s){console.log(l.red(`Snapshot "${t}" not found`));return}let r=W.getCode(e,n),i=W.getCode(e,s);console.log(),console.log(l.bold(`\u{1F4CA} Diff: ${n.name} \u2192 ${s.name}`)),console.log(l.gray("\u2500".repeat(50))),console.log();let a=diffLines(r,i),c=0,g=0;for(let u of a){let p=u.value.split(`
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 Rt(){if(!G.getSession()){console.log(l.yellow("No active collaboration session."));return}await G.leaveRoom(),console.log(l.green("\u2713 Left the collaboration session."));}async function _t(){let e=G.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 G.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 Gs(){return $.getSnapshotsDir()}function Ut(e){return join(Gs(),e)}function jt(e){return join(Ut(e),"meta.json")}function je(e){return join(Ut(e),"files")}function Mt(e){let o=je(e);existsSync(o)||mkdirSync(o,{recursive:true});}function ve(e){let o=jt(e);return existsSync(o)?JSON.parse(readFileSync(o,"utf-8")):{problemId:e,problemTitle:"",snapshots:[]}}function Ft(e,o){Mt(e),writeFileSync(jt(e),JSON.stringify(o,null,2));}var W={save(e,o,t,n,s){Mt(e);let r=ve(e);o&&(r.problemTitle=o);let i=r.snapshots.length>0?Math.max(...r.snapshots.map(C=>C.id))+1:1,a=s||`snapshot-${i}`,c=r.snapshots.find(C=>C.name===a);if(c)return {error:`Snapshot with name "${a}" already exists (ID: ${c.id})`};let g=ge[n]||n,u=`${i}_${a}.${g}`,p=join(je(e),u);writeFileSync(p,t,"utf-8");let b={id:i,name:a,fileName:u,language:n,lines:t.split(`
232
+ `).length,createdAt:new Date().toISOString()};return r.snapshots.push(b),Ft(e,r),b},list(e){return ve(e).snapshots},getMeta(e){return ve(e)},get(e,o){let t=ve(e),n=t.snapshots.find(r=>r.id===parseInt(o,10));return n||t.snapshots.find(r=>r.name===o)||null},getCode(e,o){let t=join(je(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=ve(e),n=this.get(e,o);if(!n)return false;let s=join(je(e),n.fileName);return existsSync(s)&&unlinkSync(s),t.snapshots=t.snapshots.filter(r=>r.id!==n.id),Ft(e,t),true},hasSnapshots(e){return this.list(e).length>0}};function Ks(e){let o=new Date(e),n=new Date().getTime()-o.getTime(),s=Math.floor(n/6e4),r=Math.floor(s/60),i=Math.floor(r/24);return s<1?"just now":s<60?`${s}m ago`:r<24?`${r}h ago`:`${i}d ago`}async function Wt(e,o){let t=w.getWorkDir();try{let n=await O(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 s=await readFile(n,"utf-8"),r=extname(n).slice(1),i=ae(r)||r,c=basename(n).match(/^\d+\.(.+)\.\w+$/),g=c?c[1]:"",u=W.save(e,g,s,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 Ht(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 s=Ks(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(s)}`);}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 Vt(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 s=await O(t,e);if(!s){console.log(l.red(`No solution file found for problem ${e}`));return}let r=await readFile(s,"utf-8"),i=`backup-before-restore-${Date.now()}`,a=extname(s).slice(1),c=ae(a)||a;W.save(e,"",r,c,i);let g=W.getCode(e,n);await writeFile(s,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(s)}`),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 zt(e,o,t){try{let n=W.get(e,o),s=W.get(e,t);if(!n){console.log(l.red(`Snapshot "${o}" not found`));return}if(!s){console.log(l.red(`Snapshot "${t}" not found`));return}let r=W.getCode(e,n),i=W.getCode(e,s);console.log(),console.log(l.bold(`\u{1F4CA} Diff: ${n.name} \u2192 ${s.name}`)),console.log(l.gray("\u2500".repeat(50))),console.log();let a=diffLines(r,i),c=0,g=0;for(let u of a){let p=u.value.split(`
233
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 "+s.lines+" lines")}`);}catch(n){console.log(l.red("Failed to diff snapshots")),n instanceof Error&&console.log(l.gray(n.message));}}async function Bt(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 Yt(e,o){let t=e.split(`
234
- `),n=t.length;console.log(),console.log(l.bold.cyan(`=== ${o} (${n} lines) ===`)),console.log(l.gray("\u2500".repeat(60))),t.forEach((s,r)=>{let i=(r+1).toString().padStart(3);console.log(l.gray(i+" \u2502 ")+s);});}function Js(e,o,t,n){let s=e.split(`
234
+ `),n=t.length;console.log(),console.log(l.bold.cyan(`=== ${o} (${n} lines) ===`)),console.log(l.gray("\u2500".repeat(60))),t.forEach((s,r)=>{let i=(r+1).toString().padStart(3);console.log(l.gray(i+" \u2502 ")+s);});}function er(e,o,t,n){let s=e.split(`
235
235
  `).length,r=o.split(`
236
236
  `).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(s+" \u2192 "+r+" lines")}`);}function no(e,o,t,n,s){if(s)Js(e,o,t,n);else {Yt(e,t),Yt(o,n);let r=diffLines(e,o),i=0,a=0;for(let c of r){let g=c.value.split(`
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 Qt(e,o){let{authorized:t}=await v();if(!t)return;let n=w.getWorkDir(),s=Ie("Finding solution file...").start();try{let r=await O(n,e);if(!r){s.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(r,"utf-8");if(s.text="Fetching comparison target...",o.file){if(s.stop(),!existsSync(o.file)){console.log(l.red(`File not found: ${o.file}`));return}if(!me(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(`
239
- For security reasons, you can only diff files from within your workspace.`));return}let p=await readFile(o.file,"utf-8");no(i,p,"Your Solution",o.file,o.unified??!1);return}let a=await h.getProblemById(e);if(!a){s.fail(`Problem ${e} not found`);return}if(o.submission){let p=parseInt(o.submission,10),b=await h.getSubmissionDetails(p);s.stop(),no(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){s.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));s.stop(),no(i,u.code,"Your Solution","Last Accepted",o.unified??!1);}catch(r){s.fail("Failed to diff"),r instanceof Error&&console.log(l.red(r.message));}}async function Kt(){let e=$.getActive(),o=$.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 Xt(){let e=$.list(),o=$.getActive();console.log(),console.log(l.bold("Workspaces:")),console.log();for(let t of e){let n=$.getConfig(t),s=t===o?l.green("\u25B8 "):" ",r=t===o?l.green.bold(t):t;console.log(`${s}${r}`),console.log(` ${l.gray(n.workDir)}`);}console.log();}async function Zt(e,o){if($.exists(e)){console.log(l.red(`Workspace "${e}" already exists`));return}let t=o.workdir??join(homedir(),"leetcode",e),n={workDir:t,lang:"typescript"};$.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 en(e){if(!$.exists(e)){console.log(l.red(`Workspace "${e}" not found`)),console.log(l.gray("Use `leetcode workspace list` to see available workspaces"));return}if($.setActive(e)){let t=$.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 on(e){if(e==="default"){console.log(l.red("Cannot delete the default workspace"));return}if(!$.exists(e)){console.log(l.red(`Workspace "${e}" not found`));return}let{confirmed:o}=await eo.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=$.delete(e);console.log(t?l.green(`\u2713 Deleted workspace "${e}"`):l.red("Failed to delete workspace"));}var so=join(homedir(),".leetcode"),ve=join(so,"version-cache.json"),sr=1440*60*1e3;function rr(){existsSync(so)||mkdirSync(so,{recursive:true});}function tn(){if(existsSync(ve))try{return JSON.parse(readFileSync(ve,"utf-8"))}catch{return null}return null}function ir(e){rr(),writeFileSync(ve,JSON.stringify(e,null,2));}var se={shouldCheck(){let e=tn();return e?Date.now()-e.lastCheck>sr:true},getCached(){return tn()},updateCache(e,o){ir({lastCheck:Date.now(),latestVersion:e,hasBreakingChanges:o});},clearCache(){existsSync(ve)&&unlinkSync(ve);}};var ur=fileURLToPath(import.meta.url),pr=dirname(ur),fr="https://registry.npmjs.org/@night-slayer18/leetcode-cli/latest",yr="@night-slayer18/leetcode-cli";function ye(){try{let e=join(pr,"../package.json");return JSON.parse(readFileSync(e,"utf-8")).version}catch{return "0.0.0"}}async function rn(){let o=(await pn(fr,{timeout:{request:1e4},retry:{limit:2}}).json()).version,t=ye(),n=parseInt(t.split(".")[0]),r=parseInt(o.split(".")[0])>n;return {version:o,hasBreakingChanges:r}}function io(e,o){let t=e.split(".").map(Number),n=o.split(".").map(Number);for(let s=0;s<3;s++){if(n[s]>t[s])return true;if(n[s]<t[s])return false}return false}function hr(e,o,t){console.log();let n=60,s="\u256D"+"\u2500".repeat(n-2)+"\u256E",r="\u2570"+"\u2500".repeat(n-2)+"\u256F";console.log(l.cyan(s));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 ${yr}`;console.log(l.cyan("\u2502")+a.padEnd(n+8)+l.cyan("\u2502")),console.log(l.cyan(r)),console.log();}async function an(e){let o=ye();e.force&&se.clearCache();let t=se.getCached(),n,s;if(t&&!se.shouldCheck()&&!e.force)n=t.latestVersion,s=t.hasBreakingChanges;else {let r=Ie("Checking for updates...").start();try{let i=await rn();n=i.version,s=i.hasBreakingChanges,se.updateCache(n,s),r.stop();}catch(i){r.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}}io(o,n)?(hr(o,n,s),e.checkOnly||s&&(console.log(l.yellow("\u{1F4A1} Tip: Review the changelog before updating to check for breaking changes.")),console.log(l.gray(` Run: leetcode changelog
240
- `)))):(console.log(),console.log(l.green("\u2713")+` You're on the latest version (${l.cyan(o)})`),console.log());}async function ln(){if(!se.shouldCheck()){let e=se.getCached();e&&io(ye(),e.latestVersion)&&sn(ye(),e.latestVersion,e.hasBreakingChanges);return}try{let e=await rn();se.updateCache(e.version,e.hasBreakingChanges),io(ye(),e.version)&&sn(ye(),e.version,e.hasBreakingChanges);}catch{}}function sn(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 Cr=fileURLToPath(import.meta.url),Pr=dirname(Cr),Tr="https://raw.githubusercontent.com/night-slayer18/leetcode-cli/main/docs/releases.md";function Dr(){try{let e=join(Pr,"../package.json");return JSON.parse(readFileSync(e,"utf-8")).version}catch{return "0.0.0"}}function xr(e,o){let t=e.replace("v","").split(".").map(Number),n=o.replace("v","").split(".").map(Number);for(let s=0;s<3;s++){if(t[s]>n[s])return true;if(t[s]<n[s])return false}return false}async function Er(){return await pn(Tr,{timeout:{request:1e4},retry:{limit:2}}).text()}function Lr(e){let o=[],t=/^## (v[\d.]+)/gm,n=[...e.matchAll(t)];for(let s=0;s<n.length;s++){let r=n[s],i=r[1],a=r.index+r[0].length,c=s+1<n.length?n[s+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 Ar(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 s=o.split(`
241
- `),r=false;for(let i of s)if(!(i.trim()===""&&!r)){if(i.startsWith("> **Release Date**")){let a=i.replace("> **Release Date**: ","").trim();console.log(l.gray(` \u{1F4C5} ${a}`));continue}if(i.startsWith("> **Focus**")){let a=i.replace("> **Focus**: ","").trim();console.log(l.gray(` \u{1F3AF} ${a}`)),console.log();continue}if(i.startsWith("### ")){let a=i.replace("### ","").trim();if(console.log(),/^[\u{1F300}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/u.test(a))console.log(l.bold.yellow(` ${a}`));else {let g="\u{1F4CC}";a.includes("Breaking")?g="\u26A0\uFE0F":a.includes("Feature")||a.includes("New")?g="\u{1F680}":a.includes("Fix")||a.includes("Bug")?g="\u{1F41B}":a.includes("Security")?g="\u{1F512}":a.includes("Improvement")?g="\u2728":a.includes("Architecture")?g="\u{1F3D7}\uFE0F":a.includes("Testing")?g="\u{1F9EA}":a.includes("Config")&&(g="\u2699\uFE0F"),console.log(l.bold.yellow(` ${g} ${a}`));}r=true;continue}if(i.startsWith("#### ")){let a=i.replace("#### ","").trim();console.log(l.bold.white(` ${a}`));continue}if(i.startsWith("- **")){let a=i.match(/^- \*\*(.+?)\*\*:?\s*(.*)/);console.log(a?l.cyan(` \u2022 ${l.bold(a[1])}`)+(a[2]?l.white(`: ${a[2]}`):""):l.cyan(` \u2022 ${i.replace("- ","")}`));continue}if(i.startsWith("- ")){let a=i.replace("- ","").trim();console.log(l.white(` \u2022 ${a}`));continue}i.startsWith("---")||i.trim()===">"||i.trim()&&console.log(l.gray(` ${i.trim()}`));}}async function cn(e,o={}){let t=Ie("Fetching changelog...").start();try{let n=await Er();t.stop();let s=Lr(n);if(s.length===0){console.log(l.yellow("No release entries found."));return}let r=Dr(),i=s;if(e){let a=e.startsWith("v")?e:`v${e}`;if(i=s.filter(c=>c.version===a),i.length===0){console.log(l.red(`Version ${e} not found in changelog.`)),console.log(l.gray("Available versions: "+s.map(c=>c.version).join(", ")));return}}else if(o.latest)i=s.slice(0,1);else if(o.breaking){if(i=s.filter(a=>a.hasBreakingChanges),i.length===0){console.log(l.green("\u2713 No breaking changes in any release."));return}}else if(o.all)i=s;else {if(i=s.filter(a=>xr(a.version,r)),i.length===0){console.log(l.green(`\u2713 You're on the latest version (${r})`)),console.log(l.gray("Use --all to see the full changelog."));return}console.log(l.gray(`Showing changes since your version (${r})`)),console.log(l.gray("Use --all to see the full changelog."));}console.log(),console.log(l.bold.cyan("\u{1F4CB} LeetCode CLI Release Notes")),console.log(l.gray("\u2500".repeat(50))),console.log();for(let a of i)Ar(a.version,a.content,a.hasBreakingChanges),console.log(l.gray("\u2500".repeat(60))),console.log();if(!e&&!o.latest){let a=s.filter(c=>c.hasBreakingChanges).length;console.log(l.gray(`Showing ${i.length} of ${s.length} releases`)),a>0&&!o.breaking&&console.log(l.yellow(`${a} release(s) contain breaking changes. Use --breaking to filter.`));}}catch{t.fail("Failed to fetch changelog"),console.log(l.gray(" Could not fetch release notes from GitHub.")),console.log(l.gray(" Visit: https://github.com/night-slayer18/leetcode-cli/blob/main/docs/releases.md"));}}var T=new Command;T.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)});T.name("leetcode").usage("[command] [options]").description(l.bold.cyan("\u{1F525} A modern LeetCode CLI built with TypeScript")).version("2.1.0","-v, --version","Output the version number").helpOption("-h, --help","Display help for command").addHelpText("after",`
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(s+" \u2192 "+r+" lines")}`);}function so(e,o,t,n,s){if(s)er(e,o,t,n);else {Yt(e,t),Yt(o,n);let r=diffLines(e,o),i=0,a=0;for(let c of r){let g=c.value.split(`
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 Jt(e,o){let{authorized:t}=await v();if(!t)return;let n=w.getWorkDir(),s=Ue("Finding solution file...").start();try{let r=await O(n,e);if(!r){s.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(r,"utf-8");if(s.text="Fetching comparison target...",o.file){if(s.stop(),!existsSync(o.file)){console.log(l.red(`File not found: ${o.file}`));return}if(!me(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(`
239
+ 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){s.fail(`Problem ${e} not found`);return}if(o.submission){let p=parseInt(o.submission,10),b=await h.getSubmissionDetails(p);s.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){s.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));s.stop(),so(i,u.code,"Your Solution","Last Accepted",o.unified??!1);}catch(r){s.fail("Failed to diff"),r instanceof Error&&console.log(l.red(r.message));}}async function Kt(){let e=$.getActive(),o=$.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 Xt(){let e=$.list(),o=$.getActive();console.log(),console.log(l.bold("Workspaces:")),console.log();for(let t of e){let n=$.getConfig(t),s=t===o?l.green("\u25B8 "):" ",r=t===o?l.green.bold(t):t;console.log(`${s}${r}`),console.log(` ${l.gray(n.workDir)}`);}console.log();}async function Zt(e,o){if($.exists(e)){console.log(l.red(`Workspace "${e}" already exists`));return}let t=o.workdir??join(homedir(),"leetcode",e),n={workDir:t,lang:"typescript"};$.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 en(e){if(!$.exists(e)){console.log(l.red(`Workspace "${e}" not found`)),console.log(l.gray("Use `leetcode workspace list` to see available workspaces"));return}if($.setActive(e)){let t=$.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 on(e){if(e==="default"){console.log(l.red("Cannot delete the default workspace"));return}if(!$.exists(e)){console.log(l.red(`Workspace "${e}" not found`));return}let{confirmed:o}=await oo.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=$.delete(e);console.log(t?l.green(`\u2713 Deleted workspace "${e}"`):l.red("Failed to delete workspace"));}var ro=join(homedir(),".leetcode"),Ce=join(ro,"version-cache.json"),cr=1440*60*1e3;function gr(){existsSync(ro)||mkdirSync(ro,{recursive:true});}function tn(){if(existsSync(Ce))try{return JSON.parse(readFileSync(Ce,"utf-8"))}catch{return null}return null}function mr(e){gr(),writeFileSync(Ce,JSON.stringify(e,null,2));}var se={shouldCheck(){let e=tn();return e?Date.now()-e.lastCheck>cr:true},getCached(){return tn()},updateCache(e,o){mr({lastCheck:Date.now(),latestVersion:e,hasBreakingChanges:o});},clearCache(){existsSync(Ce)&&unlinkSync(Ce);}};function ye(e,o){let t=e.replace("v","").split(".").map(Number),n=o.replace("v","").split(".").map(Number);for(let s=0;s<3;s++){let r=t[s]||0,i=n[s]||0;if(r>i)return true;if(r<i)return false}return false}function sn(e,o){let t=parseInt(e.replace("v","").split(".")[0])||0;return (parseInt(o.replace("v","").split(".")[0])||0)>t}var hr=fileURLToPath(import.meta.url),an=dirname(hr),br="https://registry.npmjs.org/@night-slayer18/leetcode-cli/latest",wr="@night-slayer18/leetcode-cli";function he(){let e=[join(an,"../package.json"),join(an,"../../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 cn(){let o=(await wn(br,{timeout:{request:1e4},retry:{limit:2}}).json()).version,t=he(),n=sn(t,o);return {version:o,hasBreakingChanges:n}}function Sr(e,o,t){console.log();let n=60,s="\u256D"+"\u2500".repeat(n-2)+"\u256E",r="\u2570"+"\u2500".repeat(n-2)+"\u256F";console.log(l.cyan(s));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 ${wr}`;console.log(l.cyan("\u2502")+a.padEnd(n+8)+l.cyan("\u2502")),console.log(l.cyan(r)),console.log();}async function gn(e){let o=he();e.force&&se.clearCache();let t=se.getCached(),n,s;if(t&&!se.shouldCheck()&&!e.force)n=t.latestVersion,s=t.hasBreakingChanges;else {let r=Ue("Checking for updates...").start();try{let i=await cn();n=i.version,s=i.hasBreakingChanges,se.updateCache(n,s),r.stop();}catch(i){r.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}}ye(o,n)?(Sr(o,n,s),e.checkOnly||s&&(console.log(l.yellow("\u{1F4A1} Tip: Review the changelog before updating to check for breaking changes.")),console.log(l.gray(` Run: leetcode changelog
240
+ `)))):(console.log(),console.log(l.green("\u2713")+` You're on the latest version (${l.cyan(o)})`),console.log());}async function mn(){if(!se.shouldCheck()){let e=se.getCached();e&&ye(he(),e.latestVersion)&&ln(he(),e.latestVersion,e.hasBreakingChanges);return}try{let e=await cn();se.updateCache(e.version,e.hasBreakingChanges),ye(he(),e.version)&&ln(he(),e.version,e.hasBreakingChanges);}catch{}}function ln(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 Tr=fileURLToPath(import.meta.url),un=dirname(Tr),Dr="https://raw.githubusercontent.com/night-slayer18/leetcode-cli/main/docs/releases.md";function xr(){let e=[join(un,"../package.json"),join(un,"../../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 Er(){return await wn(Dr,{timeout:{request:1e4},retry:{limit:2}}).text()}function Lr(e){let o=[],t=/^## v?([\d.]+)/gm,n=[...e.matchAll(t)];for(let s=0;s<n.length;s++){let r=n[s],i=`v${r[1]}`,a=r.index+r[0].length,c=s+1<n.length?n[s+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 Ar(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 s=o.split(`
241
+ `),r=false;for(let i of s)if(!(i.trim()===""&&!r)){if(i.startsWith("> **Release Date**")){let a=i.replace("> **Release Date**: ","").trim();console.log(l.gray(` \u{1F4C5} ${a}`));continue}if(i.startsWith("> **Focus**")){let a=i.replace("> **Focus**: ","").trim();console.log(l.gray(` \u{1F3AF} ${a}`)),console.log();continue}if(i.startsWith("### ")){let a=i.replace("### ","").trim();if(console.log(),/^[\u{1F300}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/u.test(a))console.log(l.bold.yellow(` ${a}`));else {let g="\u{1F4CC}";a.includes("Breaking")?g="\u26A0\uFE0F":a.includes("Feature")||a.includes("New")?g="\u{1F680}":a.includes("Fix")||a.includes("Bug")?g="\u{1F41B}":a.includes("Security")?g="\u{1F512}":a.includes("Improvement")?g="\u2728":a.includes("Architecture")?g="\u{1F3D7}\uFE0F":a.includes("Testing")?g="\u{1F9EA}":a.includes("Config")&&(g="\u2699\uFE0F"),console.log(l.bold.yellow(` ${g} ${a}`));}r=true;continue}if(i.startsWith("#### ")){let a=i.replace("#### ","").trim();console.log(l.bold.white(` ${a}`));continue}if(i.startsWith("- **")){let a=i.match(/^- \*\*(.+?)\*\*:?\s*(.*)/);console.log(a?l.cyan(` \u2022 ${l.bold(a[1])}`)+(a[2]?l.white(`: ${a[2]}`):""):l.cyan(` \u2022 ${i.replace("- ","")}`));continue}if(i.startsWith("- ")){let a=i.replace("- ","").trim();console.log(l.white(` \u2022 ${a}`));continue}i.startsWith("---")||i.trim()===">"||i.trim()&&console.log(l.gray(` ${i.trim()}`));}}async function pn(e,o={}){let t=Ue("Fetching changelog...").start();try{let n=await Er();t.stop();let s=Lr(n);if(s.length===0){console.log(l.yellow("No release entries found."));return}let r=xr(),i=s;if(e){let a=e.startsWith("v")?e:`v${e}`;if(i=s.filter(c=>c.version===a),i.length===0){console.log(l.red(`Version ${e} not found in changelog.`)),console.log(l.gray("Available versions: "+s.map(c=>c.version).join(", ")));return}}else if(o.latest)i=s.slice(0,1);else if(o.breaking){if(i=s.filter(a=>a.hasBreakingChanges),i.length===0){console.log(l.green("\u2713 No breaking changes in any release."));return}}else if(o.all)i=s;else {if(i=s.filter(a=>ye(a.version,r)),i.length===0){console.log(l.green(`\u2713 You're on the latest version (${r})`)),console.log(l.gray("Use --all to see the full changelog."));return}console.log(l.gray(`Showing changes since your version (${r})`)),console.log(l.gray("Use --all to see the full changelog."));}console.log(),console.log(l.bold.cyan("\u{1F4CB} LeetCode CLI Release Notes")),console.log(l.gray("\u2500".repeat(50))),console.log();for(let a of i)Ar(a.version,a.content,a.hasBreakingChanges),console.log(l.gray("\u2500".repeat(60))),console.log();if(!e&&!o.latest){let a=s.filter(c=>c.hasBreakingChanges).length;console.log(l.gray(`Showing ${i.length} of ${s.length} releases`)),a>0&&!o.breaking&&console.log(l.yellow(`${a} release(s) contain breaking changes. Use --breaking to filter.`));}}catch{t.fail("Failed to fetch changelog"),console.log(l.gray(" Could not fetch release notes from GitHub.")),console.log(l.gray(" Visit: https://github.com/night-slayer18/leetcode-cli/blob/main/docs/releases.md"));}}var T=new Command;T.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)});T.name("leetcode").usage("[command] [options]").description(l.bold.cyan("\u{1F525} A modern LeetCode CLI built with TypeScript")).version("2.1.1","-v, --version","Output the version number").helpOption("-h, --help","Display help for command").addHelpText("after",`
242
242
  ${l.yellow("Examples:")}
243
243
  ${l.cyan("$ leetcode login")} Login to LeetCode
244
244
  ${l.cyan("$ leetcode list -d easy")} List easy problems
@@ -266,7 +266,7 @@ ${l.yellow("Examples:")}
266
266
  ${l.cyan("$ leetcode show 1")} Show by problem ID
267
267
  ${l.cyan("$ leetcode show two-sum")} Show by problem slug
268
268
  ${l.cyan("$ leetcode s 412")} Short alias
269
- `).action(Ae);T.command("daily").alias("d").description("Show today's daily challenge").addHelpText("after",`
269
+ `).action(Re);T.command("daily").alias("d").description("Show today's daily challenge").addHelpText("after",`
270
270
  ${l.yellow("Examples:")}
271
271
  ${l.cyan("$ leetcode daily")} Show today's challenge
272
272
  ${l.cyan("$ leetcode d")} Short alias
@@ -290,7 +290,7 @@ ${l.gray("Files are organized by: workDir/Difficulty/Category/")}
290
290
  ${l.yellow("Examples:")}
291
291
  ${l.cyan("$ leetcode pick-batch 1 2 3")} Pick problems 1, 2, and 3
292
292
  ${l.cyan("$ leetcode pick-batch 1 2 3 -l py")} Pick with Python
293
- `).action(Jo);T.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",`
293
+ `).action(Qo);T.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
294
  ${l.yellow("Examples:")}
295
295
  ${l.cyan("$ leetcode test 1")} Test by problem ID
296
296
  ${l.cyan("$ leetcode test two-sum")} Test by problem slug
@@ -312,7 +312,7 @@ ${l.yellow("Examples:")}
312
312
  ${l.cyan("$ leetcode diff 1 -u")} Show unified diff
313
313
  ${l.cyan("$ leetcode diff 1 -s 12345")} Compare with specific submission
314
314
  ${l.cyan("$ leetcode diff 1 -f other.py")} Compare with local file
315
- `).action(Qt);T.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",`
315
+ `).action(Jt);T.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
316
  ${l.yellow("Examples:")}
317
317
  ${l.cyan("$ leetcode submissions 1")} View submissions for problem
318
318
  ${l.cyan("$ leetcode submissions 1 -n 5")} Show last 5 submissions
@@ -383,7 +383,7 @@ ${l.yellow("Examples:")}
383
383
  ${l.cyan("$ leetcode timer 1 -m 30")} Start with 30 minute limit
384
384
  ${l.cyan("$ leetcode timer --stats")} Show your solve time statistics
385
385
  ${l.cyan("$ leetcode timer --stop")} Stop active timer
386
- `).action((e,o)=>Pt(e,o));var Ce=T.command("workspace").description("Manage workspaces for different contexts");Ce.command("current").description("Show current workspace").action(Kt);Ce.command("list").description("List all workspaces").action(Xt);Ce.command("create <name>").description("Create a new workspace").option("-w, --workdir <path>","Set working directory for this workspace").action(Zt);Ce.command("use <name>").description("Switch to a workspace").action(en);Ce.command("delete <name>").description("Delete a workspace").action(on);var he=T.command("collab").description("Collaborative coding with a partner").addHelpText("after",`
386
+ `).action((e,o)=>Pt(e,o));var Pe=T.command("workspace").description("Manage workspaces for different contexts");Pe.command("current").description("Show current workspace").action(Kt);Pe.command("list").description("List all workspaces").action(Xt);Pe.command("create <name>").description("Create a new workspace").option("-w, --workdir <path>","Set working directory for this workspace").action(Zt);Pe.command("use <name>").description("Switch to a workspace").action(en);Pe.command("delete <name>").description("Delete a workspace").action(on);var be=T.command("collab").description("Collaborative coding with a partner").addHelpText("after",`
387
387
  ${l.yellow("Subcommands:")}
388
388
  ${l.cyan("host <id>")} Create a room and get a code to share
389
389
  ${l.cyan("join <code>")} Join a room with the shared code
@@ -397,7 +397,7 @@ ${l.yellow("Examples:")}
397
397
  ${l.gray("$ leetcode collab join ABC123")} Join your partner's session
398
398
  ${l.gray("$ leetcode collab sync")} Upload your code after solving
399
399
  ${l.gray("$ leetcode collab compare")} Compare solutions
400
- `);he.command("host <problemId>").description("Host a collaboration session").action(xt);he.command("join <roomCode>").description("Join a collaboration session").action(Et);he.command("sync").description("Sync your code with partner").action(Lt);he.command("compare").description("Compare your solution with partner").action(At);he.command("leave").description("Leave the collaboration session").action(Rt);he.command("status").description("Show collaboration status").action(_t);var Pe=T.command("snapshot").description("Save and restore solution versions").addHelpText("after",`
400
+ `);be.command("host <problemId>").description("Host a collaboration session").action(xt);be.command("join <roomCode>").description("Join a collaboration session").action(Et);be.command("sync").description("Sync your code with partner").action(Lt);be.command("compare").description("Compare your solution with partner").action(At);be.command("leave").description("Leave the collaboration session").action(Rt);be.command("status").description("Show collaboration status").action(_t);var Te=T.command("snapshot").description("Save and restore solution versions").addHelpText("after",`
401
401
  ${l.yellow("Subcommands:")}
402
402
  ${l.cyan("save <id> [name]")} Save current solution as a snapshot
403
403
  ${l.cyan("list <id>")} List all snapshots for a problem
@@ -410,16 +410,16 @@ ${l.yellow("Examples:")}
410
410
  ${l.gray("$ leetcode snapshot list 1")} List snapshots
411
411
  ${l.gray("$ leetcode snapshot restore 1 2")} Restore snapshot #2
412
412
  ${l.gray("$ leetcode snapshot diff 1 1 2")} Compare snapshots
413
- `);Pe.command("save <id> [name]").description("Save current solution as a snapshot").action(Wt);Pe.command("list <id>").description("List all snapshots for a problem").action(Ht);Pe.command("restore <id> <snapshot>").description("Restore a snapshot").action(Vt);Pe.command("diff <id> <snap1> <snap2>").description("Compare two snapshots").action(zt);Pe.command("delete <id> <snapshot>").description("Delete a snapshot").action(Bt);T.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",`
413
+ `);Te.command("save <id> [name]").description("Save current solution as a snapshot").action(Wt);Te.command("list <id>").description("List all snapshots for a problem").action(Ht);Te.command("restore <id> <snapshot>").description("Restore a snapshot").action(Vt);Te.command("diff <id> <snap1> <snap2>").description("Compare two snapshots").action(zt);Te.command("delete <id> <snapshot>").description("Delete a snapshot").action(Bt);T.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
414
  ${l.yellow("Examples:")}
415
415
  ${l.cyan("$ leetcode update")} Check for updates
416
416
  ${l.cyan("$ leetcode update --force")} Force re-check npm registry
417
417
  ${l.cyan("$ leetcode update --check-only")} Just check, minimal output
418
- `).action(an);T.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",`
418
+ `).action(gn);T.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
419
  ${l.yellow("Examples:")}
420
420
  ${l.cyan("$ leetcode changelog")} Show what's new since your version
421
421
  ${l.cyan("$ leetcode changelog --all")} View full changelog
422
422
  ${l.cyan("$ leetcode changelog 2.0.0")} Show specific version
423
423
  ${l.cyan("$ leetcode changelog --latest")} Show latest version only
424
424
  ${l.cyan("$ leetcode changelog --breaking")} Filter to breaking changes
425
- `).action((e,o)=>cn(e,o));T.showHelpAfterError("(add --help for additional information)");var _r=process.argv.length>2&&!["update","changelog","--version","-v","--help","-h"].includes(process.argv[2]);_r&&ln().catch(()=>{});T.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(),T.outputHelp());
425
+ `).action((e,o)=>pn(e,o));T.showHelpAfterError("(add --help for additional information)");var _r=process.argv.length>2&&!["update","changelog","--version","-v","--help","-h"].includes(process.argv[2]);_r&&mn().catch(()=>{});T.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(),T.outputHelp());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@night-slayer18/leetcode-cli",
3
- "version": "2.1.0",
3
+ "version": "2.1.1",
4
4
  "description": "A modern LeetCode CLI built with TypeScript",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",