utiller 1.0.451 → 1.0.453
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/spider/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_index=require("../index.js");class Spider{constructor(e,{visible:t=!1,host:i=""}){(0,_defineProperty2.default)(this,"browser",null),(0,_defineProperty2.default)(this,"puppeteer",void 0),(0,_defineProperty2.default)(this,"visible",!0),(0,_defineProperty2.default)(this,"getBrowser",async()=>{const e=await this.puppeteer.launch({headless:!this.visible});for(const t of await e.pages())await t.close();return e}),(0,_defineProperty2.default)(this,"initial",async()=>{this.browser=await this.getBrowser()}),(0,_defineProperty2.default)(this,"getPuTeerPage",async({browser:e=this.browser,type:t="desktop",incognito:i=!1,href:o="",timeout:a=0})=>{let r;if(i){const t=await e.createBrowserContext();r=await t.newPage()}else r=await e.newPage();return await this.randomViewport({page:r,type:t}),_index.utiller.isUndefinedNullEmpty(o)||await r.goto(o,{waitUntil:"networkidle2",timeout:a}),r}),(0,_defineProperty2.default)(this,"randomViewport",async({page:e,type:t="desktop"})=>{const i=_index.utiller.getRandomValue(1080,1920),o=_index.utiller.getRandomValue(1680,1920);await e.setViewport({width:i,height:o})}),(0,_defineProperty2.default)(this,"getPageOfSilent",async({browser:e=this.browser,type:t="desktop",timeout:i=0})=>this.getPuTeerPage({browser:e,type:t,timeout:i})),(0,_defineProperty2.default)(this,"activatePage4Load",async({browser:e=this.browser,href:t="",type:i="desktop",timeout:o=0,incognito:a=!1})=>await this.getPuTeerPage({browser:e,href:t,type:i,timeout:o,incognito:a})),(0,_defineProperty2.default)(this,"activatePage4Task",async({browser:e=this.browser,href:t="",type:i="desktop",timeout:o=0,fetcher:a=async e=>!0,incognito:r=!1})=>{const n=await this.activatePage4Load({browser:e,href:t,type:i,timeout:o,incognito:r}),s=await a(n);return await this.close(n),s}),(0,_defineProperty2.default)(this,"auto",async({page:e,incognito:t=!1,href:i,timeout:o=0})=>this.isPuTeerPage(e)?(_index.utiller.isUndefinedNullEmpty(i)||await e.goto(i,{waitUntil:"networkidle2",timeout:o}),await this.randomViewport(e),e):await this.activatePage4Load({incognito:t,timeout:o,href:i})),(0,_defineProperty2.default)(this,"isPuTeerPage",e=>e?.focus),(0,_defineProperty2.default)(this,"clickNextPageTilEnd",async({page:e,selector:t=".pagination-container .pagination > *",sign:i="»"})=>{try{const o=await e.$$(t);if(!o||0===o.length)return console.log("⚠️ 找不到頁面按鈕們"),!1;console.log(`📍 找到 ${o.length} 個頁面按鈕`);let a=null;for(const e of[...o].reverse())if(await this.fetchAttributeOfEl(e,await this.isElementTagBy(e,"a")?"":"a","innerText")===i){a=e;break}return a?(console.log("✅ 找到下一頁按鈕"),await a.evaluate(e=>e.disabled||e.classList.contains("disabled"))?(console.log("⚠️ 下一頁按鈕已禁用 (已是最後一頁)"),!1):(console.log("🖱️ 點擊下一頁按鈕..."),await a.click(),await e.waitForNavigation({waitUntil:"networkidle2",timeout:0}).catch(()=>{}),console.log("✅ 成功翻到下一頁"),!0)):(console.log("⚠️ 找不到下一頁按鈕 (»)"),!1)}catch(e){return console.log(`❌ 點擊下一頁出錯: ${e.message}`),!1}}),(0,_defineProperty2.default)(this,"wait4Until",async(e,{timeout:t=0}={})=>{await e.waitForNavigation({waitUntil:"networkidle2",timeout:t}).catch(()=>{})}),(0,_defineProperty2.default)(this,"fetchElementsTilPageScrollEnd",async({page:e,href:t="",fetcher:i=async e=>{},stringOfLoadingSelector:o,incognito:a=!1,timeout:r})=>{const n=await this.auto({page:e,incognito:a,href:t,timeout:r});await this.scrollToBottomAndCheck(n,{stringOfLoadingSelector:o});const s=await i(n);return await this.close(n),s}),(0,_defineProperty2.default)(this,"fetchAttributesOfEl",async(e,t,i)=>{let o;if(t&&""!==t.trim()){if(o=await e.$(t),!o)return console.warn(`⚠️ 找不到元素: ${t}`),{}}else o=e;const a={},r={};for(const[e,t]of Object.entries(i)){if("object"==typeof t&&null!==t&&!Array.isArray(t)){Object.assign(r,t);continue}const i=String(t);if(i.startsWith("$$$")){const t=i.substring(3),o=parseFloat(t);isNaN(o)?(console.warn(`⚠️ 無法解析數字: ${i}`),r[e]=void 0):r[e]=o;continue}if(i.startsWith("###")){const t=i.substring(3);r[e]=t;continue}if(i.startsWith("@@@")){const t=i.substring(3).toLowerCase().trim();let o;"true"===t||"1"===t||"yes"===t||"y"===t||"on"===t?o=!0:("false"===t||"0"===t||"no"===t||"n"===t||"off"===t||""===t||console.warn(`⚠️ 無法解析布林值: ${i},默認為 false`),o=!1),r[e]=o;continue}a[e]=t}const n=await o.evaluate((e,t)=>{const i={};for(const[o,a]of Object.entries(t)){const t=void 0!==e[a]?e[a]:e.getAttribute(a);i[o]=null!==t?t:void 0}return i},a);return{...n,...r}}),(0,_defineProperty2.default)(this,"fetchAttributeOfEl",async(e,t,i)=>{let o;if(t&&""!==t.trim()){if(o=await e.$(t),!o)return void console.warn(`⚠️ 找不到元素: ${t}`)}else o=e;return await o.evaluate((e,t)=>{const i=void 0!==e[t]?e[t]:e.getAttribute(t);return null!==i?i:void 0},i)}),(0,_defineProperty2.default)(this,"isElementTagBy",async(e,t)=>await e.evaluate((e,t)=>e.tagName.toLowerCase()===t.toLowerCase(),t)),(0,_defineProperty2.default)(this,"waitForLoadingToVanish",async(e,t,i=1e4)=>{if(!t)return!0;try{return await e.waitForSelector(t,{hidden:!0,timeout:i}),!0}catch(e){return console.warn(`警告: Loading Bar ${t} 在 ${i}ms 內未消失,將強制繼續執行。`),!1}}),(0,_defineProperty2.default)(this,"extractBlockTexts",async e=>e?await e.evaluate(e=>{const t=[],i=new Set;return e.querySelectorAll(":scope > *").forEach(e=>{if(["SCRIPT","STYLE","IMG"].includes(e.tagName))return;let o=e.textContent.trim();o.length>0&&(i.has(o)||(t.push(o),i.add(o)))}),t}):[]),(0,_defineProperty2.default)(this,"scrollToBottomAndCheck",async(e,{minDelay:t=2e3,maxRetries:i=3,stringOfLoadingSelector:o,loadingTimeout:a=6e3}={})=>{console.log("🚀 開始執行智能滾動檢查...");let r=await e.evaluate(()=>document.body.scrollHeight),n=0;for(;;){await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(e=>setTimeout(e,t)),o&&await this.waitForLoadingToVanish(e,o,a);let s=await e.evaluate(()=>document.body.scrollHeight);if(s===r){if(n++,n>=i){console.log(`✅ 連續 ${i} 次未檢測到新內容,判定已到達最底部。`);break}console.log(`🔄 高度未變化,正在重試等待... (${n}/${i})`),await new Promise(e=>setTimeout(e,1e3))}else console.log(`⬇️ 檢測到新內容 (高度: ${r} -> ${s}),繼續滾動...`),r=s,n=0}}),(0,_defineProperty2.default)(this,"getSelectorRoute",async(e,t)=>await e.evaluate(e=>(e=>{if(e.id)return`#${e.id}`;let t=[];for(;e.parentElement;){let i=e.tagName.toLowerCase();Array.from(e.parentElement.children).filter(t=>t.tagName===e.tagName).length>1&&(i+=`:nth-child(${Array.prototype.indexOf.call(e.parentElement.children,e)+1})`),t.unshift(i),e=e.parentElement}return t.join(" > ")})(e),t)),(0,_defineProperty2.default)(this,"waitSelectorTilAppear",async(e,t,i=1e4)=>{try{return await e.waitForSelector(t,{visible:!0,timeout:i}),console.log(`元素 ${t} 已在 ${e.url()} 上出現!`),!0}catch(e){const o=`元素 ${t} 未在 ${i/1e3} 秒內出現。`;console.error(o,e)}}),(0,_defineProperty2.default)(this,"close",async e=>{if(e)try{const t=e.browserContext();t===e.browser().defaultBrowserContext()?await e.close():await t.close()}catch(e){console.error("關閉頁面/Context 時發生錯誤:",e)}}),(0,_defineProperty2.default)(this,"terminate",async()=>{await this.browser.close()}),this.puppeteer=e,this.visible=t,this.host=i}async fetchElementsTilPageEnd({page:e,href:t="",fetcher:i=async e=>[],selectorOfPagingN:o,signOfPagingN:a="»",incognito:r=!1,timeout:n=0}){const s=await this.auto({page:e,incognito:r,href:t,timeout:n});let l=[];try{do{await _index.utiller.syncDelay(10);const e=await i(s);l=l.concat(e)}while(await this.clickNextPageTilEnd({page:s,selector:o,sign:a}))}catch(e){return console.error(`抓取失敗: ${e.message}`),[]}finally{await this.close(s)}return l}async clearCookies(e){await e.deleteCookie(...await e.cookies())}async checkSelectorExists(e,t){return!!await e.$(t)}async finish(){await this.browser.close()}async clickSolution(e,t){await e.evaluate(e=>{e.click()},t)}async managePages(e,t=this.browser){const i=e=>{try{const t=new URL(e);return _index.utiller.getUrlPath(this.host,t.pathname)}catch(e){return null}};t.on("targetcreated",async t=>{if("page"===t.type())try{const o=await t.page();if(!o)return;const a=o.url();if("about:blank"===a)return;const r=i(a);r&&r!==e&&(console.log(`[攔截新分頁] 偵測到非法網址: ${r} (目標應為: ${e}),正在關閉...`),await o.close())}catch(e){console.error(`[新分頁檢查錯誤] 無法處理頁面: ${e.message}`)}});try{const o=await t.pages();for(const t of o){const o=t.url();if(t.isClosed()||"about:blank"===o)continue;const a=i(o);a&&a!==e&&(console.log(`[清理舊分頁] 發現非法網址: ${a} (目標應為: ${e}),正在關閉...`),await t.close())}}catch(e){console.error(`[舊分頁清理錯誤] ${e.message}`)}console.log("頁面管理已啟動,保持監聽 10 秒..."),await new Promise(e=>setTimeout(e,1e4))}async checkElementVisibleWithRetry(e,t,i=3e4,o=1e3){const a=Date.now();try{for(;Date.now()-a<i;){if(await e.$(t)){if(await e.evaluate(e=>{const t=document.querySelector(e);if(!t)return!1;const i=window.getComputedStyle(t);return"none"!==i.display&&"hidden"!==i.visibility&&"0"!==i.opacity},t))return console.log(`元素 ${t} 存在且可見`),!0;console.log(`元素 ${t} 存在但不可見,繼續等待...`)}else console.log(`元素 ${t} 不存在,繼續等待...`);await new Promise(e=>setTimeout(e,o))}return console.log(`超時:元素 ${t} 未在 ${i/1e3} 秒內變為可見`),!1}catch(e){return console.error(`發生錯誤: ${e.message}`),!1}}}var _default=exports.default=Spider;
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_index=require("../index.js"),_configerer=require("configerer"),_lodash=_interopRequireDefault(require("lodash"));class Spider{constructor(e,{visible:t=!1,host:o=""}){(0,_defineProperty2.default)(this,"browser",null),(0,_defineProperty2.default)(this,"puppeteer",void 0),(0,_defineProperty2.default)(this,"visible",!0),(0,_defineProperty2.default)(this,"establishBrowserCore",async()=>{const e=await this.puppeteer.launch({headless:!this.visible});for(const t of await e.pages())await t.close();return e}),(0,_defineProperty2.default)(this,"getCurrentBrowser",()=>this.browser),(0,_defineProperty2.default)(this,"initial",async()=>{this.browser=await this.establishBrowserCore()}),(0,_defineProperty2.default)(this,"getPuTeerPage",async({browser:e=this.browser,type:t="desktop",incognito:o=!1,href:i="",timeout:a=0})=>{let r;if(o){const t=await e.createBrowserContext();r=await t.newPage()}else r=await e.newPage();return await this.randomViewport({page:r,type:t}),_index.utiller.isUndefinedNullEmpty(i)||await r.goto(i,{waitUntil:"networkidle2",timeout:a}),r}),(0,_defineProperty2.default)(this,"randomViewport",async({page:e,type:t="desktop"})=>{const o=_index.utiller.getRandomValue(1080,1920),i=_index.utiller.getRandomValue(1680,1920);await e.setViewport({width:o,height:i})}),(0,_defineProperty2.default)(this,"getPageOfSilent",async({browser:e=this.browser,type:t="desktop",timeout:o=0})=>this.getPuTeerPage({browser:e,type:t,timeout:o})),(0,_defineProperty2.default)(this,"activatePage4Load",async({browser:e=this.browser,href:t="",type:o="desktop",timeout:i=0,incognito:a=!1})=>await this.getPuTeerPage({browser:e,href:t,type:o,timeout:i,incognito:a})),(0,_defineProperty2.default)(this,"activatePage4Task",async({browser:e=this.browser,href:t="",type:o="desktop",timeout:i=0,fetcher:a=async e=>!0,incognito:r=!1})=>{const n=await this.activatePage4Load({browser:e,href:t,type:o,timeout:i,incognito:r}),s=await a(n);return await this.close(n),s}),(0,_defineProperty2.default)(this,"auto",async({page:e,incognito:t=!1,href:o,timeout:i=0})=>this.isPuTeerPage(e)?(_index.utiller.isUndefinedNullEmpty(o)||await e.goto(o,{waitUntil:"networkidle2",timeout:i}),await this.randomViewport(e),e):await this.activatePage4Load({incognito:t,timeout:i,href:o})),(0,_defineProperty2.default)(this,"isPuTeerPage",e=>e?.focus),(0,_defineProperty2.default)(this,"clickNextPageTilEnd",async({page:e,selector:t=".pagination-container .pagination > *",sign:o="»"})=>{try{const i=await e.$$(t);if(!i||0===i.length)return console.log("⚠️ 找不到頁面按鈕們"),!1;console.log(`📍 找到 ${i.length} 個頁面按鈕`);let a=null;for(const e of[...i].reverse())if(await this.fetchAttributeOfEl(e,await this.isElementTagBy(e,"a")?"":"a","innerText")===o){a=e;break}return a?(console.log("✅ 找到下一頁按鈕"),await a.evaluate(e=>e.disabled||e.classList.contains("disabled"))?(console.log("⚠️ 下一頁按鈕已禁用 (已是最後一頁)"),!1):(console.log("🖱️ 點擊下一頁按鈕..."),await this.clickAndWait4Page(e,a,{selectorOfAnchor:t}),console.log("✅ 成功翻到下一頁"),!0)):(console.log(`⚠️ 找不到下一頁按鈕 (${o})`),!1)}catch(e){return console.log(`❌ 點擊下一頁出錯: ${e.message}`),!1}}),(0,_defineProperty2.default)(this,"getElementSnapshot",async(e,t)=>{try{const o=await e.waitForSelector(t,{timeout:1e3});return await e.evaluate(e=>e.outerHTML,o)}catch(e){return null}}),(0,_defineProperty2.default)(this,"clickAndWait4Page",async(e,t,{selectorOfAnchor:o=null,timeoutOfApiWatcher:i=500,timeoutOfNavigation:a=3e4,specificity:r=!1}={})=>{let n=!1,s=null,l=null;const c=r?["xhr","fetch","websocket","eventsource","other"]:["xhr","fetch"],u=t=>{c.includes(t.resourceType())&&(n||(n=!0,s=t.url(),e.off("request",u),console.log(`📡 偵測到 API 請求 (${t.resourceType()}): ${s}`)))};console.log("🖱️ 執行點擊..."),o&&(l=await this.getElementSnapshot(e,o),l?console.log(`📸 成功獲取錨點快照 (${o},長度: ${l.length})`):console.log("⚠️ 無法獲取錨點快照,DOM 變化偵測將被忽略。")),await t.click(),e.on("request",u);try{await Promise.race([new Promise(e=>{let t;const o=setTimeout(()=>{clearInterval(t),n||e("TIMEOUT_NO_API")},i);t=setInterval(()=>{n&&(clearTimeout(o),clearInterval(t),e("API_FIRED"))},50)})])}catch(e){console.warn("Race 過程中發生錯誤:",e.message)}if(e.off("request",u),n&&s){console.log(`✅ 偵測到 API,切換至長等待 (兼容 AJAX/導航/DOM,${a}ms)...`);const t=[e.waitForResponse(e=>e.url()===s&&e.status()>=200&&e.status()<300,{timeout:a}),e.waitForNavigation({waitUntil:"networkidle2",timeout:a}).catch(()=>"NAVIGATION_TIMEOUT")];l&&t.push(e.waitForFunction((e,t)=>{const o=document.querySelector(e);return!o||o.outerHTML!==t},{timeout:a},o,l).catch(e=>{if("TimeoutError"===e.name)return"DOM_CHANGE_TIMEOUT";throw e}));try{await Promise.race(t),console.log("✅ 等待條件滿足(API 響應、頁面導航或 DOM 變化已完成)。")}catch(e){if("TimeoutError"!==e.name)throw e;console.log("⚠️ 長等待超時,API/導航可能發生錯誤或頁面載入極慢。")}}else{if(l){if(await this.getElementSnapshot(e,o)===l)throw console.log("❌ 未偵測到 API/導航,且 DOM 錨點無變化。拋出未變化錯誤。"),new Error("[已到最後一頁]後並未re-render頁面列表(例:...18 -> 19[current]...)");console.log("✅ 未偵測到 API,但 DOM 錨點有變化,等待 DOM 穩定。")}else console.log(`✅ ${i}ms 內未偵測到 API,無快照比對,等待 DOM 穩定。`);await _index.utiller.syncDelay(365)}}),(0,_defineProperty2.default)(this,"wait4Until",async(e,{timeout:t=0}={})=>{await e.waitForNavigation({waitUntil:"networkidle2",timeout:t}).catch(()=>{})}),(0,_defineProperty2.default)(this,"fetchElementsTilPageScrollEnd",async({page:e,href:t="",fetcher:o=async e=>{},stringOfLoadingSelector:i,incognito:a=!1,timeout:r})=>{const n=await this.auto({page:e,incognito:a,href:t,timeout:r});await o(n),await this.scrollToBottomAndCheck(n,{stringOfLoadingSelector:i});const s=await o(n);return await this.close(n),s}),(0,_defineProperty2.default)(this,"fetchAttributesOfEl",async(e,t,o)=>{let i;if(t&&""!==t.trim()){if(i=await e.$(t),!i)return console.warn(`⚠️ 找不到元素: ${t}`),{}}else i=e;const a={},r={};for(const[e,t]of Object.entries(o)){if("object"==typeof t&&null!==t&&!Array.isArray(t)){Object.assign(r,t);continue}const o=String(t);if(o.startsWith("$$$")){const t=o.substring(3),i=parseFloat(t);isNaN(i)?(console.warn(`⚠️ 無法解析數字: ${o}`),r[e]=void 0):r[e]=i;continue}if(o.startsWith("###")){const t=o.substring(3);r[e]=t;continue}if(o.startsWith("@@@")){const t=o.substring(3).toLowerCase().trim();let i;"true"===t||"1"===t||"yes"===t||"y"===t||"on"===t?i=!0:("false"===t||"0"===t||"no"===t||"n"===t||"off"===t||""===t||console.warn(`⚠️ 無法解析布林值: ${o},默認為 false`),i=!1),r[e]=i;continue}a[e]=t}const n=await i.evaluate((e,t)=>{const o={};for(const[i,a]of Object.entries(t)){const t=void 0!==e[a]?e[a]:e.getAttribute(a);o[i]=null!==t?t:void 0}return o},a);return{...n,...r}}),(0,_defineProperty2.default)(this,"fetchAttributeOfEl",async(e,t,o)=>{let i;if(t&&""!==t.trim()){if(i=await e.$(t),!i)return void console.warn(`⚠️ 找不到元素: ${t}`)}else i=e;return await i.evaluate((e,t)=>{const o=void 0!==e[t]?e[t]:e.getAttribute(t);return null!==o?o:void 0},o)}),(0,_defineProperty2.default)(this,"isElementTagBy",async(e,t)=>await e.evaluate((e,t)=>e.tagName.toLowerCase()===t.toLowerCase(),t)),(0,_defineProperty2.default)(this,"waitForLoadingToVanish",async(e,t,o=1e4)=>{if(!t)return!0;try{return await e.waitForSelector(t,{hidden:!0,timeout:o}),!0}catch(e){return console.warn(`警告: Loading Bar ${t} 在 ${o}ms 內未消失,將強制繼續執行。`),!1}}),(0,_defineProperty2.default)(this,"extractBlockTexts",async e=>e?await e.evaluate(e=>{const t=[],o=new Set;return e.querySelectorAll(":scope > *").forEach(e=>{if(["SCRIPT","STYLE","IMG"].includes(e.tagName))return;let i=e.textContent.trim();i.length>0&&(o.has(i)||(t.push(i),o.add(i)))}),t}):[]),(0,_defineProperty2.default)(this,"scrollToBottomAndCheck",async(e,{minDelay:t=2e3,maxRetries:o=3,stringOfLoadingSelector:i,loadingTimeout:a=6e3,fetcher:r}={})=>{console.log("🚀 開始執行智能滾動檢查...");let n=await e.evaluate(()=>document.body.scrollHeight),s=0;for(;;){await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(e=>setTimeout(e,t)),i&&(await this.waitForLoadingToVanish(e,i,a),_lodash.default.isFunction(r)&&await r(e));let l=await e.evaluate(()=>document.body.scrollHeight);if(l===n){if(s++,s>=o){console.log(`✅ 連續 ${o} 次未檢測到新內容,判定已到達最底部。`);break}console.log(`🔄 高度未變化,正在重試等待... (${s}/${o})`),await new Promise(e=>setTimeout(e,1e3))}else console.log(`⬇️ 檢測到新內容 (高度: ${n} -> ${l}),繼續滾動...`),n=l,s=0}}),(0,_defineProperty2.default)(this,"getSelectorRoute",async(e,t)=>await e.evaluate(e=>(e=>{if(e.id)return`#${e.id}`;let t=[];for(;e.parentElement;){let o=e.tagName.toLowerCase();Array.from(e.parentElement.children).filter(t=>t.tagName===e.tagName).length>1&&(o+=`:nth-child(${Array.prototype.indexOf.call(e.parentElement.children,e)+1})`),t.unshift(o),e=e.parentElement}return t.join(" > ")})(e),t)),(0,_defineProperty2.default)(this,"waitSelectorTilAppear",async(e,t,o=1e4)=>{try{return await e.waitForSelector(t,{visible:!0,timeout:o}),console.log(`元素 ${t} 已在 ${e.url()} 上出現!`),!0}catch(e){const i=`元素 ${t} 未在 ${o/1e3} 秒內出現。`;console.error(i,e)}}),(0,_defineProperty2.default)(this,"close",async e=>{if(e)try{const t=e.browserContext();t===e.browser().defaultBrowserContext()?await e.close():await t.close()}catch(e){console.error("關閉頁面/Context 時發生錯誤:",e)}}),(0,_defineProperty2.default)(this,"terminate",async()=>{await this.browser.close()}),this.puppeteer=e,this.visible=t,this.host=o}async fetchElementsTilPageEnd({page:e,href:t="",fetcher:o=async e=>[],selectorOfPagingN:i,signOfPagingN:a="»",incognito:r=!1,timeout:n=0}){const s=await this.auto({page:e,incognito:r,href:t,timeout:n});let l=[];try{do{await _index.utiller.syncDelay(10);const e=await o(s);l=l.concat(e)}while(await this.clickNextPageTilEnd({page:s,selector:i,sign:a,timeout:n}))}catch(e){return console.error(`抓取失敗: ${e.message}`),[]}finally{await this.close(s)}return l}async clearCookies(e){await e.deleteCookie(...await e.cookies())}async checkSelectorExists(e,t){return!!await e.$(t)}async finish(){await this.browser.close()}async clickSolution(e,t){await e.evaluate(e=>{e.click()},t)}async managePages(e,t=this.browser){const o=e=>{try{const t=new URL(e);return _index.utiller.getUrlPath(this.host,t.pathname)}catch(e){return null}};t.on("targetcreated",async t=>{if("page"===t.type())try{const i=await t.page();if(!i)return;const a=i.url();if("about:blank"===a)return;const r=o(a);r&&r!==e&&(console.log(`[攔截新分頁] 偵測到非法網址: ${r} (目標應為: ${e}),正在關閉...`),await i.close())}catch(e){console.error(`[新分頁檢查錯誤] 無法處理頁面: ${e.message}`)}});try{const i=await t.pages();for(const t of i){const i=t.url();if(t.isClosed()||"about:blank"===i)continue;const a=o(i);a&&a!==e&&(console.log(`[清理舊分頁] 發現非法網址: ${a} (目標應為: ${e}),正在關閉...`),await t.close())}}catch(e){console.error(`[舊分頁清理錯誤] ${e.message}`)}console.log("頁面管理已啟動,保持監聽 10 秒..."),await new Promise(e=>setTimeout(e,1e4))}async checkElementVisibleWithRetry(e,t,o=3e4,i=1e3){const a=Date.now();try{for(;Date.now()-a<o;){if(await e.$(t)){if(await e.evaluate(e=>{const t=document.querySelector(e);if(!t)return!1;const o=window.getComputedStyle(t);return"none"!==o.display&&"hidden"!==o.visibility&&"0"!==o.opacity},t))return console.log(`元素 ${t} 存在且可見`),!0;console.log(`元素 ${t} 存在但不可見,繼續等待...`)}else console.log(`元素 ${t} 不存在,繼續等待...`);await new Promise(e=>setTimeout(e,i))}return console.log(`超時:元素 ${t} 未在 ${o/1e3} 秒內變為可見`),!1}catch(e){return console.error(`發生錯誤: ${e.message}`),!1}}}var _default=exports.default=Spider;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_path2=_interopRequireDefault(require("path")),_fs=_interopRequireDefault(require("fs")),_promises=_interopRequireDefault(require("fs/promises")),_lodash=_interopRequireDefault(require("lodash")),_child_process=_interopRequireDefault(require("child_process")),_configerer=require("configerer"),_index=_interopRequireDefault(require("./index")),_index2=_interopRequireDefault(require("../exceptioner/index")),_pdfParse=_interopRequireDefault(require("pdf-parse")),_del=_interopRequireDefault(require("del")),_fsExtra=_interopRequireDefault(require("fs-extra")),_prompt=_interopRequireDefault(require("prompt"));class NodeUtiller extends _index.default{constructor(...e){super(...e),(0,_defineProperty2.default)(this,"isPersistIntoLogFile",!0),(0,_defineProperty2.default)(this,"findFilePathByExtension",(e,t=[],...i)=>{const s=new RegExp(`^[^.].+.(${_lodash.default.join(t,"|")})$`);return this.findFilePathBy(e,e=>s.test(e.fileNameExtension),...i)}),(0,_defineProperty2.default)(this,"executeCommandLine",async e=>{const t=this;return this.appendInfo(`執行腳本 ${e}`),new Promise(function(i,s){_child_process.default.exec(e,(e,a,n)=>{if(t.appendInfo(`${a}`),t.appendInfo(`${n}`),e)return t.appendError(`執行錯誤: ${e}`),void s(e);i(a.trim())})})}),(0,_defineProperty2.default)(this,"getStringOfTerserCommandLine",e=>{const t=[];if(e.compress){const i=[];e.compress.drop_console&&i.push("drop_console=true"),e.compress.drop_debugger&&i.push("drop_debugger=true"),e.compress.passes&&i.push(`passes=${e.compress.passes}`),e.compress.dead_code&&i.push("dead_code=true"),e.compress.unused&&i.push("unused=true"),i.length>0&&t.push(`--compress ${i.join(",")}`)}return!0===e.mangle&&t.push("--mangle"),e.format&&(!0===e.format.beautify&&t.push("--beautify"),!1===e.format.comments?t.push("--no-comments"):"all"===e.format.comments?t.push("--comments all"):e.format.comments&&
|
|
2
2
|
// 例如:comments: /@license|@preserve/
|
|
3
|
-
t.push(`--comments "${e.format.comments}"`),e.format.indent_level&&t.push(`--format indent_level=${e.format.indent_level}`)),t.join(" ")}),(0,_defineProperty2.default)(this,"getPathAfterSpecificFolder",(e,t="src")=>{const i=e.split(_path2.default.sep);for(let e=i.length-1;e>=0;e--)if(i[e]===t)return"/"+i.slice(e+1).join("/");return""}),(0,_defineProperty2.default)(this,"getPathAfterSrc",e=>this.getPathAfterSpecificFolder(e))}findSpecificFolderByPath(e,t){const i=_path2.default.resolve(e).split(_path2.default.sep);for(;i.length;){const e=_path2.default.join(...i,t);if(_fs.default.existsSync(e))return e;i.pop()}return null}async getPDFText(e){let t=_fs.default.readFileSync(e);return(0,_pdfParse.default)(t).then(e=>e)}printf(){this.appendInfo("i can use in node.js only yo yo")}findFilePathBy(e,t=()=>!0,...i){if(!_fs.default.existsSync(e))return[];const s=[],a=_fs.default.readdirSync(e,{withFileTypes:!0});for(const n of a){if(i.includes(n.name))continue;const a=_path2.default.join(e,n.name);if(n.isDirectory())s.push(...this.findFilePathBy(a,t,...i));else if(n.isFile()){const e=this.getPathInfo(a);t(e)&&s.push(e)}}return s}isPathExist(e){return _fs.default.existsSync(e)}renameFile(e,t="fileName"){if(!this.isFile(e)||!t)return void this.appendError(`renameFile 錯誤, path: ${e}, newName: ${t}`);const i=_path2.default.dirname(e),s=_path2.default.extname(e),a=_path2.default.join(i,`${t}${s}`);_fs.default.renameSync(e,a)}getPathInfo(e){const t=_path2.default.resolve(e),i={path:e,absolute:t,isFile:!1,isDirectory:!0,dirName:void 0,folderName:void 0,dirPath:void 0,folderPath:void 0,extension:void 0,fileName:void 0,fileNameExtension:void 0,lastModifiedTime:void 0,name:void 0};if(this.isFile(t)){i.extension=t.split(".").pop();const e=t.split("/").pop().split(".");e.pop(),i.fileName=e.join("."),i.name=e.join("."),i.dirName=_lodash.default.nth(t.split("/"),-2),i.folderName=_lodash.default.nth(t.split("/"),-2),i.isFile=!0,i.dirPath=this.getFolderPathOfSpecificPath(t),i.folderPath=this.getFolderPathOfSpecificPath(t),i.isDirectory=!1,i.fileNameExtension=`${i.fileName}.${i.extension}`,i.lastModifiedTime=this.getFileLastModifiedTime(t)}return this.isDirectory(t)&&(i.dirName=t.split("/").pop()),i}syncExecuteCommandLine(e){const t=this;this.appendInfo(`執行腳本 ${e}`),_child_process.default.exec(`${e}`,(e,i,s)=>{t.appendInfo(`${i}`),t.appendInfo(`${s}`),null!==e&&t.appendError(`exec error: ${e}`)})}persistByPath(e){const t=_path2.default.isAbsolute(e),i=e.split("/").filter(Boolean),s=i[i.length-1],a=""!==_path2.default.extname(s);let n=t?_path2.default.sep:"";for(let e=0;e<i.length;e++)n=_path2.default.join(n,i[e]),_fs.default.existsSync(n)||(e===i.length-1&&a?_fs.default.writeFileSync(n,""):_fs.default.mkdirSync(n,{recursive:!1}));return _path2.default.resolve(e)}async copyFromFolderToDestFolder(e,t,i=!0,s=!1,a=()=>!0){if(!_fs.default.existsSync(e)||!_fs.default.existsSync(e))throw new _index2.default(8009,`${e} or ${t} is not exist!`);this.appendInfo(`正在複製ing ${e}/* => ${t}/* succeed`),_fsExtra.default.copySync(e,t,{preserveTimestamps:s,override:i,filter:a}),this.appendInfo(`複製成功 ${e}/* => ${t}/* succeed`)}cleanAllFiles(e){this.isDirectory(e)&&(this.appendInfo(`準備清除底下的所有 ${e}`),_fsExtra.default.emptyDirSync(e),this.appendInfo(`成功清除底下的所有 ${e}`))}async deleteSelfByPath(e,t){_fs.default.existsSync(e)&&(this.appendInfo(`準備刪掉 ${e},{force:${t}}`),await(0,_del.default)(e,{force:t}),this.appendInfo(`成功刪掉了 ${e}`))}async deleteFileOrFolder(e){this.appendInfo(`刪掉了 ${e}`),await(0,_del.default)(e)}async deleteChildByPath(e,t=!1){const i=this.getChildPathByPath(e);for(const e of i)await this.deleteSelfByPath(e.absolute,t)}getFileCountsOfFolder(e){return this.isDirectory(e)?_fs.default.readdirSync(e).length:-1}async reinstallNodeModules(e="../",...t){const i=[...t,"node_modules","utiller","configerer"],s=this.findFilePathBy(e,e=>_lodash.default.isEqual(e.fileNameExtension,"package.json"),...i);for(const e of s){const t=this.getFileDirPath(e.absolute),i=`${t}node_modules`,s=`${t}package-lock.json`;await(0,_del.default)(s),this.appendInfo(`刪掉了 ${s}`),await(0,_del.default)(i),this.appendInfo(`刪掉了 ${i}`)}for(const e of s){const t=this.getFileDirPath(e.absolute),i=`${t}node_modules`;_fs.default.existsSync(i)||await this.executeCommandLine(`cd ${t} && npm install`)}}getNamesOfFolderChild(e){return this.getChildPathByPath(e).filter(e=>e.isDirectory).map(e=>e.dirName)}getChildPathByPath(e){try{return _fs.default.readdirSync(e).map(t=>this.getPathInfo(_path2.default.join(e,t)))}catch(e){throw new _index2.default(8002,e)}}copySingleFile(e,t,i,s=!1){const a=i&&i.trim()?_path2.default.join(t,i):t;if(_fs.default.existsSync(a)&&!s)throw new _index2.default(8006,a);_fs.default.copyFileSync(e,a)}ensureFolderExists(e){const t=_path2.default.resolve(e);_fs.default.existsSync(t)||_fs.default.mkdirSync(t,{recursive:!0})}getNodeEnvVariable(e,t=void 0){const i=process.env[e];return void 0===i?t:i}isDirectory(e){return!!this.isPathExist(e)&&_fs.default.lstatSync(e).isDirectory()}isFile(e){return!!this.isPathExist(e)&&_fs.default.lstatSync(e).isFile()}isImageFile(e){return["svg","png","jpg","jpeg"].includes(e.extension)}async cleanChildFiles(e,t=()=>!0,...i){if(!_fs.default.existsSync(e))return!1;const s=this.findFilePathBy(e,t,...i),a=s.filter(e=>!this.isImageFile(e));return await Promise.allSettled(a.map(e=>(this.cleanFileContent(e.absolute),this.appendInfo(`成功 cleanChildFiles() -> '${e.path}'`),Promise.resolve()))),s}cleanFileContent(e){this.syncDeleteFile(e)}async syncWithExistPackage(e="../"){const t=this.findFilePathBy(e,e=>_lodash.default.isEqual(e.fileNameExtension,"package.json"),"node_modules");for(let e of t)try{_lodash.default.isEqual(e.dirName,"..")||this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${e.dirName}`,`cd ${this.getFolderPathOfSpecificPath(e.absolute)}`)}catch(e){this.appendInfo(e.message)}}async packageTemplatify(e,t){const i=this.getChildPathByPath(e).map(e=>e.absolute.split("/").pop());if(this.has(i,t))throw new _index2.default(8004,` packageName ===> '${t}'`);const s=`${e}/${t}`;_fs.default.mkdirSync(s),_fs.default.copyFileSync("./template/sample.babel.config.js",`${s}/babel.config.js`),_fs.default.copyFileSync("./template/sample.terser.config.js",`${s}/terser.config.js`);const a=this.getJsonObjByFilePath("./template/sample.package.json");a.name=t,this.writeFileInJSON(`${s}/package.json`,a),this.persistByPath(`${s}/src`);const n=String.format(this.getFileContextInRaw("./template/sample.src.index.js"),t,"明悅",new Date);_fs.default.writeFileSync(`${s}/src/index.js`,n);const r=`${this.findSpecificFolderByPath(s,".idea")}/workspace.xml`;if(this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${t}`,`cd ${_path2.default.resolve(s)}`),_fs.default.existsSync(r)){const e=this.getFileContextInRaw(r).split("\n"),i=_lodash.default.findIndex(e,e=>this.has(e,'name="RunManager'));this.insertToArray(e,i,`<configuration name="${t}" \n type="NodeJSConfigurationType" \n path-to-node="$USER_HOME$/.nvm/versions/node/v18.19.1/bin/node" \n node-parameters="--require @babel/register" \n path-to-js-file="${_path2.default.resolve(s)}/src/index.js" \n working-dir="${_path2.default.resolve(s)}" >`," <envs>",' <env name="self_debug" value="true" />',' <env name="is_node" value="true" />'," </envs>",' <method v="2" />',"</configuration>");const a=_lodash.default.findIndex(e,e=>_lodash.default.isEqual(_lodash.default.trim(e),"<list>"),i);this.insertToArray(e,a,` <item itemvalue="Node.js.${t}" />`),_fs.default.writeFileSync(r,e.join("\n"))}else this.appendError(`${r} not exist`);await this.executeCommandLine(`cd ${_path2.default.resolve(s)} && npm install`),this.appendInfo(`build ${t} succeed!`)}appendInfo(...e){return this.appendLog(_configerer.configerer.PATH_INFO_LOG,e,!1)}appendError(...e){return this.appendLog(_configerer.configerer.PATH_ERROR_LOG,e,!0)}appendLog(e,t,i=!1){const s=`${this.getCurrentTimeFormat()} ${i?"ERROR":"LOG"} : ${t.map(this.stringifyLog).join(" ,")}`;this.isProductionEnvironment()||(i?console.error(...t):console.log(...t)),this.isPersistIntoLogFile&&this.appendFile(e,s)}stringifyLog(e){return"object"==typeof e?JSON.stringify(e):String(e)}appendFile(e,t,i=!0,s=!1){try{const a=_path2.default.resolve(e);s&&_fs.default.existsSync(a)&&_fs.default.unlinkSync(a),_fs.default.existsSync(a)||this.persistByPath(a);const n=`${i?"\n":""}${t}`;_fs.default.appendFileSync(a,n)}catch(e){throw new _index2.default(8001,e)}}disableLogMessagePersistent(){this.isPersistIntoLogFile=!1}getLogString(e){return e.map(e=>this.isJson(e)||_lodash.default.isObject(e)||_lodash.default.isArray(e)?this.deepFlat(e):e).join(" ,")}async persistJsonFilePrettier(e,t,i=!1){e=_path2.default.resolve(e),this.appendFile(e,JSON.stringify(t),!0,!0),i||await this.prettier(e,120)}printCollectionToFile(e){const t=`./logs/__temp_${this.getCurrentTimeFormat()}.txt`;this.persistByPath("./logs/"),this.appendFile(t,this.deepFlat(e," \n\n, ")),this.appendInfo(`collectionToFile succeed, file name ==> ${t}`)}async readFileContentByPath(e,t={}){return t[e]??(t[e]=await _promises.default.readFile(e,"utf-8"))}singleFileTemplatify(e="./"){const t=this.findFilePathByExtension(e,["js"],"node_modules");for(const e of t){const t=this.getFileContextInRaw(e.absolute).trim();if(_lodash.default.isEmpty(t)){this.appendInfo(e.fileName,e.absolute);const t=_lodash.default.isEqual(e.fileName,"index")?e.dirName:e.fileName;_fs.default.writeFileSync(e.absolute,String.format(this.getFileContextInRaw(".\n /template/s\n ample.src.index.js"),t,"明悅",new Date))}}}isFileEmpty(e){const t=this.getFileContextInRaw(e);return!t||!t.trim()}copySingleFileConservative(e,t){const{absolute:i,lastModifiedTime:s}=t;if(!this.isPathExist(i)||this.isFileEmpty(i))return void this.appendInfo(`${i} is empty file, ignore copy behavior`);const a=_fs.default.existsSync(e);a&&this.getFileLastModifiedTime(e)>s?this.appendInfo(`${e} is the latest, ignore this run`):(a||this.appendInfo(`${e} does not exist, safe to copy.`),this.ensureFolderExists(_path2.default.dirname(e)),this.copySingleFile(i,e,void 0,!0))}syncDeleteFile(e){_fs.default.existsSync(e)&&_fs.default.unlinkSync(e)}getFileContextInJSON(e){try{if(_fs.default.existsSync(e))return JSON.parse(_fs.default.readFileSync(e,"utf-8"))}catch(e){throw new _index2.default(9999,e.message)}return{}}getFileContextInRaw(e){return _fs.default.existsSync(e)?_fs.default.readFileSync(e,"utf-8"):""}writeFileInJSON(e,t){let i=JSON.stringify(t,null,2);_fs.default.writeFileSync(e,i)}async generatePackage(e="./",t=!1,i=!0,...s){let a=this.findFilePathByExtension(e,["json"],"node_modules","release");a=_lodash.default.filter(a,e=>_lodash.default.isEqual(e.fileName,"package")),a=a.map(e=>this.getFolderPathOfSpecificPath(e.absolute));for(const e of a)if(this.isAndEquals(...s.map(t=>()=>!this.has(e,t)))){const s=await this.generateTempFolderWithCleanSrc(e);await this.deleteSelfByPath(_path2.default.join(e,"release"),!0);const a=this.persistByPath(_path2.default.join(e,"release"));await this.executeCommandLine(`cd ${e} && babel ./temp --out-dir ./release/lib --config-file ./babel.config.js`);const n=require(_path2.default.join(e,"./terser.config.js")),r=this.getStringOfTerserCommandLine(n);await this.executeCommandLine(`cd ${e}/release/lib && find . -type f -name "*.js" -exec terser {} -o {} ${r} \\;`);const o=_path2.default.join(e,"package.json");try{const s="sample.npm.module.index.js";this.copySingleFile(`/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/${s}`,a,"index.js",!0);const n=`${e}/release/index.js`;await this.executeCommandLine(`terser ${n} -o ${n} ${r}`);const l=_path2.default.join(e,"template");if(this.isPathExist(l)&&await this.copyFromFolderToDestFolder(l,this.persistByPath(_path2.default.join(a,"template"))),t){const{moduleName:e,version:t}=await this.upgradePackageJsonVersion(o);await this.updateVersionOfTemplate(e,t)}this.copySingleFile(o,_path2.default.join(a,"package.json"),void 0,!0),i||!this.isPathExist(_path2.default.join(a,"node_module"))?await this.executeCommandLine(`cd ${a} && yarn install --production`):this.appendInfo("ignore node-module install behavior"),this.appendInfo(`build ${e} succeed`),t&&await this.executeCommandLine(`cd ${a} && npm publish`)}catch(e){throw await this.deleteSelfByPath(a,!0),new _index2.default(9999,`generatePackage 報錯, ${e.message}`)}finally{await this.deleteSelfByPath(s,!0)}}}async updateVersionOfTemplate(e,t){const i=["/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/admin.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/web.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/functions.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/sample.package.json","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/package.json"];for(const s of i)if(this.isPathExist(s)){let i=!1;const a=this.getJsonObjByFilePath(s);if(a&&a.dependencies&&a.dependencies[e]){a.dependencies[e]=`^${t}`;try{await this.writeJsonThanPrettier(s,a),i=!0}catch(e){i=!0}}i||await this.updateFileOfSpecificLine(s,i=>` "${e}":"^${t}"${_lodash.default.endsWith(_lodash.default.trim(i),",")?",":""}`,t=>_lodash.default.startsWith(_lodash.default.trim(t),`"${e}"`))}await this.copyFromFolderToDestFolder("/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/","/Users/davidtu/cross-achieve/high/idea-inventer/newp/template/",!0,!0)}async updateFileOfSpecificLine(e,t=e=>"updated",i=e=>!0){const s=this.getFileContextInRaw(e).split("\n"),a=s.findIndex(i);-1!==a&&(s[a]=t(s[a]),this.appendFile(e,s.join("\n"),!0,!0),await this.prettier(e))}async writeJsonThanPrettier(e,t){this.writeFileInJSON(e,t),await this.prettier(e)}async enrichEachPackageJson(e){const t=new Set(["package","admin.package","web.package","functions.package"]),i=this.findFilePathByExtension(e,["json"],"gen","node_modules","release").filter(e=>t.has(e.fileName));if(0!==i.length)for(const{absolute:e}of i){const t=this.getJsonObjByFilePath(e);t.scripts||={},t.scripts.updateConfigerer="npm update configerer --save",await this.writeJsonThanPrettier(e,t)}}insertShellCommand(e=_configerer.configerer.BASE_SHELL_SCRIPT,t,i){if(this.isStringContainInLines(this.getFileContextInRaw(e),t))throw new _index2.default(8007,`alias ${t} is exist`);{const s=`alias ${t}='${i}'`;this.appendFile(e,s)}}getAdminCredential(){return this.getJsonObjByFilePath("/Users/davidtu/cross-achieve/mimi/idea-inventer/firebaser/key/mimi19up-firebase-adminsdk.json")}isEmptyFile(e){return!this.isPathExist(e)||_lodash.default.isEmpty(this.getFileContextInRaw(e).trim())}isEmptyFolder(e){return 0===_fs.default.readdirSync(e).length}async prettier(e,t=200){await this.executeCommandLine(`cd ${_path2.default.resolve(".")} && npx prettier --write ${_path2.default.resolve(e)} --print-width ${t}`)}getFileLastModifiedTime(e){return _fs.default.statSync(e).mtimeMs}getJsonObjByFilePath(e){return this.appendInfo(`ready to json path:${e}`),JSON.parse(this.getFileContextInRaw(e))}async upgradePackageJsonVersion(e){if(_lodash.default.isEqual("json",this.getPathInfo(e).extension)){const t=this.getJsonObjByFilePath(e);return t.version=this.getStringOfVersionIncrement(t.version),await this.writeJsonThanPrettier(e,t),{version:t.version,moduleName:t.name}}throw new _index2.default(8020,`path is not package.json, which is ${e}`)}async reWriteJsonAttribute(e,...t){const{extension:i}=this.getPathInfo(e);if("json"!==i)throw new _index2.default(9999,`reWriteJsonAttribute() => path is not package.json, which is ${e}`);const s=t.find(e=>"object"!=typeof e||null===e);if(s)throw new _index2.default(9999,`84451515 attr is not object, which is 'type=${typeof s} => ${s}'`);const a=this.getJsonObjByFilePath(e);for(const e of t)a[this.getObjectKey(e)]=this.getObjectValue(e);return await this.writeJsonThanPrettier(e,a),{version:a.version,moduleName:a.name}}getVersionOfPackageJson(e){return this.getAttributeValueOfJson(e,"version","1.0.0")}getAttributeValueOfJson(e,t,i=void 0){if(_lodash.default.isEqual("json",this.getPathInfo(e).extension))return this.getJsonObjByFilePath(e)[t]??i;throw new _index2.default(8020,`path is not package.json, which is ${e}`)}getVersionOfJsFile(e){return this.getAttributeValueOfJsFile(e,"version","project without version notice")}getAttributeValueOfJsFile(e,t,i=void 0){if(_lodash.default.isEqual(this.getExtensionFromPath(e),"js"))return require(_path2.default.resolve(e)).default[t]??i;throw new _index2.default(8020,`path is not js file, which is ${e}`)}async rewriteAttributeOfSourceJs(e,...t){if(!this.isPathExist(e))throw new _index2.default(9999,`4849813 ${e} is not exist`);for(const i of t){if(!_lodash.default.isObject(i))throw new _index2.default(9999,`4984651 attr is not object, which is 'type=${typeof i} => ${i}'`);const t=this.getObjectKey(i),s=this.getObjectValue(i),a=this.getFileContextInRaw(e).split("\n");a[_lodash.default.findIndex(a,e=>_lodash.default.startsWith(_lodash.default.trim(e),`${t}`))]=` ${t}: '${s}',`,this.appendFile(e,a.join("\n"),!0,!0)}return t}async getAnswerFromPromptQ(e=[{name:"name",require:!0,description:"type the name"}]){return _prompt.default.start(),await _prompt.default.get(e)}async getObjectFromPromptQ(...e){return _prompt.default.start(),await _prompt.default.get(e)}async generateTempFolderWithCleanSrc(e){this.appendInfo("generateTempFolderWithCleanSrc",e);const t=_path2.default.join(e,"src"),i=_path2.default.join(e,"temp");if(!_fs.default.existsSync(t))return i;this.appendInfo("generateTempFolderWithCleanSrc","source",t),this.persistByPath(i),await this.copyFromFolderToDestFolder(t,i);const s=this.findFilePathBy(i);for(const{absolute:e}of s){const t=this.getFileContextInRaw(e).split("\n"),i=t.map(e=>e.trim()),s=i.findIndex(e=>e.startsWith("if (configerer.DEBUG_MODE)")),a=i.lastIndexOf("}");if(s>=0&&a>s){t.splice(s,a-s+1);const i=t.join("\n");this.appendFile(e,i,!0,!0),await this.executeCommandLine(`cd ${_path2.default.dirname(e)} && npx prettier --write "${e}"`)}}return i}rewriteFile2File(e,t){const i=this.getFileContextInRaw(e);if(!i.trim())throw new _index2.default(9999,`${e} 為空,避免覆蓋`);this.appendFile(t,i,!0,!0),this.appendInfo(`rewrite from:${e} => to:${t} 成功`)}getStringOfHeadOfFile(e){if(this.isPathExist(e)){const t=this.getFileContextInRaw(e);return _lodash.default.head(t.split("\n"))}return""}isFileEditSucceed(e){if(!this.isPathExist(e))return!1;const t=this.getPathInfo(e),i=this.getFileContextInRaw(e).trim();if(""===i)return this.appendInfo(`74985465 path ${t.path} is empty file, file would not persist`),!1;try{const e=i.split("\n")[0].match(/const\s+([a-zA-Z_]\w*)\s*=\s*(true|false)\s*;?/);if(!e||_lodash.default.size(e)<3)return!1;if(!0==("true"===e[2]))return!0}catch(e){return this.appendError(`66445411 ${e.message}`),!1}return!1}joinRespectingDot(...e){const t=e[0]?.startsWith("./"),i=e[0]?.startsWith("./")?[e[0].slice(2),...e.slice(1)]:e,s=_path2.default.join(...i);return t&&!_path2.default.isAbsolute(s)?`./${s}`:s}}var _default=exports.default=NodeUtiller;
|
|
3
|
+
t.push(`--comments "${e.format.comments}"`),e.format.indent_level&&t.push(`--format indent_level=${e.format.indent_level}`)),t.join(" ")}),(0,_defineProperty2.default)(this,"getPathAfterSpecificFolder",(e,t="src")=>{const i=e.split(_path2.default.sep);for(let e=i.length-1;e>=0;e--)if(i[e]===t)return"/"+i.slice(e+1).join("/");return""}),(0,_defineProperty2.default)(this,"getPathAfterSrc",e=>this.getPathAfterSpecificFolder(e))}findSpecificFolderByPath(e,t){const i=_path2.default.resolve(e).split(_path2.default.sep);for(;i.length;){const e=_path2.default.join(...i,t);if(_fs.default.existsSync(e))return e;i.pop()}return null}async getPDFText(e){let t=_fs.default.readFileSync(e);return(0,_pdfParse.default)(t).then(e=>e)}printf(){this.appendInfo("i can use in node.js only yo yo")}findFilePathBy(e,t=()=>!0,...i){if(!_fs.default.existsSync(e))return[];const s=[],a=_fs.default.readdirSync(e,{withFileTypes:!0});for(const n of a){if(i.includes(n.name))continue;const a=_path2.default.join(e,n.name);if(n.isDirectory())s.push(...this.findFilePathBy(a,t,...i));else if(n.isFile()){const e=this.getPathInfo(a);t(e)&&s.push(e)}}return s}isPathExist(e){return _fs.default.existsSync(e)}renameFile(e,t="fileName"){if(!this.isFile(e)||!t)return void this.appendError(`renameFile 錯誤, path: ${e}, newName: ${t}`);const i=_path2.default.dirname(e),s=_path2.default.extname(e),a=_path2.default.join(i,`${t}${s}`);_fs.default.renameSync(e,a)}getPathInfo(e){const t=_path2.default.resolve(e),i={path:e,absolute:t,isFile:!1,isDirectory:!0,dirName:void 0,folderName:void 0,dirPath:void 0,folderPath:void 0,extension:void 0,fileName:void 0,fileNameExtension:void 0,lastModifiedTime:void 0,name:void 0};if(this.isFile(t)){i.extension=t.split(".").pop();const e=t.split("/").pop().split(".");e.pop(),i.fileName=e.join("."),i.name=e.join("."),i.dirName=_lodash.default.nth(t.split("/"),-2),i.folderName=_lodash.default.nth(t.split("/"),-2),i.isFile=!0,i.dirPath=this.getFolderPathOfSpecificPath(t),i.folderPath=this.getFolderPathOfSpecificPath(t),i.isDirectory=!1,i.fileNameExtension=`${i.fileName}.${i.extension}`,i.lastModifiedTime=this.getFileLastModifiedTime(t)}return this.isDirectory(t)&&(i.dirName=t.split("/").pop()),i}syncExecuteCommandLine(e){const t=this;this.appendInfo(`執行腳本 ${e}`),_child_process.default.exec(`${e}`,(e,i,s)=>{t.appendInfo(`${i}`),t.appendInfo(`${s}`),null!==e&&t.appendError(`exec error: ${e}`)})}persistByPath(e){const t=_path2.default.isAbsolute(e),i=e.split("/").filter(Boolean),s=i[i.length-1],a=""!==_path2.default.extname(s);let n=t?_path2.default.sep:"";for(let e=0;e<i.length;e++)n=_path2.default.join(n,i[e]),_fs.default.existsSync(n)||(e===i.length-1&&a?_fs.default.writeFileSync(n,""):_fs.default.mkdirSync(n,{recursive:!1}));return _path2.default.resolve(e)}async copyFromFolderToDestFolder(e,t,i=!0,s=!1,a=()=>!0){if(!_fs.default.existsSync(e)||!_fs.default.existsSync(e))throw new _index2.default(8009,`${e} or ${t} is not exist!`);this.appendInfo(`正在複製ing ${e}/* => ${t}/* succeed`),_fsExtra.default.copySync(e,t,{preserveTimestamps:s,override:i,filter:a}),this.appendInfo(`複製成功 ${e}/* => ${t}/* succeed`)}cleanAllFiles(e){this.isDirectory(e)&&(this.appendInfo(`準備清除底下的所有 ${e}`),_fsExtra.default.emptyDirSync(e),this.appendInfo(`成功清除底下的所有 ${e}`))}async deleteSelfByPath(e,t){_fs.default.existsSync(e)&&(this.appendInfo(`準備刪掉 ${e},{force:${t}}`),await(0,_del.default)(e,{force:t}),this.appendInfo(`成功刪掉了 ${e}`))}async deleteFileOrFolder(e){this.appendInfo(`刪掉了 ${e}`),await(0,_del.default)(e)}async deleteChildByPath(e,t=!1){const i=this.getChildPathByPath(e);for(const e of i)await this.deleteSelfByPath(e.absolute,t)}getFileCountsOfFolder(e){return this.isDirectory(e)?_fs.default.readdirSync(e).length:-1}async reinstallNodeModules(e="../",...t){const i=[...t,"node_modules","utiller","configerer"],s=this.findFilePathBy(e,e=>_lodash.default.isEqual(e.fileNameExtension,"package.json"),...i);for(const e of s){const t=this.getFileDirPath(e.absolute),i=`${t}node_modules`,s=`${t}package-lock.json`;await(0,_del.default)(s),this.appendInfo(`刪掉了 ${s}`),await(0,_del.default)(i),this.appendInfo(`刪掉了 ${i}`)}for(const e of s){const t=this.getFileDirPath(e.absolute),i=`${t}node_modules`;_fs.default.existsSync(i)||await this.executeCommandLine(`cd ${t} && npm install`)}}getNamesOfFolderChild(e){return this.getChildPathByPath(e).filter(e=>e.isDirectory).map(e=>e.dirName)}getChildPathByPath(e){try{return _fs.default.readdirSync(e).map(t=>this.getPathInfo(_path2.default.join(e,t)))}catch(e){throw new _index2.default(8002,e)}}copySingleFile(e,t,i,s=!1){const a=i&&i.trim()?_path2.default.join(t,i):t;if(_fs.default.existsSync(a)&&!s)throw new _index2.default(8006,a);_fs.default.copyFileSync(e,a)}ensureFolderExists(e){const t=_path2.default.resolve(e);_fs.default.existsSync(t)||_fs.default.mkdirSync(t,{recursive:!0})}getNodeEnvVariable(e,t=void 0){const i=process.env[e];return void 0===i?t:i}isDirectory(e){return!!this.isPathExist(e)&&_fs.default.lstatSync(e).isDirectory()}isFile(e){return!!this.isPathExist(e)&&_fs.default.lstatSync(e).isFile()}isImageFile(e){return["svg","png","jpg","jpeg"].includes(e.extension)}async cleanChildFiles(e,t=()=>!0,...i){if(!_fs.default.existsSync(e))return!1;const s=this.findFilePathBy(e,t,...i),a=s.filter(e=>!this.isImageFile(e));return await Promise.allSettled(a.map(e=>(this.cleanFileContent(e.absolute),this.appendInfo(`成功 cleanChildFiles() -> '${e.path}'`),Promise.resolve()))),s}cleanFileContent(e){this.syncDeleteFile(e)}async syncWithExistPackage(e="../"){const t=this.findFilePathBy(e,e=>_lodash.default.isEqual(e.fileNameExtension,"package.json"),"node_modules");for(let e of t)try{_lodash.default.isEqual(e.dirName,"..")||this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${e.dirName}`,`cd ${this.getFolderPathOfSpecificPath(e.absolute)}`)}catch(e){this.appendInfo(e.message)}}async packageTemplatify(e,t){const i=this.getChildPathByPath(e).map(e=>e.absolute.split("/").pop());if(this.has(i,t))throw new _index2.default(8004,` packageName ===> '${t}'`);const s=`${e}/${t}`;_fs.default.mkdirSync(s),_fs.default.copyFileSync("./template/sample.babel.config.js",`${s}/babel.config.js`),_fs.default.copyFileSync("./template/sample.terser.config.js",`${s}/terser.config.js`);const a=this.getJsonObjByFilePath("./template/sample.package.json");a.name=t,this.writeFileInJSON(`${s}/package.json`,a),this.persistByPath(`${s}/src`);const n=String.format(this.getFileContextInRaw("./template/sample.src.index.js"),t,"明悅",new Date);_fs.default.writeFileSync(`${s}/src/index.js`,n);const r=`${this.findSpecificFolderByPath(s,".idea")}/workspace.xml`;if(this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${t}`,`cd ${_path2.default.resolve(s)}`),_fs.default.existsSync(r)){const e=this.getFileContextInRaw(r).split("\n"),i=_lodash.default.findIndex(e,e=>this.has(e,'name="RunManager'));this.insertToArray(e,i,`<configuration name="${t}" \n type="NodeJSConfigurationType" \n path-to-node="$USER_HOME$/.nvm/versions/node/v20.19.5/bin/node" \n node-parameters="--require @babel/register" \n path-to-js-file="${_path2.default.resolve(s)}/src/index.js" \n working-dir="${_path2.default.resolve(s)}" >`," <envs>",' <env name="self_debug" value="true" />',' <env name="is_node" value="true" />'," </envs>",' <method v="2" />',"</configuration>");const a=_lodash.default.findIndex(e,e=>_lodash.default.isEqual(_lodash.default.trim(e),"<list>"),i);this.insertToArray(e,a,` <item itemvalue="Node.js.${t}" />`),_fs.default.writeFileSync(r,e.join("\n"))}else this.appendError(`${r} not exist`);await this.executeCommandLine(`cd ${_path2.default.resolve(s)} && npm install`),this.appendInfo(`build ${t} succeed!`)}appendInfo(...e){return this.appendLog(_configerer.configerer.PATH_INFO_LOG,e,!1)}appendError(...e){return this.appendLog(_configerer.configerer.PATH_ERROR_LOG,e,!0)}appendLog(e,t,i=!1){const s=`${this.getCurrentTimeFormat()} ${i?"ERROR":"LOG"} : ${t.map(this.stringifyLog).join(" ,")}`;this.isProductionEnvironment()||(i?console.error(...t):console.log(...t)),this.isPersistIntoLogFile&&this.appendFile(e,s)}stringifyLog(e){return"object"==typeof e?JSON.stringify(e):String(e)}appendFile(e,t,i=!0,s=!1){try{const a=_path2.default.resolve(e);s&&_fs.default.existsSync(a)&&_fs.default.unlinkSync(a),_fs.default.existsSync(a)||this.persistByPath(a);const n=`${i?"\n":""}${t}`;_fs.default.appendFileSync(a,n)}catch(e){throw new _index2.default(8001,e)}}disableLogMessagePersistent(){this.isPersistIntoLogFile=!1}getLogString(e){return e.map(e=>this.isJson(e)||_lodash.default.isObject(e)||_lodash.default.isArray(e)?this.deepFlat(e):e).join(" ,")}async persistJsonFilePrettier(e,t,i=!1){e=_path2.default.resolve(e),this.appendFile(e,JSON.stringify(t),!0,!0),i||await this.prettier(e,120)}printCollectionToFile(e){const t=`./logs/__temp_${this.getCurrentTimeFormat()}.txt`;this.persistByPath("./logs/"),this.appendFile(t,this.deepFlat(e," \n\n, ")),this.appendInfo(`collectionToFile succeed, file name ==> ${t}`)}async readFileContentByPath(e,t={}){return t[e]??(t[e]=await _promises.default.readFile(e,"utf-8"))}singleFileTemplatify(e="./"){const t=this.findFilePathByExtension(e,["js"],"node_modules");for(const e of t){const t=this.getFileContextInRaw(e.absolute).trim();if(_lodash.default.isEmpty(t)){this.appendInfo(e.fileName,e.absolute);const t=_lodash.default.isEqual(e.fileName,"index")?e.dirName:e.fileName;_fs.default.writeFileSync(e.absolute,String.format(this.getFileContextInRaw(".\n /template/s\n ample.src.index.js"),t,"明悅",new Date))}}}isFileEmpty(e){const t=this.getFileContextInRaw(e);return!t||!t.trim()}copySingleFileConservative(e,t){const{absolute:i,lastModifiedTime:s}=t;if(!this.isPathExist(i)||this.isFileEmpty(i))return void this.appendInfo(`${i} is empty file, ignore copy behavior`);const a=_fs.default.existsSync(e);a&&this.getFileLastModifiedTime(e)>s?this.appendInfo(`${e} is the latest, ignore this run`):(a||this.appendInfo(`${e} does not exist, safe to copy.`),this.ensureFolderExists(_path2.default.dirname(e)),this.copySingleFile(i,e,void 0,!0))}syncDeleteFile(e){_fs.default.existsSync(e)&&_fs.default.unlinkSync(e)}getFileContextInJSON(e){try{if(_fs.default.existsSync(e))return JSON.parse(_fs.default.readFileSync(e,"utf-8"))}catch(e){throw new _index2.default(9999,e.message)}return{}}getFileContextInRaw(e){return _fs.default.existsSync(e)?_fs.default.readFileSync(e,"utf-8"):""}writeFileInJSON(e,t){let i=JSON.stringify(t,null,2);_fs.default.writeFileSync(e,i)}async generatePackage(e="./",t=!1,i=!0,...s){let a=this.findFilePathByExtension(e,["json"],"node_modules","release");a=_lodash.default.filter(a,e=>_lodash.default.isEqual(e.fileName,"package")),a=a.map(e=>this.getFolderPathOfSpecificPath(e.absolute));for(const e of a)if(this.isAndEquals(...s.map(t=>()=>!this.has(e,t)))){const s=await this.generateTempFolderWithCleanSrc(e);await this.deleteSelfByPath(_path2.default.join(e,"release"),!0);const a=this.persistByPath(_path2.default.join(e,"release"));await this.executeCommandLine(`cd ${e} && babel ./temp --out-dir ./release/lib --config-file ./babel.config.js`);const n=require(_path2.default.join(e,"./terser.config.js")),r=this.getStringOfTerserCommandLine(n);await this.executeCommandLine(`cd ${e}/release/lib && find . -type f -name "*.js" -exec terser {} -o {} ${r} \\;`);const o=_path2.default.join(e,"package.json");try{const s="sample.npm.module.index.js";this.copySingleFile(`/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/${s}`,a,"index.js",!0);const n=`${e}/release/index.js`;await this.executeCommandLine(`terser ${n} -o ${n} ${r}`);const l=_path2.default.join(e,"template");if(this.isPathExist(l)&&await this.copyFromFolderToDestFolder(l,this.persistByPath(_path2.default.join(a,"template"))),t){const{moduleName:e,version:t}=await this.upgradePackageJsonVersion(o);await this.updateVersionOfTemplate(e,t)}this.copySingleFile(o,_path2.default.join(a,"package.json"),void 0,!0),i||!this.isPathExist(_path2.default.join(a,"node_module"))?await this.executeCommandLine(`cd ${a} && yarn install --production`):this.appendInfo("ignore node-module install behavior"),this.appendInfo(`build ${e} succeed`),t&&await this.executeCommandLine(`cd ${a} && npm publish`)}catch(e){throw await this.deleteSelfByPath(a,!0),new _index2.default(9999,`generatePackage 報錯, ${e.message}`)}finally{await this.deleteSelfByPath(s,!0)}}}async updateVersionOfTemplate(e,t){const i=["/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/admin.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/web.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/functions.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/sample.package.json","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/package.json"];for(const s of i)if(this.isPathExist(s)){let i=!1;const a=this.getJsonObjByFilePath(s);if(a&&a.dependencies&&a.dependencies[e]){a.dependencies[e]=`^${t}`;try{await this.writeJsonThanPrettier(s,a),i=!0}catch(e){i=!0}}i||await this.updateFileOfSpecificLine(s,i=>` "${e}":"^${t}"${_lodash.default.endsWith(_lodash.default.trim(i),",")?",":""}`,t=>_lodash.default.startsWith(_lodash.default.trim(t),`"${e}"`))}await this.copyFromFolderToDestFolder("/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/","/Users/davidtu/cross-achieve/high/idea-inventer/newp/template/",!0,!0)}async updateFileOfSpecificLine(e,t=e=>"updated",i=e=>!0){const s=this.getFileContextInRaw(e).split("\n"),a=s.findIndex(i);-1!==a&&(s[a]=t(s[a]),this.appendFile(e,s.join("\n"),!0,!0),await this.prettier(e))}async writeJsonThanPrettier(e,t){this.writeFileInJSON(e,t),await this.prettier(e)}async enrichEachPackageJson(e){const t=new Set(["package","admin.package","web.package","functions.package"]),i=this.findFilePathByExtension(e,["json"],"gen","node_modules","release").filter(e=>t.has(e.fileName));if(0!==i.length)for(const{absolute:e}of i){const t=this.getJsonObjByFilePath(e);t.scripts||={},t.scripts.updateConfigerer="npm update configerer --save",await this.writeJsonThanPrettier(e,t)}}insertShellCommand(e=_configerer.configerer.BASE_SHELL_SCRIPT,t,i){if(this.isStringContainInLines(this.getFileContextInRaw(e),t))throw new _index2.default(8007,`alias ${t} is exist`);{const s=`alias ${t}='${i}'`;this.appendFile(e,s)}}getAdminCredential(){return this.getJsonObjByFilePath("/Users/davidtu/cross-achieve/mimi/idea-inventer/firebaser/key/mimi19up-firebase-adminsdk.json")}isEmptyFile(e){return!this.isPathExist(e)||_lodash.default.isEmpty(this.getFileContextInRaw(e).trim())}isEmptyFolder(e){return 0===_fs.default.readdirSync(e).length}async prettier(e,t=200){await this.executeCommandLine(`cd ${_path2.default.resolve(".")} && npx prettier --write ${_path2.default.resolve(e)} --print-width ${t}`)}getFileLastModifiedTime(e){return _fs.default.statSync(e).mtimeMs}getJsonObjByFilePath(e){return this.appendInfo(`ready to json path:${e}`),JSON.parse(this.getFileContextInRaw(e))}async upgradePackageJsonVersion(e){if(_lodash.default.isEqual("json",this.getPathInfo(e).extension)){const t=this.getJsonObjByFilePath(e);return t.version=this.getStringOfVersionIncrement(t.version),await this.writeJsonThanPrettier(e,t),{version:t.version,moduleName:t.name}}throw new _index2.default(8020,`path is not package.json, which is ${e}`)}async reWriteJsonAttribute(e,...t){const{extension:i}=this.getPathInfo(e);if("json"!==i)throw new _index2.default(9999,`reWriteJsonAttribute() => path is not package.json, which is ${e}`);const s=t.find(e=>"object"!=typeof e||null===e);if(s)throw new _index2.default(9999,`84451515 attr is not object, which is 'type=${typeof s} => ${s}'`);const a=this.getJsonObjByFilePath(e);for(const e of t)a[this.getObjectKey(e)]=this.getObjectValue(e);return await this.writeJsonThanPrettier(e,a),{version:a.version,moduleName:a.name}}getVersionOfPackageJson(e){return this.getAttributeValueOfJson(e,"version","1.0.0")}getAttributeValueOfJson(e,t,i=void 0){if(_lodash.default.isEqual("json",this.getPathInfo(e).extension))return this.getJsonObjByFilePath(e)[t]??i;throw new _index2.default(8020,`path is not package.json, which is ${e}`)}getVersionOfJsFile(e){return this.getAttributeValueOfJsFile(e,"version","project without version notice")}getAttributeValueOfJsFile(e,t,i=void 0){if(_lodash.default.isEqual(this.getExtensionFromPath(e),"js"))return require(_path2.default.resolve(e)).default[t]??i;throw new _index2.default(8020,`path is not js file, which is ${e}`)}async rewriteAttributeOfSourceJs(e,...t){if(!this.isPathExist(e))throw new _index2.default(9999,`4849813 ${e} is not exist`);for(const i of t){if(!_lodash.default.isObject(i))throw new _index2.default(9999,`4984651 attr is not object, which is 'type=${typeof i} => ${i}'`);const t=this.getObjectKey(i),s=this.getObjectValue(i),a=this.getFileContextInRaw(e).split("\n");a[_lodash.default.findIndex(a,e=>_lodash.default.startsWith(_lodash.default.trim(e),`${t}`))]=` ${t}: '${s}',`,this.appendFile(e,a.join("\n"),!0,!0)}return t}async getAnswerFromPromptQ(e=[{name:"name",require:!0,description:"type the name"}]){return _prompt.default.start(),await _prompt.default.get(e)}async getObjectFromPromptQ(...e){return _prompt.default.start(),await _prompt.default.get(e)}async generateTempFolderWithCleanSrc(e){this.appendInfo("generateTempFolderWithCleanSrc",e);const t=_path2.default.join(e,"src"),i=_path2.default.join(e,"temp");if(!_fs.default.existsSync(t))return i;this.appendInfo("generateTempFolderWithCleanSrc","source",t),this.persistByPath(i),await this.copyFromFolderToDestFolder(t,i);const s=this.findFilePathBy(i);for(const{absolute:e}of s){const t=this.getFileContextInRaw(e).split("\n"),i=t.map(e=>e.trim()),s=i.findIndex(e=>e.startsWith("if (configerer.DEBUG_MODE)")),a=i.lastIndexOf("}");if(s>=0&&a>s){t.splice(s,a-s+1);const i=t.join("\n");this.appendFile(e,i,!0,!0),await this.executeCommandLine(`cd ${_path2.default.dirname(e)} && npx prettier --write "${e}"`)}}return i}rewriteFile2File(e,t){const i=this.getFileContextInRaw(e);if(!i.trim())throw new _index2.default(9999,`${e} 為空,避免覆蓋`);this.appendFile(t,i,!0,!0),this.appendInfo(`rewrite from:${e} => to:${t} 成功`)}getStringOfHeadOfFile(e){if(this.isPathExist(e)){const t=this.getFileContextInRaw(e);return _lodash.default.head(t.split("\n"))}return""}isFileEditSucceed(e){if(!this.isPathExist(e))return!1;const t=this.getPathInfo(e),i=this.getFileContextInRaw(e).trim();if(""===i)return this.appendInfo(`74985465 path ${t.path} is empty file, file would not persist`),!1;try{const e=i.split("\n")[0].match(/const\s+([a-zA-Z_]\w*)\s*=\s*(true|false)\s*;?/);if(!e||_lodash.default.size(e)<3)return!1;if(!0==("true"===e[2]))return!0}catch(e){return this.appendError(`66445411 ${e.message}`),!1}return!1}joinRespectingDot(...e){const t=e[0]?.startsWith("./"),i=e[0]?.startsWith("./")?[e[0].slice(2),...e.slice(1)]:e,s=_path2.default.join(...i);return t&&!_path2.default.isAbsolute(s)?`./${s}`:s}}var _default=exports.default=NodeUtiller;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "utiller",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.453",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"node-html-parser": "^7.0.1",
|
|
27
27
|
"pdf-parse": "^1.1.1",
|
|
28
28
|
"prompt": "^1.1.0",
|
|
29
|
+
"puppeteer": "^24.31.0",
|
|
29
30
|
"uuid": "^8.3.2"
|
|
30
31
|
},
|
|
31
32
|
"devDependencies": {
|