@oiyo/core 0.0.3 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +2 -2
- package/README.md +1 -1
- package/dist/index.cjs +19 -9
- package/dist/index.d.cts +391 -43
- package/dist/index.d.mts +391 -43
- package/dist/index.mjs +19 -9
- package/package.json +3 -11
- package/dist/types-B6aQQOoW.d.mts +0 -53
- package/dist/types-Bnj1jLZh.d.cts +0 -53
- package/dist/types.cjs +0 -7
- package/dist/types.d.cts +0 -52
- package/dist/types.d.mts +0 -52
- package/dist/types.mjs +0 -7
package/dist/index.mjs
CHANGED
|
@@ -1,15 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @oiyo/core v0.0
|
|
2
|
+
* @oiyo/core v0.1.0
|
|
3
3
|
* Copyright (c) 2026 skiyee. All rights reserved.
|
|
4
4
|
* Commercial software. See LICENSE for terms.
|
|
5
|
-
* Official site: https://oiyo.
|
|
5
|
+
* Official site: https://oiyo.js.org
|
|
6
6
|
*/
|
|
7
|
-
import{
|
|
8
|
-
`.repeat(e):``;
|
|
7
|
+
import{createRequire as e}from"node:module";import t,{pid as n}from"node:process";import r from"node:readline";import{blue as i,bold as a,cyan as o,dim as s,red as c,yellow as l}from"ansis";import{existsSync as u,mkdirSync as d,renameSync as ee,statSync as f,unlinkSync as te,writeFileSync as ne}from"node:fs";import{lstat as p,readFile as m,readdir as re,realpath as ie,stat as h}from"node:fs/promises";import{basename as g,dirname as _,join as v,matchesGlob as y,normalize as b,parse as x,relative as S,resolve as C,sep as ae}from"pathe";import{createHash as oe}from"node:crypto";import{parse as w}from"@babel/parser";import se from"@babel/traverse";import{glob as ce}from"tinyglobby";import{parse as T}from"@vue/compiler-sfc";import{DEFAULT_EXCLUDE as le,resolveOiyoConfig as ue}from"@oiyo/config";import{defineComponent as de}from"vue";import E from"magic-string";import{loadConfig as fe,watchConfig as pe}from"c12";import{defu as me}from"defu";import{stat as he,unwatchFile as ge,watch as _e,watchFile as ve}from"fs";import{lstat as ye,open as be,readdir as xe,realpath as Se,stat as Ce}from"fs/promises";import{EventEmitter as we}from"events";import*as D from"path";import{Readable as Te}from"node:stream";import O,{join as Ee,relative as De,resolve as Oe,sep as ke}from"node:path";import{type as Ae}from"os";const k={silent:0,error:1,warn:2,info:3,debug:4,verbose:5};let je,Me,Ne=0,Pe;function Fe(){let e=t.stdout.rows-2,n=e>0?`
|
|
8
|
+
`.repeat(e):``;t.stdout.write(n),r.cursorTo(t.stdout,0,0),r.clearScreenDown(t.stdout)}function Ie(){return Pe??=new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`numeric`,second:`numeric`}),Pe}function A(e=`info`,n={}){if(n.customLogger)return n.customLogger;let r=new WeakSet,u=new Set,{prefix:d=`[OIYO]`,scope:ee,allowClearScreen:f=!0,console:te=globalThis.console}=n,ne=k[e],p=f&&t.stdout.isTTY&&!t.env.CI,m=p?Fe:()=>{};function re(e,t,n={}){let r=ie(e,n.scope??ee);return n.timestamp?`${s(Ie().format(new Date))} ${i(d)} ${r} ${t}`:`${i(a(d))} ${r} ${t}`}function ie(e,t){if(!t)return` `;let n=`[${t.toUpperCase()}]`;return{info:o(n),warn:l(n),error:c(n),debug:s(o(n))}[e]}function h(e,t,n={}){if(ne<k[e])return;let i=e;if(n.error&&r.add(n.error),p){if(e===je&&t===Me){Ne++,m(),te[e](re(e,t,n),l(`(x${Ne+1})`));return}Ne=0,je=e,Me=t,n.clear&&m()}te[i](re(e,t,n))}let g={hasWarned:!1,withScope(t){return A(e,{...n,scope:t})},debug(e,t){h(`debug`,e,t)},info(e,t){h(`info`,e,t)},warn(e,t){g.hasWarned=!0,h(`warn`,e,t)},warnOnce(e,t){u.has(e)||(u.add(e),g.hasWarned=!0,h(`warn`,e,t))},error(e,t){g.hasWarned=!0,h(`error`,e,t)},clearScreen(e){ne>=k[e]&&m()},hasErrorLogged(e){return r.has(e)}};return g}const j=typeof se==`function`?se:se.default,Le=e(import.meta.url),Re=`**/*`;function M(e){return e?Array.isArray(e)?e:[e]:[]}function ze(e){if(!u(e))return[Re];try{return f(e).isFile()?[g(e)]:[Re]}catch{return[Re]}}async function N(e){let{dir:t,pattern:n,ignore:r}=e;if(!u(t))return[];let i=f(t).isFile()?_(t):t,a=M(n),o=a.length>0?a:ze(t);try{return(await ce(o,{cwd:i,absolute:!0,ignore:M(r)})).map(e=>b(C(e)))}catch(e){return console.error(`[oiyo] Error scanning file:`,e),[]}}function P(e,t,n){let r=b(e),i=b(t);if(u(i))try{if(f(i).isFile())return r===i}catch{return!1}if(r!==i&&!r.startsWith(`${i}/`))return!1;let a=b(S(i,r)),o=M(n?.pattern);return M(n?.ignore).some(e=>y(a,e))?!1:o.length===0?!0:o.some(e=>y(a,e))}function F(e,t=8){return oe(`sha256`).update(e).digest(`hex`).slice(0,t)}function I(e,t){let r=`${e}.${n}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;return ne(r,t,`utf-8`),u(e)&&te(e),ee(r,e),!0}function Be(e,t,n){let r=b(S(e,t));return n?.stripExtension&&(r=r.replace(/\.[cm]?[jt]sx?$/,``)),r.startsWith(`.`)?r:`./${r}`}function L(e){return!e.startsWith(`.`)&&!e.startsWith(`/`)&&!/^[a-z]:[\\/]/i.test(e)}function Ve(e){let t=e.split(`/`).filter(Boolean);return e.startsWith(`@`)?t.slice(0,2).join(`/`):t[0]||e}function He(e,t){if(!L(t))return{path:b(C(e,t))};try{let n=Ve(t),r=_(b(Le.resolve(`${n}/package.json`,{paths:[e]}))),i=t.slice(n.length).replace(/^\/+/,``);return{importBase:t.replace(/\\/g,`/`),path:b(i?C(r,i):r)}}catch{return{path:b(C(e,t))}}}function Ue(e,t,n){if(!n)return e;let r=b(S(t,e));return!r||r===`.`?n:`${n}/${r}`}function We(e,t,n){return L(t)?n?.stripExtension?t.replace(/\.[cm]?[jt]sx?$/,``):t:Be(e,t,n)}function Ge(e){if(!e)return``;let t=e.replace(/\p{Lu}/gu,e=>`-${e.toLowerCase()}`);return t.startsWith(`-`)?t.slice(1):t}function R(e){return e?e.replace(/[-_](.)/g,(e,t)=>t.toUpperCase()).replace(/^(.)/,e=>e.toUpperCase()):``}function Ke(e,t){let n=w(e,{sourceType:`module`,plugins:[`typescript`]}),r={start:0,end:0};return j(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 qe(e){return e.replace(/\s+/g,``)}const Je=e(import.meta.url),Ye=[`.ts`,`.mts`,`.cts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.jsx`,`.vue`,`.d.ts`,`.d.mts`,`.d.cts`];function Xe(e){let t=e.split(`/`).filter(Boolean);return e.startsWith(`@`)?t.slice(0,2).join(`/`):t[0]||e}function Ze(e,t){let n=b(e);for(;;){let e=C(n,`node_modules`,t,`package.json`);if(u(e))return b(e);let r=_(n);if(r===n)return;n=r}}function Qe(e,t,n){let r=b(C(x(e).dir,t)),i=n?.preferTypes?[`.d.ts`,`.d.mts`,`.d.cts`,...Ye]:Ye;if(u(r))return r;for(let e of i){let t=`${r}${e}`;if(u(t))return b(t)}for(let e of i){let t=C(r,`index${e}`);if(u(t))return b(t)}return r}function $e(e,t){if(!e||typeof e!=`object`)return t===`import`&&typeof e==`string`?e:void 0;if(t===`types`){let t=e.types;if(typeof t==`string`)return t;if(t&&typeof t==`object`){let e=t;return typeof e.import==`string`?e.import:typeof e.require==`string`?e.require:typeof e.default==`string`?e.default:void 0}}let n=e;return typeof n.import==`string`?n.import:typeof n.default==`string`?n.default:typeof n.require==`string`?n.require:void 0}async function et(e,t,n){try{let r=Xe(t),i=Ze(e,r)||b(Je.resolve(`${r}/package.json`,{paths:[e]})),a=_(i),o=JSON.parse(await m(i,`utf-8`)),s=t.slice(r.length).replace(/^\/+/,``),c=s?`./${s}`:`.`,l=typeof o.exports==`object`&&o.exports?o.exports[c]??(c===`.`?o.exports:void 0):void 0,u=n?.preferTypes?$e(l,`types`)||(c===`.`?o.types:void 0):$e(l,`import`)||(c===`.`?o.module||o.main:void 0);return b(u?C(a,u):Je.resolve(t,{paths:[e]}))}catch{return}}async function tt(e,t,n){return L(t)?await et(_(e),t,n)||t:Qe(e,t,n)}function nt(e,t){return t.startsWith(`.`)||t.startsWith(`/`)?Qe(e,t,{preferTypes:!0}):t}function rt(e,t,n){return L(t)?n||(Ze(e,Xe(t))?t.replace(/\\/g,`/`):void 0):n}async function it(e,t){if(!e.importBase||!L(e.importBase))return{typePath:e.path,valuePath:e.path};let n=await et(t,e.importBase),r=await et(t,e.importBase,{preferTypes:!0});return{typePath:r||n||e.path,valuePath:n||r||e.path}}function at(e,t){return!t||!e.importPath||!L(t)?e:e.importPath.startsWith(`${t}/..`)||e.importPath.startsWith(`${t}/.`)?{...e,importPath:t}:e}function ot(e){let t=R(e);return t?t[0].toLowerCase()+t.slice(1):``}function st(e){try{return w(e,{sourceType:`module`,plugins:[`typescript`,`jsx`]})}catch{return w(`(${e})`,{sourceType:`module`,plugins:[`typescript`,`jsx`]})}}function z(e){return e.type===`Identifier`?[e.name]:e.type===`ObjectPattern`?e.properties.flatMap(e=>e.type===`ObjectProperty`?z(e.value):e.type===`RestElement`?z(e.argument):[]):e.type===`ArrayPattern`?e.elements.flatMap(e=>e?z(e):[]):e.type===`AssignmentPattern`?z(e.left):e.type===`RestElement`?z(e.argument):[]}function ct(e){let t=x(e);return ot(t.name===`index`?x(t.dir).name:t.name)}function lt(e,t){if(!e.endsWith(`.vue`))return t;try{let{descriptor:n}=T(t,{filename:e});return[n.script?.content,n.scriptSetup?.content].filter(e=>!!e).join(`
|
|
9
|
+
`)}catch{return t}}async function ut(e,t,n=e,r){let i=st(lt(e,t)),a=[],o=[],s=[],c=!1;if(r?.visitedFiles?.add(e),j(i,{ExportDefaultDeclaration(){c=!0},ExportAllDeclaration(e){let t=e.node.source?.value;t&&s.push({exportKind:e.node.exportKind,source:t})},ExportNamedDeclaration(t){let{node:i}=t,s=i.exportKind;if(i.declaration)switch(i.declaration.type){case`FunctionDeclaration`:case`TSDeclareFunction`:case`ClassDeclaration`:case`TSEnumDeclaration`:s!==`type`&&i.declaration.id?.name&&a.push({exportName:i.declaration.id.name,filePath:e,importPath:n,name:i.declaration.id.name});break;case`VariableDeclaration`:if(s===`type`)break;for(let t of i.declaration.declarations)for(let r of z(t.id))a.push({exportName:r,filePath:e,importPath:n,name:r});break;case`TSInterfaceDeclaration`:case`TSTypeAliasDeclaration`:r?.includeTypes&&i.declaration.id?.name&&o.push({exportName:i.declaration.id.name,filePath:e,importPath:n,name:i.declaration.id.name});break}for(let t of i.specifiers){if(t.type!==`ExportSpecifier`){if(s===`type`&&!r?.includeTypes||t.exported.type!==`Identifier`)continue;a.push({exportName:t.exported.name,filePath:e,importPath:n,name:t.exported.name});continue}if(s===`type`||t.exportKind===`type`){if(!r?.includeTypes||t.exported.type!==`Identifier`)continue;let a=t.exported.name,s=e,c=n;i.source?.value&&t.local.type===`Identifier`&&(a=t.local.name,c=nt(e,i.source.value),s=L(c)?e:c),o.push({exportName:a,filePath:s,importPath:c,name:t.exported.name});continue}t.exported.type===`Identifier`&&a.push({exportName:t.exported.name,filePath:e,importPath:n,name:t.exported.name})}}}),c){let t=ct(e);t&&a.push({exportName:`default`,filePath:e,importPath:n,name:t})}for(let t of s){let i=await tt(e,t.source,{preferTypes:r?.includeTypes});if(!(!i||L(i)||r?.visitedFiles?.has(i)))try{let e=await ut(i,await m(i,`utf-8`),n,{includeTypes:r?.includeTypes,visitedFiles:r?.visitedFiles});t.exportKind!==`type`&&a.push(...e.valueItems.map(e=>({...e,importPath:n}))),r?.includeTypes&&o.push(...e.typeItems.map(e=>({...e,importPath:n})))}catch{continue}}return{typeItems:o,valueItems:a}}function dt(e){let t=st(e),n=new Set;return j(t,{Program(e){Object.keys(e.scope.bindings).forEach(e=>n.add(e)),e.stop()}}),n}function ft(e,t,n){let r=st(e),i=new Set(t),a=new Set(n?.boundNames||[]),o=new Set;return j(r,{ReferencedIdentifier(e){let t=e.node.name;a.has(t)||e.scope.hasBinding(t)||i.has(t)&&o.add(t)}}),o}function pt(e){let t=e.importPath||e.filePath;return e.exportName===`default`?`import ${e.name} from '${t}'`:e.exportName===e.name?`import { ${e.name} } from '${t}'`:`import { ${e.exportName} as ${e.name} } from '${t}'`}function mt(e,t){let n=We(t,e.importPath||e.filePath,{stripExtension:!0});return` const ${e.name}: typeof import('${n}')['${e.exportName}'];`}const ht=[`**/*.ts`,`**/*.mts`,`**/*.cts`,`**/*.js`,`**/*.mjs`,`**/*.cjs`,`**/*.tsx`,`**/*.jsx`];function gt(e){return typeof e==`string`?{isType:void 0,localName:e,sourceName:e}:{isType:e.isType,localName:e.as||e.name,sourceName:e.name}}function _t(e){return typeof e!=`string`&&e.only!==void 0}function vt(e,t){let n=C(e.rootDir,e.srcDir),r=typeof t==`string`?t:t.from,i=He(n,r);return{exclude:typeof t==`string`?void 0:t.exclude,ignore:typeof t==`string`?void 0:t.ignore,importBase:rt(n,r,i.importBase),path:i.path,pattern:typeof t==`string`?void 0:t.pattern,types:typeof t==`string`?!1:t.types}}function yt(e){return(Array.isArray(e)?e:[e]).map(e=>typeof e==`string`?{exclude:[],ignore:[],importBase:void 0,pattern:ht,path:b(C(e)),types:!1}:{exclude:e.exclude||[],ignore:e.ignore,importBase:e.importBase,pattern:e.pattern||ht,path:b(C(e.path)),types:e.types||!1})}function bt(e){return JSON.stringify({exclude:[...e.exclude||[]].sort(),ignore:M(e.ignore),importBase:e.importBase,path:e.path,pattern:M(e.pattern),types:e.types||!1})}function xt(e){return{exportName:e.export||e.name,filePath:e.from,importPath:e.from,name:e.name}}function St(e,t){return{importPath:We(t,e.importPath||e.filePath,{stripExtension:!0}),specifier:e.exportName===e.name?e.name:`${e.exportName} as ${e.name}`}}function Ct(e){return`${e.filePath}#${e.exportName}`}var wt=class{constructor(e,t){this._config=e,this.autoApis=[],this.autoApiTypes=[],this.autoApiMap=new Map,this.autoApiTypeMap=new Map,this.includedApis=[],this.includedApiTypes=[],this.apiSources=[],this.oiyoState=t.oiyoState,this.logger=t.logger.withScope(`AUTO_API`),this.registerConfigScanners()}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return C(this.typesDir,`apis.d.ts`)}isAutoApiPath(e){let t=b(e);return this.apiSources.some(e=>P(t,e.path,{ignore:e.ignore,pattern:e.pattern}))}includeApi(e){let t=Array.isArray(e)?e:[e];this.includedApis.push(...t.map(xt))}includeApiType(e){let t=Array.isArray(e)?e:[e];this.includedApiTypes.push(...t.map(xt))}includeApis(e){for(let t of yt(e)){let e=bt(t);this.apiSources.some(t=>bt(t)===e)||this.apiSources.push(t)}}registerConfigScanners(){for(let e of this._config.scan?.apis||[]){if(!_t(e)){this.includeApis(vt(this._config,e));continue}for(let t of e.only){let{isType:n,localName:r,sourceName:i}=gt(t),a={export:i===r?void 0:i,from:e.from,name:r};n??e.types?this.includeApiType(a):this.includeApi(a)}}}resetCollectedState(){this.autoApis=[],this.autoApiTypes=[],this.autoApiMap.clear(),this.autoApiTypeMap.clear()}registerValue(e,t){let n=this.autoApiMap.get(e.name);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||n.filePath===e.filePath&&n.exportName!==`default`&&e.exportName===`default`||this.logger.warn(`自动 API 名称冲突: ${e.name} 已存在,已跳过 ${Ct(e)}`),!1):(this.autoApiMap.set(e.name,e),t?.trackScanned&&this.autoApis.push(e),!0)}registerType(e,t){let n=this.autoApiTypeMap.get(e.name);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||this.logger.warn(`自动 API 类型名称冲突: ${e.name} 已存在,已跳过 ${Ct(e)}`),!1):(this.autoApiTypeMap.set(e.name,e),t?.trackScanned&&this.autoApiTypes.push(e),!0)}seedIncludedRegistrations(){this.includedApis.forEach(e=>this.registerValue(e)),this.includedApiTypes.forEach(e=>this.registerType(e))}registerScannedValueItems(e,t){for(let n of t){let t=at(n,e.importBase);(e.exclude||[]).includes(t.name)||this.registerValue(t,{trackScanned:!0})}}registerScannedTypeItems(e,t){for(let n of t){let t=at(n,e.importBase);(e.exclude||[]).includes(t.name)||this.registerType(t,{trackScanned:!0})}}async scanSourceFiles(e,t,n,r){for(let i of t)try{let t=await ut(i,await m(i,`utf-8`),Ue(i,n,e.importBase),{includeTypes:r.includeTypes,visitedFiles:new Set});r.registerValues&&this.registerScannedValueItems(e,t.valueItems),r.registerTypes&&this.registerScannedTypeItems(e,t.typeItems)}catch{this.logger.warn(`解析自动 API 文件失败,已跳过: ${i}`)}}async collectApis(){let e=C(this._config.rootDir,this._config.srcDir);this.resetCollectedState(),this.seedIncludedRegistrations();for(let t of this.apiSources){let{typePath:n,valuePath:r}=await it(t,e),i=await N({dir:r,ignore:t.ignore,pattern:t.pattern});if(t.types&&r===n){await this.scanSourceFiles(t,i,r,{includeTypes:!0,registerTypes:!0,registerValues:!0});continue}if(await this.scanSourceFiles(t,i,r,{includeTypes:!1,registerValues:!0}),!t.types)continue;let a=r===n?i:await N({dir:n,ignore:t.ignore,pattern:t.pattern});await this.scanSourceFiles(t,a,n,{includeTypes:!0,registerTypes:!0})}return this.autoApis}collectBoundNames(e){return dt(e)}resolveImports(e,t){return!e||this.autoApiMap.size===0?[]:Array.from(ft(e,this.autoApiMap.keys(),t)).sort().map(e=>pt(this.autoApiMap.get(e)))}resolveImport(e){let t=this.autoApiMap.get(e);if(t)return pt(t)}generateDeclaration(){let e=Array.from(this.autoApiTypeMap.values()).sort((e,t)=>e.name.localeCompare(t.name)).reduce((e,t)=>{let n=St(t,this.typesDir),r=e.get(n.importPath)||[];return r.push(n.specifier),e.set(n.importPath,r),e},new Map);return[`// Generated by oiyo`,`declare global {`,...Array.from(this.autoApiMap.values()).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>mt(e,this.typesDir)),`}`,``,`declare global {`,...Array.from(e.entries()).flatMap(([e,t])=>[` // @ts-ignore`,` export type { ${t.join(`, `)} } from '${e}';`]),`}`,``,`export {}`,``].join(`
|
|
10
|
+
`)}writeDeclaration(){return d(this.typesDir,{recursive:!0}),I(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}};const Tt=/<\/?\s*([a-z][\w-]*)\b/gi,Et=[`**/*.vue`,`**/*.nvue`];function Dt(e){return typeof e==`string`?{localName:e,sourceName:e}:{localName:e.as||e.name,sourceName:e.name}}function Ot(e){return typeof e!=`string`&&e.only!==void 0}function kt(e,t){let n=He(C(e.rootDir,e.srcDir),typeof t==`string`?t:t.from);return{chain:typeof t==`string`?!0:t.chain,ignore:typeof t==`string`?void 0:t.ignore,importBase:n.importBase,path:n.path,pattern:typeof t==`string`?void 0:t.pattern,prefix:typeof t==`string`?void 0:t.prefix}}function At(e){return(e.scan?.components||[]).filter(e=>!Ot(e)).map(t=>kt(e,t))}function B(e,t){let n=b(t);return At(e).some(e=>P(n,e.path,{ignore:e.ignore,pattern:e.pattern}))}function jt(e){return e?R(e):``}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}function Nt(e,t,n){let{dir:r,name:i}=x(S(t,e)),a=r&&r!==`.`?r.split(ae).filter(Boolean):[];(i!==`index`||a.length===0)&&a.push(i);let o=Mt(a),s=n?.chain===!1?o.slice(-1):o;return`${jt(n?.prefix)}${s.map(e=>R(e)).join(``)}`}function Pt(e){let t=new Set;Tt.lastIndex=0;let n=Tt.exec(e);for(;n;)t.add(n[1]),n=Tt.exec(e);return t}function Ft(e){return e.includes(`-`)?R(e):e}function It(e){return{componentName:e.name,exportName:e.export||`default`,filePath:e.from,importPath:e.from}}function Lt(e){return(Array.isArray(e)?e:[e]).map(e=>typeof e==`string`?{chain:!0,ignore:[],importBase:void 0,pattern:Et,path:b(C(e)),prefix:void 0}:{chain:e.chain??!0,ignore:e.ignore,importBase:e.importBase,pattern:e.pattern||Et,path:b(C(e.path)),prefix:e.prefix})}function Rt(e){return JSON.stringify({chain:e.chain,ignore:M(e.ignore),importBase:e.importBase,path:e.path,pattern:M(e.pattern),prefix:e.prefix})}function zt(e){let t=e.importPath||e.filePath;return e.exportName===`default`?`import ${e.componentName} from '${t}'`:e.exportName===e.componentName?`import { ${e.componentName} } from '${t}'`:`import { ${e.exportName} as ${e.componentName} } from '${t}'`}function Bt(e,t){let n=We(t,e.importPath||e.filePath);return` ${e.componentName}: typeof import('${n}')['${e.exportName}'];`}var Vt=class{constructor(e,t){this._config=e,this.autoComponents=[],this.registeredComponents=[],this.componentSources=[],this.autoComponentMap=new Map,this.oiyoState=t.oiyoState,this.logger=t.logger.withScope(`AUTO_COMPONENT`),this.registerConfigScanners()}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return C(this.typesDir,`components.d.ts`)}isAutoComponentPath(e){let t=b(e);return this.componentSources.some(e=>P(t,e.path,{ignore:e.ignore,pattern:e.pattern}))}registerComponent(e){this.registeredComponents.push(It(e))}registerComponents(e){for(let t of Lt(e)){let e=Rt(t);this.componentSources.some(t=>Rt(t)===e)||this.componentSources.push(t)}}registerConfigScanners(){for(let e of this._config.scan?.components||[]){if(!Ot(e)){this.registerComponents(kt(this._config,e));continue}for(let t of e.only){let{localName:n,sourceName:r}=Dt(t);this.registerComponent({export:r,from:e.from,name:e.prefix?`${R(e.prefix)}${n}`:n})}}}setResolvedComponent(e,t){let n=this.autoComponentMap.get(e.componentName);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||this.logger.warn(`组件名称冲突: ${e.componentName} 已存在,已跳过 ${e.filePath}`),!1):(this.autoComponentMap.set(e.componentName,e),t?.trackScanned&&this.autoComponents.push(e),!0)}async collectComponents(){this.autoComponents=[],this.autoComponentMap.clear(),this.registeredComponents.forEach(e=>this.setResolvedComponent(e));for(let e of this.componentSources)(await N({dir:e.path,ignore:e.ignore,pattern:e.pattern})).forEach(t=>{let n=e.path===t?_(t):e.path;this.setResolvedComponent({componentName:Nt(t,n,{chain:e.chain,prefix:e.prefix}),exportName:`default`,filePath:t,importPath:Ue(t,e.path,e.importBase)},{trackScanned:!0})});return this.autoComponents}resolveComponentImports(e,t){if(!e||this.autoComponentMap.size===0)return[];let n=[],r=new Set,i=t?b(t):void 0;for(let t of Pt(e)){let e=Ft(t),a=this.autoComponentMap.get(e);a&&(i&&a.filePath===i||r.has(e)||(r.add(e),n.push(zt(a))))}return n}resolveComponentImport(e,t){let n=this.autoComponentMap.get(e);if(!n)return;let r=t?b(t):void 0;if(!(r&&n.filePath===r))return zt(n)}generateDeclaration(){return[`// Generated by oiyo`,`declare module 'vue' {`,` export interface GlobalComponents {`,...Array.from(this.autoComponentMap.values()).sort((e,t)=>e.componentName.localeCompare(t.componentName)).map(e=>Bt(e,this.typesDir)),` }`,`}`,``,`export {}`,``].join(`
|
|
11
|
+
`)}writeDeclaration(){return d(this.typesDir,{recursive:!0}),I(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}};function Ht(e){return e.includes(`<OiyoLayout`)||e.includes(`<oiyo-layout`)}function Ut(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 Wt(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 Gt(e,t){let{dir:n,name:r}=x(S(t,e));return(n&&n!==`.`?[...n.split(ae),r]:[r]).map(e=>Ge(e)).join(`-`)}function Kt(e){return`OiyoLayout${e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}`}const qt=de({name:`OiyoLayout`,setup(e,t){return()=>t.slots.default?.()}});var Jt=class{constructor(e,t){this.config=e,this.layoutFiles=[],this.logger=t.logger.withScope(`LAYOUT`),this.oiyoState=t.oiyoState}get srcDir(){return C(this.config.rootDir,this.config.srcDir)}get layoutDir(){return C(this.srcDir,this.config.dir?.layouts||`layouts`)}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return C(this.typesDir,`layouts.d.ts`)}isLayoutPath(e){let t=b(e);return!t.endsWith(`.vue`)&&!t.endsWith(`.nvue`)||[...le,...this.config.exclude||[]].some(e=>y(t,e))||B(this.config,t)?!1:t.startsWith(`${this.layoutDir}/`)}setLayout(e){if(this.layoutFiles.findIndex(({filePath:t})=>t===e)!==-1)return!1;let t=Gt(e,this.layoutDir),n=Kt(t);return this.layoutFiles.push({useName:t,componentName:n,filePath:e}),!0}async registerLayouts(){let e=await N({dir:this.layoutDir,pattern:[`**/*.vue`,`**/*.nvue`]});return this.layoutFiles=[],e.filter(e=>this.isLayoutPath(e)).map(e=>this.setLayout(e)),this.layoutFiles}generateDeclaration(){return[`// Generated by oiyo`,``,`declare module '@skiyee/oiyo/api' {`,` interface OiyoLayouts {`,...this.layoutFiles.slice().sort((e,t)=>e.useName.localeCompare(t.useName)).map(({useName:e,filePath:t})=>` '${e}': typeof import('${Be(this.typesDir,t)}')['default'];`),` }`,``,` type LayoutKey = keyof OiyoLayouts extends never ? string : keyof OiyoLayouts;`,``,` interface PageMeta {`,` layout?: LayoutKey | false;`,` }`,`}`,``,`export {}`,``].join(`
|
|
12
|
+
`)}writeDeclaration(){return d(this.typesDir,{recursive:!0}),I(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}applyLayout(e,t){if(!Ht(t))return{template:t,script:``,imports:[]};if(e===!1)return{template:Ut(t),script:``,imports:[]};e===void 0&&(e=`default`);let n=this.layoutFiles.find(t=>t.useName===e);return n?{template:Wt(t,n.componentName),script:``,imports:[`import ${n.componentName} from '${n.filePath}'`]}:(this.logger.error(`未找到布局 "${e}",请检查布局名称或文件位置是否正确`),{template:t,script:``,imports:[]})}};function Yt(e){if(!e||!e.includes(`import`))return[];let t=w(e,{sourceType:`module`,plugins:[`typescript`]}),n=[];return j(t,{ImportDeclaration(t){let r=e.substring(t.node.start,t.node.end);n.push(r)}}),n}function Xt(e){if(!e||!e.includes(`import`))return new Set;let t=w(e,{sourceType:`module`,plugins:[`typescript`]}),n=new Set;return j(t,{ImportDeclaration(e){for(let t of e.node.specifiers)n.add(t.local.name)}}),n}function Zt(e){if(!e||!e.includes(`import`))return e;let t=w(e,{sourceType:`module`,plugins:[`typescript`]}),n=[];j(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 Qt(e,t){let n=$t(t),r=$t(e);for(let[e,t]of r){let r=n.get(e);r?en(r,t):n.set(e,t)}return tn(n)}function $t(e){let t=new Map;for(let n of e)j(w(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 en(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 tn(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}function nn(e){if(!e.includes(`defineRootContext`))return``;let{descriptor:t}=T(e);if(!t.scriptSetup)return``;let n=e=t.scriptSetup.content,r=rn(n);return n.substring(r.start,r.end+1).trim()}function rn(e){return Ke(e,`defineRootContext`)}function an(e){if(!e.includes(`<template`))return``;let{descriptor:t}=T(e);return(t.template?.content||``).trim()}function on(e,t){let n=e.replace(/\{\{([\s\S]*?)\}\}/g,(e,n)=>e.replace(n,sn(n,t)));return n=n.replace(/((?:v-(?!for\b)[\w-]+(?::[\w-]+)?|[:@][\w-]+)\s*=\s*)(["'])([\s\S]*?)\2/g,(e,n,r,i)=>`${n}${r}${sn(i,t)}${r}`),n}function sn(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=w(`(${e})`,{sourceType:`module`,plugins:[`typescript`]}),r=new E(e);return j(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 cn(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=on(n,t),n.trim()}function ln(e){if(!e)return;let t=e?.content;if(t){let e=un(t);return e.script?e:void 0}}function un(e){let t=w(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return j(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 dn(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 fn=`virtual:oiyo-root-context`,V=`\0${fn}`;function pn(e){let{script:t,imports:n}=e,r=[];return n?.length&&(r.push(...n),r.push(``)),t?(r.push(`let rootContextInstance = null`),r.push(``),r.push(`export function useRootContext() {`),r.push(`if (!rootContextInstance) {`),r.push(`const factory = ${t}`),r.push(`rootContextInstance = factory()`),r.push(`}`),r.push(`return rootContextInstance`),r.push(`}`)):(r.push(`export function useRootContext() {`),r.push(`return {}`),r.push(`}`)),r.join(`
|
|
13
|
+
`)}const mn=e=>e();var hn=class{constructor(e,t){this.config=e,this.rootView={imports:[],template:`<OiyoPage />`,script:``},this.shouldRefreshVM=e=>{let t=``;this.rootMarco&&(t=F(qe(`defineRootContext(${this.rootMarco.script})`)));let n=F(qe(nn(e)));return t!==n},this.logger=t.logger.withScope(`ROOT`),this.oiyoAutoApi=t.oiyoAutoApi}get srcDir(){return C(this.config.rootDir,this.config.srcDir)}get rootPath(){return C(this.srcDir,`App.vue`)}isRootPath(e){return e===this.rootPath}parseRoot(e){let{descriptor:t}=T(e),n=ln(t.scriptSetup);if(n?.script&&t.scriptSetup?.content&&this.oiyoAutoApi){let e=this.oiyoAutoApi.collectBoundNames(t.scriptSetup.content),r=this.oiyoAutoApi.resolveImports(n.script,{boundNames:e});r.length>0&&(n.imports=Qt(r,n.imports||[]))}return this.rootView={template:cn(t.template,{varName:n?.variable,varProperties:n?.properties}),imports:[],script:``},n&&(this.rootMarco=n,this.rootVM=pn(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 E(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=rn(e);if(r.start!==r.end){e.includes(`virtual:oiyo-root-context`)||n.appendLeft(t.scriptSetup.loc.start.offset,`
|
|
14
|
+
import { useRootContext } from 'virtual:oiyo-root-context'
|
|
15
|
+
`);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 F(this.rootView.template)!==F(an(e))}applyRoot(e){let t=[],n=``,r=``;return e.template&&(n=dn(this.rootView.template,e.template.content)),e.scriptSetup&&(t.push(...this.rootView.imports),r=`${this.rootView.script}\n${e.scriptSetup.content}`),{imports:t,script:r,template:n}}};function gn(e,t){if(!e.includes(`definePageMeta`))return``;if(!t){let{descriptor:t}=T(e);if(!t.scriptSetup)return``;e=t.scriptSetup.content}let n=_n(e);return e.substring(n.start,n.end+1).trim()}function _n(e){return Ke(e,`definePageMeta`)}function vn(e){return e.replace(/definePageMeta\s*\(\s*\{[\s\S]*?\}\s*\)/g,``).trim()}function yn(e){let t=w(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return j(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=bn(t),e.stop())}}}),n}function bn(e){let t={};for(let n of e.properties)if(n.type===`ObjectProperty`){let e=xn(n.key),r=Sn(n.value);e&&(t[e]=r)}return t}function xn(e){return e.type===`Identifier`?e.name:e.type===`StringLiteral`?e.value:null}function Sn(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=>Sn(e)).filter(e=>e!==void 0);case`ObjectExpression`:return bn(e);default:return}}function Cn(e){return`'${e.startsWith(`/`)?e:`/${e}`}'`}function wn(e){let t=new Set;for(let n of e.pages||[])t.add(Cn(n.path));for(let n of e.subPackages||[])for(let e of n.pages||[])t.add(Cn(v(n.root,e.path)));return Array.from(t).sort()}function Tn(e){let t=new Set;for(let n of e.tabBar?.list||[])t.add(Cn(n.pagePath));return Array.from(t).sort()}function En(e){return e.length>0?e.join(` |
|
|
16
|
+
`):`string`}function Dn(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 On(e){let t=wn(e),n=Tn(e);return[`/* eslint-disable */`,`// Generated by oiyo`,``,`interface NavigateToOptions {`,` url: ${En(t)};`,`}`,`interface RedirectToOptions extends NavigateToOptions {}`,``,`interface SwitchTabOptions {`,n.length>0?` url: ${n.join(` |
|
|
17
|
+
`)};`:``,`}`,``,`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(`
|
|
18
|
+
`)}const kn=e=>{},An=de({name:`OiyoPage`});var jn=class{constructor(e,t){this.pageFiles=[],this.pagesConfig={},this.config=e,this.logger=t.logger.withScope(`ROUTE`),this.oiyoState=t.oiyoState,this.oiyoRoot=t.oiyoRoot,this.oiyoLayout=t.oiyoLayout}get srcDir(){return C(this.config.rootDir,this.config.srcDir)}get mainPageDir(){return C(this.srcDir,this.config.dir.mainPackage)}get subPageDirs(){return this.config.dir.subPackages.map(e=>C(this.srcDir,e))}get pagesJsonPath(){return C(this.srcDir,`pages.json`)}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return C(this.typesDir,`pages.d.ts`)}resolvePagesJson(e){return me(Dn(this.pageFiles),e||this.pagesConfig)}async loadPagesConfig(){try{let{config:e,configFile:t}=await fe({name:`pages`,cwd:this.srcDir});this.pagesConfig=e||{}}catch{this.pagesConfig={},this.logger.warn(`加载 pages 配置失败,已采用空配置`)}return this.pagesConfig}async watchPagesConfig(e){if(this.pagesConfigWatcher)return;let t=await pe({name:`pages`,cwd:this.srcDir,acceptHMR({getDiff:e}){return e().length===0},onWatch:e=>{},onUpdate:({newConfig:t})=>{this.pagesConfig=t.config||{},this.writePagesJson(),e&&Promise.resolve(e()).catch(e=>{this.logger.error(`pages 配置更新回调失败,页面配置已更新但后续回调未完成`,{error:e})})}});this.pagesConfig=t.config||this.pagesConfig,this.pagesConfigWatcher=t}async unwatchPagesConfig(){this.pagesConfigWatcher&&=(await this.pagesConfigWatcher.unwatch(),void 0)}isPagePath(e){let t=b(e);return!t.endsWith(`.vue`)&&!t.endsWith(`.nvue`)||[...le,...this.config.exclude||[]].some(e=>y(t,e))||B(this.config,t)?!1:[this.mainPageDir,...this.subPageDirs].some(e=>t.startsWith(`${e}/`))}toPageFile(e,t){let n=!0,r=this.mainPageDir,i=this.subPageDirs.find(t=>e.startsWith(`${t}/`));i&&(n=!1);let a=x(S(n?this.srcDir:i,e)),o=a.dir===``?a.name:v(a.dir,a.name),s=n?r:i;return{filePath:e,pagePath:o,pageBelong:S(this.srcDir,s),pageMeta:t}}setPageFile(e){let t=this.pageFiles.findIndex(({pagePath:t,pageBelong:n})=>t===e.pagePath&&n===e.pageBelong);if(t===-1)return this.pageFiles.push(e),!0;let n=this.pageFiles[t],r=JSON.stringify(n.pageMeta)!==JSON.stringify(e.pageMeta);return r&&(this.pageFiles[t]=e),r}async loadPagesJson(){try{let e=await m(this.pagesJsonPath,`utf-8`),t=JSON.parse(e);for(let e of t.pages||[]){let{path:t,...n}=e,r=C(this.srcDir,e.path),i=this.toPageFile(r,n);this.setPageFile(i)}for(let e of t.subPackages||[]){let t=e.root;for(let n of e.pages||[]){let{path:e,...r}=n,i=C(this.srcDir,t,n.path);this.setPageFile(this.toPageFile(i,r))}}}catch(e){this.logger.error(`加载 pages.json 失败,已跳过现有文件内容,请检查 pages.json 是否存在且格式正确:`,{error:e})}}writePagesJson(e){try{let t=this.resolvePagesJson(e),n=`${JSON.stringify(t,null,2)}\n`;I(this.pagesJsonPath,n),this.writeDeclaration(e)}catch(e){this.logger.error(`写入 pages.json 失败,请检查目标文件权限和内容格式:`,{error:e})}}generateDeclaration(e){return On(this.resolvePagesJson(e))}writeDeclaration(e){try{d(this.typesDir,{recursive:!0}),I(this.declarationPath,this.generateDeclaration(e)),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`写入 pages.d.ts 失败,请检查目标文件权限和内容格式:`,{error:e})}return this.declarationPath}async registerPages(){let e=[this.mainPageDir,...this.subPageDirs],t=(await Promise.all(e.map(e=>N({dir:e,pattern:[`**/*.vue`,`**/*.nvue`]})))).flat(2).filter(e=>this.isPagePath(e));for(let e of t){let t=await m(e,`utf-8`),n={},r=gn(t);r&&(n=yn(r)),this.setPageFile(this.toPageFile(e,n))}return this.pageFiles}async tryUpdatePage(e,t){let n=yn(e);this.setPageFile(this.toPageFile(t,n))&&(this.writePagesJson(),await new Promise(e=>setTimeout(e,100)))}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}=T(e),r=new E(e);if(!n.template?.content)return{code:r.toString(),sourceMap:r.generateMap()};n.scriptSetup&&await this.tryUpdatePage(n.scriptSetup.content,t);let i=this.oiyoRoot.applyRoot(n),a=[...i.imports],o=i.template,s=i.script,c={};n.scriptSetup&&(c=this.pageFiles.find(e=>t.startsWith(e.filePath))?.pageMeta||{},s=vn(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=Yt(n.scriptSetup.content);a=Qt(a,e),s=Zt(s),r.overwrite(n.scriptSetup.loc.start.offset,n.scriptSetup.loc.end.offset,`${a.join(`
|
|
9
19
|
`)}\n${s}`)}else if(s||a.length>0){let e=[`<script setup>`,...a,s,`<\/script>`].filter(Boolean).join(`
|
|
10
|
-
`);r.appendRight(n.template.loc.end.offset+11,`\n\n${e}`)}return{code:r.toString(),sourceMap:r.generateMap()}}};const j={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},M={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:j.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(M);const N=`READDIRP_RECURSIVE_ERROR`,rt=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,N]),P=[j.DIR_TYPE,j.EVERYTHING_TYPE,j.FILE_DIR_TYPE,j.FILE_TYPE],it=new Set([j.DIR_TYPE,j.EVERYTHING_TYPE,j.FILE_DIR_TYPE]),at=new Set([j.EVERYTHING_TYPE,j.FILE_DIR_TYPE,j.FILE_TYPE]),ot=e=>rt.has(e.code),st=process.platform===`win32`,F=e=>!0,I=e=>{if(e===void 0)return F;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 F};var ct=class extends Ce{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...M,...e},{root:n,type:r}=t;this._fileFilter=I(t.fileFilter),this._directoryFilter=I(t.directoryFilter);let i=t.lstat?le:pe;st?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??M.depth,this._wantsDir=r?it.has(r):!1,this._wantsFile=r?at.has(r):!1,this._wantsEverything=r===j.EVERYTHING_TYPE,this._root=Ee(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 de(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=Ee(we(t,r));n={path:Te(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){ot(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 fe(t),n=await le(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===De){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=N,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 lt(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=j.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&&!P.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${P.join(`, `)}`);return t.root=e,new ct(t)}const L=()=>{},R=process.platform,ut=R===`win32`,dt=R===`darwin`,ft=R===`linux`,pt=R===`freebsd`,mt=Oe()===`OS400`,z={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},B=z,ht={lstat:ye,stat:x},V=`listeners`,H=`errHandlers`,U=`rawEmitters`,gt=[V,H,U],_t=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(`.`)),vt=e=>_t.has(S.extname(e).slice(1).toLowerCase()),W=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},G=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},yt=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},K=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},bt=e=>e instanceof Set?e.size===0:!e,q=new Map;function xt(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&J(S.resolve(e,r),V,S.join(e,r))};try{return _e(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const J=(e,t,n,r,i)=>{let a=q.get(e);a&&W(a[t],e=>{e(n,r,i)})},St=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=q.get(t),c;if(!n.persistent)return c=xt(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)G(s,V,i),G(s,H,a),G(s,U,o);else{if(c=xt(e,n,J.bind(null,t,V),a,J.bind(null,t,U)),!c)return;c.on(B.ERROR,async n=>{let r=J.bind(null,t,H);if(s&&(s.watcherUnusable=!0),ut&&n.code===`EPERM`)try{await(await be(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},q.set(t,s)}return()=>{K(s,V,i),K(s,H,a),K(s,U,o),bt(s.listeners)&&(s.watcher.close(),q.delete(t),gt.forEach(yt(s)),s.watcher=void 0,Object.freeze(s))}},Y=new Map,Ct=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=Y.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(y(t),o=void 0),o?(G(o,V,i),G(o,U,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:ve(t,n,(n,r)=>{W(o.rawEmitters,e=>{e(B.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&W(o.listeners,t=>t(e,n))})},Y.set(t,o)),()=>{K(o,V,i),K(o,U,a),bt(o.listeners)&&(Y.delete(t),y(t),o.options=o.watcher=void 0,Object.freeze(o))}};var wt=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=S.dirname(e),i=S.basename(e);this.fsw._getWatchedDir(r).add(i);let a=S.resolve(e),o={persistent:n.persistent};t||=L;let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&vt(i)?n.binaryInterval:n.interval,s=Ct(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=St(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=S.dirname(e),i=S.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 x(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(B.CHANGE,e,n),(dt||ft||pt)&&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(B.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(B.ADD,e,0))return;this.fsw._emit(B.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 b(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(B.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(B.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=S.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=S.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=S.join(i,S.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(B.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(S.dirname(e)),c=s.has(S.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(B.ADD_DIR,e,t),s.add(S.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 ht[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=S.resolve(e),l=s?await b(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 b(e):e;if(this.fsw.closed)return;let a=S.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(B.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(S.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}}};
|
|
20
|
+
`);r.appendRight(n.template.loc.end.offset+11,`\n\n${e}`)}return{code:r.toString(),sourceMap:r.generateMap()}}};function Mn(e){return e.endsWith(`.vue`)||e.endsWith(`.nvue`)}function Nn(e){return b(e.split(`?`,1)[0])}function Pn(e,t){return[...e,t].filter(Boolean).join(`
|
|
21
|
+
`)}function Fn(e,t,n){let r=[`<script setup>`,n,`<\/script>`].filter(Boolean).join(`
|
|
22
|
+
`);if(t.template){e.appendRight(t.template.loc.end.offset+11,`\n\n${r}`);return}e.append(`\n${r}`)}function In(e,t,n){let r=Qt(n,Yt(t.content)),i=Zt(t.content);e.overwrite(t.loc.start.offset,t.loc.end.offset,Pn(r,i))}function Ln(e){let t=new Set,n=e.matchAll(/<\/?\s*([a-z][\w-]*)\b/gi);for(let e of n){let n=e[1];t.add(n.includes(`-`)?n.split(`-`).filter(Boolean).map(e=>e[0].toUpperCase()+e.slice(1)).join(``):n)}return t}function Rn(e){let t=new Set;return e.script?.content&&Xt(e.script.content).forEach(e=>t.add(e)),e.scriptSetup?.content&&Xt(e.scriptSetup.content).forEach(e=>t.add(e)),t}function zn(e,t,n){let{descriptor:r}=T(e),i=Rn(r),a=r.template?.content?Array.from(Ln(r.template.content)).filter(e=>!i.has(e)).map(e=>n.autoComponent.resolveComponentImport(e,t)).filter(e=>!!e):[],o=r.scriptSetup?.content?n.autoApi.resolveImports(r.scriptSetup.content,{boundNames:i}):r.script?.content?n.autoApi.resolveImports(r.script.content,{boundNames:i}):[];if(a.length===0&&o.length===0)return null;let s=new E(e);return r.scriptSetup?(In(s,r.scriptSetup,[...a,...o]),{code:s.toString(),sourceMap:s.generateMap()}):r.script?(o.length>0&&In(s,r.script,o),a.length>0&&Fn(s,r,Pn(a,``)),{code:s.toString(),sourceMap:s.generateMap()}):(Fn(s,r,Pn([...a,...o],``)),{code:s.toString(),sourceMap:s.generateMap()})}function Bn(){let e;return[{name:`oiyo:auto`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`AUTO`)},transform(t,n){let r=Nn(n);return!Mn(r)||!r.startsWith(`${e.root.srcDir}/`)&&r!==e.root.rootPath?void 0:zn(t,r,e)||void 0}}]}const H={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},Vn={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:H.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(Vn);const Hn=`READDIRP_RECURSIVE_ERROR`,Un=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,Hn]),Wn=[H.DIR_TYPE,H.EVERYTHING_TYPE,H.FILE_DIR_TYPE,H.FILE_TYPE],Gn=new Set([H.DIR_TYPE,H.EVERYTHING_TYPE,H.FILE_DIR_TYPE]),Kn=new Set([H.EVERYTHING_TYPE,H.FILE_DIR_TYPE,H.FILE_TYPE]),qn=e=>Un.has(e.code),Jn=process.platform===`win32`,Yn=e=>!0,Xn=e=>{if(e===void 0)return Yn;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 Yn};var Zn=class extends Te{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...Vn,...e},{root:n,type:r}=t;this._fileFilter=Xn(t.fileFilter),this._directoryFilter=Xn(t.directoryFilter);let i=t.lstat?p:h;Jn?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??Vn.depth,this._wantsDir=r?Gn.has(r):!1,this._wantsFile=r?Kn.has(r):!1,this._wantsEverything=r===H.EVERYTHING_TYPE,this._root=Oe(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 re(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=Oe(Ee(t,r));n={path:De(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){qn(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 p(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===ke){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=Hn,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 Qn(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&&!Wn.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${Wn.join(`, `)}`);return t.root=e,new Zn(t)}const $n=()=>{},U=process.platform,er=U===`win32`,tr=U===`darwin`,nr=U===`linux`,rr=U===`freebsd`,ir=Ae()===`OS400`,W={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},G=W,ar={lstat:ye,stat:Ce},K=`listeners`,q=`errHandlers`,J=`rawEmitters`,or=[K,q,J],sr=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(`.`)),cr=e=>sr.has(D.extname(e).slice(1).toLowerCase()),lr=(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)},ur=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]},dr=e=>e instanceof Set?e.size===0:!e,Z=new Map;function fr(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&Q(D.resolve(e,r),K,D.join(e,r))};try{return _e(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const Q=(e,t,n,r,i)=>{let a=Z.get(e);a&&lr(a[t],e=>{e(n,r,i)})},pr=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=Z.get(t),c;if(!n.persistent)return c=fr(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=fr(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),er&&n.code===`EPERM`)try{await(await be(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),dr(s.listeners)&&(s.watcher.close(),Z.delete(t),or.forEach(ur(s)),s.watcher=void 0,Object.freeze(s))}},mr=new Map,hr=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=mr.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(ge(t),o=void 0),o?(Y(o,K,i),Y(o,J,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:ve(t,n,(n,r)=>{lr(o.rawEmitters,e=>{e(G.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&lr(o.listeners,t=>t(e,n))})},mr.set(t,o)),()=>{X(o,K,i),X(o,J,a),dr(o.listeners)&&(mr.delete(t),ge(t),o.options=o.watcher=void 0,Object.freeze(o))}};var gr=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=D.dirname(e),i=D.basename(e);this.fsw._getWatchedDir(r).add(i);let a=D.resolve(e),o={persistent:n.persistent};t||=$n;let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&cr(i)?n.binaryInterval:n.interval,s=hr(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=pr(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=D.dirname(e),i=D.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 Ce(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),(tr||nr||rr)&&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 Se(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=D.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=D.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=D.join(i,D.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(D.dirname(e)),c=s.has(D.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(G.ADD_DIR,e,t),s.add(D.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 ar[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=D.resolve(e),l=s?await Se(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 Se(e):e;if(this.fsw.closed)return;let a=D.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(D.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}}};
|
|
11
23
|
/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
|
|
12
|
-
const Tt=/\\/g,Et=/\/\//,Dt=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Ot=/^\.[/\\]/;function X(e){return Array.isArray(e)?e:[e]}const Z=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function kt(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=S.relative(e.path,t);return n?!n.startsWith(`..`)&&!S.isAbsolute(n):!1}return!1}:()=>!1}function At(e){if(typeof e!=`string`)throw Error(`string expected`);e=S.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 jt(e,t,n){let r=At(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function Mt(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=X(e).map(e=>kt(e));return t==null?(e,t)=>jt(n,e,t):jt(n,t)}const Q=e=>{let t=X(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Pt)},Nt=e=>{let t=e.replace(Tt,`/`),n=!1;for(t.startsWith(`//`)&&(n=!0);t.match(Et);)t=t.replace(Et,`/`);return n&&(t=`/`+t),t},Pt=e=>Nt(S.normalize(Nt(e))),Ft=(e=``)=>t=>typeof t==`string`?Pt(S.isAbsolute(t)?t:S.join(e,t)):t,It=(e,t)=>S.isAbsolute(e)?e:S.join(t,e),Lt=Object.freeze(new Set);var Rt=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 xe(n)}catch{this._removeWatcher&&this._removeWatcher(S.dirname(n),S.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=L,this.items=Lt,Object.freeze(this)}},zt=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(Ot,``),this.watchPath=r,this.fullWatchPath=S.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?`stat`:`lstat`}entryPath(e){return S.join(this.watchPath,S.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)}},Bt=class extends Se{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?X(e.ignored):X([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};mt&&(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=L,this._readyEmitted=!0,process.nextTick(()=>this.emit(z.READY)))},this._emitRaw=(...e)=>this.emit(z.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new wt(this),Object.freeze(r)}_addIgnoredPath(e){if(Z(e)){for(let t of this._ignoredPaths)if(Z(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)Z(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=Q(e);return r&&(i=i.map(e=>It(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(S.dirname(e),S.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Q(e),{cwd:n}=this.options;return t.forEach(e=>{!S.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=S.join(n,e)),e=S.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?S.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==z.ERROR&&this.emit(z.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;ut&&(t=S.normalize(t)),r.cwd&&(t=S.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===z.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(z.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===z.ADD&&this._pendingUnlinks.has(t)&&(e=z.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===z.ADD||e===z.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=z.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===z.CHANGE&&!this._throttle(z.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===z.ADD||e===z.ADD_DIR||e===z.CHANGE)){let e=r.cwd?S.join(r.cwd,t):t,n;try{n=await x(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(z.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&&!S.isAbsolute(e)&&(s=S.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){ge(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&&Dt.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(Ft(e));this._userIgnored=Mt([...[...this._ignoredPaths].map(Ft(e)),...t],void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new zt(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=S.resolve(e);return this._watched.has(t)||this._watched.set(t,new Rt(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=S.join(e,t),i=S.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=S.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===z.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?z.UNLINK_DIR:z.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=S.dirname(e);this._getWatchedDir(t).remove(S.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=lt(e,{type:z.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 Vt(e,t={}){let n=new Bt(t);return n.add(e),n}function Ht(e){if(!e.includes(`defineRootContext`))return``;let{descriptor:t}=g(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 Me(e,`defineRootContext`)}function Wt(e){if(!e.includes(`<template`))return``;let{descriptor:t}=g(e);return(t.template?.content||``).trim()}function Gt(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 /> 占位节点`);if(t.varName&&(n=n.replace(RegExp(`\\b${t.varName}\\b`,`g`),`$oiyoRootContext`)),t.varProperties?.length)for(let{local:e,original:r}of t.varProperties)n=n.replace(RegExp(`\\b${e}\\b`,`g`),`$oiyoRootContext.${r}`);return n.trim()}function Kt(e){if(!e)return;let t=e?.content;if(t){let e=qt(t);return e.script?e:void 0}}function qt(e){let t=p(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return C(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 Jt(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 Yt=`virtual:oiyo-root-context`,$=`\0${Yt}`;function Xt(e){let{script:t,imports:n}=e,r=[];return n?.length&&(r.push(...n),r.push(``)),t?(r.push(`let rootContextInstance = null`),r.push(``),r.push(`export function useRootContext() {`),r.push(`if (!rootContextInstance) {`),r.push(`const factory = ${t}`),r.push(`rootContextInstance = factory()`),r.push(`}`),r.push(`return rootContextInstance`),r.push(`}`)):(r.push(`export function useRootContext() {`),r.push(`return {}`),r.push(`}`)),r.join(`
|
|
13
|
-
`)}
|
|
14
|
-
import { useRootContext } from 'virtual:oiyo-root-context'
|
|
15
|
-
`);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 w(this.rootView.template)!==w(Wt(e))}applyRoot(e){let t=[],n=``,r=``;return e.template&&(n=Jt(this.rootView.template,e.template.content)),e.scriptSetup&&(t.push(...this.rootView.imports),r=`${this.rootView.script}\n${e.scriptSetup.content}`),{imports:t,script:r,template:n}}};function Qt(e){let t=!1,n=`build`;return e.logger.withScope(`VITE`),[{name:`oiyo:build`,apply:`build`,enforce:`pre`,configResolved(e){n=e.command},async buildStart(){if(t)return;await Promise.all([e.page.loadPagesConfig(),e.page.loadPagesJson(),e.layout.registerLayouts()]);let r=t=>{e.layout.isLayoutPath(t)&&e.layout.registerLayouts()};n===`serve`&&Vt(e.layout.layoutDir,{ignoreInitial:!0}).on(`add`,r).on(`unlink`,r),t=!0},async transform(t,n){if(e.root.isRootPath(n))return e.root.parseRoot(t),e.root.transformRoot(t);if(e.page.isPagePath(n))return this.addWatchFile(e.root.rootPath),e.page.transformPage(t,n)},resolveId(e){if(e===`virtual:oiyo-root-context`)return $},load(t){if(t===$)return e.root.rootVM||`export function useRootContext() {return {}}`},async closeBundle(){await e.page.unwatchPagesConfig()}}]}function $t(){return[{name:`oiyo:deps`,enforce:`pre`,config(e){return _(e,{optimizeDeps:{exclude:[`@skiyee/oiyo`]}})}}]}function en(e){let n=t(e),r=D();r.withScope(`CONFIG`);let i=new Zt(n,{logger:r}),a=new ze(n,{logger:r});return{logger:r,root:i,layout:a,page:new A(n,{oiyoRoot:i,oiyoLayout:a,logger:r})}}function tn(e){return e.logger.withScope(`VITE`),e.logger.withScope(`HMR`),[{name:`oiyo:serve`,apply:`serve`,enforce:`pre`,async buildStart(){await Promise.all([e.page.loadPagesConfig(),e.page.loadPagesJson(),e.layout.registerLayouts()])},configureServer(t){e.page.watchPagesConfig(()=>{t.hot.send({type:`full-reload`})});let n=t=>{e.layout.isLayoutPath(t)&&e.layout.registerLayouts()};t.watcher.on(`add`,n),t.watcher.on(`unlink`,n)},async transform(t,n){if(e.root.isRootPath(n))return e.root.parseRoot(t),e.root.transformRoot(t);if(e.page.isPagePath(n))return this.addWatchFile(e.root.rootPath),e.page.transformPage(t,n)},resolveId(e){if(e===`virtual:oiyo-root-context`)return $},load(t){if(t===$)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($);e&&(n.moduleGraph.invalidateModule(e),i=!0)}if(i){n.hot.send({type:`full-reload`});return}}},async closeBundle(){await e.page.unwatchPagesConfig()}}]}function nn(e={}){let t=en(e);return[...$t(),...tn(t),...Qt(t)]}export{T as LogLevels,nn as OiyoCorePlugin,ze as OiyoLayout,A as OiyoPage,Zt as OiyoRoot,$ as RESOLVED_VIRTUAL_ROOT_CONTEXT_ID,Yt as VIRTUAL_ROOT_CONTEXT_ID,D as createLogger};
|
|
24
|
+
const _r=/\\/g,vr=/\/\//,yr=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,br=/^\.[/\\]/;function $(e){return Array.isArray(e)?e:[e]}const xr=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function Sr(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=D.relative(e.path,t);return n?!n.startsWith(`..`)&&!D.isAbsolute(n):!1}return!1}:()=>!1}function Cr(e){if(typeof e!=`string`)throw Error(`string expected`);e=D.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 wr(e,t,n){let r=Cr(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function Tr(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=$(e).map(e=>Sr(e));return t==null?(e,t)=>wr(n,e,t):wr(n,t)}const Er=e=>{let t=$(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Or)},Dr=e=>{let t=e.replace(_r,`/`),n=!1;for(t.startsWith(`//`)&&(n=!0);t.match(vr);)t=t.replace(vr,`/`);return n&&(t=`/`+t),t},Or=e=>Dr(D.normalize(Dr(e))),kr=(e=``)=>t=>typeof t==`string`?Or(D.isAbsolute(t)?t:D.join(e,t)):t,Ar=(e,t)=>D.isAbsolute(e)?e:D.join(t,e),jr=Object.freeze(new Set);var Mr=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 xe(n)}catch{this._removeWatcher&&this._removeWatcher(D.dirname(n),D.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=$n,this.items=jr,Object.freeze(this)}},Nr=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(br,``),this.watchPath=r,this.fullWatchPath=D.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?`stat`:`lstat`}entryPath(e){return D.join(this.watchPath,D.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)}},Pr=class extends we{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};ir&&(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=$n,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 gr(this),Object.freeze(r)}_addIgnoredPath(e){if(xr(e)){for(let t of this._ignoredPaths)if(xr(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)xr(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=Er(e);return r&&(i=i.map(e=>Ar(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(D.dirname(e),D.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Er(e),{cwd:n}=this.options;return t.forEach(e=>{!D.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=D.join(n,e)),e=D.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?D.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;er&&(t=D.normalize(t)),r.cwd&&(t=D.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?D.join(r.cwd,t):t,n;try{n=await Ce(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&&!D.isAbsolute(e)&&(s=D.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){he(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&&yr.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(kr(e));this._userIgnored=Tr([...[...this._ignoredPaths].map(kr(e)),...t],void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Nr(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=D.resolve(e);return this._watched.has(t)||this._watched.set(t,new Mr(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=D.join(e,t),i=D.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=D.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=D.dirname(e);this._getWatchedDir(t).remove(D.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=Qn(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 Fr(e,t={}){let n=new Pr(t);return n.add(e),n}function Ir(){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.autoApi.collectApis(),e.autoComponent.collectComponents(),e.route.loadPagesConfig(),e.route.loadPagesJson(),e.layout.registerLayouts()]),e.autoApi.writeDeclaration(),e.autoComponent.writeDeclaration(),e.layout.writeDeclaration(),e.route.writeDeclaration();let r=async t=>{e.layout.isLayoutPath(t)&&(await e.layout.registerLayouts(),e.layout.writeDeclaration()),e.autoComponent.isAutoComponentPath(t)&&(await e.autoComponent.collectComponents(),e.autoComponent.writeDeclaration()),e.autoApi.isAutoApiPath(t)&&(await e.autoApi.collectApis(),e.autoApi.writeDeclaration())};n===`serve`&&Fr(e.layout.layoutDir,{ignoreInitial:!0}).on(`add`,e=>void r(e)).on(`unlink`,e=>void r(e)).on(`change`,e=>void r(e)),t=!0},async transform(t,n){if(e.root.isRootPath(n))return e.root.parseRoot(t),e.root.transformRoot(t);if(e.route.isPagePath(n))return this.addWatchFile(e.root.rootPath),e.route.transformPage(t,n)},resolveId(e){if(e===`virtual:oiyo-root-context`)return V},load(t){if(t===V)return e.root.rootVM||`export function useRootContext() {return {}}`},async closeBundle(){await e.route.unwatchPagesConfig()}}]}var Lr=class{constructor(e){this.config=e}get stateDir(){return C(this.config.rootDir,`.oiyo`)}get typesDir(){return C(this.stateDir,`types`)}get srcDir(){return C(this.config.rootDir,this.config.srcDir)}get declarationEntryPath(){return C(this.stateDir,`oiyo.d.ts`)}get appTsconfigPath(){return C(this.stateDir,`tsconfig.app.json`)}get nodeTsconfigPath(){return C(this.stateDir,`tsconfig.node.json`)}relativeToState(e){return b(S(this.stateDir,e))}stringifyJson(e){return`${JSON.stringify(e,null,2)}\n`}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(`
|
|
25
|
+
`)}generateAppTsconfig(){let e=this.relativeToState(this.config.rootDir),t=this.relativeToState(this.srcDir),n=this.relativeToState(this.stateDir);return this.stringifyJson({compilerOptions:{paths:{"~/*":[v(t,`*`)],"~~/*":[v(e,`*`)],"@/*":[v(t,`*`)],"@@/*":[v(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:[v(n,`oiyo.d.ts`),v(t,`**/*`),v(e,`*.d.ts`)],exclude:[v(t,`pages.config.*`),v(e,`dist`),v(e,`node_modules`),v(e,`vite.config.*`),v(e,`oiyo.config.*`)]})}generateNodeTsconfig(){let e=this.relativeToState(this.config.rootDir),t=this.relativeToState(this.srcDir);return this.stringifyJson({compilerOptions:{paths:{},esModuleInterop:!0,skipLibCheck:!0,target:`ESNext`,allowJs:!0,resolveJsonModule:!0,moduleDetection:`force`,isolatedModules:!0,verbatimModuleSyntax:!0,allowArbitraryExtensions:!0,strict:!0,noUncheckedIndexedAccess:!0,forceConsistentCasingInFileNames:!0,noImplicitOverride:!0,module:`preserve`,noEmit:!0,types:[],moduleResolution:`Bundler`,useDefineForClassFields:!0},include:[v(e,`oiyo.config.*`),v(e,`vite.config.*`),v(e,`vitest.config.*`)],exclude:[v(t,`**/*`),v(e,`dist`),v(e,`node_modules`)]})}writeAppTsconfig(){return d(this.stateDir,{recursive:!0}),I(this.appTsconfigPath,this.generateAppTsconfig()),this.appTsconfigPath}writeNodeTsconfig(){return d(this.stateDir,{recursive:!0}),I(this.nodeTsconfigPath,this.generateNodeTsconfig()),this.nodeTsconfigPath}writeDeclarationEntry(){return d(this.stateDir,{recursive:!0}),I(this.declarationEntryPath,this.generateDeclarationEntry()),this.writeAppTsconfig(),this.writeNodeTsconfig(),this.declarationEntryPath}ensureDeclarationEntry(){return u(this.appTsconfigPath)||this.writeAppTsconfig(),u(this.nodeTsconfigPath)||this.writeNodeTsconfig(),u(this.declarationEntryPath)?this.declarationEntryPath:this.writeDeclarationEntry()}};function Rr(e){let t=ue(e),n=A();n.withScope(`CONFIG`);let r=new Lr(t),i=new Vt(t,{logger:n,oiyoState:r}),a=new wt(t,{logger:n,oiyoState:r}),o=new hn(t,{oiyoAutoApi:a,logger:n}),s=new Jt(t,{logger:n,oiyoState:r});return{logger:n,config:t,autoApi:a,autoComponent:i,layout:s,state:r,route:new jn(t,{logger:n,oiyoState:r,oiyoRoot:o,oiyoLayout:s}),root:o}}function zr(e){return[{name:`oiyo:deps`,enforce:`pre`,async config(t){let{config:n}=await fe({name:`oiyo`,cwd:t.root}),r=Rr(n||e);return me(t,{oiyo:r,resolve:{alias:{"~":O.resolve(r.config.rootDir,r.config.srcDir),"@":O.resolve(r.config.rootDir,r.config.srcDir),"@@":O.normalize(r.config.rootDir),"~~":O.normalize(r.config.rootDir)}},optimizeDeps:{exclude:[`@skiyee/oiyo`]}})}}]}function Br(){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.autoApi.collectApis(),e.autoComponent.collectComponents(),e.route.loadPagesConfig(),e.route.loadPagesJson(),e.layout.registerLayouts()]),e.autoApi.writeDeclaration(),e.autoComponent.writeDeclaration(),e.layout.writeDeclaration(),e.route.writeDeclaration()},configureServer(t){e.route.watchPagesConfig(()=>{t.hot.send({type:`full-reload`})});let n=async n=>{let r=!1;e.layout.isLayoutPath(n)&&(await e.layout.registerLayouts(),e.layout.writeDeclaration(),r=!0),e.autoComponent.isAutoComponentPath(n)&&(await e.autoComponent.collectComponents(),e.autoComponent.writeDeclaration(),r=!0),e.autoApi.isAutoApiPath(n)&&(await e.autoApi.collectApis(),e.autoApi.writeDeclaration(),r=!0),r&&t.hot.send({type:`full-reload`})};t.watcher.on(`add`,e=>void n(e)),t.watcher.on(`unlink`,e=>void n(e)),t.watcher.on(`change`,e=>void n(e))},async transform(t,n){if(e.root.isRootPath(n))return e.root.parseRoot(t),e.root.transformRoot(t);if(e.route.isPagePath(n))return this.addWatchFile(e.root.rootPath),e.route.transformPage(t,n)},resolveId(e){if(e===`virtual:oiyo-root-context`)return V},load(t){if(t===V)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(V);e&&(n.moduleGraph.invalidateModule(e),i=!0)}if(i){n.hot.send({type:`full-reload`});return}}},async closeBundle(){await e.route.unwatchPagesConfig()}}]}function Vr(e={}){return[...zr(e),...Br(),...Ir(),...Bn()]}export{k as LogLevels,Vr as OiyoCorePlugin,qt as OiyoLayout,wt as OiyoModAutoApi,Vt as OiyoModAutoComponent,Jt as OiyoModLayout,hn as OiyoModRoot,jn as OiyoModRoute,An as OiyoPage,Lr as OiyoState,V as RESOLVED_VIRTUAL_ROOT_CONTEXT_ID,fn as VIRTUAL_ROOT_CONTEXT_ID,A as createLogger,kn as definePageMeta,mn as defineRootContext,B as isScannedComponentPath,Nt as resolveComponentName,At as resolveScannedComponentSources};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oiyo/core",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.0
|
|
4
|
+
"version": "0.1.0",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "skiyee",
|
|
7
7
|
"email": "319619193@qq.com",
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
},
|
|
10
10
|
"license": "SEE LICENSE IN LICENSE",
|
|
11
11
|
"funding": "https://github.com/skiyee/sponsors",
|
|
12
|
-
"homepage": "https://oiyo.
|
|
12
|
+
"homepage": "https://oiyo.js.org",
|
|
13
13
|
"repository": {
|
|
14
14
|
"type": "git",
|
|
15
15
|
"url": "git+https://github.com/skiyee/oiyo.git"
|
|
@@ -26,14 +26,6 @@
|
|
|
26
26
|
"import": "./dist/index.mjs",
|
|
27
27
|
"require": "./dist/index.cjs"
|
|
28
28
|
},
|
|
29
|
-
"./types": {
|
|
30
|
-
"types": {
|
|
31
|
-
"import": "./dist/types.d.mts",
|
|
32
|
-
"require": "./dist/types.d.cts"
|
|
33
|
-
},
|
|
34
|
-
"import": "./dist/types.mjs",
|
|
35
|
-
"require": "./dist/types.cjs"
|
|
36
|
-
},
|
|
37
29
|
"./package.json": "./package.json"
|
|
38
30
|
},
|
|
39
31
|
"main": "./dist/index.cjs",
|
|
@@ -57,7 +49,7 @@
|
|
|
57
49
|
"pathe": "^2.0.3",
|
|
58
50
|
"tinyglobby": "^0.2.15",
|
|
59
51
|
"vue": "3.4.21",
|
|
60
|
-
"@oiyo/config": "0.0
|
|
52
|
+
"@oiyo/config": "0.1.0"
|
|
61
53
|
},
|
|
62
54
|
"devDependencies": {
|
|
63
55
|
"chokidar": "4.0.3",
|
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @oiyo/core v0.0.3
|
|
3
|
-
* Copyright (c) 2026 skiyee. All rights reserved.
|
|
4
|
-
* Commercial software. See LICENSE for terms.
|
|
5
|
-
* Official site: https://oiyo.pages.dev
|
|
6
|
-
*/
|
|
7
|
-
import { GlobalStyle } from "@oiyo/config";
|
|
8
|
-
|
|
9
|
-
//#region src/page/types.d.ts
|
|
10
|
-
/**
|
|
11
|
-
* 可序列化的页面元信息值类型
|
|
12
|
-
* 用于静态提取和 pages.json 生成
|
|
13
|
-
*/
|
|
14
|
-
type PageMetaValue = string | number | boolean | null | PageMetaObject | PageMetaValue[];
|
|
15
|
-
/**
|
|
16
|
-
* 可序列化的页面元信息对象
|
|
17
|
-
*/
|
|
18
|
-
interface PageMetaObject {
|
|
19
|
-
[key: string]: PageMetaValue | undefined;
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* 页面元信息基础字段
|
|
23
|
-
*/
|
|
24
|
-
interface BasePageMeta {
|
|
25
|
-
/** 页面类型 */
|
|
26
|
-
type?: 'page' | 'home';
|
|
27
|
-
/** 使用的布局名称,false 表示不使用布局 */
|
|
28
|
-
layout?: string | false;
|
|
29
|
-
/** 中间件 */
|
|
30
|
-
middleware?: string | string[];
|
|
31
|
-
/** uni-app 页面样式配置 */
|
|
32
|
-
style?: GlobalStyle;
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* 已解析的页面元信息
|
|
36
|
-
* 用于编译期静态提取和 pages.json 生成
|
|
37
|
-
*/
|
|
38
|
-
interface ResolvedPageMeta extends BasePageMeta, PageMetaObject {}
|
|
39
|
-
/**
|
|
40
|
-
* 页面文件信息
|
|
41
|
-
*/
|
|
42
|
-
interface PageFile {
|
|
43
|
-
/** 页面路径(相对于 srcDir,不含扩展名) */
|
|
44
|
-
pagePath: string;
|
|
45
|
-
/** 页面文件的绝对路径 */
|
|
46
|
-
filePath: string;
|
|
47
|
-
/** 页面元信息 */
|
|
48
|
-
pageMeta: ResolvedPageMeta;
|
|
49
|
-
/** 所属包(main 或子包名称) */
|
|
50
|
-
pageBelong: string;
|
|
51
|
-
}
|
|
52
|
-
//#endregion
|
|
53
|
-
export { PageFile as n, ResolvedPageMeta as r, BasePageMeta as t };
|
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @oiyo/core v0.0.3
|
|
3
|
-
* Copyright (c) 2026 skiyee. All rights reserved.
|
|
4
|
-
* Commercial software. See LICENSE for terms.
|
|
5
|
-
* Official site: https://oiyo.pages.dev
|
|
6
|
-
*/
|
|
7
|
-
import { GlobalStyle } from "@oiyo/config";
|
|
8
|
-
|
|
9
|
-
//#region src/page/types.d.ts
|
|
10
|
-
/**
|
|
11
|
-
* 可序列化的页面元信息值类型
|
|
12
|
-
* 用于静态提取和 pages.json 生成
|
|
13
|
-
*/
|
|
14
|
-
type PageMetaValue = string | number | boolean | null | PageMetaObject | PageMetaValue[];
|
|
15
|
-
/**
|
|
16
|
-
* 可序列化的页面元信息对象
|
|
17
|
-
*/
|
|
18
|
-
interface PageMetaObject {
|
|
19
|
-
[key: string]: PageMetaValue | undefined;
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* 页面元信息基础字段
|
|
23
|
-
*/
|
|
24
|
-
interface BasePageMeta {
|
|
25
|
-
/** 页面类型 */
|
|
26
|
-
type?: 'page' | 'home';
|
|
27
|
-
/** 使用的布局名称,false 表示不使用布局 */
|
|
28
|
-
layout?: string | false;
|
|
29
|
-
/** 中间件 */
|
|
30
|
-
middleware?: string | string[];
|
|
31
|
-
/** uni-app 页面样式配置 */
|
|
32
|
-
style?: GlobalStyle;
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* 已解析的页面元信息
|
|
36
|
-
* 用于编译期静态提取和 pages.json 生成
|
|
37
|
-
*/
|
|
38
|
-
interface ResolvedPageMeta extends BasePageMeta, PageMetaObject {}
|
|
39
|
-
/**
|
|
40
|
-
* 页面文件信息
|
|
41
|
-
*/
|
|
42
|
-
interface PageFile {
|
|
43
|
-
/** 页面路径(相对于 srcDir,不含扩展名) */
|
|
44
|
-
pagePath: string;
|
|
45
|
-
/** 页面文件的绝对路径 */
|
|
46
|
-
filePath: string;
|
|
47
|
-
/** 页面元信息 */
|
|
48
|
-
pageMeta: ResolvedPageMeta;
|
|
49
|
-
/** 所属包(main 或子包名称) */
|
|
50
|
-
pageBelong: string;
|
|
51
|
-
}
|
|
52
|
-
//#endregion
|
|
53
|
-
export { PageFile as n, ResolvedPageMeta as r, BasePageMeta as t };
|
package/dist/types.cjs
DELETED
package/dist/types.d.cts
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @oiyo/core v0.0.3
|
|
3
|
-
* Copyright (c) 2026 skiyee. All rights reserved.
|
|
4
|
-
* Commercial software. See LICENSE for terms.
|
|
5
|
-
* Official site: https://oiyo.pages.dev
|
|
6
|
-
*/
|
|
7
|
-
import { t as BasePageMeta } from "./types-Bnj1jLZh.cjs";
|
|
8
|
-
import { DefineComponent } from "vue";
|
|
9
|
-
|
|
10
|
-
//#region src/types/component.d.ts
|
|
11
|
-
declare module 'vue' {
|
|
12
|
-
interface GlobalComponents {
|
|
13
|
-
/**
|
|
14
|
-
* OIYO 视图占位组件,用于显示当前活跃页面
|
|
15
|
-
*/
|
|
16
|
-
OiyoPage: DefineComponent<object>;
|
|
17
|
-
/**
|
|
18
|
-
* OIYO 布局占位组件,用于显示页面所使用布局组件
|
|
19
|
-
*/
|
|
20
|
-
OiyoLayout: DefineComponent<object>;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
//#endregion
|
|
24
|
-
//#region src/types/marco.d.ts
|
|
25
|
-
/**
|
|
26
|
-
* 页面元信息
|
|
27
|
-
* 用户在 definePageMeta() 中使用的类型
|
|
28
|
-
* 支持通过 declare module '@skiyee/oiyo' 进行扩展
|
|
29
|
-
*/
|
|
30
|
-
interface PageMeta extends BasePageMeta {
|
|
31
|
-
/** 其他自定义字段 */
|
|
32
|
-
[key: string]: unknown;
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* 根上下文工厂函数
|
|
36
|
-
*/
|
|
37
|
-
type RootContextFactory<T extends object> = () => T;
|
|
38
|
-
declare global {
|
|
39
|
-
/**
|
|
40
|
-
* 定义页面元信息
|
|
41
|
-
* @param meta 页面元信息配置
|
|
42
|
-
*/
|
|
43
|
-
function definePageMeta(meta: PageMeta): void;
|
|
44
|
-
/**
|
|
45
|
-
* 定义根上下文
|
|
46
|
-
* @param factory 返回上下文对象的工厂函数
|
|
47
|
-
* @returns 上下文对象
|
|
48
|
-
*/
|
|
49
|
-
function defineRootContext<T extends object>(factory: RootContextFactory<T>): T;
|
|
50
|
-
}
|
|
51
|
-
//#endregion
|
|
52
|
-
export { PageMeta, RootContextFactory };
|
package/dist/types.d.mts
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @oiyo/core v0.0.3
|
|
3
|
-
* Copyright (c) 2026 skiyee. All rights reserved.
|
|
4
|
-
* Commercial software. See LICENSE for terms.
|
|
5
|
-
* Official site: https://oiyo.pages.dev
|
|
6
|
-
*/
|
|
7
|
-
import { t as BasePageMeta } from "./types-B6aQQOoW.mjs";
|
|
8
|
-
import { DefineComponent } from "vue";
|
|
9
|
-
|
|
10
|
-
//#region src/types/component.d.ts
|
|
11
|
-
declare module 'vue' {
|
|
12
|
-
interface GlobalComponents {
|
|
13
|
-
/**
|
|
14
|
-
* OIYO 视图占位组件,用于显示当前活跃页面
|
|
15
|
-
*/
|
|
16
|
-
OiyoPage: DefineComponent<object>;
|
|
17
|
-
/**
|
|
18
|
-
* OIYO 布局占位组件,用于显示页面所使用布局组件
|
|
19
|
-
*/
|
|
20
|
-
OiyoLayout: DefineComponent<object>;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
//#endregion
|
|
24
|
-
//#region src/types/marco.d.ts
|
|
25
|
-
/**
|
|
26
|
-
* 页面元信息
|
|
27
|
-
* 用户在 definePageMeta() 中使用的类型
|
|
28
|
-
* 支持通过 declare module '@skiyee/oiyo' 进行扩展
|
|
29
|
-
*/
|
|
30
|
-
interface PageMeta extends BasePageMeta {
|
|
31
|
-
/** 其他自定义字段 */
|
|
32
|
-
[key: string]: unknown;
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* 根上下文工厂函数
|
|
36
|
-
*/
|
|
37
|
-
type RootContextFactory<T extends object> = () => T;
|
|
38
|
-
declare global {
|
|
39
|
-
/**
|
|
40
|
-
* 定义页面元信息
|
|
41
|
-
* @param meta 页面元信息配置
|
|
42
|
-
*/
|
|
43
|
-
function definePageMeta(meta: PageMeta): void;
|
|
44
|
-
/**
|
|
45
|
-
* 定义根上下文
|
|
46
|
-
* @param factory 返回上下文对象的工厂函数
|
|
47
|
-
* @returns 上下文对象
|
|
48
|
-
*/
|
|
49
|
-
function defineRootContext<T extends object>(factory: RootContextFactory<T>): T;
|
|
50
|
-
}
|
|
51
|
-
//#endregion
|
|
52
|
-
export { PageMeta, RootContextFactory };
|