@oiyo/core 0.3.0-beta.1 → 0.3.0-beta.3

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/dist/index.cjs CHANGED
@@ -1,26 +1,26 @@
1
1
  /**
2
- * @oiyo/core v0.3.0-beta.1
2
+ * @oiyo/core v0.3.0-beta.3
3
3
  * Copyright (c) 2026 skiyee. All rights reserved.
4
4
  * Commercial software. See LICENSE for terms.
5
5
  * Official site: https://oiyo.js.org
6
6
  */
7
7
  Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`node:process`);c=s(c,1);let l=require(`node:readline`);l=s(l,1);let u=require(`ansis`),d=require(`node:fs`);d=s(d,1);let f=require(`node:fs/promises`);f=s(f,1);let p=require(`pathe`);p=s(p,1);let ee=require(`node:crypto`),m=require(`node:module`),h=require(`@babel/parser`),g=require(`@babel/traverse`);g=s(g,1);let _=require(`tinyglobby`);_=s(_,1);let v=require(`node:url`);v=s(v,1);let te=require(`enhanced-resolve`);te=s(te,1);let ne=require(`node:os`);ne=s(ne,1);let y=require(`node:path`);y=s(y,1);let b=require(`magic-string`);b=s(b,1);let x=require(`@vue/compiler-sfc`),S=require(`@oiyo/config`),re=require(`vue`),ie=require(`c12`),C=require(`fs`),w=require(`fs/promises`),ae=require(`events`),T=require(`path`),E=s(T,1);T=s(T);let oe=require(`node:stream`),se=require(`os`),ce=require(`defu`);const D={silent:0,error:1,warn:2,info:3,debug:4,verbose:5};let le,ue,de=0,fe;function pe(){let e=c.default.stdout.rows-2,t=e>0?`
8
- `.repeat(e):``;c.default.stdout.write(t),l.default.cursorTo(c.default.stdout,0,0),l.default.clearScreenDown(c.default.stdout)}function me(){return fe??=new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`numeric`,second:`numeric`}),fe}function he(e=`info`,t={}){if(t.customLogger)return t.customLogger;let n=new WeakSet,r=new Set,{prefix:i=`[OIYO]`,scope:a,allowClearScreen:o=!0,console:s=globalThis.console}=t,l=D[e],d=o&&c.default.stdout.isTTY&&!c.default.env.CI,f=d?pe:()=>{};function p(e,t,n={}){let r=ee(e,n.scope??a);return n.timestamp?`${(0,u.dim)(me().format(new Date))} ${(0,u.blue)(i)} ${r} ${t}`:`${(0,u.blue)((0,u.bold)(i))} ${r} ${t}`}function ee(e,t){if(!t)return` `;let n=`[${t.toUpperCase()}]`;return{info:(0,u.cyan)(n),warn:(0,u.yellow)(n),error:(0,u.red)(n),debug:(0,u.dim)((0,u.cyan)(n))}[e]}function m(e,t,r={}){if(l<D[e])return;let i=e;if(r.error&&n.add(r.error),d){if(e===le&&t===ue){de++,f(),s[e](p(e,t,r),(0,u.yellow)(`(x${de+1})`));return}de=0,le=e,ue=t,r.clear&&f()}s[i](p(e,t,r))}let h={hasWarned:!1,withScope(n){return he(e,{...t,scope:n})},debug(e,t){m(`debug`,e,t)},info(e,t){m(`info`,e,t)},warn(e,t){h.hasWarned=!0,m(`warn`,e,t)},warnOnce(e,t){r.has(e)||(r.add(e),h.hasWarned=!0,m(`warn`,e,t))},error(e,t){h.hasWarned=!0,m(`error`,e,t)},clearScreen(e){l>=D[e]&&f()},hasErrorLogged(e){return n.has(e)}};return h}const O=typeof g.default==`function`?g.default:g.default.default;(0,m.createRequire)(require(`url`).pathToFileURL(__filename).href);const k=`**/*`;function A(e){return e==null?[]:Array.isArray(e)?e:[e]}function ge(e){return e?Array.isArray(e)?e:[e]:[]}function _e(e){if(!(0,d.existsSync)(e))return[k];try{return(0,d.statSync)(e).isFile()?[(0,p.basename)(e)]:[k]}catch{return[k]}}async function ve(e){let{dir:t,pattern:n,ignore:r}=e;if(!(0,d.existsSync)(t))return[];let i=(0,d.statSync)(t).isFile()?(0,p.dirname)(t):t,a=ge(n),o=a.length>0?a:_e(t);try{return(await(0,_.glob)(o,{cwd:i,absolute:!0,ignore:ge(r)})).map(e=>(0,p.normalize)((0,p.resolve)(e)))}catch(e){return console.error(`[oiyo] Error scanning file:`,e),[]}}function j(e,t=8){return(0,ee.createHash)(`sha256`).update(e).digest(`hex`).slice(0,t)}function M(e,t){let n=`${e}.${c.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;return(0,d.writeFileSync)(n,t,`utf-8`),(0,d.existsSync)(e)&&(0,d.unlinkSync)(e),(0,d.renameSync)(n,e),!0}function ye(e){if(!e)return``;let t=e.replace(/\p{Lu}/gu,e=>`-${e.toLowerCase()}`);return t.startsWith(`-`)?t.slice(1):t}function N(e){return e?e.replace(/[-_](.)/g,(e,t)=>t.toUpperCase()).replace(/^(.)/,e=>e.toUpperCase()):``}function be(e){let t=N(e);return t?t[0].toLowerCase()+t.slice(1):``}function xe(e,t){let n=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),r={start:0,end:0};return O(n,{CallExpression(e){let{callee:n,arguments:i}=e.node;n.type===`Identifier`&&n.name===t&&i.length>0&&e.node.start!=null&&e.node.end!=null&&(r.start=e.node.start,r.end=e.node.end,e.stop())}}),r}function Se(e){return e.replace(/\s+/g,``)}function Ce(e){let t=p.extname(e);return t?e.slice(0,-t.length):e}function P(e){try{return d.existsSync(e)&&d.statSync(e).isFile()}catch{return!1}}async function we(e){let{dir:t,pattern:n,ignore:r}=e;if(!d.existsSync(t))return[];let i=t,a=A(n);P(t)&&(i=p.dirname(t),a=[p.basename(t)]);try{return(await _.glob(a,{cwd:i,ignore:A(r),absolute:!0})).map(e=>p.normalize(e))}catch(e){return console.error(`[oiyo] Error scanning file:`,e),[]}}const Te=te.default.create.sync({conditionNames:[`require`,`import`,`types`],extensions:[`.ts`,`.js`,`.json`,`.vue`,`.cjs`,`.mjs`]}),F=new Set,I=new Map;function L(e,t){let{cwd:n}=Object.assign({cwd:v.fileURLToPath(require(`url`).pathToFileURL(__filename).href)},t);if(F.has(e))return null;if(I.has(e))return I.get(e);try{let t=Te(n,e);if(!t)return F.add(e),null;let r=p.normalize(t);return I.set(e,r),p.normalize(r)}catch{return F.add(e),null}}const R=new Map;function Ee(e,t={cwd:v.fileURLToPath(require(`url`).pathToFileURL(__filename).href)}){let{cwd:n}=t;if(F.has(e))return null;if(R.has(e))return R.get(e);let r=L(e,{cwd:n});if(!r)return;let i=p.dirname(r),{root:a}=p.parse(i),o=p.resolve(i,a);for(;i;){let t=p.join(i,`package.json`);if(P(t)){let n=p.dirname(t);return R.set(e,n),n}if(i===o||i===a)break;i=p.dirname(i)}}function De(e){if(e.startsWith(`.`)||p.isAbsolute(e))return null;let t=e.split(`/`).filter(Boolean);return t.length===0?null:e.startsWith(`@`)?t.length>=2?`${t[0]}/${t[1]}`:null:t[0]||e}function Oe(e){let t=De(e);if(!t)return null;let n=Ee(t);return n?{root:n,name:t}:null}function ke(e){try{return(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]})}catch{return(0,h.parse)(`(${e})`,{sourceType:`module`,plugins:[`typescript`]})}}const Ae=(e,t)=>{let n=e=>{let r=e.type;return r===`Identifier`?[e.name]:r===`ObjectPattern`?e.properties.flatMap(e=>e.type===`ObjectProperty`?n(e.value):e.type===`RestElement`?n(e.argument):(t?.logger?.debug(`未被识别的 ObjectPattern ${e}`),[])):r===`ArrayPattern`?e.elements.flatMap(e=>e?e.type===`RestElement`?n(e.argument):n(e):[]):r===`AssignmentPattern`?n(e.left):(t?.logger?.debug(`未被识别的 Node ${e}`),[])};return e.flatMap(e=>n(e.id))};async function je(e,t={}){let n=new Set,r=new Set,i=new Set,a=async e=>{O(ke(await f.readFile(e,`utf-8`)),{ExportAllDeclaration({node:e}){i.add(e.source.value)},ExportDefaultDeclaration({node:e}){let t=e.declaration;switch(t.type){case`Identifier`:n.add(t.name);break;case`ClassDeclaration`:case`FunctionDeclaration`:t.id?n.add(t.id.name):n.add(`default`);break;default:n.add(`default`);break}},ExportNamedDeclaration({node:e}){if(e.declaration){let i=e.declaration;switch(i.type){case`VariableDeclaration`:Ae(i.declarations,{logger:t?.logger}).map(e=>n.add(e));break;case`ClassDeclaration`:case`FunctionDeclaration`:i.id?.name&&n.add(i.id.name);break;case`TSTypeAliasDeclaration`:case`TSInterfaceDeclaration`:t?.includeTypes===!0&&r.add(i.id.name);break;case`TSEnumDeclaration`:case`TSModuleDeclaration`:if(i.id.type===`StringLiteral`)break;n.add(i.id.name);break;case`TSDeclareFunction`:i.id?.name&&n.add(i.id.name);break;default:t?.logger?.debug(`未被识别的 ExportNamedDeclaration.declaration ${i}`);break}}else if(e.specifiers){let i=e.exportKind===`type`;e.specifiers.forEach(e=>{switch(e.type){case`ExportSpecifier`:if(e.exported.type===`StringLiteral`)break;if(i??=e.exportKind===`type`,i){t?.includeTypes===!0&&r.add(e.exported.name);break}n.add(e.exported.name);break;case`ExportNamespaceSpecifier`:n.add(e.exported.name);break;default:t?.logger?.debug(`未被识别的 ExportNamedDeclaration.specifiers ${e}`);break}})}}}),i.size&&await Promise.all(Array.from(i.keys()).map(async t=>{i.delete(t);let n=L(t.startsWith(`.`)?p.join(p.dirname(e),t):t);return n?a(n):Promise.resolve()}))};return await a(e),{values:n,types:r}}function Me(e){let t=ke(e),n=new Set;return O(t,{Program(e){n=new Set(Object.keys(e.scope.globals))}}),n}function Ne(e=[],t){return e.reduce((e,n)=>{let r=t(n);return e[r]||(e[r]=[]),e[r].push(n),e},{})}function Pe(e,t,n){return n===`default`?`import ${t} from '${e}'`:n===t?`import { ${t} } from '${e}'`:`import { ${n} as ${t} } from '${e}'`}function Fe(e,t,n,r){return e=r?.baseDir?p.relative(r?.baseDir,e):e,e=r?.noExtension?Ce(e):e,`const ${t}: typeof import('${e}')['${n}'];`}function Ie(e,t,n,r){return e=r?.baseDir?p.relative(r?.baseDir,e):e,`${t}: typeof import('${e}')['${n}'];`}function Le(e){if(typeof e!=`string`||e===``)return!1;for(let t of e.matchAll(/(\\).|([@?!+*]\(.*\))/g))if(t[2])return!0;return!1}const Re={"{":`}`,"(":`)`,"[":`]`};function ze(e){if(e[0]===`!`)return!0;let t=0,n=-2,r=-2,i=-2,a=-2,o=-2;for(;t<e.length;){if(e[t]===`*`||e[t+1]===`?`&&/[\].+)]/.test(e[t])||r!==-1&&e[t]===`[`&&e[t+1]!==`]`&&(r<t&&(r=e.indexOf(`]`,t)),r>t&&(o===-1||o>r||(o=e.indexOf(`\\`,t),o===-1||o>r)))||i!==-1&&e[t]===`{`&&e[t+1]!==`}`&&(i=e.indexOf(`}`,t),i>t&&(o=e.indexOf(`\\`,t),o===-1||o>i))||a!==-1&&e[t]===`(`&&e[t+1]===`?`&&/[:!=]/.test(e[t+2])&&e[t+3]!==`)`&&(a=e.indexOf(`)`,t),a>t&&(o=e.indexOf(`\\`,t),o===-1||o>a))||n!==-1&&e[t]===`(`&&e[t+1]!==`|`&&(n<t&&(n=e.indexOf(`|`,t)),n!==-1&&e[n+1]!==`)`&&(a=e.indexOf(`)`,n),a>n&&(o=e.indexOf(`\\`,n),o===-1||o>a))))return!0;if(e[t]===`\\`){let n=e[t+1];t+=2;let r=Re[n];if(r){let n=e.indexOf(r,t);n!==-1&&(t=n+1)}if(e[t]===`!`)return!0}else t++}return!1}function Be(e){return typeof e!=`string`||e===``?!1:Le(e)?!0:ze(e)}const Ve=/\\/g,He=/\\([!*?|[\](){}])/g;function Ue(e){ne.platform()===`win32`&&!e.includes(`/`)&&(e=e.replace(Ve,`/`)),We(e)&&(e+=`/`),e+=`a`;do e=y.posix.dirname(e);while(Ge(e));return e.replace(He,`$1`)}function We(e){let t=e.slice(-1),n;switch(t){case`}`:n=`{`;break;case`]`:n=`[`;break;default:return!1}let r=e.indexOf(n);return r<0?!1:e.slice(r+1,-1).includes(`/`)}function Ge(e){return/\([^()]+$/.test(e)||e[0]===`{`||e[0]===`[`||/[^\\][{[]/.test(e)?!0:Be(e)}function z(e){return typeof e==`string`}function Ke(e){let t=p.parse(e);return be(t.name===`index`?p.parse(t.dir).name:t.name)}var qe=class{config;logger;oiyoState;sources=new Map;apis=new Map;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`API`),this.oiyoState=t.oiyoState}get srcDir(){return p.resolve(this.config.rootDir,this.config.srcDir)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return p.resolve(this.declarationDir,`apis.d.ts`)}shouldSkipImport(e){return[`definePageMeta`,`defineRootContext`].includes(e)}recordApiSource(e){return e.patterns?.length?(A(e.patterns).forEach(t=>{let n=p.resolve(e.dir,t);this.sources.set(n,e)}),!0):(this.sources.set(e.dir,e),!0)}toApiSource(e){let t={from:``,dir:``,types:!1,patterns:[`*.js`,`*.ts`],isNodeModule:!1};z(e)?t.from=e:Object.assign(t,e);let n=Be(t.from);if(n){let e=t.from,n=Ue(t.from);t.from=n,t.patterns=[e.slice(n.length+1)]}let r=Oe(t.from);if(r){if(t.isNodeModule=!0,!n)if(t.only?.length)t.dir=t.from,t.patterns=[];else{let n=L(t.from);n?(t.dir=n,t.patterns=[]):this.logger.warn(`无法找到 Api 的扫描源,请注意是否存在该来源 from: ${z(e)?e:e.from}`)}if(!t.dir){let e=p.relative(r.name,t.from);t.dir=p.resolve(r.root,e)}}else t.dir=p.resolve(this.srcDir,t.from);return P(t.dir)&&(t.patterns=[]),this.recordApiSource(t),t}saveApi(e){let t=this.apis.get(e.importName);return t&&t.filePath!==e.filePath?(this.logger.warnOnce(`API名称冲突: “${e.importName}” 已存在,已跳过来自 “${e.importPath}” 的重复导出`),t):(this.apis.set(e.importName,e),e)}async directApi(e){return e.only?.map(t=>{let n={filePath:e.dir,exportName:``,importName:``,importPath:e.from,isNodeModule:!0,isType:!1};return z(t)?(n.exportName=t,n.importName=t):(n.exportName=t.name,n.importName=t.as||t.name,n.isType=!!t.isType),this.saveApi(n),n})}async scanApi(e){let t=await ve({dir:e.dir,ignore:e.ignore,pattern:e.patterns}),n=new Set;return Promise.all(t.map(async t=>{let r=Ce(t);if(n.has(r))return;n.add(r);let{values:i,types:a}=await je(t,{includeTypes:e.types,logger:this.logger}),o=t;if(e.isNodeModule&&(o=p.join(e.from,p.relative(e.dir,t))),e.exclude?.length&&e.exclude.forEach(e=>i.delete(e)),e.only?.length){e.only.forEach(n=>{let{name:r,as:s,isType:c=!1}=z(n)?{name:n}:n;if(!(c?a.has(r):i.has(r)))return;let l={filePath:t,exportName:r,importName:s??r,importPath:o,isNodeModule:e.isNodeModule,isType:c};this.saveApi(l)});return}i.forEach(n=>{let r={filePath:t,exportName:n,importName:n===`default`?Ke(t):n,importPath:o,isNodeModule:e.isNodeModule,isType:!1};this.saveApi(r)}),a.forEach(n=>{let r={filePath:t,exportName:n,importName:n,importPath:o,isNodeModule:e.isNodeModule,isType:!0};this.saveApi(r)})}))}async scanApis(){let e=this.config.scan?.apis||[];return Promise.all(e.map(async e=>{let t=this.toApiSource(e);return t.isNodeModule&&!P(t.dir)&&t.only?this.directApi(t):this.scanApi(t)}))}findApiSource(e){let t=Array.from([...this.sources.keys()]).find(t=>e===t||p.matchesGlob(e,t));if(t)return this.sources.get(t)}isApi(e){return!!this.findApiSource(e)}async enterApi(e){let t=this.findApiSource(e);if(!t)return this.logger.warn(`未找到Api匹配源无法录入Api`),!1;let{values:n,types:r}=await je(e,{includeTypes:t.types,logger:this.logger}),i=e;return t.exclude?.length&&t.exclude.forEach(e=>n.delete(e)),t.only?.length?(t.only.forEach(a=>{let{name:o,as:s,isType:c=!1}=z(a)?{name:a}:a;if(!(c?r.has(o):n.has(o)))return;let l={filePath:e,exportName:o,importName:s??o,importPath:i,isNodeModule:t.isNodeModule,isType:c};this.saveApi(l)}),!0):(n.forEach(n=>{let r={filePath:e,exportName:n,importName:n===`default`?Ke(e):n,importPath:i,isNodeModule:t.isNodeModule,isType:!1};this.saveApi(r)}),r.forEach(n=>{let r={filePath:e,exportName:n,importName:n,importPath:i,isNodeModule:t.isNodeModule,isType:!0};this.saveApi(r)}),!0)}exitApi(e){let t=Array.from(this.apis.values()).filter(t=>t.filePath===e);return t.length?(t.forEach(e=>{this.apis.delete(e.importName)}),!0):!1}generateDeclaration(){let e=Ne(Array.from(this.apis.values()).sort((e,t)=>e.importName.localeCompare(t.importName)),e=>e.isType?`type`:`value`),t=e.value||[],n=Ne(e.type||[],e=>{let t=e.isNodeModule?void 0:this.declarationDir;return t?p.relative(t,e.importPath):e.importPath})||{},r=e=>n[e].map(e=>e.importName===e.exportName?e.importName:`${e.exportName} as ${e.importName}`).join(`, `);return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`declare global {`,...t.map(e=>` ${Fe(e.importPath,e.importName,e.exportName,{baseDir:e.isNodeModule?void 0:this.declarationDir})}`),`}`,``,`declare global {`,...Object.keys(n).map(e=>[` // @ts-ignore`,` export type { ${r(e)} } from '${e}';`].join(`
8
+ `.repeat(e):``;c.default.stdout.write(t),l.default.cursorTo(c.default.stdout,0,0),l.default.clearScreenDown(c.default.stdout)}function me(){return fe??=new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`numeric`,second:`numeric`}),fe}function he(e=`info`,t={}){if(t.customLogger)return t.customLogger;let n=new WeakSet,r=new Set,{prefix:i=`[OIYO]`,scope:a,allowClearScreen:o=!0,console:s=globalThis.console}=t,l=D[e],d=o&&c.default.stdout.isTTY&&!c.default.env.CI,f=d?pe:()=>{};function p(e,t,n={}){let r=ee(e,n.scope??a);return n.timestamp?`${(0,u.dim)(me().format(new Date))} ${(0,u.blue)(i)} ${r} ${t}`:`${(0,u.blue)((0,u.bold)(i))} ${r} ${t}`}function ee(e,t){if(!t)return` `;let n=`[${t.toUpperCase()}]`;return{info:(0,u.cyan)(n),warn:(0,u.yellow)(n),error:(0,u.red)(n),debug:(0,u.dim)((0,u.cyan)(n))}[e]}function m(e,t,r={}){if(l<D[e])return;let i=e;if(r.error&&n.add(r.error),d){if(e===le&&t===ue){de++,f(),s[e](p(e,t,r),(0,u.yellow)(`(x${de+1})`));return}de=0,le=e,ue=t,r.clear&&f()}s[i](p(e,t,r))}let h={hasWarned:!1,withScope(n){return he(e,{...t,scope:n})},debug(e,t){m(`debug`,e,t)},info(e,t){m(`info`,e,t)},warn(e,t){h.hasWarned=!0,m(`warn`,e,t)},warnOnce(e,t){r.has(e)||(r.add(e),h.hasWarned=!0,m(`warn`,e,t))},error(e,t){h.hasWarned=!0,m(`error`,e,t)},clearScreen(e){l>=D[e]&&f()},hasErrorLogged(e){return n.has(e)}};return h}const O=typeof g.default==`function`?g.default:g.default.default;(0,m.createRequire)(require(`url`).pathToFileURL(__filename).href);const ge=`**/*`;function k(e){return e==null?[]:Array.isArray(e)?e:[e]}function _e(e){return e?Array.isArray(e)?e:[e]:[]}function ve(e){if(!(0,d.existsSync)(e))return[ge];try{return(0,d.statSync)(e).isFile()?[(0,p.basename)(e)]:[ge]}catch{return[ge]}}async function ye(e){let{dir:t,pattern:n,ignore:r}=e;if(!(0,d.existsSync)(t))return[];let i=(0,d.statSync)(t).isFile()?(0,p.dirname)(t):t,a=_e(n),o=a.length>0?a:ve(t);try{return(await(0,_.glob)(o,{cwd:i,absolute:!0,ignore:_e(r)})).map(e=>(0,p.normalize)((0,p.resolve)(e)))}catch(e){return console.error(`[oiyo] Error scanning file:`,e),[]}}function A(e,t=8){return(0,ee.createHash)(`sha256`).update(e).digest(`hex`).slice(0,t)}function j(e,t){let n=`${e}.${c.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;return(0,d.writeFileSync)(n,t,`utf-8`),(0,d.existsSync)(e)&&(0,d.unlinkSync)(e),(0,d.renameSync)(n,e),!0}function be(e){if(!e)return``;let t=e.replace(/\p{Lu}/gu,e=>`-${e.toLowerCase()}`);return t.startsWith(`-`)?t.slice(1):t}function M(e){return e?e.replace(/[-_](.)/g,(e,t)=>t.toUpperCase()).replace(/^(.)/,e=>e.toUpperCase()):``}function xe(e){let t=M(e);return t?t[0].toLowerCase()+t.slice(1):``}function Se(e,t){let n=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),r={start:0,end:0};return O(n,{CallExpression(e){let{callee:n,arguments:i}=e.node;n.type===`Identifier`&&n.name===t&&i.length>0&&e.node.start!=null&&e.node.end!=null&&(r.start=e.node.start,r.end=e.node.end,e.stop())}}),r}function Ce(e){return e.replace(/\s+/g,``)}function we(e){let t=p.extname(e);return t?e.slice(0,-t.length):e}function N(e){try{return d.existsSync(e)&&d.statSync(e).isFile()}catch{return!1}}async function Te(e){let{dir:t,pattern:n,ignore:r}=e;if(!d.existsSync(t))return[];let i=t,a=k(n);N(t)&&(i=p.dirname(t),a=[p.basename(t)]);try{return(await _.glob(a,{cwd:i,ignore:k(r),absolute:!0})).map(e=>p.normalize(e))}catch(e){return console.error(`[oiyo] Error scanning file:`,e),[]}}const Ee=te.default.create.sync({conditionNames:[`require`,`import`,`types`],extensions:[`.ts`,`.js`,`.json`,`.vue`,`.cjs`,`.mjs`]}),P=new Set,F=new Map;function I(e,t){let{cwd:n}=Object.assign({cwd:v.fileURLToPath(require(`url`).pathToFileURL(__filename).href)},t);if(P.has(e))return null;if(F.has(e))return F.get(e);try{let t=Ee(n,e);if(!t)return P.add(e),null;let r=p.normalize(t);return F.set(e,r),p.normalize(r)}catch{return P.add(e),null}}const L=new Map;function De(e,t={cwd:v.fileURLToPath(require(`url`).pathToFileURL(__filename).href)}){let{cwd:n}=t;if(P.has(e))return null;if(L.has(e))return L.get(e);let r=I(e,{cwd:n});if(!r)return;let i=p.dirname(r),{root:a}=p.parse(i),o=p.resolve(i,a);for(;i;){let t=p.join(i,`package.json`);if(N(t)){let n=p.dirname(t);return L.set(e,n),n}if(i===o||i===a)break;i=p.dirname(i)}}function Oe(e){if(e.startsWith(`.`)||p.isAbsolute(e))return null;let t=e.split(`/`).filter(Boolean);return t.length===0?null:e.startsWith(`@`)?t.length>=2?`${t[0]}/${t[1]}`:null:t[0]||e}function ke(e){let t=Oe(e);if(!t)return null;let n=De(t);return n?{root:n,name:t}:null}function R(e){try{return(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]})}catch{return(0,h.parse)(`(${e})`,{sourceType:`module`,plugins:[`typescript`]})}}const Ae=(e,t)=>{let n=e=>{let r=e.type;return r===`Identifier`?[e.name]:r===`ObjectPattern`?e.properties.flatMap(e=>e.type===`ObjectProperty`?n(e.value):e.type===`RestElement`?n(e.argument):(t?.logger?.debug(`未被识别的 ObjectPattern ${e}`),[])):r===`ArrayPattern`?e.elements.flatMap(e=>e?e.type===`RestElement`?n(e.argument):n(e):[]):r===`AssignmentPattern`?n(e.left):(t?.logger?.debug(`未被识别的 Node ${e}`),[])};return e.flatMap(e=>n(e.id))};async function je(e,t={}){let n=new Set,r=new Set,i=new Set,a=async e=>{O(R(await f.readFile(e,`utf-8`)),{ExportAllDeclaration({node:e}){i.add(e.source.value)},ExportDefaultDeclaration({node:e}){let t=e.declaration;switch(t.type){case`Identifier`:n.add(t.name);break;case`ClassDeclaration`:case`FunctionDeclaration`:t.id?n.add(t.id.name):n.add(`default`);break;default:n.add(`default`);break}},ExportNamedDeclaration({node:e}){if(e.declaration){let i=e.declaration;switch(i.type){case`VariableDeclaration`:Ae(i.declarations,{logger:t?.logger}).map(e=>n.add(e));break;case`ClassDeclaration`:case`FunctionDeclaration`:i.id?.name&&n.add(i.id.name);break;case`TSTypeAliasDeclaration`:case`TSInterfaceDeclaration`:t?.includeTypes===!0&&r.add(i.id.name);break;case`TSEnumDeclaration`:case`TSModuleDeclaration`:if(i.id.type===`StringLiteral`)break;n.add(i.id.name);break;case`TSDeclareFunction`:i.id?.name&&n.add(i.id.name);break;default:t?.logger?.debug(`未被识别的 ExportNamedDeclaration.declaration ${i}`);break}}else if(e.specifiers){let i=e.exportKind===`type`;e.specifiers.forEach(e=>{switch(e.type){case`ExportSpecifier`:if(e.exported.type===`StringLiteral`)break;if(i??=e.exportKind===`type`,i){t?.includeTypes===!0&&r.add(e.exported.name);break}n.add(e.exported.name);break;case`ExportNamespaceSpecifier`:n.add(e.exported.name);break;default:t?.logger?.debug(`未被识别的 ExportNamedDeclaration.specifiers ${e}`);break}})}}}),i.size&&await Promise.all(Array.from(i.keys()).map(async t=>{i.delete(t);let n=I(t.startsWith(`.`)?p.join(p.dirname(e),t):t);return n?a(n):Promise.resolve()}))};return await a(e),{values:n,types:r}}function Me(e){let t=R(e),n=new Set;return O(t,{Program(e){n=new Set(Object.keys(e.scope.globals))}}),n}function Ne(e=[],t){return e.reduce((e,n)=>{let r=t(n);return e[r]||(e[r]=[]),e[r].push(n),e},{})}function Pe(e,t,n){return n===`default`?`import ${t} from '${e}'`:n===t?`import { ${t} } from '${e}'`:`import { ${n} as ${t} } from '${e}'`}function Fe(e,t,n,r){return e=r?.baseDir?p.relative(r?.baseDir,e):e,e=r?.noExtension?we(e):e,`const ${t}: typeof import('${e}')['${n}'];`}function Ie(e,t,n,r){return e=r?.baseDir?p.relative(r?.baseDir,e):e,`${t}: typeof import('${e}')['${n}'];`}function Le(e){if(typeof e!=`string`||e===``)return!1;for(let t of e.matchAll(/(\\).|([@?!+*]\(.*\))/g))if(t[2])return!0;return!1}const Re={"{":`}`,"(":`)`,"[":`]`};function ze(e){if(e[0]===`!`)return!0;let t=0,n=-2,r=-2,i=-2,a=-2,o=-2;for(;t<e.length;){if(e[t]===`*`||e[t+1]===`?`&&/[\].+)]/.test(e[t])||r!==-1&&e[t]===`[`&&e[t+1]!==`]`&&(r<t&&(r=e.indexOf(`]`,t)),r>t&&(o===-1||o>r||(o=e.indexOf(`\\`,t),o===-1||o>r)))||i!==-1&&e[t]===`{`&&e[t+1]!==`}`&&(i=e.indexOf(`}`,t),i>t&&(o=e.indexOf(`\\`,t),o===-1||o>i))||a!==-1&&e[t]===`(`&&e[t+1]===`?`&&/[:!=]/.test(e[t+2])&&e[t+3]!==`)`&&(a=e.indexOf(`)`,t),a>t&&(o=e.indexOf(`\\`,t),o===-1||o>a))||n!==-1&&e[t]===`(`&&e[t+1]!==`|`&&(n<t&&(n=e.indexOf(`|`,t)),n!==-1&&e[n+1]!==`)`&&(a=e.indexOf(`)`,n),a>n&&(o=e.indexOf(`\\`,n),o===-1||o>a))))return!0;if(e[t]===`\\`){let n=e[t+1];t+=2;let r=Re[n];if(r){let n=e.indexOf(r,t);n!==-1&&(t=n+1)}if(e[t]===`!`)return!0}else t++}return!1}function Be(e){return typeof e!=`string`||e===``?!1:Le(e)?!0:ze(e)}const Ve=/\\/g,He=/\\([!*?|[\](){}])/g;function Ue(e){ne.platform()===`win32`&&!e.includes(`/`)&&(e=e.replace(Ve,`/`)),We(e)&&(e+=`/`),e+=`a`;do e=y.posix.dirname(e);while(Ge(e));return e.replace(He,`$1`)}function We(e){let t=e.slice(-1),n;switch(t){case`}`:n=`{`;break;case`]`:n=`[`;break;default:return!1}let r=e.indexOf(n);return r<0?!1:e.slice(r+1,-1).includes(`/`)}function Ge(e){return/\([^()]+$/.test(e)||e[0]===`{`||e[0]===`[`||/[^\\][{[]/.test(e)?!0:Be(e)}function z(e){return typeof e==`string`}function Ke(e){let t=p.parse(e);return xe(t.name===`index`?p.parse(t.dir).name:t.name)}var qe=class{config;logger;oiyoState;sources=new Map;apis=new Map;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`API`),this.oiyoState=t.oiyoState}get srcDir(){return p.resolve(this.config.rootDir,this.config.srcDir)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return p.resolve(this.declarationDir,`apis.d.ts`)}shouldSkipImport(e){return[`definePageMeta`,`defineRootContext`].includes(e)}recordApiSource(e){return e.patterns?.length?(k(e.patterns).forEach(t=>{let n=p.resolve(e.dir,t);this.sources.set(n,e)}),!0):(this.sources.set(e.dir,e),!0)}toApiSource(e){let t={from:``,dir:``,types:!1,patterns:[`*.js`,`*.ts`],isNodeModule:!1};z(e)?t.from=e:Object.assign(t,e);let n=Be(t.from);if(n){let e=t.from,n=Ue(t.from);t.from=n,t.patterns=[e.slice(n.length+1)]}let r=ke(t.from);if(r){if(t.isNodeModule=!0,!n)if(t.only?.length)t.dir=t.from,t.patterns=[];else{let n=I(t.from);n?(t.dir=n,t.patterns=[]):this.logger.warn(`无法找到 Api 的扫描源,请注意是否存在该来源 from: ${z(e)?e:e.from}`)}if(!t.dir){let e=p.relative(r.name,t.from);t.dir=p.resolve(r.root,e)}}else t.dir=p.resolve(this.srcDir,t.from);return N(t.dir)&&(t.patterns=[]),this.recordApiSource(t),t}saveApi(e){let t=this.apis.get(e.importName);return t&&t.filePath!==e.filePath?(this.logger.warnOnce(`API名称冲突: “${e.importName}” 已存在,已跳过来自 “${e.importPath}” 的重复导出`),t):(this.apis.set(e.importName,e),e)}async directApi(e){return e.only?.map(t=>{let n={filePath:e.dir,exportName:``,importName:``,importPath:e.from,isNodeModule:!0,isType:!1};return z(t)?(n.exportName=t,n.importName=t):(n.exportName=t.name,n.importName=t.as||t.name,n.isType=!!t.isType),this.saveApi(n),n})}async scanApi(e){let t=await ye({dir:e.dir,ignore:e.ignore,pattern:e.patterns}),n=new Set;return Promise.all(t.map(async t=>{let r=we(t);if(n.has(r))return;n.add(r);let{values:i,types:a}=await je(t,{includeTypes:e.types,logger:this.logger}),o=t;if(e.isNodeModule&&(o=p.join(e.from,p.relative(e.dir,t))),e.exclude?.length&&e.exclude.forEach(e=>i.delete(e)),e.only?.length){e.only.forEach(n=>{let{name:r,as:s,isType:c=!1}=z(n)?{name:n}:n;if(!(c?a.has(r):i.has(r)))return;let l={filePath:t,exportName:r,importName:s??r,importPath:o,isNodeModule:e.isNodeModule,isType:c};this.saveApi(l)});return}i.forEach(n=>{let r={filePath:t,exportName:n,importName:n===`default`?Ke(t):n,importPath:o,isNodeModule:e.isNodeModule,isType:!1};this.saveApi(r)}),a.forEach(n=>{let r={filePath:t,exportName:n,importName:n,importPath:o,isNodeModule:e.isNodeModule,isType:!0};this.saveApi(r)})}))}async scanApis(){let e=this.config.scan?.apis||[];return Promise.all(e.map(async e=>{let t=this.toApiSource(e);return t.isNodeModule&&!N(t.dir)&&t.only?this.directApi(t):this.scanApi(t)}))}findApiSource(e){let t=Array.from([...this.sources.keys()]).find(t=>e===t||p.matchesGlob(e,t));if(t)return this.sources.get(t)}isApi(e){return!!this.findApiSource(e)}async enterApi(e){let t=this.findApiSource(e);if(!t)return this.logger.warn(`未找到Api匹配源无法录入Api`),!1;let{values:n,types:r}=await je(e,{includeTypes:t.types,logger:this.logger}),i=e;return t.exclude?.length&&t.exclude.forEach(e=>n.delete(e)),t.only?.length?(t.only.forEach(a=>{let{name:o,as:s,isType:c=!1}=z(a)?{name:a}:a;if(!(c?r.has(o):n.has(o)))return;let l={filePath:e,exportName:o,importName:s??o,importPath:i,isNodeModule:t.isNodeModule,isType:c};this.saveApi(l)}),!0):(n.forEach(n=>{let r={filePath:e,exportName:n,importName:n===`default`?Ke(e):n,importPath:i,isNodeModule:t.isNodeModule,isType:!1};this.saveApi(r)}),r.forEach(n=>{let r={filePath:e,exportName:n,importName:n,importPath:i,isNodeModule:t.isNodeModule,isType:!0};this.saveApi(r)}),!0)}exitApi(e){let t=Array.from(this.apis.values()).filter(t=>t.filePath===e);return t.length?(t.forEach(e=>{this.apis.delete(e.importName)}),!0):!1}generateDeclaration(){let e=Ne(Array.from(this.apis.values()).sort((e,t)=>e.importName.localeCompare(t.importName)),e=>e.isType?`type`:`value`),t=e.value||[],n=Ne(e.type||[],e=>{let t=e.isNodeModule?void 0:this.declarationDir;return t?p.relative(t,e.importPath):e.importPath})||{},r=e=>n[e].map(e=>e.importName===e.exportName?e.importName:`${e.exportName} as ${e.importName}`).join(`, `);return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`declare global {`,...t.map(e=>` ${Fe(e.importPath,e.importName,e.exportName,{baseDir:e.isNodeModule?void 0:this.declarationDir})}`),`}`,``,`declare global {`,...Object.keys(n).map(e=>[` // @ts-ignore`,` export type { ${r(e)} } from '${e}';`].join(`
9
9
  `)),`}`,``,`export {}`,``].join(`
10
- `)}writeDeclaration(){try{d.mkdirSync(this.declarationDir,{recursive:!0}),M(this.declarationFile,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`无法写入 apis.d.ts 组件类型声明,请检查目标文件权限和内容格式:`,{error:e})}}applyApis(e,t){let n=new b.default(e);if(!e)return{code:n.toString(),map:n.generateMap()};let r=Array.from(Me(e));if(!r.length)return{code:n.toString(),map:n.generateMap()};let i=r.map(e=>{let n=this.apis.get(e);return!n||t&&n.filePath===t||this.shouldSkipImport(e)?null:Pe(n.importPath,n.importName,n.exportName)}).filter(e=>!!e);if(!i.length)return{code:n.toString(),map:n.generateMap()};let a=i.join(`
11
- `);return n.prepend(`${a}\n`),{code:n.toString(),map:n.generateMap()}}};function Je(e){let t=new Set,n=e.matchAll(/<\/?\s*([a-z][\w-]*)\b/gi);for(let e of n)t.add(N(e[1]));return t}function Ye(e){if(!e||!e.includes(`import`))return new Set;let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n=new Set;return O(t,{ImportDeclaration(e){for(let t of e.node.specifiers)n.add(t.local.name)}}),n}function Xe(e,t,n){let r=p.relative(t,e),{dir:i,name:a}=p.parse(r),o=i&&i!==`.`?i.split(p.sep).filter(Boolean):[];(a!==`index`||o.length===0)&&o.push(a);let s=Ze(o),c=n?.chain===!1?s.slice(-1):s;return`${n?.prefix?N(n?.prefix):``}${c.map(e=>N(e)).join(``)}`}function Ze(e){if(e.length<2)return e;let t=e.slice();return t[t.length-1]===t[t.length-2]&&t.pop(),t}var Qe=class{config;logger;oiyoState;oiyoApi;sources=new Map;components=new Map;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`COMPONENT`),this.oiyoState=t.oiyoState,this.oiyoApi=t.oiyoApi}get srcDir(){return p.resolve(this.config.rootDir,this.config.srcDir)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return p.resolve(this.declarationDir,`components.d.ts`)}shouldSkipImport(e){return[`OiyoPage`,`OiyoLayout`].includes(e)}recordComponentSource(e){return e.patterns?.length?(A(e.patterns).forEach(t=>{let n=p.resolve(e.dir,t);this.sources.set(n,e)}),!0):(this.sources.set(e.dir,e),!0)}toComponentSource(e){let t={from:``,dir:``,chain:!0,patterns:[`**/*.vue`,`**/*.nvue`],isNodeModule:!1};if(z(e)?t.from=e:Object.assign(t,e),Be(t.from)){let e=t.from,n=Ue(t.from),r=n===`.`;t.from=n,t.patterns=[r?e:e.slice(n.length+1)]}let n=Oe(t.from);if(n){t.isNodeModule=!0;let e=p.relative(n.name,t.from);t.dir=p.resolve(n.root,e),t?.only?.length&&(t.patterns=[])}else t.dir=p.resolve(this.srcDir,t.from);return P(t.dir)&&(t.patterns=[]),this.recordComponentSource(t),t}saveComponent(e){let t=this.components.get(e.importName);return t&&t.filePath!==e.filePath?(this.logger.warnOnce(`组件名名称冲突: “${e.importName}” 已存在,已跳过来自 “${e.importPath}” 的重复导出`),!1):(this.components.set(e.importName,e),!0)}async scanComponentByDirect(e){return e.only?.map(t=>{let n={filePath:e.dir,exportName:``,importName:``,importPath:e.from,isNodeModule:!0};return z(t)?(n.exportName=t,n.importName=t):(n.exportName=t.name,n.importName=t.as||t.name),e.prefix&&(n.importName=N(`${e.prefix}${n.importName}`)),this.saveComponent(n),n})}async scanComponentByDir(e){return(await we({dir:e.dir,ignore:e.ignore,pattern:e.patterns})).map(t=>{let n=Xe(t,e.dir===t?p.dirname(t):e.dir,{chain:e.chain,prefix:e.prefix}),r=t;e.isNodeModule&&(r=p.join(e.from,p.relative(e.dir,t)));let i={filePath:t,exportName:`default`,importName:n,importPath:r,isNodeModule:e.isNodeModule};return this.saveComponent(i),i})}async scanComponent(e){return e.isNodeModule&&e.only?.length?this.scanComponentByDirect(e):this.scanComponentByDir(e)}async scanComponents(){let e=this.config.scan?.components||[];await Promise.all(e.map(async e=>{let t=this.toComponentSource(e);await this.scanComponent(t)}))}findComponentSource(e){let t=Array.from([...this.sources.keys()]).find(t=>p.matchesGlob(e,t));if(t)return this.sources.get(t)}isComponent(e){return!!this.findComponentSource(e)}enterComponent(e){let t=this.findComponentSource(e);if(!t)return this.logger.warn(`未找到组件匹配源无法录入组件`),!1;let n={filePath:e,exportName:`default`,importName:Xe(e,t.dir===e?p.dirname(e):t.dir,{chain:t.chain,prefix:t.prefix}),importPath:e,isNodeModule:!1};return this.saveComponent(n),!0}exitComponent(e){let t=Array.from(this.components.values()).find(t=>t.filePath===e);if(t)return this.components.delete(t.importName),t}generateDeclaration(){return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`declare module 'vue' {`,` export interface GlobalComponents {`,...Array.from(this.components.values()).sort((e,t)=>e.importName.localeCompare(t.importName)).map(e=>` ${Ie(e.importPath,e.importName,e.exportName,{baseDir:e.isNodeModule?void 0:this.declarationDir})}`),` }`,`}`,``,`export {}`,``].join(`
12
- `)}writeDeclaration(){try{d.mkdirSync(this.declarationDir,{recursive:!0}),M(this.declarationFile,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`无法写入 components.d.ts 组件类型声明,请检查目标文件权限和内容格式:`,{error:e})}}applyComponents(e,t,n={withApis:!0}){let{descriptor:r}=(0,x.parse)(e),i=new b.default(e),a=r.template?.content;if(!a)return{code:i.toString(),map:i.generateMap()};let o=Array.from(Je(a)),s=o,c=[],l=[r.scriptSetup?.content,r.script?.content].filter(e=>!!e);if(l.length){let[e,t]=l.flatMap(e=>[Ye(e),Me(e)]);s=o.filter(t=>!e.has(t)),n?.withApis&&(c=Array.from(t))}if(!s.length&&!c.length)return{code:i.toString(),map:i.generateMap()};let u=s.map(e=>{let n=this.components.get(e);return!n||t&&n.filePath===t||this.shouldSkipImport(e)?null:Pe(n.importPath,n.importName,n.exportName)}).filter(e=>!!e),d=c.map(e=>{let n=this.oiyoApi.apis.get(e);return!n||t&&n.filePath===t||this.oiyoApi.shouldSkipImport(e)?null:Pe(n.importPath,n.importName,n.exportName)}).filter(e=>!!e);if(!u.length&&!d.length)return{code:i.toString(),map:i.generateMap()};let f=[...u,...d].join(`
10
+ `)}writeDeclaration(){try{d.mkdirSync(this.declarationDir,{recursive:!0}),j(this.declarationFile,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`无法写入 apis.d.ts 组件类型声明,请检查目标文件权限和内容格式:`,{error:e})}}applyApis(e,t){let n=new b.default(e);if(!e)return{code:n.toString(),map:n.generateMap()};let r=Array.from(Me(e));if(!r.length)return{code:n.toString(),map:n.generateMap()};let i=r.map(e=>{let n=this.apis.get(e);return!n||t&&n.filePath===t||this.shouldSkipImport(e)?null:Pe(n.importPath,n.importName,n.exportName)}).filter(e=>!!e);if(!i.length)return{code:n.toString(),map:n.generateMap()};let a=i.join(`
11
+ `);return n.prepend(`${a}\n`),{code:n.toString(),map:n.generateMap()}}};function Je(e){let t=new Set,n=e.matchAll(/<\/?\s*([a-z][\w-]*)\b/gi);for(let e of n)t.add(M(e[1]));return t}function Ye(e){if(!e||!e.includes(`import`))return new Set;let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n=new Set;return O(t,{ImportDeclaration(e){for(let t of e.node.specifiers)n.add(t.local.name)}}),n}function Xe(e,t,n){let r=p.relative(t,e),{dir:i,name:a}=p.parse(r),o=i&&i!==`.`?i.split(p.sep).filter(Boolean):[];(a!==`index`||o.length===0)&&o.push(a);let s=Ze(o),c=n?.chain===!1?s.slice(-1):s;return`${n?.prefix?M(n?.prefix):``}${c.map(e=>M(e)).join(``)}`}function Ze(e){if(e.length<2)return e;let t=e.slice();return t[t.length-1]===t[t.length-2]&&t.pop(),t}var Qe=class{config;logger;oiyoState;oiyoApi;sources=new Map;components=new Map;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`COMPONENT`),this.oiyoState=t.oiyoState,this.oiyoApi=t.oiyoApi}get srcDir(){return p.resolve(this.config.rootDir,this.config.srcDir)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return p.resolve(this.declarationDir,`components.d.ts`)}shouldSkipImport(e){return[`OiyoPage`,`OiyoLayout`].includes(e)}recordComponentSource(e){return e.patterns?.length?(k(e.patterns).forEach(t=>{let n=p.resolve(e.dir,t);this.sources.set(n,e)}),!0):(this.sources.set(e.dir,e),!0)}toComponentSource(e){let t={from:``,dir:``,chain:!0,patterns:[`**/*.vue`,`**/*.nvue`],isNodeModule:!1};if(z(e)?t.from=e:Object.assign(t,e),Be(t.from)){let e=t.from,n=Ue(t.from),r=n===`.`;t.from=n,t.patterns=[r?e:e.slice(n.length+1)]}let n=ke(t.from);if(n){t.isNodeModule=!0;let e=p.relative(n.name,t.from);t.dir=p.resolve(n.root,e),t?.only?.length&&(t.patterns=[])}else t.dir=p.resolve(this.srcDir,t.from);return N(t.dir)&&(t.patterns=[]),this.recordComponentSource(t),t}saveComponent(e){let t=this.components.get(e.importName);return t&&t.filePath!==e.filePath?(this.logger.warnOnce(`组件名名称冲突: “${e.importName}” 已存在,已跳过来自 “${e.importPath}” 的重复导出`),!1):(this.components.set(e.importName,e),!0)}async scanComponentByDirect(e){return e.only?.map(t=>{let n={filePath:e.dir,exportName:``,importName:``,importPath:e.from,isNodeModule:!0};return z(t)?(n.exportName=t,n.importName=t):(n.exportName=t.name,n.importName=t.as||t.name),e.prefix&&(n.importName=M(`${e.prefix}${n.importName}`)),this.saveComponent(n),n})}async scanComponentByDir(e){return(await Te({dir:e.dir,ignore:e.ignore,pattern:e.patterns})).map(t=>{let n=Xe(t,e.dir===t?p.dirname(t):e.dir,{chain:e.chain,prefix:e.prefix}),r=t;e.isNodeModule&&(r=p.join(e.from,p.relative(e.dir,t)));let i={filePath:t,exportName:`default`,importName:n,importPath:r,isNodeModule:e.isNodeModule};return this.saveComponent(i),i})}async scanComponent(e){return e.isNodeModule&&e.only?.length?this.scanComponentByDirect(e):this.scanComponentByDir(e)}async scanComponents(){let e=this.config.scan?.components||[];await Promise.all(e.map(async e=>{let t=this.toComponentSource(e);await this.scanComponent(t)}))}findComponentSource(e){let t=Array.from([...this.sources.keys()]).find(t=>p.matchesGlob(e,t));if(t)return this.sources.get(t)}isComponent(e){return!!this.findComponentSource(e)}enterComponent(e){let t=this.findComponentSource(e);if(!t)return this.logger.warn(`未找到组件匹配源无法录入组件`),!1;let n={filePath:e,exportName:`default`,importName:Xe(e,t.dir===e?p.dirname(e):t.dir,{chain:t.chain,prefix:t.prefix}),importPath:e,isNodeModule:!1};return this.saveComponent(n),!0}exitComponent(e){let t=Array.from(this.components.values()).find(t=>t.filePath===e);if(t)return this.components.delete(t.importName),t}generateDeclaration(){return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`declare module 'vue' {`,` export interface GlobalComponents {`,...Array.from(this.components.values()).sort((e,t)=>e.importName.localeCompare(t.importName)).map(e=>` ${Ie(e.importPath,e.importName,e.exportName,{baseDir:e.isNodeModule?void 0:this.declarationDir})}`),` }`,`}`,``,`export {}`,``].join(`
12
+ `)}writeDeclaration(){try{d.mkdirSync(this.declarationDir,{recursive:!0}),j(this.declarationFile,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`无法写入 components.d.ts 组件类型声明,请检查目标文件权限和内容格式:`,{error:e})}}applyComponents(e,t,n={withApis:!0}){let{descriptor:r}=(0,x.parse)(e),i=new b.default(e),a=r.template?.content;if(!a)return{code:i.toString(),map:i.generateMap()};let o=Array.from(Je(a)),s=o,c=[],l=[r.scriptSetup?.content,r.script?.content].filter(e=>!!e);if(l.length){let[e,t]=l.flatMap(e=>[Ye(e),Me(e)]);s=o.filter(t=>!e.has(t)),n?.withApis&&(c=Array.from(t))}if(!s.length&&!c.length)return{code:i.toString(),map:i.generateMap()};let u=s.map(e=>{let n=this.components.get(e);return!n||t&&n.filePath===t||this.shouldSkipImport(e)?null:Pe(n.importPath,n.importName,n.exportName)}).filter(e=>!!e),d=c.map(e=>{let n=this.oiyoApi.apis.get(e);return!n||t&&n.filePath===t||this.oiyoApi.shouldSkipImport(e)?null:Pe(n.importPath,n.importName,n.exportName)}).filter(e=>!!e);if(!u.length&&!d.length)return{code:i.toString(),map:i.generateMap()};let f=[...u,...d].join(`
13
13
  `),p=r.scriptSetup;if(!p){let e=[`<script setup>`,f,`<\/script>`].join(`
14
- `);return i.prepend(`${e}\n\n`),{code:i.toString(),map:i.generateMap()}}return i.appendRight(p.loc.start.offset,`\n${f}`),{code:i.toString(),map:i.generateMap()}}};function $e(e){return e.includes(`<OiyoLayout`)||e.includes(`<oiyo-layout`)}function et(e){let t=e;return t=t.replace(/<OiyoLayout[^>]*?\/>/g,``),t=t.replace(/<OiyoLayout[^>]*>/g,``),t=t.replace(/<\/OiyoLayout>/g,``),t=t.replace(/<oiyo-layout[^>]*?\/>/g,``),t=t.replace(/<oiyo-layout[^>]*>/g,``),t=t.replace(/<\/oiyo-layout>/g,``),t}function tt(e,t){let n=e;return n=n.replace(/<OiyoLayout[^>]*?\/>/g,``),n=n.replace(/<OiyoLayout[^>]*>/g,`<${t}>`),n=n.replace(/<\/OiyoLayout>/g,`</${t}>`),n=n.replace(/<oiyo-layout[^>]*?\/>/g,``),n=n.replace(/<oiyo-layout[^>]*>/g,`<${t}>`),n=n.replace(/<\/oiyo-layout>/g,`</${t}>`),n}function nt(e,t){let{dir:n,name:r}=(0,p.parse)((0,p.relative)(t,e));return(n&&n!==`.`?[...n.split(p.sep),r]:[r]).map(e=>ye(e)).join(`-`)}function rt(e){return`OiyoLayout${e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}`}var it=class{config;logger;oiyoState;layouts=new Map;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`LAYOUT`),this.oiyoState=t.oiyoState}get srcDir(){return p.resolve(this.config.rootDir,this.config.srcDir)}get layoutDir(){return p.resolve(this.srcDir,this.config.dir?.layouts||`layouts`)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return p.resolve(this.declarationDir,`layouts.d.ts`)}toLayout(e){let t=nt(e,this.layoutDir);return{filePath:e,componentName:rt(t),useName:t}}saveLayout(e){return this.layouts.has(e.useName)?!1:(this.layouts.set(e.useName,e),!0)}async scanLayouts(){return(await ve({dir:this.layoutDir,pattern:[`**/*.vue`,`**/*.nvue`],ignore:[...S.DEFAULT_EXCLUDE,...this.config.exclude||[]]})).forEach(e=>{let t=this.toLayout(e);this.saveLayout(t)&&this.logger.debug(`通过“扫描模式”录入页面: ${t.useName}`)}),this.layouts}isLayout(e){return!e.endsWith(`.vue`)&&!e.endsWith(`.nvue`)||[...S.DEFAULT_EXCLUDE,...this.config.exclude||[]].some(t=>p.matchesGlob(e,t))?!1:e.startsWith(`${this.layoutDir}/`)}enterLayout(e){let t=this.toLayout(e),n=this.saveLayout(t);return n&&this.logger.debug(`通过“主动模式”录入布局: ${t.useName}`),n}exitLayout(e){let t=Array.from(this.layouts.values()).find(t=>t.filePath===e);if(!t)return!1;let n=this.layouts.delete(t.useName);return n&&this.logger.debug(`通过“主动模式”脱离布局: ${t.useName}`),n}generateDeclaration(){return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`declare module '@skiyee/oiyo/api' {`,` interface OiyoLayouts {`,...Array.from(this.layouts.values()).sort((e,t)=>e.useName.localeCompare(t.useName)).map(({useName:e,filePath:t})=>` ${Ie(t,`'${e}'`,`default`,{baseDir:this.declarationDir})}`),` }`,``,` type LayoutKey = keyof OiyoLayouts extends never ? string : keyof OiyoLayouts;`,``,` interface PageMeta {`,` layout?: LayoutKey | false;`,` }`,`}`,``,`export {}`,``].join(`
15
- `)}writeDeclaration(){try{return(0,d.mkdirSync)(this.declarationDir,{recursive:!0}),M(this.declarationFile,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),!0}catch(e){return this.logger.error(`无法写入 layouts.d.ts 布局类型声明,请检查目标文件权限和内容格式:`,{error:e}),!1}}applyLayout(e,t){if(!$e(t))return{template:t,script:``,imports:[]};if(e===!1)return{template:et(t),script:``,imports:[]};e===void 0&&(e=`default`);let n=this.layouts.get(e);return n?{template:tt(t,n.componentName),script:``,imports:[`import ${n.componentName} from '${n.filePath}'`]}:(this.logger.error(`未找到布局 "${e}",请检查布局名称或文件位置是否正确`),{template:t,script:``,imports:[]})}};const at=(0,re.defineComponent)({name:`OiyoLayout`,setup(e,t){return()=>t.slots.default?.()}});function ot(e,t){let n=ke(e),r={start:0,end:0};return O(n,{CallExpression(e){let{callee:n,arguments:i}=e.node;n.type===`Identifier`&&n.name===t&&i.length>0&&e.node.start!=null&&e.node.end!=null&&(r.start=e.node.start,r.end=e.node.end,e.stop())}}),r}function st(e){if(!e.includes(`defineRootContext`))return``;let{descriptor:t}=(0,x.parse)(e);if(!t.scriptSetup)return``;let n=e=t.scriptSetup.content,r=ct(n);return n.substring(r.start,r.end+1).trim()}function ct(e){return ot(e,`defineRootContext`)}function lt(e){if(!e.includes(`<template`))return``;let{descriptor:t}=(0,x.parse)(e);return(t.template?.content||``).trim()}function ut(e,t){let n=e.replace(/\{\{([\s\S]*?)\}\}/g,(e,n)=>e.replace(n,dt(n,t)));return n=n.replace(/((?:v-(?!for\b)[\w-]+(?::[\w-]+)?|[:@][\w-]+)\s*=\s*)(["'])([\s\S]*?)\2/g,(e,n,r,i)=>`${n}${r}${dt(i,t)}${r}`),n}function dt(e,t){let n=new Map;t.varName&&n.set(t.varName,`$oiyoRootContext`);for(let{local:e,original:r}of t.varProperties||[])n.set(e,`$oiyoRootContext.${r}`);if(n.size===0)return e;try{let t=(0,h.parse)(`(${e})`,{sourceType:`module`,plugins:[`typescript`]}),r=new b.default(e);return O(t,{Identifier(e){if(!e.isReferencedIdentifier())return;let t=n.get(e.node.name);if(!t)return;let i=e.node.start,a=e.node.end;if(!(i==null||a==null)){if(e.parentPath.isObjectProperty()&&e.parent.shorthand&&e.parent.value===e.node){r.overwrite(i-1,a-1,`${e.node.name}: ${t}`);return}r.overwrite(i-1,a-1,t)}}}),r.toString()}catch{return e}}function ft(e,t){if(!e)throw Error(`[oiyo] App.vue 必须包含 <template> 节点`);let n=e.content;if(!(n.includes(`<OiyoPage`)||n.includes(`<oiyo-page`)))throw Error(`[oiyo] App.vue 的 template 必须包含 <OiyoPage /> 或 <oiyo-page /> 占位节点`);return n=ut(n,t),n.trim()}function pt(e){if(!e)return;let t=e?.content;if(t){let e=mt(t);return e.script?e:void 0}}function mt(e){let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return O(t,{ImportDeclaration(t){let r=e.substring(t.node.start,t.node.end);n.imports??=[],n.imports.push(r)},CallExpression(t){let{callee:r,arguments:i}=t.node;if(r.type===`Identifier`&&r.name===`defineRootContext`&&i.length>0){let r=i[0];r.start!=null&&r.end!=null&&(n.script=e.substring(r.start,r.end));let a=t.findParent(e=>e.isVariableDeclarator());if(a&&a.isVariableDeclarator()){let e=a.node.id;e.type===`Identifier`?n.variable=e.name:e.type===`ObjectPattern`&&(n.properties=e.properties.filter(e=>e.type===`ObjectProperty`).map(e=>({original:e.key.type===`Identifier`?e.key.name:String(e.key.value),local:e.value.type===`Identifier`?e.value.name:e.key.name})))}}}}),n}function ht(e,t){let n=e;return n=n.replace(/<OiyoPage[^>]*?\/>/g,t),n=n.replace(/<OiyoPage[^>]*>\s*<\/OiyoPage>/g,t),n=n.replace(/<oiyo-page[^>]*?\/>/g,t),n=n.replace(/<oiyo-page[^>]*>\s*<\/oiyo-page>/g,t),n}const gt=`virtual:oiyo-root-context`,B=`\0${gt}`;function _t(e){let{script:t,imports:n}=e,r=[];return n?.length&&(r.push(...n),r.push(``)),t?r.push(`let rootContextInstance = null`,``,`export function useRootContext() {`,` if (!rootContextInstance) {`,` const factory = ${t}`,` rootContextInstance = factory()`,` }`,``,` return rootContextInstance`,`}`):r.push(`export function useRootContext() {`,` return {}`,`}`),r.join(`
14
+ `);return i.prepend(`${e}\n\n`),{code:i.toString(),map:i.generateMap()}}return i.appendRight(p.loc.start.offset,`\n${f}`),{code:i.toString(),map:i.generateMap()}}};function $e(e){return e.includes(`<OiyoLayout`)||e.includes(`<oiyo-layout`)}function et(e){let t=e;return t=t.replace(/<OiyoLayout[^>]*?\/>/g,``),t=t.replace(/<OiyoLayout[^>]*>/g,``),t=t.replace(/<\/OiyoLayout>/g,``),t=t.replace(/<oiyo-layout[^>]*?\/>/g,``),t=t.replace(/<oiyo-layout[^>]*>/g,``),t=t.replace(/<\/oiyo-layout>/g,``),t}function tt(e,t){let n=e;return n=n.replace(/<OiyoLayout[^>]*?\/>/g,``),n=n.replace(/<OiyoLayout[^>]*>/g,`<${t}>`),n=n.replace(/<\/OiyoLayout>/g,`</${t}>`),n=n.replace(/<oiyo-layout[^>]*?\/>/g,``),n=n.replace(/<oiyo-layout[^>]*>/g,`<${t}>`),n=n.replace(/<\/oiyo-layout>/g,`</${t}>`),n}function nt(e,t){let{dir:n,name:r}=(0,p.parse)((0,p.relative)(t,e));return(n&&n!==`.`?[...n.split(p.sep),r]:[r]).map(e=>be(e)).join(`-`)}function rt(e){return`OiyoLayout${M(e)}`}var it=class{config;logger;oiyoState;layouts=new Map;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`LAYOUT`),this.oiyoState=t.oiyoState}get srcDir(){return this.oiyoState.srcDir}get layoutDir(){return p.resolve(this.srcDir,this.config.dir?.layouts||`layouts`)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return p.resolve(this.declarationDir,`layouts.d.ts`)}toLayout(e){let t=nt(e,this.layoutDir);return{filePath:e,componentName:rt(t),useName:t}}saveLayout(e){return this.layouts.has(e.useName)?!1:(this.layouts.set(e.useName,e),!0)}async scanLayouts(){return(await ye({dir:this.layoutDir,pattern:[`**/*.vue`,`**/*.nvue`],ignore:[...S.DEFAULT_EXCLUDE,...this.config.exclude||[]]})).forEach(e=>{let t=this.toLayout(e);this.saveLayout(t)&&this.logger.debug(`通过“扫描模式”录入布局: ${t.useName}`)}),this.layouts}isLayout(e){return!e.endsWith(`.vue`)&&!e.endsWith(`.nvue`)||[...S.DEFAULT_EXCLUDE,...this.config.exclude||[]].some(t=>p.matchesGlob(e,t))?!1:e.startsWith(`${this.layoutDir}/`)}enterLayout(e){let t=this.toLayout(e),n=this.saveLayout(t);return n&&this.logger.debug(`通过“主动模式”录入布局: ${t.useName}`),n}exitLayout(e){let t=Array.from(this.layouts.values()).find(t=>t.filePath===e);if(!t)return!1;let n=this.layouts.delete(t.useName);return n&&this.logger.debug(`通过“主动模式”脱离布局: ${t.useName}`),n}generateDeclaration(){return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`declare module '@skiyee/oiyo/api' {`,` interface OiyoLayouts {`,...Array.from(this.layouts.values()).sort((e,t)=>e.useName.localeCompare(t.useName)).map(({useName:e,filePath:t})=>` ${Ie(t,`'${e}'`,`default`,{baseDir:this.declarationDir})}`),` }`,``,` type LayoutKey = keyof OiyoLayouts extends never ? string : keyof OiyoLayouts;`,``,` interface PageMeta {`,` layout?: LayoutKey | false;`,` }`,`}`,``,`export {}`,``].join(`
15
+ `)}writeDeclaration(){try{return(0,d.mkdirSync)(this.declarationDir,{recursive:!0}),j(this.declarationFile,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),!0}catch(e){return this.logger.error(`无法写入 layouts.d.ts 布局类型声明,请检查目标文件权限和内容格式:`,{error:e}),!1}}applyLayout(e,t){if(!$e(t))return{template:t,script:``,imports:[]};if(e===!1)return{template:et(t),script:``,imports:[]};e===void 0&&(e=`default`);let n=this.layouts.get(e);return n?{template:tt(t,n.componentName),script:``,imports:[`import ${n.componentName} from '${n.filePath}'`]}:(this.logger.error(`未找到布局 "${e}",请检查布局名称或文件位置是否正确`),{template:t,script:``,imports:[]})}};const at=(0,re.defineComponent)({name:`OiyoLayout`,setup(e,t){return()=>t.slots.default?.()}});function ot(e,t){let n=R(e),r={start:0,end:0};return O(n,{CallExpression(e){let{callee:n,arguments:i}=e.node;n.type===`Identifier`&&n.name===t&&i.length>0&&e.node.start!=null&&e.node.end!=null&&(r.start=e.node.start,r.end=e.node.end,e.stop())}}),r}function st(e){if(!e.includes(`defineRootContext`))return``;let{descriptor:t}=(0,x.parse)(e);if(!t.scriptSetup)return``;let n=e=t.scriptSetup.content,r=ct(n);return n.substring(r.start,r.end+1).trim()}function ct(e){return ot(e,`defineRootContext`)}function lt(e){if(!e.includes(`<template`))return``;let{descriptor:t}=(0,x.parse)(e);return(t.template?.content||``).trim()}function ut(e,t){let n=e.replace(/\{\{([\s\S]*?)\}\}/g,(e,n)=>e.replace(n,dt(n,t)));return n=n.replace(/((?:v-(?!for\b)[\w-]+(?::[\w-]+)?|[:@][\w-]+)\s*=\s*)(["'])([\s\S]*?)\2/g,(e,n,r,i)=>`${n}${r}${dt(i,t)}${r}`),n}function dt(e,t){let n=new Map;t.varName&&n.set(t.varName,`$oiyoRootContext`);for(let{local:e,original:r}of t.varProperties||[])n.set(e,`$oiyoRootContext.${r}`);if(n.size===0)return e;try{let t=(0,h.parse)(`(${e})`,{sourceType:`module`,plugins:[`typescript`]}),r=new b.default(e);return O(t,{Identifier(e){if(!e.isReferencedIdentifier())return;let t=n.get(e.node.name);if(!t)return;let i=e.node.start,a=e.node.end;if(!(i==null||a==null)){if(e.parentPath.isObjectProperty()&&e.parent.shorthand&&e.parent.value===e.node){r.overwrite(i-1,a-1,`${e.node.name}: ${t}`);return}r.overwrite(i-1,a-1,t)}}}),r.toString()}catch{return e}}function ft(e,t){if(!e)throw Error(`[oiyo] App.vue 必须包含 <template> 节点`);let n=e.content;if(!(n.includes(`<OiyoPage`)||n.includes(`<oiyo-page`)))throw Error(`[oiyo] App.vue 的 template 必须包含 <OiyoPage /> 或 <oiyo-page /> 占位节点`);return n=ut(n,t),n.trim()}function pt(e){if(!e)return;let t=e?.content;if(t){let e=mt(t);return e.script?e:void 0}}function mt(e){let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return O(t,{ImportDeclaration(t){let r=e.substring(t.node.start,t.node.end);n.imports??=[],n.imports.push(r)},CallExpression(t){let{callee:r,arguments:i}=t.node;if(r.type===`Identifier`&&r.name===`defineRootContext`&&i.length>0){let r=i[0];r.start!=null&&r.end!=null&&(n.script=e.substring(r.start,r.end));let a=t.findParent(e=>e.isVariableDeclarator());if(a&&a.isVariableDeclarator()){let e=a.node.id;e.type===`Identifier`?n.variable=e.name:e.type===`ObjectPattern`&&(n.properties=e.properties.filter(e=>e.type===`ObjectProperty`).map(e=>({original:e.key.type===`Identifier`?e.key.name:String(e.key.value),local:e.value.type===`Identifier`?e.value.name:e.key.name})))}}}}),n}function ht(e,t){let n=e;return n=n.replace(/<OiyoPage[^>]*?\/>/g,t),n=n.replace(/<OiyoPage[^>]*>\s*<\/OiyoPage>/g,t),n=n.replace(/<oiyo-page[^>]*?\/>/g,t),n=n.replace(/<oiyo-page[^>]*>\s*<\/oiyo-page>/g,t),n}const gt=`virtual:oiyo-root-context`,B=`\0${gt}`;function _t(e){let{script:t,imports:n}=e,r=[];return n?.length&&(r.push(...n),r.push(``)),t?r.push(`let rootContextInstance = null`,``,`export function useRootContext() {`,` if (!rootContextInstance) {`,` const factory = ${t}`,` rootContextInstance = factory()`,` }`,``,` return rootContextInstance`,`}`):r.push(`export function useRootContext() {`,` return {}`,`}`),r.join(`
16
16
  `)}var vt=class{config;rootView={imports:[],template:`<OiyoPage />`,script:``};rootVM;rootMarco;logger;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`ROOT`)}get srcDir(){return(0,p.resolve)(this.config.rootDir,this.config.srcDir)}get rootPath(){return(0,p.resolve)(this.srcDir,`App.vue`)}isRootPath(e){return e===this.rootPath}parseRoot(e){let{descriptor:t}=(0,x.parse)(e),n=pt(t.scriptSetup),r=ft(t.template,{varName:n?.variable,varProperties:n?.properties});return this.rootView={template:r,imports:[],script:``},n&&(this.rootMarco=n,this.rootVM=_t(n),n.script&&(this.rootView.imports.push(`import { useRootContext } from 'virtual:oiyo-root-context'`),this.rootView.script=`const $oiyoRootContext = useRootContext()`)),{view:this.rootView,marco:n}}transformRoot(e){let{descriptor:t}=(0,x.parse)(e),n=new b.default(e);if(t.template){let e=t.template.loc.start.offset-10,r=t.template.loc.end.offset+11;n.remove(e,r)}if(t.scriptSetup){let e=t.scriptSetup.content,r=ct(e);if(r.start!==r.end){e.includes(`virtual:oiyo-root-context`)||n.appendLeft(t.scriptSetup.loc.start.offset,`
17
17
  import { useRootContext } from 'virtual:oiyo-root-context'
18
- `);let i=t.scriptSetup.loc.start.offset+r.start,a=t.scriptSetup.loc.start.offset+r.end;i!==a&&n.overwrite(i,a,`useRootContext()`)}}return{code:n.toString(),sourceMap:n.generateMap()}}shouldRefreshView(e){return j(this.rootView.template)!==j(lt(e))}shouldRefreshVM=e=>{let t=``;this.rootMarco&&(t=j(Se(`defineRootContext(${this.rootMarco.script})`)));let n=j(Se(st(e)));return t!==n};applyRoot(e){let t=[],n=``,r=``;return e.template&&(n=ht(this.rootView.template,e.template.content)),t.push(...this.rootView.imports),r=`${this.rootView.script}\n${e.scriptSetup?.content||``}`,{imports:t,script:r,template:n}}};const yt=e=>e();function bt(e,...t){let n=[e,...t],r={...e},i=xt(n),a=St(n),o=Ct(n);return i&&(r.pages=i),a&&(r.subPackages=a),o&&(r.tabBar={...wt(n),list:o}),r}function xt(e){let t=[],n=!1;for(let r of e)r.pages&&(n=!0,t.push(...r.pages));return n?V(t,e=>e.path):void 0}function St(e){let t=new Map,n=!1;for(let r of e)if(r.subPackages){n=!0;for(let e of r.subPackages){let n=t.get(e.root);if(!n){t.set(e.root,{...e,pages:V(e.pages??[],e=>e.path)});continue}t.set(e.root,{...n,...e,pages:V([...n.pages??[],...e.pages??[]],e=>e.path)})}}return n?[...t.values()]:void 0}function Ct(e){let t=[],n=!1;for(let r of e)r.tabBar?.list&&(n=!0,t.push(...r.tabBar.list));return n?V(t,e=>e.pagePath):void 0}function wt(e){let t;for(let n of e)n.tabBar&&(t={...t,...n.tabBar});return t}function V(e,t){let n=new Set,r=[];for(let i=e.length-1;i>=0;i--){let a=e[i],o=t(a);if(o===void 0){r.unshift(a);continue}n.has(o)||(n.add(o),r.unshift(a))}return r}function Tt(e,t){if(!e.includes(`definePageMeta`))return``;if(!t){let{descriptor:t}=(0,x.parse)(e);if(!t.scriptSetup)return``;e=t.scriptSetup.content}let n=Et(e);return e.substring(n.start,n.end+1).trim()}function Et(e){return xe(e,`definePageMeta`)}function Dt(e){return e.replace(/definePageMeta\s*\(\s*\{[\s\S]*?\}\s*\)/g,``).trim()}function Ot(e){if(!e)return{};let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return O(t,{CallExpression(e){let{callee:t,arguments:r}=e.node;if(t.type===`Identifier`&&t.name===`definePageMeta`&&r.length>0){let t=r[0];t.type===`ObjectExpression`&&(n=kt(t),e.stop())}}}),n}function kt(e){let t={};for(let n of e.properties)if(n.type===`ObjectProperty`){let e=At(n.key),r=jt(n.value);e&&(t[e]=r)}return t}function At(e){return e.type===`Identifier`?e.name:e.type===`StringLiteral`?e.value:null}function jt(e){switch(e.type){case`StringLiteral`:return e.value;case`NumericLiteral`:return e.value;case`BooleanLiteral`:return e.value;case`NullLiteral`:return null;case`ArrayExpression`:return e.elements.map(e=>jt(e)).filter(e=>e!==void 0);case`ObjectExpression`:return kt(e);default:return}}function Mt(e){return`'${e.startsWith(`/`)?e:`/${e}`}'`}function Nt(e){let t=new Set;for(let n of e.pages||[])t.add(Mt(n.path));for(let n of e.subPackages||[])for(let e of n.pages||[])t.add(Mt((0,p.join)(n.root,e.path)));return Array.from(t).sort()}function Pt(e){let t=new Set;for(let n of e.tabBar?.list||[])t.add(Mt(n.pagePath));return Array.from(t).sort()}function Ft(e){return e.length>0?e.join(` |
18
+ `);let i=t.scriptSetup.loc.start.offset+r.start,a=t.scriptSetup.loc.start.offset+r.end;i!==a&&n.overwrite(i,a,`useRootContext()`)}}return{code:n.toString(),sourceMap:n.generateMap()}}shouldRefreshView(e){return A(this.rootView.template)!==A(lt(e))}shouldRefreshVM=e=>{let t=``;this.rootMarco&&(t=A(Ce(`defineRootContext(${this.rootMarco.script})`)));let n=A(Ce(st(e)));return t!==n};applyRoot(e){let t=[],n=``,r=``;return e.template&&(n=ht(this.rootView.template,e.template.content)),t.push(...this.rootView.imports),r=`${this.rootView.script}\n${e.scriptSetup?.content||``}`,{imports:t,script:r,template:n}}};const yt=e=>e();function bt(e,...t){let n=[e,...t],r={...e},i=xt(n),a=St(n),o=Ct(n);return i&&(r.pages=i),a&&(r.subPackages=a),o&&(r.tabBar={...wt(n),list:o}),r}function xt(e){let t=[],n=!1;for(let r of e)r.pages&&(n=!0,t.push(...r.pages));return n?V(t,e=>e.path):void 0}function St(e){let t=new Map,n=!1;for(let r of e)if(r.subPackages){n=!0;for(let e of r.subPackages){let n=t.get(e.root);if(!n){t.set(e.root,{...e,pages:V(e.pages??[],e=>e.path)});continue}t.set(e.root,{...n,...e,pages:V([...n.pages??[],...e.pages??[]],e=>e.path)})}}return n?[...t.values()]:void 0}function Ct(e){let t=[],n=!1;for(let r of e)r.tabBar?.list&&(n=!0,t.push(...r.tabBar.list));return n?V(t,e=>e.pagePath):void 0}function wt(e){let t;for(let n of e)n.tabBar&&(t={...t,...n.tabBar});return t}function V(e,t){let n=new Set,r=[];for(let i=e.length-1;i>=0;i--){let a=e[i],o=t(a);if(o===void 0){r.unshift(a);continue}n.has(o)||(n.add(o),r.unshift(a))}return r}function Tt(e,t){if(!e.includes(`definePageMeta`))return``;if(!t){let{descriptor:t}=(0,x.parse)(e);if(!t.scriptSetup)return``;e=t.scriptSetup.content}let n=Et(e);return e.substring(n.start,n.end+1).trim()}function Et(e){return Se(e,`definePageMeta`)}function Dt(e){return e.replace(/definePageMeta\s*\(\s*\{[\s\S]*?\}\s*\)/g,``).trim()}function Ot(e){if(!e)return{};let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return O(t,{CallExpression(e){let{callee:t,arguments:r}=e.node;if(t.type===`Identifier`&&t.name===`definePageMeta`&&r.length>0){let t=r[0];t.type===`ObjectExpression`&&(n=kt(t),e.stop())}}}),n}function kt(e){let t={};for(let n of e.properties)if(n.type===`ObjectProperty`){let e=At(n.key),r=jt(n.value);e&&(t[e]=r)}return t}function At(e){return e.type===`Identifier`?e.name:e.type===`StringLiteral`?e.value:null}function jt(e){switch(e.type){case`StringLiteral`:return e.value;case`NumericLiteral`:return e.value;case`BooleanLiteral`:return e.value;case`NullLiteral`:return null;case`ArrayExpression`:return e.elements.map(e=>jt(e)).filter(e=>e!==void 0);case`ObjectExpression`:return kt(e);default:return}}function Mt(e){return`'${e.startsWith(`/`)?e:`/${e}`}'`}function Nt(e){let t=new Set;for(let n of e.pages||[])t.add(Mt(n.path));for(let n of e.subPackages||[])for(let e of n.pages||[])t.add(Mt((0,p.join)(n.root,e.path)));return Array.from(t).sort()}function Pt(e){let t=new Set;for(let n of e.tabBar?.list||[])t.add(Mt(n.pagePath));return Array.from(t).sort()}function Ft(e){return e.length>0?e.join(` |
19
19
  `):`string`}function It(e){let t=e.map(e=>({path:e.pagePath,belong:e.pageBelong,...e.pageMeta})),n=[],r=new Map;t.forEach(e=>{if(e.belong===`pages`)n.push(e);else{let t=r.get(e.belong)||[];t.push(e),r.set(e.belong,t)}}),n.sort((e,t)=>{let r=n.find(t=>t.path===e.path)?.type===`home`,i=n.find(e=>e.path===t.path)?.type===`home`;return r&&!i?-1:!r&&i?1:e.path.localeCompare(t.path)});let i={pages:n.map(e=>{let{belong:t,...n}=e;return n})};return r.size>0&&(i.subPackages=Array.from(r.entries()).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({root:e,pages:t.sort((e,t)=>e.path.localeCompare(t.path)).map(e=>{let{belong:t,...n}=e;return n})}))),i}function Lt(e){let t=Nt(e),n=Pt(e);return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`interface NavigateToOptions {`,` url: ${Ft(t)};`,`}`,`interface RedirectToOptions extends NavigateToOptions {}`,``,`interface SwitchTabOptions {`,n.length>0?` url: ${n.join(` |
20
20
  `)};`:``,`}`,``,`type ReLaunchOptions = NavigateToOptions | SwitchTabOptions;`,``,`declare global {`,` interface Uni {`,` navigateTo(options: UniNamespace.NavigateToOptions & NavigateToOptions): void;`,` redirectTo(options: UniNamespace.RedirectToOptions & RedirectToOptions): void;`,` switchTab(options: UniNamespace.SwitchTabOptions & SwitchTabOptions): void;`,` reLaunch(options: UniNamespace.ReLaunchOptions & ReLaunchOptions): void;`,` }`,`}`,``,`export {}`,``].join(`
21
- `)}function Rt(e){if(!e||!e.includes(`import`))return[];let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n=[];return O(t,{ImportDeclaration(t){let r=e.substring(t.node.start,t.node.end);n.push(r)}}),n}function zt(e){if(!e||!e.includes(`import`))return e;let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n=[];O(t,{ImportDeclaration(e){n.push({start:e.node.start,end:e.node.end})}}),n.sort((e,t)=>t.start-e.start);let r=e;for(let e of n)r=r.substring(0,e.start)+r.substring(e.end);return r.trim()}function Bt(e,t){let n=Vt(t),r=Vt(e);for(let[e,t]of r){let r=n.get(e);r?Ht(r,t):n.set(e,t)}return Ut(n)}function Vt(e){let t=new Map;for(let n of e)O((0,h.parse)(n,{sourceType:`module`,plugins:[`typescript`]}),{ImportDeclaration(e){let{node:r}=e,i=r.source.value,a=t.get(i);a||(a={source:i,named:new Set,original:n},t.set(i,a));for(let e of r.specifiers)if(e.type===`ImportSpecifier`){let t=e.imported.type===`Identifier`?e.imported.name:e.imported.value;a.named.add(t)}else e.type===`ImportDefaultSpecifier`?a.defaultImport=e.local.name:e.type===`ImportNamespaceSpecifier`&&(a.namespaceImport=e.local.name)}});return t}function Ht(e,t){for(let n of t.named)e.named.add(n);!e.defaultImport&&t.defaultImport&&(e.defaultImport=t.defaultImport),!e.namespaceImport&&t.namespaceImport&&(e.namespaceImport=t.namespaceImport)}function Ut(e){let t=[];for(let[n,r]of e){if(n.includes(`_fallback_`)){t.push(r.original);continue}let e=[];if(r.defaultImport&&e.push(r.defaultImport),r.namespaceImport&&e.push(`* as ${r.namespaceImport}`),r.named.size>0){let t=Array.from(r.named).sort();e.push(`{ ${t.join(`, `)} }`)}e.length>0?t.push(`import ${e.join(`, `)} from '${n}'`):t.push(`import '${n}'`)}return t}var Wt=class{config;logger;oiyoState;oiyoRoot;oiyoLayout;pages=new Map;pagesConfig={};pagesConfigWatcher;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`ROUTE`),this.oiyoState=t.oiyoState,this.oiyoRoot=t.oiyoRoot,this.oiyoLayout=t.oiyoLayout}get srcDir(){return p.resolve(this.config.rootDir,this.config.srcDir)}get mainPageDir(){return p.resolve(this.srcDir,this.config.dir.mainPackage)}get subPageDirs(){return[...(0,_.globSync)(`*`,{cwd:p.resolve(this.srcDir,`packages`),deep:1,absolute:!0,onlyDirectories:!0,ignore:A(this.config.exclude)}),...this.config.dir.subPackages].map(e=>p.resolve(this.srcDir,e))}get pagesJsonFile(){return p.resolve(this.srcDir,`pages.json`)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return p.resolve(this.declarationDir,`pages.d.ts`)}toPage(e,t){let n=!0,r=this.mainPageDir,i=this.subPageDirs.find(t=>e.startsWith(`${t}/`));i&&(n=!1);let a=n?this.srcDir:i,o=p.relative(a,e),s=p.parse(o),c=s.dir===``?s.name:p.join(s.dir,s.name),l=n?r:i;return{filePath:e,pagePath:c,pageBelong:p.relative(this.srcDir,l),pageMeta:t||{}}}savePage(e){if(!this.pages.has(e.filePath))return this.pages.set(e.filePath,e),!0;let t=this.pages.get(e.filePath),n=JSON.stringify(t.pageMeta)!==JSON.stringify(e.pageMeta);return n&&this.pages.set(e.filePath,e),n}async loadPagesConfig(){try{let{config:e,configFile:t}=await(0,ie.loadConfig)({configFile:`pages.config`,cwd:this.srcDir});this.pagesConfig=e||{}}catch{this.pagesConfig={},this.logger.warn(`无法加载 pages.config.* 配置,已采用空配置`)}return this.pagesConfig}async loadPagesJson(){try{let e=await(0,f.readFile)(this.pagesJsonFile,`utf-8`),t=JSON.parse(e);this.pagesConfig=t}catch(e){this.logger.error(`加载 pages.json 路由文件失败,已跳过现有文件内容,请检查 pages.json 是否存在且格式正确:`,{error:e})}}async scanPages(){await this.loadPagesConfig();let e=[this.mainPageDir,...this.subPageDirs],t=(await Promise.all(e.map(e=>ve({dir:e,pattern:[`**/*.vue`,`**/*.nvue`]})))).flat(2).filter(e=>this.isPage(e));return await Promise.all(t.map(async e=>{let t=await(0,f.readFile)(e,`utf-8`),n={},r=Tt(t);r&&(n=Ot(r));let i=this.toPage(e,n);this.savePage(i)&&this.logger.debug(`通过“扫描模式”录入页面: ${i.pageBelong}&${i.pagePath}`)})),this.pages}isPage(e){return!e.endsWith(`.vue`)&&!e.endsWith(`.nvue`)||[...S.DEFAULT_EXCLUDE,...this.config.exclude||[]].some(t=>p.matchesGlob(e,t))?!1:[this.mainPageDir,...this.subPageDirs].some(t=>e.startsWith(`${t}/`))}enterPage(e){let t=this.toPage(e),n=this.savePage(t);return n&&this.logger.debug(`通过“主动模式”录入页面: ${t.pageBelong}&${t.pagePath}`),n}exitPage(e){if(!this.pages.has(e))return!1;let t=this.pages.get(e),n=this.pages.delete(e);return n&&this.logger.debug(`通过“主动模式”脱离页面: ${t.pageBelong}&${t.pagePath}`),n}resolvePagesJson(e){return bt(It(Array.from(this.pages.values())),e||this.pagesConfig)}writePagesJson(e){try{let t=this.resolvePagesJson(e),n=`${JSON.stringify(t,null,2)}\n`;return M(this.pagesJsonFile,n),!0}catch(e){return this.logger.error(`无法写入 pages.json 路由文件,请检查目标文件权限和内容格式:`,{error:e}),!1}}generateDeclaration(e){return Lt(this.resolvePagesJson(e))}writeDeclaration(e){try{(0,d.mkdirSync)(this.declarationDir,{recursive:!0}),M(this.declarationFile,this.generateDeclaration(e)),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`无法写入 pages.d.ts 页面类型声明,请检查目标文件权限和内容格式:`,{error:e})}return this.declarationFile}async watchPagesConfig(e){if(this.pagesConfigWatcher)return;let t=await(0,ie.watchConfig)({configFile:`pages.config`,cwd:this.srcDir,acceptHMR({getDiff:e}){return e().length===0},onWatch:e=>{},onUpdate:({newConfig:t})=>{this.pagesConfig=t.config||{},e&&Promise.resolve(e()).catch(e=>{this.logger.error(`无法触发 pages.config.* 配置更新回调,页面配置已更新,但后续回调未完成`,{error:e})})}});this.pagesConfig=t.config||this.pagesConfig,this.pagesConfigWatcher=t}async unwatchPagesConfig(){this.pagesConfigWatcher&&=(await this.pagesConfigWatcher.unwatch(),void 0)}async transformPage(e,t){if(!this.oiyoRoot||!this.oiyoLayout)throw Error(`[oiyo] Dependencies are missing; please contact skiyee(319619193@qq.com) to fix them.`);let{descriptor:n}=(0,x.parse)(e),r=new b.default(e);if(!n.template?.content)return{code:r.toString(),sourceMap:r.generateMap()};if(n.scriptSetup){let e=Ot(n.scriptSetup.content),r=this.toPage(t,e);this.savePage(r)&&(this.writePagesJson()&&this.writeDeclaration(),await new Promise(e=>setTimeout(e,100)))}let i=this.oiyoRoot.applyRoot(n),a=[...i.imports],o=i.template,s=i.script,c={};n.scriptSetup&&(c=this.pages.get(t)?.pageMeta||{},s=Dt(s));let l=this.oiyoLayout.applyLayout(c.layout,o);if(o=l.template,a.push(...l.imports),r.overwrite(n.template.loc.start.offset,n.template.loc.end.offset,o),n.scriptSetup){let e=Rt(n.scriptSetup.content);a=Bt(a,e),s=zt(s),r.overwrite(n.scriptSetup.loc.start.offset,n.scriptSetup.loc.end.offset,`${a.join(`
21
+ `)}function Rt(e){if(!e||!e.includes(`import`))return[];let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n=[];return O(t,{ImportDeclaration(t){let r=e.substring(t.node.start,t.node.end);n.push(r)}}),n}function zt(e){if(!e||!e.includes(`import`))return e;let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n=[];O(t,{ImportDeclaration(e){n.push({start:e.node.start,end:e.node.end})}}),n.sort((e,t)=>t.start-e.start);let r=e;for(let e of n)r=r.substring(0,e.start)+r.substring(e.end);return r.trim()}function Bt(e,t){let n=Vt(t),r=Vt(e);for(let[e,t]of r){let r=n.get(e);r?Ht(r,t):n.set(e,t)}return Ut(n)}function Vt(e){let t=new Map;for(let n of e)O((0,h.parse)(n,{sourceType:`module`,plugins:[`typescript`]}),{ImportDeclaration(e){let{node:r}=e,i=r.source.value,a=t.get(i);a||(a={source:i,named:new Set,original:n},t.set(i,a));for(let e of r.specifiers)if(e.type===`ImportSpecifier`){let t=e.imported.type===`Identifier`?e.imported.name:e.imported.value;a.named.add(t)}else e.type===`ImportDefaultSpecifier`?a.defaultImport=e.local.name:e.type===`ImportNamespaceSpecifier`&&(a.namespaceImport=e.local.name)}});return t}function Ht(e,t){for(let n of t.named)e.named.add(n);!e.defaultImport&&t.defaultImport&&(e.defaultImport=t.defaultImport),!e.namespaceImport&&t.namespaceImport&&(e.namespaceImport=t.namespaceImport)}function Ut(e){let t=[];for(let[n,r]of e){if(n.includes(`_fallback_`)){t.push(r.original);continue}let e=[];if(r.defaultImport&&e.push(r.defaultImport),r.namespaceImport&&e.push(`* as ${r.namespaceImport}`),r.named.size>0){let t=Array.from(r.named).sort();e.push(`{ ${t.join(`, `)} }`)}e.length>0?t.push(`import ${e.join(`, `)} from '${n}'`):t.push(`import '${n}'`)}return t}var Wt=class{config;logger;oiyoState;oiyoRoot;oiyoLayout;pages=new Map;pagesConfig={};pagesConfigWatcher;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`ROUTE`),this.oiyoState=t.oiyoState,this.oiyoRoot=t.oiyoRoot,this.oiyoLayout=t.oiyoLayout}get srcDir(){return p.resolve(this.config.rootDir,this.config.srcDir)}get mainPageDir(){return p.resolve(this.srcDir,this.config.dir.mainPackage)}get subPageDirs(){return[...(0,_.globSync)(`*`,{cwd:p.resolve(this.srcDir,`packages`),deep:1,absolute:!0,onlyDirectories:!0,ignore:k(this.config.exclude)}),...this.config.dir.subPackages].map(e=>p.resolve(this.srcDir,e))}get pagesJsonFile(){return p.resolve(this.srcDir,`pages.json`)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return p.resolve(this.declarationDir,`pages.d.ts`)}toPage(e,t){let n=!0,r=this.mainPageDir,i=this.subPageDirs.find(t=>e.startsWith(`${t}/`));i&&(n=!1);let a=n?this.srcDir:i,o=p.relative(a,e),s=p.parse(o),c=s.dir===``?s.name:p.join(s.dir,s.name),l=n?r:i;return{filePath:e,pagePath:c,pageBelong:p.relative(this.srcDir,l),pageMeta:t||{}}}savePage(e){if(!this.pages.has(e.filePath))return this.pages.set(e.filePath,e),!0;let t=this.pages.get(e.filePath),n=JSON.stringify(t.pageMeta)!==JSON.stringify(e.pageMeta);return n&&this.pages.set(e.filePath,e),n}async loadPagesConfig(){try{let{config:e,configFile:t}=await(0,ie.loadConfig)({configFile:`pages.config`,cwd:this.srcDir});this.pagesConfig=e||{}}catch{this.pagesConfig={},this.logger.warn(`无法加载 pages.config.* 配置,已采用空配置`)}return this.pagesConfig}async loadPagesJson(){try{let e=await(0,f.readFile)(this.pagesJsonFile,`utf-8`),t=JSON.parse(e);this.pagesConfig=t}catch(e){this.logger.error(`加载 pages.json 路由文件失败,已跳过现有文件内容,请检查 pages.json 是否存在且格式正确:`,{error:e})}}async scanPages(){await this.loadPagesConfig();let e=[this.mainPageDir,...this.subPageDirs],t=(await Promise.all(e.map(e=>ye({dir:e,pattern:[`**/*.vue`,`**/*.nvue`]})))).flat(2).filter(e=>this.isPage(e));return await Promise.all(t.map(async e=>{let t=await(0,f.readFile)(e,`utf-8`),n={},r=Tt(t);r&&(n=Ot(r));let i=this.toPage(e,n);this.savePage(i)&&this.logger.debug(`通过“扫描模式”录入页面: ${i.pageBelong}&${i.pagePath}`)})),this.pages}isPage(e){return!e.endsWith(`.vue`)&&!e.endsWith(`.nvue`)||[...S.DEFAULT_EXCLUDE,...this.config.exclude||[]].some(t=>p.matchesGlob(e,t))?!1:[this.mainPageDir,...this.subPageDirs].some(t=>e.startsWith(`${t}/`))}enterPage(e){let t=this.toPage(e),n=this.savePage(t);return n&&this.logger.debug(`通过“主动模式”录入页面: ${t.pageBelong}&${t.pagePath}`),n}exitPage(e){if(!this.pages.has(e))return!1;let t=this.pages.get(e),n=this.pages.delete(e);return n&&this.logger.debug(`通过“主动模式”脱离页面: ${t.pageBelong}&${t.pagePath}`),n}resolvePagesJson(e){return bt(It(Array.from(this.pages.values())),e||this.pagesConfig)}writePagesJson(e){try{let t=this.resolvePagesJson(e),n=`${JSON.stringify(t,null,2)}\n`;return j(this.pagesJsonFile,n),!0}catch(e){return this.logger.error(`无法写入 pages.json 路由文件,请检查目标文件权限和内容格式:`,{error:e}),!1}}generateDeclaration(e){return Lt(this.resolvePagesJson(e))}writeDeclaration(e){try{(0,d.mkdirSync)(this.declarationDir,{recursive:!0}),j(this.declarationFile,this.generateDeclaration(e)),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`无法写入 pages.d.ts 页面类型声明,请检查目标文件权限和内容格式:`,{error:e})}return this.declarationFile}async watchPagesConfig(e){if(this.pagesConfigWatcher)return;let t=await(0,ie.watchConfig)({configFile:`pages.config`,cwd:this.srcDir,acceptHMR({getDiff:e}){return e().length===0},onWatch:e=>{},onUpdate:({newConfig:t})=>{this.pagesConfig=t.config||{},e&&Promise.resolve(e()).catch(e=>{this.logger.error(`无法触发 pages.config.* 配置更新回调,页面配置已更新,但后续回调未完成`,{error:e})})}});this.pagesConfig=t.config||this.pagesConfig,this.pagesConfigWatcher=t}async unwatchPagesConfig(){this.pagesConfigWatcher&&=(await this.pagesConfigWatcher.unwatch(),void 0)}async transformPage(e,t){if(!this.oiyoRoot||!this.oiyoLayout)throw Error(`[oiyo] Dependencies are missing; please contact skiyee(319619193@qq.com) to fix them.`);let{descriptor:n}=(0,x.parse)(e),r=new b.default(e);if(!n.template?.content)return{code:r.toString(),sourceMap:r.generateMap()};if(n.scriptSetup){let e=Ot(n.scriptSetup.content),r=this.toPage(t,e);this.savePage(r)&&(this.writePagesJson()&&this.writeDeclaration(),await new Promise(e=>setTimeout(e,100)))}let i=this.oiyoRoot.applyRoot(n),a=[...i.imports],o=i.template,s=i.script,c={};n.scriptSetup&&(c=this.pages.get(t)?.pageMeta||{},s=Dt(s));let l=this.oiyoLayout.applyLayout(c.layout,o);if(o=l.template,a.push(...l.imports),r.overwrite(n.template.loc.start.offset,n.template.loc.end.offset,o),n.scriptSetup){let e=Rt(n.scriptSetup.content);a=Bt(a,e),s=zt(s),r.overwrite(n.scriptSetup.loc.start.offset,n.scriptSetup.loc.end.offset,`${a.join(`
22
22
  `)}\n${s}`)}else if(s||a.length>0){let e=[`<script setup>`,...a,s,`<\/script>`].filter(Boolean).join(`
23
23
  `);r.appendRight(n.template.loc.end.offset+11,`\n\n${e}`)}return{code:r.toString(),sourceMap:r.generateMap()}}};const Gt=e=>{},Kt=(0,re.defineComponent)({name:`OiyoPage`}),H={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},qt={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:H.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(qt);const Jt=`READDIRP_RECURSIVE_ERROR`,Yt=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,Jt]),Xt=[H.DIR_TYPE,H.EVERYTHING_TYPE,H.FILE_DIR_TYPE,H.FILE_TYPE],Zt=new Set([H.DIR_TYPE,H.EVERYTHING_TYPE,H.FILE_DIR_TYPE]),Qt=new Set([H.EVERYTHING_TYPE,H.FILE_DIR_TYPE,H.FILE_TYPE]),$t=e=>Yt.has(e.code),en=process.platform===`win32`,tn=e=>!0,nn=e=>{if(e===void 0)return tn;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return tn};var rn=class extends oe.Readable{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...qt,...e},{root:n,type:r}=t;this._fileFilter=nn(t.fileFilter),this._directoryFilter=nn(t.directoryFilter);let i=t.lstat?f.lstat:f.stat;en?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??qt.depth,this._wantsDir=r?Zt.has(r):!1,this._wantsFile=r?Qt.has(r):!1,this._wantsEverything=r===H.EVERYTHING_TYPE,this._root=(0,y.resolve)(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await(0,f.readdir)(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=(0,y.resolve)((0,y.join)(t,r));n={path:(0,y.relative)(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(e){this._onError(e);return}return n}_onError(e){$t(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return``;let t=e[this._statsProp];if(t.isFile())return`file`;if(t.isDirectory())return`directory`;if(t&&t.isSymbolicLink()){let t=e.fullPath;try{let e=await(0,f.realpath)(t),n=await(0,f.lstat)(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===y.sep){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=Jt,this._onError(n)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function an(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=H.FILE_DIR_TYPE),n&&(t.type=n),!e)throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!Xt.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${Xt.join(`, `)}`);return t.root=e,new rn(t)}const on=()=>{},U=process.platform,sn=U===`win32`,cn=U===`darwin`,ln=U===`linux`,un=U===`freebsd`,dn=(0,se.type)()===`OS400`,W={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},G=W,fn={lstat:w.lstat,stat:w.stat},K=`listeners`,q=`errHandlers`,J=`rawEmitters`,pn=[K,q,J],mn=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),hn=e=>mn.has(E.extname(e).slice(1).toLowerCase()),gn=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},Y=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},_n=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},X=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},vn=e=>e instanceof Set?e.size===0:!e,Z=new Map;function yn(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&Q(E.resolve(e,r),K,E.join(e,r))};try{return(0,C.watch)(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const Q=(e,t,n,r,i)=>{let a=Z.get(e);a&&gn(a[t],e=>{e(n,r,i)})},bn=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=Z.get(t),c;if(!n.persistent)return c=yn(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)Y(s,K,i),Y(s,q,a),Y(s,J,o);else{if(c=yn(e,n,Q.bind(null,t,K),a,Q.bind(null,t,J)),!c)return;c.on(G.ERROR,async n=>{let r=Q.bind(null,t,q);if(s&&(s.watcherUnusable=!0),sn&&n.code===`EPERM`)try{await(await(0,w.open)(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},Z.set(t,s)}return()=>{X(s,K,i),X(s,q,a),X(s,J,o),vn(s.listeners)&&(s.watcher.close(),Z.delete(t),pn.forEach(_n(s)),s.watcher=void 0,Object.freeze(s))}},xn=new Map,Sn=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=xn.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&((0,C.unwatchFile)(t),o=void 0),o?(Y(o,K,i),Y(o,J,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:(0,C.watchFile)(t,n,(n,r)=>{gn(o.rawEmitters,e=>{e(G.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&gn(o.listeners,t=>t(e,n))})},xn.set(t,o)),()=>{X(o,K,i),X(o,J,a),vn(o.listeners)&&(xn.delete(t),(0,C.unwatchFile)(t),o.options=o.watcher=void 0,Object.freeze(o))}};var Cn=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=E.dirname(e),i=E.basename(e);this.fsw._getWatchedDir(r).add(i);let a=E.resolve(e),o={persistent:n.persistent};t||=on;let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&hn(i)?n.binaryInterval:n.interval,s=Sn(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=bn(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=E.dirname(e),i=E.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(`watch`,e,5)){if(!n||n.mtimeMs===0)try{let n=await(0,w.stat)(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(G.CHANGE,e,n),(cn||ln||un)&&o.ino!==n.ino){this.fsw._closeFile(t),o=n;let r=this._watchWithNodeFs(e,s);r&&this.fsw._addPathCloser(t,r)}else o=n}catch{this.fsw._remove(r,i)}else if(a.has(i)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==o.mtimeMs)&&this.fsw._emit(G.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(G.ADD,e,0))return;this.fsw._emit(G.ADD,e,t)}return c}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await(0,w.realpath)(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==t&&(this.fsw._symlinkPaths.set(i,t),this.fsw._emit(G.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(G.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){if(e=E.join(e,``),o=this.fsw._throttle(`readdir`,e,1e3),!o)return;let s=this.fsw._getWatchedDir(n.path),c=new Set,l=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(l)return l.on(`data`,async o=>{if(this.fsw.closed){l=void 0;return}let u=o.path,d=E.join(e,u);if(c.add(u),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,e,d,u))){if(this.fsw.closed){l=void 0;return}(u===r||!r&&!s.has(u))&&(this.fsw._incrReadyCount(),d=E.join(i,E.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(G.ERROR,this._boundHandleError),new Promise((t,u)=>{if(!l)return u();l.once(`end`,()=>{if(this.fsw.closed){l=void 0;return}let u=o?o.clear():!1;t(void 0),s.getChildren().filter(t=>t!==e&&!c.has(t)).forEach(t=>{this.fsw._remove(e,t)}),l=void 0,u&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let s=this.fsw._getWatchedDir(E.dirname(e)),c=s.has(E.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(G.ADD_DIR,e,t),s.add(E.basename(e)),this.fsw._getWatchedDir(e);let l,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,void 0),this.fsw.closed))return;l=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,a,i,e,r,void 0)})}return l}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=e=>n.filterPath(e),o.filterDir=e=>n.filterDir(e));try{let n=await fn[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let s=this.fsw.options.followSymlinks,c;if(n.isDirectory()){let a=E.resolve(e),l=s?await(0,w.realpath)(e):e;if(this.fsw.closed||(c=await this._handleDir(o.watchPath,n,t,r,i,o,l),this.fsw.closed))return;a!==l&&l!==void 0&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let i=s?await(0,w.realpath)(e):e;if(this.fsw.closed)return;let a=E.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(G.ADD,o.watchPath,n),c=await this._handleDir(a,n,t,r,e,o,i),this.fsw.closed)return;i!==void 0&&this.fsw._symlinkPaths.set(E.resolve(e),i)}else c=this._handleFile(o.watchPath,n,t);return a(),c&&this.fsw._addPathCloser(e,c),!1}catch(t){if(this.fsw._handleError(t))return a(),e}}};
24
24
  /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
25
- const wn=/\\/g,Tn=/\/\//,En=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Dn=/^\.[/\\]/;function $(e){return Array.isArray(e)?e:[e]}const On=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function kn(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=T.relative(e.path,t);return n?!n.startsWith(`..`)&&!T.isAbsolute(n):!1}return!1}:()=>!1}function An(e){if(typeof e!=`string`)throw Error(`string expected`);e=T.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;e.startsWith(`//`)&&(t=!0);let n=/\/\//;for(;e.match(n);)e=e.replace(n,`/`);return t&&(e=`/`+e),e}function jn(e,t,n){let r=An(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function Mn(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=$(e).map(e=>kn(e));return t==null?(e,t)=>jn(n,e,t):jn(n,t)}const Nn=e=>{let t=$(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Fn)},Pn=e=>{let t=e.replace(wn,`/`),n=!1;for(t.startsWith(`//`)&&(n=!0);t.match(Tn);)t=t.replace(Tn,`/`);return n&&(t=`/`+t),t},Fn=e=>Pn(T.normalize(Pn(e))),In=(e=``)=>t=>typeof t==`string`?Fn(T.isAbsolute(t)?t:T.join(e,t)):t,Ln=(e,t)=>T.isAbsolute(e)?e:T.join(t,e),Rn=Object.freeze(new Set);var zn=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==`.`&&e!==`..`&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await(0,w.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(T.dirname(n),T.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=on,this.items=Rn,Object.freeze(this)}},Bn=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(Dn,``),this.watchPath=r,this.fullWatchPath=T.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?`stat`:`lstat`}entryPath(e){return T.join(this.watchPath,T.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Vn=class extends ae.EventEmitter{constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?$(e.ignored):$([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};dn&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=on,this._readyEmitted=!0,process.nextTick(()=>this.emit(W.READY)))},this._emitRaw=(...e)=>this.emit(W.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new Cn(this),Object.freeze(r)}_addIgnoredPath(e){if(On(e)){for(let t of this._ignoredPaths)if(On(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)On(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=Nn(e);return r&&(i=i.map(e=>Ln(e,r))),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||=0,this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(T.dirname(e),T.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Nn(e),{cwd:n}=this.options;return t.forEach(e=>{!T.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=T.join(n,e)),e=T.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=(this.options.cwd?T.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==W.ERROR&&this.emit(W.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;sn&&(t=T.normalize(t)),r.cwd&&(t=T.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===W.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(W.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===W.ADD&&this._pendingUnlinks.has(t)&&(e=W.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===W.ADD||e===W.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=W.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))}),this;if(e===W.CHANGE&&!this._throttle(W.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===W.ADD||e===W.ADD_DIR||e===W.CHANGE)){let e=r.cwd?T.join(r.cwd,t):t,n;try{n=await(0,w.stat)(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(W.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!T.isAbsolute(e)&&(s=T.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){(0,C.stat)(s,(i,s)=>{if(i||!l.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(l.get(e).lastChange=c),c-l.get(e).lastChange>=t?(l.delete(e),r(void 0,s)):o=setTimeout(u,a,s)})}l.has(e)||(l.set(e,{lastChange:c,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(u,a))}_isIgnored(e,t){if(this.options.atomic&&En.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(In(e)),n=[...[...this._ignoredPaths].map(In(e)),...t];this._userIgnored=Mn(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Bn(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=T.resolve(e);return this._watched.has(t)||this._watched.set(t,new zn(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=T.join(e,t),i=T.resolve(r);if(n??=this._watched.has(r)||this._watched.has(i),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(e=>this._remove(r,e));let a=this._getWatchedDir(e),o=a.has(t);a.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let s=r;if(this.options.cwd&&(s=T.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===W.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?W.UNLINK_DIR:W.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=T.dirname(e);this._getWatchedDir(t).remove(T.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n=an(e,{type:W.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once(`close`,()=>{n=void 0}),n.once(`end`,()=>{n&&=(this._streams.delete(n),void 0)}),n}};function Hn(e,t={}){let n=new Vn(t);return n.add(e),n}function Un(){let e,t=!1,n=`build`;return[{name:`oiyo:build`,apply:`build`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`VITE`),n=t.command},async buildStart(){if(t)return;await Promise.all([e.api.scanApis(),e.component.scanComponents(),e.layout.scanLayouts(),e.route.scanPages()]),e.state.canReuseGeneratedState()||(e.api.writeDeclaration(),e.component.writeDeclaration(),e.layout.writeDeclaration(),e.route.writePagesJson()&&e.route.writeDeclaration(),e.state.markGenerated());let r=async t=>{let n=(0,p.normalize)(t);e.route.isPage(n)?e.route.enterPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.enterComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?await e.api.enterApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.enterLayout(n)&&e.layout.writeDeclaration()};n===`serve`&&Hn(e.state.srcDir,{ignoreInitial:!0}).on(`add`,e=>void r(e));let i=t=>{let n=(0,p.normalize)(t);e.route.isPage(n)?e.route.exitPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.exitComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?e.api.exitApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.exitLayout(n)&&e.layout.writeDeclaration()};n===`serve`&&Hn(e.state.srcDir,{ignoreInitial:!0}).on(`unlink`,e=>void i(e));let a=async t=>{e.api.isApi(t)&&await e.api.enterApi(t)&&e.api.writeDeclaration()};n===`serve`&&Hn(e.state.srcDir,{ignoreInitial:!0}).on(`change`,e=>void a(e)),t=!0},async transform(t,n){let r=(0,p.normalize)(n);if(!r.startsWith(`${(0,p.normalize)(e.config.rootDir)}/`))return null;let i=t,a=null;return[`.ts`,`.js`].some(e=>r.endsWith(e))?(a=e.api.applyApis(t,r),i=a.code):[`.vue`,`.nvue`].some(e=>r.endsWith(e))&&(a=e.component.applyComponents(t,r,{withApis:!0}),i=a.code),e.root.isRootPath(r)?(e.root.parseRoot(i),e.root.transformRoot(i)):e.route.isPage(r)?(this.addWatchFile(e.root.rootPath),await e.route.transformPage(i,n)):a},resolveId(e){if(e===`virtual:oiyo-root-context`)return B},load(t){if(t===B)return e.root.rootVM||`export function useRootContext() {return {}}`},async closeBundle(){await e.route.unwatchPagesConfig()}}]}var Wn=`0.3.0-beta.1`,Gn=class{config;constructor(e){this.config=e}get stateDir(){return(0,p.resolve)(this.config.rootDir,`.oiyo`)}get typesDir(){return(0,p.resolve)(this.stateDir,`types`)}get srcDir(){return(0,p.resolve)(this.config.rootDir,this.config.srcDir)}get declarationEntryPath(){return(0,p.resolve)(this.stateDir,`oiyo.d.ts`)}get tsconfigPath(){return(0,p.resolve)(this.stateDir,`tsconfig.json`)}get metadataPath(){return(0,p.resolve)(this.stateDir,`oiyo.json`)}get declarationPaths(){return[this.declarationEntryPath,this.tsconfigPath,(0,p.resolve)(this.typesDir,`apis.d.ts`),(0,p.resolve)(this.typesDir,`components.d.ts`),(0,p.resolve)(this.typesDir,`layouts.d.ts`),(0,p.resolve)(this.typesDir,`pages.d.ts`)]}relativeToState(e){return(0,p.normalize)((0,p.relative)(this.stateDir,e))}stringifyJson(e){return`${JSON.stringify(e,null,2)}\n`}serializeMetadataInput(){return JSON.stringify({rootDir:(0,p.normalize)(this.config.rootDir||``),srcDir:this.config.srcDir||``,dir:this.config.dir||{},scan:this.config.scan||{},exclude:this.config.exclude||[]})}generateMetadataHash(){return j(`${Wn}:${this.serializeMetadataInput()}`,16)}generateMetadata(){return{hash:this.generateMetadataHash(),project:{rootDir:(0,p.normalize)(this.config.rootDir||``)},versions:{oiyo:Wn}}}readMetadata(){if(!(0,d.existsSync)(this.metadataPath))return null;try{return JSON.parse((0,d.readFileSync)(this.metadataPath,`utf-8`))}catch{return null}}writeMetadata(){(0,d.mkdirSync)(this.stateDir,{recursive:!0});let e=this.generateMetadata();return M(this.metadataPath,this.stringifyJson(e)),e}canReuseGeneratedState(){let e=this.readMetadata();return!e||e.project.rootDir!==(0,p.normalize)(this.config.rootDir||``)||e.versions.oiyo!==Wn||e.hash!==this.generateMetadataHash()?!1:this.declarationPaths.every(e=>(0,d.existsSync)(e))}generateDeclarationEntry(){return[`// Generated by oiyo`,``,`/// <reference types="@skiyee/oiyo/types" />`,`/// <reference path="./types/apis.d.ts" />`,`/// <reference path="./types/components.d.ts" />`,`/// <reference path="./types/layouts.d.ts" />`,`/// <reference path="./types/pages.d.ts" />`,``,`export {}`,``].join(`
26
- `)}generateTsconfig(){let e=this.relativeToState(this.config.rootDir),t=this.relativeToState(this.srcDir),n=this.relativeToState(this.stateDir);return this.stringifyJson({compilerOptions:{paths:{"~/*":[(0,p.join)(t,`*`)],"~~/*":[(0,p.join)(e,`*`)],"@/*":[(0,p.join)(t,`*`)],"@@/*":[(0,p.join)(e,`*`)]},types:[],esModuleInterop:!0,skipLibCheck:!0,target:`ES2018`,allowJs:!0,resolveJsonModule:!0,moduleDetection:`force`,isolatedModules:!0,verbatimModuleSyntax:!0,allowArbitraryExtensions:!0,strict:!0,noUncheckedIndexedAccess:!0,forceConsistentCasingInFileNames:!0,noImplicitOverride:!0,module:`preserve`,noEmit:!0,lib:[`ESNext`,`DOM`,`DOM.Iterable`],moduleResolution:`Bundler`,useDefineForClassFields:!0},include:[(0,p.join)(n,`oiyo.d.ts`),(0,p.join)(t,`**/*`),(0,p.join)(e,`*.d.ts`),(0,p.join)(e,`oiyo.config.*`),(0,p.join)(e,`vite.config.*`),(0,p.join)(e,`vitest.config.*`)],exclude:[(0,p.join)(t,`pages.config.*`),(0,p.join)(e,`dist`),(0,p.join)(e,`node_modules`)]})}writeTsconfig(){return(0,d.mkdirSync)(this.stateDir,{recursive:!0}),M(this.tsconfigPath,this.generateTsconfig()),this.tsconfigPath}writeDeclarationEntry(){return(0,d.mkdirSync)(this.stateDir,{recursive:!0}),M(this.declarationEntryPath,this.generateDeclarationEntry()),this.writeTsconfig(),this.declarationEntryPath}ensureDeclarationEntry(){return(0,d.existsSync)(this.tsconfigPath)||this.writeTsconfig(),(0,d.existsSync)(this.declarationEntryPath)?this.declarationEntryPath:this.writeDeclarationEntry()}markGenerated(){return this.writeMetadata()}};function Kn(e){let t=(0,S.resolveOiyoConfig)(e),n=he();n.withScope(`CONFIG`);let r=new Gn(t),i=new qe(t,{logger:n,oiyoState:r}),a=new Qe(t,{logger:n,oiyoState:r,oiyoApi:i}),o=new vt(t,{logger:n}),s=new it(t,{logger:n,oiyoState:r});return{logger:n,config:t,api:i,component:a,layout:s,state:r,route:new Wt(t,{logger:n,oiyoState:r,oiyoRoot:o,oiyoLayout:s}),root:o}}function qn(e){return[{name:`oiyo:deps`,enforce:`pre`,async config(t){let{config:n}=await(0,ie.loadConfig)({name:`oiyo`,cwd:t.root}),r=Kn(n||e);return(0,ce.defu)(t,{oiyo:r,resolve:{alias:{"~":y.default.resolve(r.config.rootDir,r.config.srcDir),"@":y.default.resolve(r.config.rootDir,r.config.srcDir),"@@":y.default.normalize(r.config.rootDir),"~~":y.default.normalize(r.config.rootDir)}},optimizeDeps:{exclude:[`@skiyee/oiyo`]}})}}]}function Jn(){let e;return[{name:`oiyo:serve`,apply:`serve`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`VITE`),e.logger.withScope(`HMR`)},async buildStart(){await Promise.all([e.api.scanApis(),e.component.scanComponents(),e.route.scanPages(),e.layout.scanLayouts()]),e.state.canReuseGeneratedState()||(e.api.writeDeclaration(),e.component.writeDeclaration(),e.route.writePagesJson()&&e.route.writeDeclaration(),e.layout.writeDeclaration(),e.state.markGenerated())},configureServer(t){e.route.watchPagesConfig(()=>{e.route.writePagesJson()&&e.route.writeDeclaration(),t.hot.send({type:`full-reload`})});let n=async t=>{let n=(0,p.normalize)(t);e.route.isPage(n)?e.route.enterPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.enterComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?await e.api.enterApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.enterLayout(n)&&e.layout.writeDeclaration()};t.watcher.on(`add`,e=>void n(e));let r=t=>{let n=(0,p.normalize)(t);e.route.isPage(n)?e.route.exitPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.exitComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?e.api.exitApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.exitLayout(n)&&e.layout.writeDeclaration()};t.watcher.on(`unlink`,e=>void r(e));let i=async t=>{e.api.isApi(t)&&await e.api.enterApi(t)&&e.api.writeDeclaration()};t.watcher.on(`change`,e=>void i(e))},async transform(t,n){let r=(0,p.normalize)(n);if(!r.startsWith(`${(0,p.normalize)(e.config.rootDir)}/`))return null;let i=t,a=null;return[`.ts`,`.js`].some(e=>r.endsWith(e))?(a=e.api.applyApis(t,r),i=a.code):[`.vue`,`.nvue`].some(e=>r.endsWith(e))&&(a=e.component.applyComponents(t,r,{withApis:!0}),i=a.code),e.root.isRootPath(r)?(e.root.parseRoot(i),e.root.transformRoot(i)):e.route.isPage(r)?(this.addWatchFile(e.root.rootPath),await e.route.transformPage(i,n)):a},resolveId(e){if(e===`virtual:oiyo-root-context`)return B},load(t){if(t===B)return e.root.rootVM||`export function useRootContext() {return {}}`},async handleHotUpdate({file:t,server:n,read:r}){if(e.root.isRootPath(t)){let t=await r(),i=!1;if(e.root.shouldRefreshView(t)&&(i=!0),e.root.shouldRefreshVM(t)){let e=n.moduleGraph.getModuleById(B);e&&(n.moduleGraph.invalidateModule(e),i=!0)}if(i){n.hot.send({type:`full-reload`});return}}},async closeBundle(){await e.route.unwatchPagesConfig()}}]}function Yn(e={}){return[...qn(e),...Jn(),...Un()]}exports.LogLevels=D,exports.OiyoCorePlugin=Yn,exports.OiyoLayout=at,exports.OiyoModApi=qe,exports.OiyoModComponent=Qe,exports.OiyoModLayout=it,exports.OiyoModRoot=vt,exports.OiyoModRoute=Wt,exports.OiyoPage=Kt,exports.OiyoState=Gn,exports.RESOLVED_VIRTUAL_ROOT_CONTEXT_ID=B,exports.VIRTUAL_ROOT_CONTEXT_ID=gt,exports.createLogger=he,exports.definePageMeta=Gt,exports.defineRootContext=yt;
25
+ const wn=/\\/g,Tn=/\/\//,En=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Dn=/^\.[/\\]/;function $(e){return Array.isArray(e)?e:[e]}const On=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function kn(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=T.relative(e.path,t);return n?!n.startsWith(`..`)&&!T.isAbsolute(n):!1}return!1}:()=>!1}function An(e){if(typeof e!=`string`)throw Error(`string expected`);e=T.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;e.startsWith(`//`)&&(t=!0);let n=/\/\//;for(;e.match(n);)e=e.replace(n,`/`);return t&&(e=`/`+e),e}function jn(e,t,n){let r=An(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function Mn(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=$(e).map(e=>kn(e));return t==null?(e,t)=>jn(n,e,t):jn(n,t)}const Nn=e=>{let t=$(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Fn)},Pn=e=>{let t=e.replace(wn,`/`),n=!1;for(t.startsWith(`//`)&&(n=!0);t.match(Tn);)t=t.replace(Tn,`/`);return n&&(t=`/`+t),t},Fn=e=>Pn(T.normalize(Pn(e))),In=(e=``)=>t=>typeof t==`string`?Fn(T.isAbsolute(t)?t:T.join(e,t)):t,Ln=(e,t)=>T.isAbsolute(e)?e:T.join(t,e),Rn=Object.freeze(new Set);var zn=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==`.`&&e!==`..`&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await(0,w.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(T.dirname(n),T.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=on,this.items=Rn,Object.freeze(this)}},Bn=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(Dn,``),this.watchPath=r,this.fullWatchPath=T.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?`stat`:`lstat`}entryPath(e){return T.join(this.watchPath,T.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Vn=class extends ae.EventEmitter{constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?$(e.ignored):$([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};dn&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=on,this._readyEmitted=!0,process.nextTick(()=>this.emit(W.READY)))},this._emitRaw=(...e)=>this.emit(W.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new Cn(this),Object.freeze(r)}_addIgnoredPath(e){if(On(e)){for(let t of this._ignoredPaths)if(On(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)On(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=Nn(e);return r&&(i=i.map(e=>Ln(e,r))),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||=0,this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(T.dirname(e),T.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Nn(e),{cwd:n}=this.options;return t.forEach(e=>{!T.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=T.join(n,e)),e=T.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=(this.options.cwd?T.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==W.ERROR&&this.emit(W.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;sn&&(t=T.normalize(t)),r.cwd&&(t=T.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===W.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(W.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===W.ADD&&this._pendingUnlinks.has(t)&&(e=W.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===W.ADD||e===W.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=W.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))}),this;if(e===W.CHANGE&&!this._throttle(W.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===W.ADD||e===W.ADD_DIR||e===W.CHANGE)){let e=r.cwd?T.join(r.cwd,t):t,n;try{n=await(0,w.stat)(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(W.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!T.isAbsolute(e)&&(s=T.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){(0,C.stat)(s,(i,s)=>{if(i||!l.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(l.get(e).lastChange=c),c-l.get(e).lastChange>=t?(l.delete(e),r(void 0,s)):o=setTimeout(u,a,s)})}l.has(e)||(l.set(e,{lastChange:c,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(u,a))}_isIgnored(e,t){if(this.options.atomic&&En.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(In(e)),n=[...[...this._ignoredPaths].map(In(e)),...t];this._userIgnored=Mn(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Bn(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=T.resolve(e);return this._watched.has(t)||this._watched.set(t,new zn(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=T.join(e,t),i=T.resolve(r);if(n??=this._watched.has(r)||this._watched.has(i),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(e=>this._remove(r,e));let a=this._getWatchedDir(e),o=a.has(t);a.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let s=r;if(this.options.cwd&&(s=T.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===W.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?W.UNLINK_DIR:W.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=T.dirname(e);this._getWatchedDir(t).remove(T.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n=an(e,{type:W.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once(`close`,()=>{n=void 0}),n.once(`end`,()=>{n&&=(this._streams.delete(n),void 0)}),n}};function Hn(e,t={}){let n=new Vn(t);return n.add(e),n}function Un(){let e,t=!1,n=`build`;return[{name:`oiyo:build`,apply:`build`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`VITE`),n=t.command},async buildStart(){if(t)return;await Promise.all([e.api.scanApis(),e.component.scanComponents(),e.layout.scanLayouts(),e.route.scanPages()]),e.state.canReuseGeneratedState()||(e.api.writeDeclaration(),e.component.writeDeclaration(),e.layout.writeDeclaration(),e.route.writePagesJson()&&e.route.writeDeclaration(),e.state.markGenerated());let r=async t=>{let n=p.normalize(t);e.route.isPage(n)?e.route.enterPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.enterComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?await e.api.enterApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.enterLayout(n)&&e.layout.writeDeclaration()};n===`serve`&&Hn(e.state.srcDir,{ignoreInitial:!0}).on(`add`,e=>void r(e));let i=t=>{let n=p.normalize(t);e.route.isPage(n)?e.route.exitPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.exitComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?e.api.exitApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.exitLayout(n)&&e.layout.writeDeclaration()};n===`serve`&&Hn(e.state.srcDir,{ignoreInitial:!0}).on(`unlink`,e=>void i(e));let a=async t=>{e.api.isApi(t)&&await e.api.enterApi(t)&&e.api.writeDeclaration()};n===`serve`&&Hn(e.state.srcDir,{ignoreInitial:!0}).on(`change`,e=>void a(e)),t=!0},async transform(t,n){let r=p.normalize(n);if(r.includes(`?`)||!r.startsWith(`${e.state.srcDir}/`))return null;let i=t,a=null;return[`.ts`,`.js`].some(e=>r.endsWith(e))?(a=e.api.applyApis(t,r),i=a.code):[`.vue`,`.nvue`].some(e=>r.endsWith(e))&&(a=e.component.applyComponents(t,r,{withApis:!0}),i=a.code),e.root.isRootPath(r)?(e.root.parseRoot(i),e.root.transformRoot(i)):e.route.isPage(r)?(this.addWatchFile(e.root.rootPath),await e.route.transformPage(i,r)):a},resolveId(e){if(e===`virtual:oiyo-root-context`)return B},load(t){if(t===B)return e.root.rootVM||`export function useRootContext() {return {}}`},async closeBundle(){await e.route.unwatchPagesConfig()}}]}var Wn=`0.3.0-beta.3`,Gn=class{config;constructor(e){this.config=e}get stateDir(){return(0,p.resolve)(this.config.rootDir,`.oiyo`)}get typesDir(){return(0,p.resolve)(this.stateDir,`types`)}get srcDir(){return(0,p.resolve)(this.config.rootDir,this.config.srcDir)}get declarationEntryPath(){return(0,p.resolve)(this.stateDir,`oiyo.d.ts`)}get tsconfigPath(){return(0,p.resolve)(this.stateDir,`tsconfig.json`)}get metadataPath(){return(0,p.resolve)(this.stateDir,`oiyo.json`)}get declarationPaths(){return[this.declarationEntryPath,this.tsconfigPath,(0,p.resolve)(this.typesDir,`apis.d.ts`),(0,p.resolve)(this.typesDir,`components.d.ts`),(0,p.resolve)(this.typesDir,`layouts.d.ts`),(0,p.resolve)(this.typesDir,`pages.d.ts`)]}relativeToState(e){return(0,p.normalize)((0,p.relative)(this.stateDir,e))}stringifyJson(e){return`${JSON.stringify(e,null,2)}\n`}serializeMetadataInput(){return JSON.stringify({rootDir:(0,p.normalize)(this.config.rootDir||``),srcDir:this.config.srcDir||``,dir:this.config.dir||{},scan:this.config.scan||{},exclude:this.config.exclude||[]})}generateMetadataHash(){return A(`${Wn}:${this.serializeMetadataInput()}`,16)}generateMetadata(){return{hash:this.generateMetadataHash(),project:{rootDir:(0,p.normalize)(this.config.rootDir||``)},versions:{oiyo:Wn}}}readMetadata(){if(!(0,d.existsSync)(this.metadataPath))return null;try{return JSON.parse((0,d.readFileSync)(this.metadataPath,`utf-8`))}catch{return null}}writeMetadata(){(0,d.mkdirSync)(this.stateDir,{recursive:!0});let e=this.generateMetadata();return j(this.metadataPath,this.stringifyJson(e)),e}canReuseGeneratedState(){let e=this.readMetadata();return!e||e.project.rootDir!==(0,p.normalize)(this.config.rootDir||``)||e.versions.oiyo!==Wn||e.hash!==this.generateMetadataHash()?!1:this.declarationPaths.every(e=>(0,d.existsSync)(e))}generateDeclarationEntry(){return[`// Generated by oiyo`,``,`/// <reference types="@skiyee/oiyo/types" />`,`/// <reference path="./types/apis.d.ts" />`,`/// <reference path="./types/components.d.ts" />`,`/// <reference path="./types/layouts.d.ts" />`,`/// <reference path="./types/pages.d.ts" />`,``,`export {}`,``].join(`
26
+ `)}generateTsconfig(){let e=this.relativeToState(this.config.rootDir),t=this.relativeToState(this.srcDir),n=this.relativeToState(this.stateDir);return this.stringifyJson({compilerOptions:{paths:{"~/*":[(0,p.join)(t,`*`)],"~~/*":[(0,p.join)(e,`*`)],"@/*":[(0,p.join)(t,`*`)],"@@/*":[(0,p.join)(e,`*`)]},types:[],esModuleInterop:!0,skipLibCheck:!0,target:`ES2018`,allowJs:!0,resolveJsonModule:!0,moduleDetection:`force`,isolatedModules:!0,verbatimModuleSyntax:!0,allowArbitraryExtensions:!0,strict:!0,noUncheckedIndexedAccess:!0,forceConsistentCasingInFileNames:!0,noImplicitOverride:!0,module:`preserve`,noEmit:!0,lib:[`ESNext`,`DOM`,`DOM.Iterable`],moduleResolution:`Bundler`,useDefineForClassFields:!0},include:[(0,p.join)(n,`oiyo.d.ts`),(0,p.join)(t,`**/*`),(0,p.join)(e,`*.d.ts`),(0,p.join)(e,`oiyo.config.*`),(0,p.join)(e,`vite.config.*`),(0,p.join)(e,`vitest.config.*`)],exclude:[(0,p.join)(t,`pages.config.*`),(0,p.join)(e,`dist`),(0,p.join)(e,`node_modules`)]})}writeTsconfig(){return(0,d.mkdirSync)(this.stateDir,{recursive:!0}),j(this.tsconfigPath,this.generateTsconfig()),this.tsconfigPath}writeDeclarationEntry(){return(0,d.mkdirSync)(this.stateDir,{recursive:!0}),j(this.declarationEntryPath,this.generateDeclarationEntry()),this.writeTsconfig(),this.declarationEntryPath}ensureDeclarationEntry(){return(0,d.existsSync)(this.tsconfigPath)||this.writeTsconfig(),(0,d.existsSync)(this.declarationEntryPath)?this.declarationEntryPath:this.writeDeclarationEntry()}markGenerated(){return this.writeMetadata()}};function Kn(e){let t=(0,S.resolveOiyoConfig)(e),n=he();n.withScope(`CONFIG`);let r=new Gn(t),i=new qe(t,{logger:n,oiyoState:r}),a=new Qe(t,{logger:n,oiyoState:r,oiyoApi:i}),o=new vt(t,{logger:n}),s=new it(t,{logger:n,oiyoState:r});return{logger:n,config:t,api:i,component:a,layout:s,state:r,route:new Wt(t,{logger:n,oiyoState:r,oiyoRoot:o,oiyoLayout:s}),root:o}}function qn(e){return[{name:`oiyo:deps`,enforce:`pre`,async config(t){let{config:n}=await(0,ie.loadConfig)({name:`oiyo`,cwd:t.root}),r=Kn(n||e);return(0,ce.defu)(t,{oiyo:r,resolve:{alias:{"~":y.default.resolve(r.config.rootDir,r.config.srcDir),"@":y.default.resolve(r.config.rootDir,r.config.srcDir),"@@":y.default.normalize(r.config.rootDir),"~~":y.default.normalize(r.config.rootDir)}},optimizeDeps:{exclude:[`@skiyee/oiyo`]}})}}]}function Jn(){let e;return[{name:`oiyo:serve`,apply:`serve`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`VITE`),e.logger.withScope(`HMR`)},async buildStart(){await Promise.all([e.api.scanApis(),e.component.scanComponents(),e.route.scanPages(),e.layout.scanLayouts()]),e.state.canReuseGeneratedState()||(e.api.writeDeclaration(),e.component.writeDeclaration(),e.route.writePagesJson()&&e.route.writeDeclaration(),e.layout.writeDeclaration(),e.state.markGenerated())},configureServer(t){e.route.watchPagesConfig(()=>{e.route.writePagesJson()&&e.route.writeDeclaration(),t.hot.send({type:`full-reload`})});let n=async t=>{let n=p.normalize(t);e.route.isPage(n)?e.route.enterPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.enterComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?await e.api.enterApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.enterLayout(n)&&e.layout.writeDeclaration()};t.watcher.on(`add`,e=>void n(e));let r=t=>{let n=p.normalize(t);e.route.isPage(n)?e.route.exitPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.exitComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?e.api.exitApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.exitLayout(n)&&e.layout.writeDeclaration()};t.watcher.on(`unlink`,e=>void r(e));let i=async t=>{e.api.isApi(t)&&await e.api.enterApi(t)&&e.api.writeDeclaration()};t.watcher.on(`change`,e=>void i(e))},async transform(t,n){let r=p.normalize(n);if(r.includes(`?`)||!r.startsWith(`${e.state.srcDir}/`))return null;let i=t,a=null;return[`.ts`,`.js`].some(e=>r.endsWith(e))?(a=e.api.applyApis(t,r),i=a.code):[`.vue`,`.nvue`].some(e=>r.endsWith(e))&&(a=e.component.applyComponents(t,r,{withApis:!0}),i=a.code),e.root.isRootPath(r)?(e.root.parseRoot(i),e.root.transformRoot(i)):e.route.isPage(r)?(this.addWatchFile(e.root.rootPath),await e.route.transformPage(i,r)):a},resolveId(e){if(e===`virtual:oiyo-root-context`)return B},load(t){if(t===B)return e.root.rootVM||`export function useRootContext() {return {}}`},async handleHotUpdate({file:t,server:n,read:r}){if(e.root.isRootPath(t)){let t=await r(),i=!1;if(e.root.shouldRefreshView(t)&&(i=!0),e.root.shouldRefreshVM(t)){let e=n.moduleGraph.getModuleById(B);e&&(n.moduleGraph.invalidateModule(e),i=!0)}if(i){n.hot.send({type:`full-reload`});return}}},async closeBundle(){await e.route.unwatchPagesConfig()}}]}function Yn(e={}){return[...qn(e),...Jn(),...Un()]}exports.LogLevels=D,exports.OiyoCorePlugin=Yn,exports.OiyoLayout=at,exports.OiyoModApi=qe,exports.OiyoModComponent=Qe,exports.OiyoModLayout=it,exports.OiyoModRoot=vt,exports.OiyoModRoute=Wt,exports.OiyoPage=Kt,exports.OiyoState=Gn,exports.RESOLVED_VIRTUAL_ROOT_CONTEXT_ID=B,exports.VIRTUAL_ROOT_CONTEXT_ID=gt,exports.createLogger=he,exports.definePageMeta=Gt,exports.defineRootContext=yt;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @oiyo/core v0.3.0-beta.1
2
+ * @oiyo/core v0.3.0-beta.3
3
3
  * Copyright (c) 2026 skiyee. All rights reserved.
4
4
  * Commercial software. See LICENSE for terms.
5
5
  * Official site: https://oiyo.js.org
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @oiyo/core v0.3.0-beta.1
2
+ * @oiyo/core v0.3.0-beta.3
3
3
  * Copyright (c) 2026 skiyee. All rights reserved.
4
4
  * Commercial software. See LICENSE for terms.
5
5
  * Official site: https://oiyo.js.org
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @oiyo/core v0.3.0-beta.1
2
+ * @oiyo/core v0.3.0-beta.3
3
3
  * Copyright (c) 2026 skiyee. All rights reserved.
4
4
  * Commercial software. See LICENSE for terms.
5
5
  * Official site: https://oiyo.js.org
@@ -11,7 +11,7 @@ import{createRequire as e}from"node:module";import t,{pid as n}from"node:process
11
11
  `);return n.prepend(`${a}\n`),{code:n.toString(),map:n.generateMap()}}};function kt(e){let t=new Set,n=e.matchAll(/<\/?\s*([a-z][\w-]*)\b/gi);for(let e of n)t.add(P(e[1]));return t}function At(e){if(!e||!e.includes(`import`))return new Set;let t=S(e,{sourceType:`module`,plugins:[`typescript`]}),n=new Set;return A(t,{ImportDeclaration(e){for(let t of e.node.specifiers)n.add(t.local.name)}}),n}function jt(e,t,n){let r=v.relative(t,e),{dir:i,name:a}=v.parse(r),o=i&&i!==`.`?i.split(v.sep).filter(Boolean):[];(a!==`index`||o.length===0)&&o.push(a);let s=Mt(o),c=n?.chain===!1?s.slice(-1):s;return`${n?.prefix?P(n?.prefix):``}${c.map(e=>P(e)).join(``)}`}function Mt(e){if(e.length<2)return e;let t=e.slice();return t[t.length-1]===t[t.length-2]&&t.pop(),t}var Nt=class{config;logger;oiyoState;oiyoApi;sources=new Map;components=new Map;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`COMPONENT`),this.oiyoState=t.oiyoState,this.oiyoApi=t.oiyoApi}get srcDir(){return v.resolve(this.config.rootDir,this.config.srcDir)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return v.resolve(this.declarationDir,`components.d.ts`)}shouldSkipImport(e){return[`OiyoPage`,`OiyoLayout`].includes(e)}recordComponentSource(e){return e.patterns?.length?(j(e.patterns).forEach(t=>{let n=v.resolve(e.dir,t);this.sources.set(n,e)}),!0):(this.sources.set(e.dir,e),!0)}toComponentSource(e){let t={from:``,dir:``,chain:!0,patterns:[`**/*.vue`,`**/*.nvue`],isNodeModule:!1};if(L(e)?t.from=e:Object.assign(t,e),xt(t.from)){let e=t.from,n=wt(t.from),r=n===`.`;t.from=n,t.patterns=[r?e:e.slice(n.length+1)]}let n=lt(t.from);if(n){t.isNodeModule=!0;let e=v.relative(n.name,t.from);t.dir=v.resolve(n.root,e),t?.only?.length&&(t.patterns=[])}else t.dir=v.resolve(this.srcDir,t.from);return F(t.dir)&&(t.patterns=[]),this.recordComponentSource(t),t}saveComponent(e){let t=this.components.get(e.importName);return t&&t.filePath!==e.filePath?(this.logger.warnOnce(`组件名名称冲突: “${e.importName}” 已存在,已跳过来自 “${e.importPath}” 的重复导出`),!1):(this.components.set(e.importName,e),!0)}async scanComponentByDirect(e){return e.only?.map(t=>{let n={filePath:e.dir,exportName:``,importName:``,importPath:e.from,isNodeModule:!0};return L(t)?(n.exportName=t,n.importName=t):(n.exportName=t.name,n.importName=t.as||t.name),e.prefix&&(n.importName=P(`${e.prefix}${n.importName}`)),this.saveComponent(n),n})}async scanComponentByDir(e){return(await nt({dir:e.dir,ignore:e.ignore,pattern:e.patterns})).map(t=>{let n=jt(t,e.dir===t?v.dirname(t):e.dir,{chain:e.chain,prefix:e.prefix}),r=t;e.isNodeModule&&(r=v.join(e.from,v.relative(e.dir,t)));let i={filePath:t,exportName:`default`,importName:n,importPath:r,isNodeModule:e.isNodeModule};return this.saveComponent(i),i})}async scanComponent(e){return e.isNodeModule&&e.only?.length?this.scanComponentByDirect(e):this.scanComponentByDir(e)}async scanComponents(){let e=this.config.scan?.components||[];await Promise.all(e.map(async e=>{let t=this.toComponentSource(e);await this.scanComponent(t)}))}findComponentSource(e){let t=Array.from([...this.sources.keys()]).find(t=>v.matchesGlob(e,t));if(t)return this.sources.get(t)}isComponent(e){return!!this.findComponentSource(e)}enterComponent(e){let t=this.findComponentSource(e);if(!t)return this.logger.warn(`未找到组件匹配源无法录入组件`),!1;let n={filePath:e,exportName:`default`,importName:jt(e,t.dir===e?v.dirname(e):t.dir,{chain:t.chain,prefix:t.prefix}),importPath:e,isNodeModule:!1};return this.saveComponent(n),!0}exitComponent(e){let t=Array.from(this.components.values()).find(t=>t.filePath===e);if(t)return this.components.delete(t.importName),t}generateDeclaration(){return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`declare module 'vue' {`,` export interface GlobalComponents {`,...Array.from(this.components.values()).sort((e,t)=>e.importName.localeCompare(t.importName)).map(e=>` ${_t(e.importPath,e.importName,e.exportName,{baseDir:e.isNodeModule?void 0:this.declarationDir})}`),` }`,`}`,``,`export {}`,``].join(`
12
12
  `)}writeDeclaration(){try{u.mkdirSync(this.declarationDir,{recursive:!0}),N(this.declarationFile,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`无法写入 components.d.ts 组件类型声明,请检查目标文件权限和内容格式:`,{error:e})}}applyComponents(e,t,n={withApis:!0}){let{descriptor:r}=T(e),i=new w(e),a=r.template?.content;if(!a)return{code:i.toString(),map:i.generateMap()};let o=Array.from(kt(a)),s=o,c=[],l=[r.scriptSetup?.content,r.script?.content].filter(e=>!!e);if(l.length){let[e,t]=l.flatMap(e=>[At(e),pt(e)]);s=o.filter(t=>!e.has(t)),n?.withApis&&(c=Array.from(t))}if(!s.length&&!c.length)return{code:i.toString(),map:i.generateMap()};let u=s.map(e=>{let n=this.components.get(e);return!n||t&&n.filePath===t||this.shouldSkipImport(e)?null:ht(n.importPath,n.importName,n.exportName)}).filter(e=>!!e),d=c.map(e=>{let n=this.oiyoApi.apis.get(e);return!n||t&&n.filePath===t||this.oiyoApi.shouldSkipImport(e)?null:ht(n.importPath,n.importName,n.exportName)}).filter(e=>!!e);if(!u.length&&!d.length)return{code:i.toString(),map:i.generateMap()};let f=[...u,...d].join(`
13
13
  `),p=r.scriptSetup;if(!p){let e=[`<script setup>`,f,`<\/script>`].join(`
14
- `);return i.prepend(`${e}\n\n`),{code:i.toString(),map:i.generateMap()}}return i.appendRight(p.loc.start.offset,`\n${f}`),{code:i.toString(),map:i.generateMap()}}};function Pt(e){return e.includes(`<OiyoLayout`)||e.includes(`<oiyo-layout`)}function Ft(e){let t=e;return t=t.replace(/<OiyoLayout[^>]*?\/>/g,``),t=t.replace(/<OiyoLayout[^>]*>/g,``),t=t.replace(/<\/OiyoLayout>/g,``),t=t.replace(/<oiyo-layout[^>]*?\/>/g,``),t=t.replace(/<oiyo-layout[^>]*>/g,``),t=t.replace(/<\/oiyo-layout>/g,``),t}function It(e,t){let n=e;return n=n.replace(/<OiyoLayout[^>]*?\/>/g,``),n=n.replace(/<OiyoLayout[^>]*>/g,`<${t}>`),n=n.replace(/<\/OiyoLayout>/g,`</${t}>`),n=n.replace(/<oiyo-layout[^>]*?\/>/g,``),n=n.replace(/<oiyo-layout[^>]*>/g,`<${t}>`),n=n.replace(/<\/oiyo-layout>/g,`</${t}>`),n}function Lt(e,t){let{dir:n,name:r}=ce(le(t,e));return(n&&n!==`.`?[...n.split(ue),r]:[r]).map(e=>Ze(e)).join(`-`)}function Rt(e){return`OiyoLayout${e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}`}var zt=class{config;logger;oiyoState;layouts=new Map;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`LAYOUT`),this.oiyoState=t.oiyoState}get srcDir(){return v.resolve(this.config.rootDir,this.config.srcDir)}get layoutDir(){return v.resolve(this.srcDir,this.config.dir?.layouts||`layouts`)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return v.resolve(this.declarationDir,`layouts.d.ts`)}toLayout(e){let t=Lt(e,this.layoutDir);return{filePath:e,componentName:Rt(t),useName:t}}saveLayout(e){return this.layouts.has(e.useName)?!1:(this.layouts.set(e.useName,e),!0)}async scanLayouts(){return(await Xe({dir:this.layoutDir,pattern:[`**/*.vue`,`**/*.nvue`],ignore:[...we,...this.config.exclude||[]]})).forEach(e=>{let t=this.toLayout(e);this.saveLayout(t)&&this.logger.debug(`通过“扫描模式”录入页面: ${t.useName}`)}),this.layouts}isLayout(e){return!e.endsWith(`.vue`)&&!e.endsWith(`.nvue`)||[...we,...this.config.exclude||[]].some(t=>v.matchesGlob(e,t))?!1:e.startsWith(`${this.layoutDir}/`)}enterLayout(e){let t=this.toLayout(e),n=this.saveLayout(t);return n&&this.logger.debug(`通过“主动模式”录入布局: ${t.useName}`),n}exitLayout(e){let t=Array.from(this.layouts.values()).find(t=>t.filePath===e);if(!t)return!1;let n=this.layouts.delete(t.useName);return n&&this.logger.debug(`通过“主动模式”脱离布局: ${t.useName}`),n}generateDeclaration(){return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`declare module '@skiyee/oiyo/api' {`,` interface OiyoLayouts {`,...Array.from(this.layouts.values()).sort((e,t)=>e.useName.localeCompare(t.useName)).map(({useName:e,filePath:t})=>` ${_t(t,`'${e}'`,`default`,{baseDir:this.declarationDir})}`),` }`,``,` type LayoutKey = keyof OiyoLayouts extends never ? string : keyof OiyoLayouts;`,``,` interface PageMeta {`,` layout?: LayoutKey | false;`,` }`,`}`,``,`export {}`,``].join(`
14
+ `);return i.prepend(`${e}\n\n`),{code:i.toString(),map:i.generateMap()}}return i.appendRight(p.loc.start.offset,`\n${f}`),{code:i.toString(),map:i.generateMap()}}};function Pt(e){return e.includes(`<OiyoLayout`)||e.includes(`<oiyo-layout`)}function Ft(e){let t=e;return t=t.replace(/<OiyoLayout[^>]*?\/>/g,``),t=t.replace(/<OiyoLayout[^>]*>/g,``),t=t.replace(/<\/OiyoLayout>/g,``),t=t.replace(/<oiyo-layout[^>]*?\/>/g,``),t=t.replace(/<oiyo-layout[^>]*>/g,``),t=t.replace(/<\/oiyo-layout>/g,``),t}function It(e,t){let n=e;return n=n.replace(/<OiyoLayout[^>]*?\/>/g,``),n=n.replace(/<OiyoLayout[^>]*>/g,`<${t}>`),n=n.replace(/<\/OiyoLayout>/g,`</${t}>`),n=n.replace(/<oiyo-layout[^>]*?\/>/g,``),n=n.replace(/<oiyo-layout[^>]*>/g,`<${t}>`),n=n.replace(/<\/oiyo-layout>/g,`</${t}>`),n}function Lt(e,t){let{dir:n,name:r}=ce(le(t,e));return(n&&n!==`.`?[...n.split(ue),r]:[r]).map(e=>Ze(e)).join(`-`)}function Rt(e){return`OiyoLayout${P(e)}`}var zt=class{config;logger;oiyoState;layouts=new Map;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`LAYOUT`),this.oiyoState=t.oiyoState}get srcDir(){return this.oiyoState.srcDir}get layoutDir(){return v.resolve(this.srcDir,this.config.dir?.layouts||`layouts`)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return v.resolve(this.declarationDir,`layouts.d.ts`)}toLayout(e){let t=Lt(e,this.layoutDir);return{filePath:e,componentName:Rt(t),useName:t}}saveLayout(e){return this.layouts.has(e.useName)?!1:(this.layouts.set(e.useName,e),!0)}async scanLayouts(){return(await Xe({dir:this.layoutDir,pattern:[`**/*.vue`,`**/*.nvue`],ignore:[...we,...this.config.exclude||[]]})).forEach(e=>{let t=this.toLayout(e);this.saveLayout(t)&&this.logger.debug(`通过“扫描模式”录入布局: ${t.useName}`)}),this.layouts}isLayout(e){return!e.endsWith(`.vue`)&&!e.endsWith(`.nvue`)||[...we,...this.config.exclude||[]].some(t=>v.matchesGlob(e,t))?!1:e.startsWith(`${this.layoutDir}/`)}enterLayout(e){let t=this.toLayout(e),n=this.saveLayout(t);return n&&this.logger.debug(`通过“主动模式”录入布局: ${t.useName}`),n}exitLayout(e){let t=Array.from(this.layouts.values()).find(t=>t.filePath===e);if(!t)return!1;let n=this.layouts.delete(t.useName);return n&&this.logger.debug(`通过“主动模式”脱离布局: ${t.useName}`),n}generateDeclaration(){return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`declare module '@skiyee/oiyo/api' {`,` interface OiyoLayouts {`,...Array.from(this.layouts.values()).sort((e,t)=>e.useName.localeCompare(t.useName)).map(({useName:e,filePath:t})=>` ${_t(t,`'${e}'`,`default`,{baseDir:this.declarationDir})}`),` }`,``,` type LayoutKey = keyof OiyoLayouts extends never ? string : keyof OiyoLayouts;`,``,` interface PageMeta {`,` layout?: LayoutKey | false;`,` }`,`}`,``,`export {}`,``].join(`
15
15
  `)}writeDeclaration(){try{return f(this.declarationDir,{recursive:!0}),N(this.declarationFile,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),!0}catch(e){return this.logger.error(`无法写入 layouts.d.ts 布局类型声明,请检查目标文件权限和内容格式:`,{error:e}),!1}}applyLayout(e,t){if(!Pt(t))return{template:t,script:``,imports:[]};if(e===!1)return{template:Ft(t),script:``,imports:[]};e===void 0&&(e=`default`);let n=this.layouts.get(e);return n?{template:It(t,n.componentName),script:``,imports:[`import ${n.componentName} from '${n.filePath}'`]}:(this.logger.error(`未找到布局 "${e}",请检查布局名称或文件位置是否正确`),{template:t,script:``,imports:[]})}};const Bt=Ee({name:`OiyoLayout`,setup(e,t){return()=>t.slots.default?.()}});function Vt(e,t){let n=ut(e),r={start:0,end:0};return A(n,{CallExpression(e){let{callee:n,arguments:i}=e.node;n.type===`Identifier`&&n.name===t&&i.length>0&&e.node.start!=null&&e.node.end!=null&&(r.start=e.node.start,r.end=e.node.end,e.stop())}}),r}function Ht(e){if(!e.includes(`defineRootContext`))return``;let{descriptor:t}=T(e);if(!t.scriptSetup)return``;let n=e=t.scriptSetup.content,r=Ut(n);return n.substring(r.start,r.end+1).trim()}function Ut(e){return Vt(e,`defineRootContext`)}function Wt(e){if(!e.includes(`<template`))return``;let{descriptor:t}=T(e);return(t.template?.content||``).trim()}function Gt(e,t){let n=e.replace(/\{\{([\s\S]*?)\}\}/g,(e,n)=>e.replace(n,Kt(n,t)));return n=n.replace(/((?:v-(?!for\b)[\w-]+(?::[\w-]+)?|[:@][\w-]+)\s*=\s*)(["'])([\s\S]*?)\2/g,(e,n,r,i)=>`${n}${r}${Kt(i,t)}${r}`),n}function Kt(e,t){let n=new Map;t.varName&&n.set(t.varName,`$oiyoRootContext`);for(let{local:e,original:r}of t.varProperties||[])n.set(e,`$oiyoRootContext.${r}`);if(n.size===0)return e;try{let t=S(`(${e})`,{sourceType:`module`,plugins:[`typescript`]}),r=new w(e);return A(t,{Identifier(e){if(!e.isReferencedIdentifier())return;let t=n.get(e.node.name);if(!t)return;let i=e.node.start,a=e.node.end;if(!(i==null||a==null)){if(e.parentPath.isObjectProperty()&&e.parent.shorthand&&e.parent.value===e.node){r.overwrite(i-1,a-1,`${e.node.name}: ${t}`);return}r.overwrite(i-1,a-1,t)}}}),r.toString()}catch{return e}}function qt(e,t){if(!e)throw Error(`[oiyo] App.vue 必须包含 <template> 节点`);let n=e.content;if(!(n.includes(`<OiyoPage`)||n.includes(`<oiyo-page`)))throw Error(`[oiyo] App.vue 的 template 必须包含 <OiyoPage /> 或 <oiyo-page /> 占位节点`);return n=Gt(n,t),n.trim()}function Jt(e){if(!e)return;let t=e?.content;if(t){let e=Yt(t);return e.script?e:void 0}}function Yt(e){let t=S(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return A(t,{ImportDeclaration(t){let r=e.substring(t.node.start,t.node.end);n.imports??=[],n.imports.push(r)},CallExpression(t){let{callee:r,arguments:i}=t.node;if(r.type===`Identifier`&&r.name===`defineRootContext`&&i.length>0){let r=i[0];r.start!=null&&r.end!=null&&(n.script=e.substring(r.start,r.end));let a=t.findParent(e=>e.isVariableDeclarator());if(a&&a.isVariableDeclarator()){let e=a.node.id;e.type===`Identifier`?n.variable=e.name:e.type===`ObjectPattern`&&(n.properties=e.properties.filter(e=>e.type===`ObjectProperty`).map(e=>({original:e.key.type===`Identifier`?e.key.name:String(e.key.value),local:e.value.type===`Identifier`?e.value.name:e.key.name})))}}}}),n}function Xt(e,t){let n=e;return n=n.replace(/<OiyoPage[^>]*?\/>/g,t),n=n.replace(/<OiyoPage[^>]*>\s*<\/OiyoPage>/g,t),n=n.replace(/<oiyo-page[^>]*?\/>/g,t),n=n.replace(/<oiyo-page[^>]*>\s*<\/oiyo-page>/g,t),n}const Zt=`virtual:oiyo-root-context`,R=`\0${Zt}`;function Qt(e){let{script:t,imports:n}=e,r=[];return n?.length&&(r.push(...n),r.push(``)),t?r.push(`let rootContextInstance = null`,``,`export function useRootContext() {`,` if (!rootContextInstance) {`,` const factory = ${t}`,` rootContextInstance = factory()`,` }`,``,` return rootContextInstance`,`}`):r.push(`export function useRootContext() {`,` return {}`,`}`),r.join(`
16
16
  `)}var $t=class{config;rootView={imports:[],template:`<OiyoPage />`,script:``};rootVM;rootMarco;logger;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`ROOT`)}get srcDir(){return x(this.config.rootDir,this.config.srcDir)}get rootPath(){return x(this.srcDir,`App.vue`)}isRootPath(e){return e===this.rootPath}parseRoot(e){let{descriptor:t}=T(e),n=Jt(t.scriptSetup),r=qt(t.template,{varName:n?.variable,varProperties:n?.properties});return this.rootView={template:r,imports:[],script:``},n&&(this.rootMarco=n,this.rootVM=Qt(n),n.script&&(this.rootView.imports.push(`import { useRootContext } from 'virtual:oiyo-root-context'`),this.rootView.script=`const $oiyoRootContext = useRootContext()`)),{view:this.rootView,marco:n}}transformRoot(e){let{descriptor:t}=T(e),n=new w(e);if(t.template){let e=t.template.loc.start.offset-10,r=t.template.loc.end.offset+11;n.remove(e,r)}if(t.scriptSetup){let e=t.scriptSetup.content,r=Ut(e);if(r.start!==r.end){e.includes(`virtual:oiyo-root-context`)||n.appendLeft(t.scriptSetup.loc.start.offset,`
17
17
  import { useRootContext } from 'virtual:oiyo-root-context'
@@ -22,5 +22,5 @@ import { useRootContext } from 'virtual:oiyo-root-context'
22
22
  `)}\n${s}`)}else if(s||a.length>0){let e=[`<script setup>`,...a,s,`<\/script>`].filter(Boolean).join(`
23
23
  `);r.appendRight(n.template.loc.end.offset+11,`\n\n${e}`)}return{code:r.toString(),sourceMap:r.generateMap()}}};const Dn=e=>{},On=Ee({name:`OiyoPage`}),B={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},kn={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:B.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(kn);const An=`READDIRP_RECURSIVE_ERROR`,jn=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,An]),Mn=[B.DIR_TYPE,B.EVERYTHING_TYPE,B.FILE_DIR_TYPE,B.FILE_TYPE],Nn=new Set([B.DIR_TYPE,B.EVERYTHING_TYPE,B.FILE_DIR_TYPE]),Pn=new Set([B.EVERYTHING_TYPE,B.FILE_DIR_TYPE,B.FILE_TYPE]),Fn=e=>jn.has(e.code),In=process.platform===`win32`,Ln=e=>!0,Rn=e=>{if(e===void 0)return Ln;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return Ln};var zn=class extends Le{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...kn,...e},{root:n,type:r}=t;this._fileFilter=Rn(t.fileFilter),this._directoryFilter=Rn(t.directoryFilter);let i=t.lstat?re:ae;In?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??kn.depth,this._wantsDir=r?Nn.has(r):!1,this._wantsFile=r?Pn.has(r):!1,this._wantsEverything=r===B.EVERYTHING_TYPE,this._root=Se(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await _(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=Se(be(t,r));n={path:xe(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(e){this._onError(e);return}return n}_onError(e){Fn(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return``;let t=e[this._statsProp];if(t.isFile())return`file`;if(t.isDirectory())return`directory`;if(t&&t.isSymbolicLink()){let t=e.fullPath;try{let e=await ie(t),n=await re(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===Ce){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=An,this._onError(n)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function Bn(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=B.FILE_DIR_TYPE),n&&(t.type=n),!e)throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!Mn.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${Mn.join(`, `)}`);return t.root=e,new zn(t)}const Vn=()=>{},V=process.platform,Hn=V===`win32`,Un=V===`darwin`,Wn=V===`linux`,Gn=V===`freebsd`,Kn=Re()===`OS400`,H={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},U=H,qn={lstat:Ne,stat:D},W=`listeners`,G=`errHandlers`,K=`rawEmitters`,Jn=[W,G,K],Yn=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),Xn=e=>Yn.has(O.extname(e).slice(1).toLowerCase()),Zn=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},q=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},Qn=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},J=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},$n=e=>e instanceof Set?e.size===0:!e,Y=new Map;function er(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&X(O.resolve(e,r),W,O.join(e,r))};try{return je(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const X=(e,t,n,r,i)=>{let a=Y.get(e);a&&Zn(a[t],e=>{e(n,r,i)})},tr=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=Y.get(t),c;if(!n.persistent)return c=er(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)q(s,W,i),q(s,G,a),q(s,K,o);else{if(c=er(e,n,X.bind(null,t,W),a,X.bind(null,t,K)),!c)return;c.on(U.ERROR,async n=>{let r=X.bind(null,t,G);if(s&&(s.watcherUnusable=!0),Hn&&n.code===`EPERM`)try{await(await Pe(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},Y.set(t,s)}return()=>{J(s,W,i),J(s,G,a),J(s,K,o),$n(s.listeners)&&(s.watcher.close(),Y.delete(t),Jn.forEach(Qn(s)),s.watcher=void 0,Object.freeze(s))}},nr=new Map,rr=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=nr.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(Ae(t),o=void 0),o?(q(o,W,i),q(o,K,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:Me(t,n,(n,r)=>{Zn(o.rawEmitters,e=>{e(U.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&Zn(o.listeners,t=>t(e,n))})},nr.set(t,o)),()=>{J(o,W,i),J(o,K,a),$n(o.listeners)&&(nr.delete(t),Ae(t),o.options=o.watcher=void 0,Object.freeze(o))}};var ir=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=O.dirname(e),i=O.basename(e);this.fsw._getWatchedDir(r).add(i);let a=O.resolve(e),o={persistent:n.persistent};t||=Vn;let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&Xn(i)?n.binaryInterval:n.interval,s=rr(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=tr(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=O.dirname(e),i=O.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(`watch`,e,5)){if(!n||n.mtimeMs===0)try{let n=await D(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(U.CHANGE,e,n),(Un||Wn||Gn)&&o.ino!==n.ino){this.fsw._closeFile(t),o=n;let r=this._watchWithNodeFs(e,s);r&&this.fsw._addPathCloser(t,r)}else o=n}catch{this.fsw._remove(r,i)}else if(a.has(i)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==o.mtimeMs)&&this.fsw._emit(U.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(U.ADD,e,0))return;this.fsw._emit(U.ADD,e,t)}return c}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await E(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==t&&(this.fsw._symlinkPaths.set(i,t),this.fsw._emit(U.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(U.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){if(e=O.join(e,``),o=this.fsw._throttle(`readdir`,e,1e3),!o)return;let s=this.fsw._getWatchedDir(n.path),c=new Set,l=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(l)return l.on(`data`,async o=>{if(this.fsw.closed){l=void 0;return}let u=o.path,d=O.join(e,u);if(c.add(u),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,e,d,u))){if(this.fsw.closed){l=void 0;return}(u===r||!r&&!s.has(u))&&(this.fsw._incrReadyCount(),d=O.join(i,O.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(U.ERROR,this._boundHandleError),new Promise((t,u)=>{if(!l)return u();l.once(`end`,()=>{if(this.fsw.closed){l=void 0;return}let u=o?o.clear():!1;t(void 0),s.getChildren().filter(t=>t!==e&&!c.has(t)).forEach(t=>{this.fsw._remove(e,t)}),l=void 0,u&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let s=this.fsw._getWatchedDir(O.dirname(e)),c=s.has(O.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(U.ADD_DIR,e,t),s.add(O.basename(e)),this.fsw._getWatchedDir(e);let l,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,void 0),this.fsw.closed))return;l=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,a,i,e,r,void 0)})}return l}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=e=>n.filterPath(e),o.filterDir=e=>n.filterDir(e));try{let n=await qn[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let s=this.fsw.options.followSymlinks,c;if(n.isDirectory()){let a=O.resolve(e),l=s?await E(e):e;if(this.fsw.closed||(c=await this._handleDir(o.watchPath,n,t,r,i,o,l),this.fsw.closed))return;a!==l&&l!==void 0&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let i=s?await E(e):e;if(this.fsw.closed)return;let a=O.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(U.ADD,o.watchPath,n),c=await this._handleDir(a,n,t,r,e,o,i),this.fsw.closed)return;i!==void 0&&this.fsw._symlinkPaths.set(O.resolve(e),i)}else c=this._handleFile(o.watchPath,n,t);return a(),c&&this.fsw._addPathCloser(e,c),!1}catch(t){if(this.fsw._handleError(t))return a(),e}}};
24
24
  /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
25
- const ar=/\\/g,or=/\/\//,sr=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,cr=/^\.[/\\]/;function Z(e){return Array.isArray(e)?e:[e]}const Q=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function lr(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=O.relative(e.path,t);return n?!n.startsWith(`..`)&&!O.isAbsolute(n):!1}return!1}:()=>!1}function ur(e){if(typeof e!=`string`)throw Error(`string expected`);e=O.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;e.startsWith(`//`)&&(t=!0);let n=/\/\//;for(;e.match(n);)e=e.replace(n,`/`);return t&&(e=`/`+e),e}function dr(e,t,n){let r=ur(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function fr(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=Z(e).map(e=>lr(e));return t==null?(e,t)=>dr(n,e,t):dr(n,t)}const pr=e=>{let t=Z(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(hr)},mr=e=>{let t=e.replace(ar,`/`),n=!1;for(t.startsWith(`//`)&&(n=!0);t.match(or);)t=t.replace(or,`/`);return n&&(t=`/`+t),t},hr=e=>mr(O.normalize(mr(e))),gr=(e=``)=>t=>typeof t==`string`?hr(O.isAbsolute(t)?t:O.join(e,t)):t,_r=(e,t)=>O.isAbsolute(e)?e:O.join(t,e),vr=Object.freeze(new Set);var yr=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==`.`&&e!==`..`&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await Fe(n)}catch{this._removeWatcher&&this._removeWatcher(O.dirname(n),O.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=Vn,this.items=vr,Object.freeze(this)}},br=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(cr,``),this.watchPath=r,this.fullWatchPath=O.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?`stat`:`lstat`}entryPath(e){return O.join(this.watchPath,O.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},xr=class extends Ie{constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Z(e.ignored):Z([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};Kn&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=Vn,this._readyEmitted=!0,process.nextTick(()=>this.emit(H.READY)))},this._emitRaw=(...e)=>this.emit(H.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new ir(this),Object.freeze(r)}_addIgnoredPath(e){if(Q(e)){for(let t of this._ignoredPaths)if(Q(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)Q(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=pr(e);return r&&(i=i.map(e=>_r(e,r))),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||=0,this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(O.dirname(e),O.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=pr(e),{cwd:n}=this.options;return t.forEach(e=>{!O.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=O.join(n,e)),e=O.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=(this.options.cwd?O.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==H.ERROR&&this.emit(H.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;Hn&&(t=O.normalize(t)),r.cwd&&(t=O.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===H.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(H.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===H.ADD&&this._pendingUnlinks.has(t)&&(e=H.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===H.ADD||e===H.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=H.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))}),this;if(e===H.CHANGE&&!this._throttle(H.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===H.ADD||e===H.ADD_DIR||e===H.CHANGE)){let e=r.cwd?O.join(r.cwd,t):t,n;try{n=await D(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(H.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!O.isAbsolute(e)&&(s=O.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){ke(s,(i,s)=>{if(i||!l.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(l.get(e).lastChange=c),c-l.get(e).lastChange>=t?(l.delete(e),r(void 0,s)):o=setTimeout(u,a,s)})}l.has(e)||(l.set(e,{lastChange:c,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(u,a))}_isIgnored(e,t){if(this.options.atomic&&sr.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(gr(e)),n=[...[...this._ignoredPaths].map(gr(e)),...t];this._userIgnored=fr(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new br(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=O.resolve(e);return this._watched.has(t)||this._watched.set(t,new yr(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=O.join(e,t),i=O.resolve(r);if(n??=this._watched.has(r)||this._watched.has(i),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(e=>this._remove(r,e));let a=this._getWatchedDir(e),o=a.has(t);a.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let s=r;if(this.options.cwd&&(s=O.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===H.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?H.UNLINK_DIR:H.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=O.dirname(e);this._getWatchedDir(t).remove(O.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n=Bn(e,{type:H.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once(`close`,()=>{n=void 0}),n.once(`end`,()=>{n&&=(this._streams.delete(n),void 0)}),n}};function Sr(e,t={}){let n=new xr(t);return n.add(e),n}function Cr(){let e,t=!1,n=`build`;return[{name:`oiyo:build`,apply:`build`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`VITE`),n=t.command},async buildStart(){if(t)return;await Promise.all([e.api.scanApis(),e.component.scanComponents(),e.layout.scanLayouts(),e.route.scanPages()]),e.state.canReuseGeneratedState()||(e.api.writeDeclaration(),e.component.writeDeclaration(),e.layout.writeDeclaration(),e.route.writePagesJson()&&e.route.writeDeclaration(),e.state.markGenerated());let r=async t=>{let n=b(t);e.route.isPage(n)?e.route.enterPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.enterComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?await e.api.enterApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.enterLayout(n)&&e.layout.writeDeclaration()};n===`serve`&&Sr(e.state.srcDir,{ignoreInitial:!0}).on(`add`,e=>void r(e));let i=t=>{let n=b(t);e.route.isPage(n)?e.route.exitPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.exitComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?e.api.exitApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.exitLayout(n)&&e.layout.writeDeclaration()};n===`serve`&&Sr(e.state.srcDir,{ignoreInitial:!0}).on(`unlink`,e=>void i(e));let a=async t=>{e.api.isApi(t)&&await e.api.enterApi(t)&&e.api.writeDeclaration()};n===`serve`&&Sr(e.state.srcDir,{ignoreInitial:!0}).on(`change`,e=>void a(e)),t=!0},async transform(t,n){let r=b(n);if(!r.startsWith(`${b(e.config.rootDir)}/`))return null;let i=t,a=null;return[`.ts`,`.js`].some(e=>r.endsWith(e))?(a=e.api.applyApis(t,r),i=a.code):[`.vue`,`.nvue`].some(e=>r.endsWith(e))&&(a=e.component.applyComponents(t,r,{withApis:!0}),i=a.code),e.root.isRootPath(r)?(e.root.parseRoot(i),e.root.transformRoot(i)):e.route.isPage(r)?(this.addWatchFile(e.root.rootPath),await e.route.transformPage(i,n)):a},resolveId(e){if(e===`virtual:oiyo-root-context`)return R},load(t){if(t===R)return e.root.rootVM||`export function useRootContext() {return {}}`},async closeBundle(){await e.route.unwatchPagesConfig()}}]}var $=`0.3.0-beta.1`,wr=class{config;constructor(e){this.config=e}get stateDir(){return x(this.config.rootDir,`.oiyo`)}get typesDir(){return x(this.stateDir,`types`)}get srcDir(){return x(this.config.rootDir,this.config.srcDir)}get declarationEntryPath(){return x(this.stateDir,`oiyo.d.ts`)}get tsconfigPath(){return x(this.stateDir,`tsconfig.json`)}get metadataPath(){return x(this.stateDir,`oiyo.json`)}get declarationPaths(){return[this.declarationEntryPath,this.tsconfigPath,x(this.typesDir,`apis.d.ts`),x(this.typesDir,`components.d.ts`),x(this.typesDir,`layouts.d.ts`),x(this.typesDir,`pages.d.ts`)]}relativeToState(e){return b(le(this.stateDir,e))}stringifyJson(e){return`${JSON.stringify(e,null,2)}\n`}serializeMetadataInput(){return JSON.stringify({rootDir:b(this.config.rootDir||``),srcDir:this.config.srcDir||``,dir:this.config.dir||{},scan:this.config.scan||{},exclude:this.config.exclude||[]})}generateMetadataHash(){return M(`${$}:${this.serializeMetadataInput()}`,16)}generateMetadata(){return{hash:this.generateMetadataHash(),project:{rootDir:b(this.config.rootDir||``)},versions:{oiyo:$}}}readMetadata(){if(!d(this.metadataPath))return null;try{return JSON.parse(p(this.metadataPath,`utf-8`))}catch{return null}}writeMetadata(){f(this.stateDir,{recursive:!0});let e=this.generateMetadata();return N(this.metadataPath,this.stringifyJson(e)),e}canReuseGeneratedState(){let e=this.readMetadata();return!e||e.project.rootDir!==b(this.config.rootDir||``)||e.versions.oiyo!==$||e.hash!==this.generateMetadataHash()?!1:this.declarationPaths.every(e=>d(e))}generateDeclarationEntry(){return[`// Generated by oiyo`,``,`/// <reference types="@skiyee/oiyo/types" />`,`/// <reference path="./types/apis.d.ts" />`,`/// <reference path="./types/components.d.ts" />`,`/// <reference path="./types/layouts.d.ts" />`,`/// <reference path="./types/pages.d.ts" />`,``,`export {}`,``].join(`
26
- `)}generateTsconfig(){let e=this.relativeToState(this.config.rootDir),t=this.relativeToState(this.srcDir),n=this.relativeToState(this.stateDir);return this.stringifyJson({compilerOptions:{paths:{"~/*":[y(t,`*`)],"~~/*":[y(e,`*`)],"@/*":[y(t,`*`)],"@@/*":[y(e,`*`)]},types:[],esModuleInterop:!0,skipLibCheck:!0,target:`ES2018`,allowJs:!0,resolveJsonModule:!0,moduleDetection:`force`,isolatedModules:!0,verbatimModuleSyntax:!0,allowArbitraryExtensions:!0,strict:!0,noUncheckedIndexedAccess:!0,forceConsistentCasingInFileNames:!0,noImplicitOverride:!0,module:`preserve`,noEmit:!0,lib:[`ESNext`,`DOM`,`DOM.Iterable`],moduleResolution:`Bundler`,useDefineForClassFields:!0},include:[y(n,`oiyo.d.ts`),y(t,`**/*`),y(e,`*.d.ts`),y(e,`oiyo.config.*`),y(e,`vite.config.*`),y(e,`vitest.config.*`)],exclude:[y(t,`pages.config.*`),y(e,`dist`),y(e,`node_modules`)]})}writeTsconfig(){return f(this.stateDir,{recursive:!0}),N(this.tsconfigPath,this.generateTsconfig()),this.tsconfigPath}writeDeclarationEntry(){return f(this.stateDir,{recursive:!0}),N(this.declarationEntryPath,this.generateDeclarationEntry()),this.writeTsconfig(),this.declarationEntryPath}ensureDeclarationEntry(){return d(this.tsconfigPath)||this.writeTsconfig(),d(this.declarationEntryPath)?this.declarationEntryPath:this.writeDeclarationEntry()}markGenerated(){return this.writeMetadata()}};function Tr(e){let t=Te(e),n=Ke();n.withScope(`CONFIG`);let r=new wr(t),i=new Ot(t,{logger:n,oiyoState:r}),a=new Nt(t,{logger:n,oiyoState:r,oiyoApi:i}),o=new $t(t,{logger:n}),s=new zt(t,{logger:n,oiyoState:r});return{logger:n,config:t,api:i,component:a,layout:s,state:r,route:new En(t,{logger:n,oiyoState:r,oiyoRoot:o,oiyoLayout:s}),root:o}}function Er(e){return[{name:`oiyo:deps`,enforce:`pre`,async config(t){let{config:n}=await De({name:`oiyo`,cwd:t.root}),r=Tr(n||e);return ze(t,{oiyo:r,resolve:{alias:{"~":C.resolve(r.config.rootDir,r.config.srcDir),"@":C.resolve(r.config.rootDir,r.config.srcDir),"@@":C.normalize(r.config.rootDir),"~~":C.normalize(r.config.rootDir)}},optimizeDeps:{exclude:[`@skiyee/oiyo`]}})}}]}function Dr(){let e;return[{name:`oiyo:serve`,apply:`serve`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`VITE`),e.logger.withScope(`HMR`)},async buildStart(){await Promise.all([e.api.scanApis(),e.component.scanComponents(),e.route.scanPages(),e.layout.scanLayouts()]),e.state.canReuseGeneratedState()||(e.api.writeDeclaration(),e.component.writeDeclaration(),e.route.writePagesJson()&&e.route.writeDeclaration(),e.layout.writeDeclaration(),e.state.markGenerated())},configureServer(t){e.route.watchPagesConfig(()=>{e.route.writePagesJson()&&e.route.writeDeclaration(),t.hot.send({type:`full-reload`})});let n=async t=>{let n=b(t);e.route.isPage(n)?e.route.enterPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.enterComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?await e.api.enterApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.enterLayout(n)&&e.layout.writeDeclaration()};t.watcher.on(`add`,e=>void n(e));let r=t=>{let n=b(t);e.route.isPage(n)?e.route.exitPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.exitComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?e.api.exitApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.exitLayout(n)&&e.layout.writeDeclaration()};t.watcher.on(`unlink`,e=>void r(e));let i=async t=>{e.api.isApi(t)&&await e.api.enterApi(t)&&e.api.writeDeclaration()};t.watcher.on(`change`,e=>void i(e))},async transform(t,n){let r=b(n);if(!r.startsWith(`${b(e.config.rootDir)}/`))return null;let i=t,a=null;return[`.ts`,`.js`].some(e=>r.endsWith(e))?(a=e.api.applyApis(t,r),i=a.code):[`.vue`,`.nvue`].some(e=>r.endsWith(e))&&(a=e.component.applyComponents(t,r,{withApis:!0}),i=a.code),e.root.isRootPath(r)?(e.root.parseRoot(i),e.root.transformRoot(i)):e.route.isPage(r)?(this.addWatchFile(e.root.rootPath),await e.route.transformPage(i,n)):a},resolveId(e){if(e===`virtual:oiyo-root-context`)return R},load(t){if(t===R)return e.root.rootVM||`export function useRootContext() {return {}}`},async handleHotUpdate({file:t,server:n,read:r}){if(e.root.isRootPath(t)){let t=await r(),i=!1;if(e.root.shouldRefreshView(t)&&(i=!0),e.root.shouldRefreshVM(t)){let e=n.moduleGraph.getModuleById(R);e&&(n.moduleGraph.invalidateModule(e),i=!0)}if(i){n.hot.send({type:`full-reload`});return}}},async closeBundle(){await e.route.unwatchPagesConfig()}}]}function Or(e={}){return[...Er(e),...Dr(),...Cr()]}export{k as LogLevels,Or as OiyoCorePlugin,Bt as OiyoLayout,Ot as OiyoModApi,Nt as OiyoModComponent,zt as OiyoModLayout,$t as OiyoModRoot,En as OiyoModRoute,On as OiyoPage,wr as OiyoState,R as RESOLVED_VIRTUAL_ROOT_CONTEXT_ID,Zt as VIRTUAL_ROOT_CONTEXT_ID,Ke as createLogger,Dn as definePageMeta,en as defineRootContext};
25
+ const ar=/\\/g,or=/\/\//,sr=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,cr=/^\.[/\\]/;function Z(e){return Array.isArray(e)?e:[e]}const Q=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function lr(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=O.relative(e.path,t);return n?!n.startsWith(`..`)&&!O.isAbsolute(n):!1}return!1}:()=>!1}function ur(e){if(typeof e!=`string`)throw Error(`string expected`);e=O.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;e.startsWith(`//`)&&(t=!0);let n=/\/\//;for(;e.match(n);)e=e.replace(n,`/`);return t&&(e=`/`+e),e}function dr(e,t,n){let r=ur(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function fr(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=Z(e).map(e=>lr(e));return t==null?(e,t)=>dr(n,e,t):dr(n,t)}const pr=e=>{let t=Z(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(hr)},mr=e=>{let t=e.replace(ar,`/`),n=!1;for(t.startsWith(`//`)&&(n=!0);t.match(or);)t=t.replace(or,`/`);return n&&(t=`/`+t),t},hr=e=>mr(O.normalize(mr(e))),gr=(e=``)=>t=>typeof t==`string`?hr(O.isAbsolute(t)?t:O.join(e,t)):t,_r=(e,t)=>O.isAbsolute(e)?e:O.join(t,e),vr=Object.freeze(new Set);var yr=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==`.`&&e!==`..`&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await Fe(n)}catch{this._removeWatcher&&this._removeWatcher(O.dirname(n),O.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=Vn,this.items=vr,Object.freeze(this)}},br=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(cr,``),this.watchPath=r,this.fullWatchPath=O.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?`stat`:`lstat`}entryPath(e){return O.join(this.watchPath,O.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},xr=class extends Ie{constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Z(e.ignored):Z([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};Kn&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=Vn,this._readyEmitted=!0,process.nextTick(()=>this.emit(H.READY)))},this._emitRaw=(...e)=>this.emit(H.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new ir(this),Object.freeze(r)}_addIgnoredPath(e){if(Q(e)){for(let t of this._ignoredPaths)if(Q(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)Q(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=pr(e);return r&&(i=i.map(e=>_r(e,r))),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||=0,this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(O.dirname(e),O.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=pr(e),{cwd:n}=this.options;return t.forEach(e=>{!O.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=O.join(n,e)),e=O.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=(this.options.cwd?O.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==H.ERROR&&this.emit(H.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;Hn&&(t=O.normalize(t)),r.cwd&&(t=O.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===H.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(H.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===H.ADD&&this._pendingUnlinks.has(t)&&(e=H.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===H.ADD||e===H.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=H.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))}),this;if(e===H.CHANGE&&!this._throttle(H.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===H.ADD||e===H.ADD_DIR||e===H.CHANGE)){let e=r.cwd?O.join(r.cwd,t):t,n;try{n=await D(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(H.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!O.isAbsolute(e)&&(s=O.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){ke(s,(i,s)=>{if(i||!l.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(l.get(e).lastChange=c),c-l.get(e).lastChange>=t?(l.delete(e),r(void 0,s)):o=setTimeout(u,a,s)})}l.has(e)||(l.set(e,{lastChange:c,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(u,a))}_isIgnored(e,t){if(this.options.atomic&&sr.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(gr(e)),n=[...[...this._ignoredPaths].map(gr(e)),...t];this._userIgnored=fr(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new br(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=O.resolve(e);return this._watched.has(t)||this._watched.set(t,new yr(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=O.join(e,t),i=O.resolve(r);if(n??=this._watched.has(r)||this._watched.has(i),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(e=>this._remove(r,e));let a=this._getWatchedDir(e),o=a.has(t);a.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let s=r;if(this.options.cwd&&(s=O.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===H.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?H.UNLINK_DIR:H.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=O.dirname(e);this._getWatchedDir(t).remove(O.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n=Bn(e,{type:H.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once(`close`,()=>{n=void 0}),n.once(`end`,()=>{n&&=(this._streams.delete(n),void 0)}),n}};function Sr(e,t={}){let n=new xr(t);return n.add(e),n}function Cr(){let e,t=!1,n=`build`;return[{name:`oiyo:build`,apply:`build`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`VITE`),n=t.command},async buildStart(){if(t)return;await Promise.all([e.api.scanApis(),e.component.scanComponents(),e.layout.scanLayouts(),e.route.scanPages()]),e.state.canReuseGeneratedState()||(e.api.writeDeclaration(),e.component.writeDeclaration(),e.layout.writeDeclaration(),e.route.writePagesJson()&&e.route.writeDeclaration(),e.state.markGenerated());let r=async t=>{let n=v.normalize(t);e.route.isPage(n)?e.route.enterPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.enterComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?await e.api.enterApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.enterLayout(n)&&e.layout.writeDeclaration()};n===`serve`&&Sr(e.state.srcDir,{ignoreInitial:!0}).on(`add`,e=>void r(e));let i=t=>{let n=v.normalize(t);e.route.isPage(n)?e.route.exitPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.exitComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?e.api.exitApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.exitLayout(n)&&e.layout.writeDeclaration()};n===`serve`&&Sr(e.state.srcDir,{ignoreInitial:!0}).on(`unlink`,e=>void i(e));let a=async t=>{e.api.isApi(t)&&await e.api.enterApi(t)&&e.api.writeDeclaration()};n===`serve`&&Sr(e.state.srcDir,{ignoreInitial:!0}).on(`change`,e=>void a(e)),t=!0},async transform(t,n){let r=v.normalize(n);if(r.includes(`?`)||!r.startsWith(`${e.state.srcDir}/`))return null;let i=t,a=null;return[`.ts`,`.js`].some(e=>r.endsWith(e))?(a=e.api.applyApis(t,r),i=a.code):[`.vue`,`.nvue`].some(e=>r.endsWith(e))&&(a=e.component.applyComponents(t,r,{withApis:!0}),i=a.code),e.root.isRootPath(r)?(e.root.parseRoot(i),e.root.transformRoot(i)):e.route.isPage(r)?(this.addWatchFile(e.root.rootPath),await e.route.transformPage(i,r)):a},resolveId(e){if(e===`virtual:oiyo-root-context`)return R},load(t){if(t===R)return e.root.rootVM||`export function useRootContext() {return {}}`},async closeBundle(){await e.route.unwatchPagesConfig()}}]}var $=`0.3.0-beta.3`,wr=class{config;constructor(e){this.config=e}get stateDir(){return x(this.config.rootDir,`.oiyo`)}get typesDir(){return x(this.stateDir,`types`)}get srcDir(){return x(this.config.rootDir,this.config.srcDir)}get declarationEntryPath(){return x(this.stateDir,`oiyo.d.ts`)}get tsconfigPath(){return x(this.stateDir,`tsconfig.json`)}get metadataPath(){return x(this.stateDir,`oiyo.json`)}get declarationPaths(){return[this.declarationEntryPath,this.tsconfigPath,x(this.typesDir,`apis.d.ts`),x(this.typesDir,`components.d.ts`),x(this.typesDir,`layouts.d.ts`),x(this.typesDir,`pages.d.ts`)]}relativeToState(e){return b(le(this.stateDir,e))}stringifyJson(e){return`${JSON.stringify(e,null,2)}\n`}serializeMetadataInput(){return JSON.stringify({rootDir:b(this.config.rootDir||``),srcDir:this.config.srcDir||``,dir:this.config.dir||{},scan:this.config.scan||{},exclude:this.config.exclude||[]})}generateMetadataHash(){return M(`${$}:${this.serializeMetadataInput()}`,16)}generateMetadata(){return{hash:this.generateMetadataHash(),project:{rootDir:b(this.config.rootDir||``)},versions:{oiyo:$}}}readMetadata(){if(!d(this.metadataPath))return null;try{return JSON.parse(p(this.metadataPath,`utf-8`))}catch{return null}}writeMetadata(){f(this.stateDir,{recursive:!0});let e=this.generateMetadata();return N(this.metadataPath,this.stringifyJson(e)),e}canReuseGeneratedState(){let e=this.readMetadata();return!e||e.project.rootDir!==b(this.config.rootDir||``)||e.versions.oiyo!==$||e.hash!==this.generateMetadataHash()?!1:this.declarationPaths.every(e=>d(e))}generateDeclarationEntry(){return[`// Generated by oiyo`,``,`/// <reference types="@skiyee/oiyo/types" />`,`/// <reference path="./types/apis.d.ts" />`,`/// <reference path="./types/components.d.ts" />`,`/// <reference path="./types/layouts.d.ts" />`,`/// <reference path="./types/pages.d.ts" />`,``,`export {}`,``].join(`
26
+ `)}generateTsconfig(){let e=this.relativeToState(this.config.rootDir),t=this.relativeToState(this.srcDir),n=this.relativeToState(this.stateDir);return this.stringifyJson({compilerOptions:{paths:{"~/*":[y(t,`*`)],"~~/*":[y(e,`*`)],"@/*":[y(t,`*`)],"@@/*":[y(e,`*`)]},types:[],esModuleInterop:!0,skipLibCheck:!0,target:`ES2018`,allowJs:!0,resolveJsonModule:!0,moduleDetection:`force`,isolatedModules:!0,verbatimModuleSyntax:!0,allowArbitraryExtensions:!0,strict:!0,noUncheckedIndexedAccess:!0,forceConsistentCasingInFileNames:!0,noImplicitOverride:!0,module:`preserve`,noEmit:!0,lib:[`ESNext`,`DOM`,`DOM.Iterable`],moduleResolution:`Bundler`,useDefineForClassFields:!0},include:[y(n,`oiyo.d.ts`),y(t,`**/*`),y(e,`*.d.ts`),y(e,`oiyo.config.*`),y(e,`vite.config.*`),y(e,`vitest.config.*`)],exclude:[y(t,`pages.config.*`),y(e,`dist`),y(e,`node_modules`)]})}writeTsconfig(){return f(this.stateDir,{recursive:!0}),N(this.tsconfigPath,this.generateTsconfig()),this.tsconfigPath}writeDeclarationEntry(){return f(this.stateDir,{recursive:!0}),N(this.declarationEntryPath,this.generateDeclarationEntry()),this.writeTsconfig(),this.declarationEntryPath}ensureDeclarationEntry(){return d(this.tsconfigPath)||this.writeTsconfig(),d(this.declarationEntryPath)?this.declarationEntryPath:this.writeDeclarationEntry()}markGenerated(){return this.writeMetadata()}};function Tr(e){let t=Te(e),n=Ke();n.withScope(`CONFIG`);let r=new wr(t),i=new Ot(t,{logger:n,oiyoState:r}),a=new Nt(t,{logger:n,oiyoState:r,oiyoApi:i}),o=new $t(t,{logger:n}),s=new zt(t,{logger:n,oiyoState:r});return{logger:n,config:t,api:i,component:a,layout:s,state:r,route:new En(t,{logger:n,oiyoState:r,oiyoRoot:o,oiyoLayout:s}),root:o}}function Er(e){return[{name:`oiyo:deps`,enforce:`pre`,async config(t){let{config:n}=await De({name:`oiyo`,cwd:t.root}),r=Tr(n||e);return ze(t,{oiyo:r,resolve:{alias:{"~":C.resolve(r.config.rootDir,r.config.srcDir),"@":C.resolve(r.config.rootDir,r.config.srcDir),"@@":C.normalize(r.config.rootDir),"~~":C.normalize(r.config.rootDir)}},optimizeDeps:{exclude:[`@skiyee/oiyo`]}})}}]}function Dr(){let e;return[{name:`oiyo:serve`,apply:`serve`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`VITE`),e.logger.withScope(`HMR`)},async buildStart(){await Promise.all([e.api.scanApis(),e.component.scanComponents(),e.route.scanPages(),e.layout.scanLayouts()]),e.state.canReuseGeneratedState()||(e.api.writeDeclaration(),e.component.writeDeclaration(),e.route.writePagesJson()&&e.route.writeDeclaration(),e.layout.writeDeclaration(),e.state.markGenerated())},configureServer(t){e.route.watchPagesConfig(()=>{e.route.writePagesJson()&&e.route.writeDeclaration(),t.hot.send({type:`full-reload`})});let n=async t=>{let n=v.normalize(t);e.route.isPage(n)?e.route.enterPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.enterComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?await e.api.enterApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.enterLayout(n)&&e.layout.writeDeclaration()};t.watcher.on(`add`,e=>void n(e));let r=t=>{let n=v.normalize(t);e.route.isPage(n)?e.route.exitPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.exitComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?e.api.exitApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.exitLayout(n)&&e.layout.writeDeclaration()};t.watcher.on(`unlink`,e=>void r(e));let i=async t=>{e.api.isApi(t)&&await e.api.enterApi(t)&&e.api.writeDeclaration()};t.watcher.on(`change`,e=>void i(e))},async transform(t,n){let r=v.normalize(n);if(r.includes(`?`)||!r.startsWith(`${e.state.srcDir}/`))return null;let i=t,a=null;return[`.ts`,`.js`].some(e=>r.endsWith(e))?(a=e.api.applyApis(t,r),i=a.code):[`.vue`,`.nvue`].some(e=>r.endsWith(e))&&(a=e.component.applyComponents(t,r,{withApis:!0}),i=a.code),e.root.isRootPath(r)?(e.root.parseRoot(i),e.root.transformRoot(i)):e.route.isPage(r)?(this.addWatchFile(e.root.rootPath),await e.route.transformPage(i,r)):a},resolveId(e){if(e===`virtual:oiyo-root-context`)return R},load(t){if(t===R)return e.root.rootVM||`export function useRootContext() {return {}}`},async handleHotUpdate({file:t,server:n,read:r}){if(e.root.isRootPath(t)){let t=await r(),i=!1;if(e.root.shouldRefreshView(t)&&(i=!0),e.root.shouldRefreshVM(t)){let e=n.moduleGraph.getModuleById(R);e&&(n.moduleGraph.invalidateModule(e),i=!0)}if(i){n.hot.send({type:`full-reload`});return}}},async closeBundle(){await e.route.unwatchPagesConfig()}}]}function Or(e={}){return[...Er(e),...Dr(),...Cr()]}export{k as LogLevels,Or as OiyoCorePlugin,Bt as OiyoLayout,Ot as OiyoModApi,Nt as OiyoModComponent,zt as OiyoModLayout,$t as OiyoModRoot,En as OiyoModRoute,On as OiyoPage,wr as OiyoState,R as RESOLVED_VIRTUAL_ROOT_CONTEXT_ID,Zt as VIRTUAL_ROOT_CONTEXT_ID,Ke as createLogger,Dn as definePageMeta,en as defineRootContext};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oiyo/core",
3
3
  "type": "module",
4
- "version": "0.3.0-beta.1",
4
+ "version": "0.3.0-beta.3",
5
5
  "author": {
6
6
  "name": "skiyee",
7
7
  "email": "319619193@qq.com",
@@ -50,7 +50,7 @@
50
50
  "magic-string": "^0.30.21",
51
51
  "pathe": "^2.0.3",
52
52
  "tinyglobby": "^0.2.15",
53
- "@oiyo/config": "0.3.0-beta.1"
53
+ "@oiyo/config": "0.3.0-beta.3"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@babel/types": "^7.29.0",