├── README.md ├── packages ├── keepalive │ ├── README.md │ ├── tsconfig.json │ ├── package.json │ └── src │ │ └── index.tsx └── coderduan-umi │ ├── src │ ├── index.ts │ ├── constants.ts │ ├── generate.ts │ ├── server.ts │ ├── build.ts │ ├── html.ts │ ├── appData.ts │ ├── routes.ts │ ├── config.ts │ ├── entry.ts │ ├── mock.ts │ ├── styles.ts │ ├── hd.ts │ └── dev.ts │ ├── tsconfig.json │ ├── templates │ └── page │ │ └── index.tsx.tpl │ ├── compiled │ ├── glob │ │ ├── LICENSE │ │ ├── package.json │ │ ├── index.d.ts │ │ └── index.js │ ├── portfinder │ │ ├── package.json │ │ └── LICENSE │ ├── ws │ │ ├── LICENSE │ │ ├── package.json │ │ └── index.d.ts │ ├── postcss │ │ ├── LICENSE │ │ └── package.json │ ├── http-proxy-middleware │ │ ├── LICENSE │ │ └── package.json │ ├── commander │ │ ├── LICENSE │ │ ├── package.json │ │ ├── typings │ │ │ └── index.d.ts │ │ └── index.js │ ├── @alitajs │ │ └── postcss-plugin-px2rem │ │ │ └── package.json │ └── express │ │ └── index.d.ts │ ├── bin │ └── coderduan-umi.js │ ├── client │ └── client.ts │ └── package.json ├── .gitignore ├── pnpm-workspace.yaml ├── .vscode └── settings.json ├── examples └── app │ ├── src │ ├── layouts │ │ ├── index.css │ │ └── index.tsx │ ├── pages │ │ ├── home.css │ │ ├── index.tsx │ │ ├── abc │ │ │ └── index.tsx │ │ ├── me.tsx │ │ ├── users.tsx │ │ └── home.tsx │ └── index.tsx │ ├── coderduan-umi.config.ts │ ├── www │ └── index.html │ ├── package.json │ └── mock │ └── app.ts ├── learn ├── 3.1html │ └── index.html ├── 3.4react-jsx │ └── index.html ├── 3.3react │ └── index.html └── 3.2mvc │ └── index.html ├── package.json ├── scripts └── bundleDeps.ts └── tsconfig.base.json /README.md: -------------------------------------------------------------------------------- 1 | # 手写前端框架 2 | -------------------------------------------------------------------------------- /packages/keepalive/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | lib 3 | www 4 | dist -------------------------------------------------------------------------------- /packages/coderduan-umi/src/index.ts: -------------------------------------------------------------------------------- 1 | console.log("hello coderduan-umi"); 2 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - "packages/*" 3 | - "examples/*" 4 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": ["coderduan", "outdir", "portfinder"] 3 | } 4 | -------------------------------------------------------------------------------- /examples/app/src/layouts/index.css: -------------------------------------------------------------------------------- 1 | .coderduan-umi-layout { 2 | font-size: 26px; 3 | } 4 | -------------------------------------------------------------------------------- /examples/app/src/pages/home.css: -------------------------------------------------------------------------------- 1 | .coderduan-umi-home { 2 | background-color: skyblue; 3 | font-size: 40px; 4 | } 5 | -------------------------------------------------------------------------------- /examples/app/src/pages/index.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | export default function index() { 4 | return
index
; 5 | } 6 | -------------------------------------------------------------------------------- /packages/coderduan-umi/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.base.json", 3 | "compilerOptions": { 4 | "outDir": "./lib", 5 | "rootDir": "./src" 6 | }, 7 | "include": ["src", "client"] 8 | } 9 | -------------------------------------------------------------------------------- /examples/app/src/pages/abc/index.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import type { FC } from "react"; 3 | 4 | interface AbcProps {} 5 | 6 | const AbcPage: FC = () => { 7 | return
Hello xiaoduan
; 8 | }; 9 | 10 | export default AbcPage; 11 | -------------------------------------------------------------------------------- /examples/app/src/pages/me.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { Link } from "react-router-dom"; 3 | 4 | const Me = () => { 5 | return ( 6 | <> 7 |

Me

8 | to Hello 9 | 10 | ); 11 | }; 12 | export default Me; 13 | -------------------------------------------------------------------------------- /packages/coderduan-umi/templates/page/index.tsx.tpl: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import type { FC } from 'react'; 3 | 4 | interface {{{ name }}}Props {} 5 | 6 | const {{{ name }}}Page: FC<{{{ name }}}Props> = () => { 7 | return
Hello {{{ hi }}}
; 8 | }; 9 | 10 | export default {{{ name }}}Page; -------------------------------------------------------------------------------- /examples/app/coderduan-umi.config.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | title: "Hello coderduan-umi", 3 | keepalive: [/./, "/users"], 4 | proxy: { 5 | "/api": { 6 | target: "http://jsonplaceholder.typicode.com/", 7 | changeOrigin: true, 8 | pathRewrite: { "^/api": "" }, 9 | }, 10 | }, 11 | }; 12 | -------------------------------------------------------------------------------- /packages/keepalive/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.base.json", 3 | "compilerOptions": { 4 | "jsx": "react-jsx", 5 | "declaration": true, 6 | "outDir": "./lib", 7 | "rootDir": "./src", 8 | "strict": false, 9 | "target": "ESNext" 10 | }, 11 | "include": ["src", "client"] 12 | } 13 | -------------------------------------------------------------------------------- /examples/app/www/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | coderduan-umi 6 | 7 | 8 | 9 |
10 | loading... 11 |
12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /learn/3.1html/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
5 | loading... 6 |
7 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /packages/coderduan-umi/src/constants.ts: -------------------------------------------------------------------------------- 1 | export const DEFAULT_OUTDIR = "dist"; 2 | export const DEFAULT_ENTRY_POINT = "coderduan-umi.tsx"; 3 | export const DEFAULT_FRAMEWORK_NAME = "coderduan-umi"; 4 | export const DEFAULT_PLATFORM = "browser"; 5 | export const DEFAULT_HOST = "localhost"; 6 | export const DEFAULT_PORT = 8888; 7 | export const DEFAULT_BUILD_PORT = 8989; 8 | export const DEFAULT_TEMPLATE = ".coderduan-umi"; 9 | export const DEFAULT_GLOBAL_LAYOUTS = "layouts/index.tsx"; 10 | export const DEFAULT_CONFIG_FILE = "coderduan-umi.config.ts"; 11 | -------------------------------------------------------------------------------- /examples/app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@examples/app", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "scripts": { 6 | "build": "coderduan-umi build", 7 | "dev": "coderduan-umi dev", 8 | "serve": "cd dist && serve", 9 | "g": "coderduan-umi generate" 10 | }, 11 | "dependencies": { 12 | "@alita/flow": "^3.0.1", 13 | "@coderduan-umi/keepalive": "workspace:^0.0.1", 14 | "antd-mobile": "^5.22.0", 15 | "antd-mobile-icons": "^0.3.0", 16 | "coderduan-umi": "workspace:*", 17 | "lorem-ipsum": "^2.0.8", 18 | "mockjs": "^1.1.0", 19 | "react": "^18.2.0", 20 | "react-dom": "^18.2.0", 21 | "react-router": "^6.3.0", 22 | "react-router-dom": "^6.3.0" 23 | }, 24 | "devDependencies": { 25 | "serve": "^14.0.1" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/glob/LICENSE: -------------------------------------------------------------------------------- 1 | The ISC License 2 | 3 | Copyright (c) 2009-2022 Isaac Z. Schlueter and Contributors 4 | 5 | Permission to use, copy, modify, and/or distribute this software for any 6 | purpose with or without fee is hereby granted, provided that the above 7 | copyright notice and this permission notice appear in all copies. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR 15 | IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16 | -------------------------------------------------------------------------------- /packages/coderduan-umi/src/generate.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import fs from 'fs'; 3 | import { lodash, generateFile, prompts } from '@umijs/utils'; 4 | 5 | export const generate = async (args: string[]) => { 6 | const [type, name] = args; 7 | const absSrcPath = path.resolve(process.cwd(), 'src'); 8 | const absPagesPath = path.resolve(absSrcPath, 'pages'); 9 | 10 | const questions = [{ 11 | name: 'hi', 12 | type: 'text', 13 | message: `What's your name?` 14 | }] as prompts.PromptObject[] 15 | 16 | if (fs.existsSync(absPagesPath) && type && name) { 17 | generateFile({ 18 | path: path.join(__dirname, `../templates/${type}`), 19 | target: path.join(absPagesPath, name), 20 | data: { 21 | name: lodash.upperFirst(name), 22 | }, 23 | questions 24 | }) 25 | } 26 | } -------------------------------------------------------------------------------- /packages/keepalive/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@coderduan-umi/keepalive", 3 | "version": "0.0.1", 4 | "description": "react keepalive库", 5 | "main": "lib/index.js", 6 | "types": "lib.index.d.ts", 7 | "scripts": { 8 | "build": "tsc", 9 | "dev": "pnpm build --watch" 10 | }, 11 | "publishConfig": { 12 | "access": "public" 13 | }, 14 | "repository": { 15 | "type": "git", 16 | "url": "git+https://github.com/gaoxiaoduan/coderduan-umi.git" 17 | }, 18 | "keywords": [], 19 | "author": "gaoxiaoduan", 20 | "license": "ISC", 21 | "bugs": { 22 | "url": "https://github.com/gaoxiaoduan/coderduan-umi/issues" 23 | }, 24 | "homepage": "https://github.com/gaoxiaoduan/coderduan-umi#readme", 25 | "devDependencies": { 26 | "react": "^18.2.0", 27 | "react-dom": "^18.2.0", 28 | "react-router": "^6.3.0", 29 | "react-router-dom": "^6.3.0" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/portfinder/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "portfinder", 3 | "description": "A simple tool to find an open port on the current machine", 4 | "version": "1.0.32", 5 | "author": "Charlie Robbins ", 6 | "repository": { 7 | "type": "git", 8 | "url": "git@github.com:http-party/node-portfinder.git" 9 | }, 10 | "keywords": [ 11 | "http", 12 | "ports", 13 | "utilities" 14 | ], 15 | "files": [ 16 | "lib" 17 | ], 18 | "dependencies": { 19 | "async": "^2.6.4", 20 | "debug": "^3.2.7", 21 | "mkdirp": "^0.5.6" 22 | }, 23 | "devDependencies": { 24 | "vows": "^0.8.3" 25 | }, 26 | "main": "./lib/portfinder", 27 | "types": "./lib/portfinder.d.ts", 28 | "scripts": { 29 | "test": "vows test/*-test.js --spec" 30 | }, 31 | "engines": { 32 | "node": ">= 0.12.0" 33 | }, 34 | "license": "MIT" 35 | } 36 | -------------------------------------------------------------------------------- /examples/app/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom/client"; 3 | import { HashRouter, Route, Routes } from "react-router-dom"; 4 | import KeepAliveLayout from "@coderduan-umi/keepalive"; 5 | import Layout from "./layouts/index"; 6 | import Home from "./pages/home"; 7 | import Users from "./pages/users"; 8 | import Me from "./pages/me"; 9 | 10 | const App = () => { 11 | return ( 12 | 13 | 14 | 15 | }> 16 | } /> 17 | } /> 18 | } /> 19 | 20 | 21 | 22 | 23 | ); 24 | }; 25 | 26 | const root = ReactDOM.createRoot(document.getElementById("root")); 27 | root.render(React.createElement(App)); 28 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "build": "pnpm -r --filter './packages/**' run build", 5 | "dev": "pnpm -r --filter './packages/**' --parallel dev" 6 | }, 7 | "repository": { 8 | "type": "git", 9 | "url": "git+https://github.com/gaoxiaoduan/coderduan-umi.git" 10 | }, 11 | "keywords": [], 12 | "author": "gaoxiaoduan", 13 | "license": "ISC", 14 | "bugs": { 15 | "url": "https://github.com/gaoxiaoduan/coderduan-umi/issues" 16 | }, 17 | "homepage": "https://github.com/gaoxiaoduan/coderduan-umi#readme", 18 | "devDependencies": { 19 | "@types/minimist": "^1.2.2", 20 | "@types/node": "^18.7.14", 21 | "@types/resolve": "^1.20.2", 22 | "@vercel/ncc": "^0.34.0", 23 | "dts-packer": "^0.0.3", 24 | "esbuild": "^0.15.5", 25 | "esno": "^0.16.3", 26 | "fs-extra": "^10.1.0", 27 | "minimist": "^1.2.6", 28 | "resolve": "^1.22.1", 29 | "typescript": "^4.7.4" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /examples/app/mock/app.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response } from "express"; 2 | import mockjs from "mockjs"; 3 | 4 | export default { 5 | "GET /mock/hello": { 6 | text: "Malita", 7 | }, 8 | "GET /mock/tags": mockjs.mock({ 9 | "list|50": [{ name: "@name", "value|1-50": 50, "type|0-1": 1 }], 10 | }), 11 | "POST /mock/list": (req: Request, res: Response) => { 12 | const dataSource = [ 13 | { 14 | id: 1, 15 | title: "Title 1", 16 | }, 17 | { 18 | id: 2, 19 | title: "Title 2", 20 | }, 21 | { 22 | id: 3, 23 | title: "Title 3", 24 | }, 25 | { 26 | id: 4, 27 | title: "Title 4", 28 | }, 29 | { 30 | id: 5, 31 | title: "Title 5", 32 | }, 33 | ]; 34 | const { body } = req; 35 | 36 | const { pageSize, offset } = body; 37 | return res.json({ 38 | total: dataSource.length, 39 | data: dataSource.slice(offset, offset + pageSize), 40 | }); 41 | }, 42 | }; 43 | -------------------------------------------------------------------------------- /learn/3.4react-jsx/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | coderduan-umi 8 | 9 | 10 | 11 | 12 | 13 |
14 | loading... 15 |
16 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /learn/3.3react/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | coderduan-umi 8 | 9 | 10 | 11 | 12 |
13 | loading... 14 |
15 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /packages/coderduan-umi/src/server.ts: -------------------------------------------------------------------------------- 1 | import { Server as HttpServer } from "http"; 2 | import { WebSocketServer } from "../compiled/ws"; 3 | 4 | export function createWebSocketServer(server: HttpServer) { 5 | const wss = new WebSocketServer({ noServer: true }); 6 | 7 | server.on("upgrade", (req, socket, head) => { 8 | if (req.headers["sec-websocket-protocol"] === "coderduan-umi-hmr") { 9 | wss.handleUpgrade(req, socket, head, (ws) => { 10 | wss.emit("connection", ws, req); 11 | }); 12 | } 13 | }); 14 | 15 | wss.on("connection", (socket) => { 16 | socket.send(JSON.stringify({ type: "connected" })); 17 | }); 18 | 19 | wss.on("error", (e: Error & { code: string }) => { 20 | if (e.code !== "EADDRINUSE") { 21 | console.error(`WebSocket server error:\n${e.stack || e.message}`); 22 | } 23 | }); 24 | 25 | return { 26 | send(message: string) { 27 | wss.clients.forEach((client) => { 28 | if (client.readyState === 1) { 29 | client.send(message); 30 | } 31 | }); 32 | }, 33 | wss, 34 | close() { 35 | wss.close(); 36 | }, 37 | }; 38 | } 39 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/ws/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011 Einar Otto Stangvik 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/portfinder/LICENSE: -------------------------------------------------------------------------------- 1 | node-portfinder 2 | 3 | Copyright (c) 2012 Charlie Robbins 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | "Software"), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 20 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 22 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/postcss/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright 2013 Andrey Sitnik 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/http-proxy-middleware/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Steven Chim 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/commander/LICENSE: -------------------------------------------------------------------------------- 1 | (The MIT License) 2 | 3 | Copyright (c) 2011 TJ Holowaychuk 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | 'Software'), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 21 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 22 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /packages/coderduan-umi/bin/coderduan-umi.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | const { program } = require("../compiled/commander"); 3 | program 4 | .version(require("../package.json").version, "-v, -V", "输出框架版本") 5 | .description("手写前端框架") 6 | .usage(" [options]"); 7 | 8 | program 9 | .command("help") 10 | .alias("-h") 11 | .description("帮助命令") 12 | .action(function (name, options) { 13 | console.log(` 14 | 这是coderduan-umi框架 15 | 16 | 支持的命令: 17 | version:-v, -V 输出当前框架版本 18 | help,-h 输出帮助程序 19 | 20 | Example call: 21 | $ coderduan-umi --help 22 | `); 23 | }); 24 | 25 | program 26 | .command("dev") 27 | .description("框架开发命令") 28 | .action(function () { 29 | const { dev } = require("../lib/dev"); 30 | dev(); 31 | }); 32 | 33 | program 34 | .command("generate") 35 | .alias("g") 36 | .description("微生成器") 37 | .action(function (_, options) { 38 | const { generate } = require("../lib/generate"); 39 | generate(options.args); 40 | }); 41 | 42 | program 43 | .command("build") 44 | .description("框架构建命令") 45 | .action(function () { 46 | const { build } = require("../lib/build"); 47 | build(); 48 | }); 49 | 50 | program.parse(process.argv); 51 | -------------------------------------------------------------------------------- /packages/coderduan-umi/client/client.ts: -------------------------------------------------------------------------------- 1 | function getSocketHost() { 2 | const url: any = window.location; 3 | const host = url.host; 4 | const isHttps = url.protocol === "https:"; 5 | return `${isHttps ? "wss" : "ws"}://${host}`; 6 | } 7 | 8 | if ("WebSocket" in window) { 9 | const socket = new WebSocket(getSocketHost(), "coderduan-umi-hmr"); 10 | 11 | let pingTimer: NodeJS.Timer | null = null; 12 | socket.addEventListener("message", async ({ data }) => { 13 | data = JSON.parse(data); 14 | if (data.type === "connected") { 15 | console.log(`[coderduan-umi] connected.`); 16 | // 心跳包 17 | pingTimer = setInterval(() => socket.send("ping"), 1000 * 30); 18 | } 19 | if (data.type === "reload") window.location.reload(); 20 | }); 21 | 22 | // 等待重连 23 | async function waitForSuccessfulPing(ms = 1000) { 24 | while (true) { 25 | try { 26 | await fetch(`/__coderduan-umi_ping`); 27 | break; 28 | } catch (error) { 29 | await new Promise((resolve) => setTimeout(resolve, ms)); 30 | } 31 | } 32 | } 33 | 34 | socket.addEventListener("close", async () => { 35 | if (pingTimer) clearInterval(pingTimer); 36 | console.info("[coderduan-umi] Dev disconnected. Polling for restart..."); 37 | await waitForSuccessfulPing(); 38 | window.location.reload(); 39 | }); 40 | } 41 | -------------------------------------------------------------------------------- /packages/coderduan-umi/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "coderduan-umi", 3 | "version": "0.0.4", 4 | "description": "", 5 | "main": "lib/index.js", 6 | "bin": { 7 | "coderduan-umi": "./bin/coderduan-umi.js" 8 | }, 9 | "scripts": { 10 | "build": "pnpm esbuild ./src/** --bundle --outdir=lib --platform=node --external:esbuild --loader:.node=file", 11 | "build:client": "pnpm esbuild ./client/** --bundle --outdir=lib/client --external:esbuild", 12 | "build:deps": "pnpm esno ../../scripts/bundleDeps.ts", 13 | "dev": "pnpm build --watch" 14 | }, 15 | "repository": { 16 | "type": "git", 17 | "url": "git+https://github.com/gaoxiaoduan/coderduan-umi.git" 18 | }, 19 | "keywords": [], 20 | "author": "gaoxiaoduan (https://github.com/gaoxiaoduan)", 21 | "license": "ISC", 22 | "bugs": { 23 | "url": "https://github.com/gaoxiaoduan/coderduan-umi/issues" 24 | }, 25 | "homepage": "https://github.com/gaoxiaoduan/coderduan-umi#readme", 26 | "dependencies": { 27 | "@alitajs/postcss-plugin-px2rem": "^0.0.1", 28 | "@umijs/utils": "4.0.0-rc.15", 29 | "commander": "^9.4.0", 30 | "express": "4.17.3", 31 | "glob": "^8.0.3", 32 | "http-proxy-middleware": "^2.0.6", 33 | "portfinder": "^1.0.32", 34 | "postcss": "^8.4.16", 35 | "ws": "^8.8.1" 36 | }, 37 | "devDependencies": { 38 | "@types/express": "^4.17.13", 39 | "@types/glob": "^7.2.0", 40 | "@types/ws": "^8.5.3" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/app/src/pages/users.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { LoremIpsum } from "lorem-ipsum"; 3 | import { IndexBar, List } from "antd-mobile"; 4 | 5 | export const lorem = new LoremIpsum({ 6 | sentencesPerParagraph: { 7 | max: 8, 8 | min: 4, 9 | }, 10 | wordsPerSentence: { 11 | max: 16, 12 | min: 4, 13 | }, 14 | }); 15 | 16 | const getRandomList = (min: number, max: number): string[] => { 17 | return new Array(Math.floor(Math.random() * (max - min) + min)).fill(""); 18 | }; 19 | 20 | const charCodeOfA = "A".charCodeAt(0); 21 | const groups = Array(26) 22 | .fill("") 23 | .map((_, i) => ({ 24 | title: String.fromCharCode(charCodeOfA + i), 25 | items: getRandomList(3, 10).map(() => lorem.generateWords(2)), 26 | })); 27 | 28 | const Users = () => { 29 | return ( 30 | <> 31 | 32 | {groups.map((group) => { 33 | const { title, items } = group; 34 | return ( 35 | 40 | 41 | {items.map((item, index) => ( 42 | {item} 43 | ))} 44 | 45 | 46 | ); 47 | })} 48 | 49 | 50 | ); 51 | }; 52 | 53 | export default Users; 54 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/glob/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "Isaac Z. Schlueter (http://blog.izs.me/)", 3 | "name": "glob", 4 | "description": "a little globber", 5 | "version": "8.0.3", 6 | "repository": { 7 | "type": "git", 8 | "url": "git://github.com/isaacs/node-glob.git" 9 | }, 10 | "main": "glob.js", 11 | "files": [ 12 | "glob.js", 13 | "sync.js", 14 | "common.js" 15 | ], 16 | "engines": { 17 | "node": ">=12" 18 | }, 19 | "dependencies": { 20 | "fs.realpath": "^1.0.0", 21 | "inflight": "^1.0.4", 22 | "inherits": "2", 23 | "minimatch": "^5.0.1", 24 | "once": "^1.3.0" 25 | }, 26 | "devDependencies": { 27 | "memfs": "^3.2.0", 28 | "mkdirp": "0", 29 | "rimraf": "^2.2.8", 30 | "tap": "^16.0.1", 31 | "tick": "0.0.6" 32 | }, 33 | "tap": { 34 | "before": "test/00-setup.js", 35 | "after": "test/zz-cleanup.js", 36 | "statements": 90, 37 | "branches": 90, 38 | "functions": 90, 39 | "lines": 90, 40 | "jobs": 1 41 | }, 42 | "scripts": { 43 | "prepublish": "npm run benchclean", 44 | "profclean": "rm -f v8.log profile.txt", 45 | "test": "tap", 46 | "test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js", 47 | "bench": "bash benchmark.sh", 48 | "prof": "bash prof.sh && cat profile.txt", 49 | "benchclean": "node benchclean.js" 50 | }, 51 | "license": "ISC", 52 | "funding": { 53 | "url": "https://github.com/sponsors/isaacs" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /packages/coderduan-umi/src/build.ts: -------------------------------------------------------------------------------- 1 | import { build as esbuild } from "esbuild"; 2 | import { style } from "./styles"; 3 | import { 4 | DEFAULT_PLATFORM 5 | } from "./constants"; 6 | import { getAppData } from "./appData"; 7 | import { getRoutes } from "./routes"; 8 | import { generateEntry } from "./entry"; 9 | import { generateHtml } from "./html"; 10 | import { getUserConfig } from "./config"; 11 | 12 | export const build = async () => { 13 | const cwd = process.cwd(); 14 | 15 | // 生命周期 16 | 17 | // 获取项目元信息 18 | const appData = await getAppData({ cwd }); 19 | 20 | // 获取用户数据 21 | const userConfig = await getUserConfig({ appData, isProduction: true }); 22 | 23 | // 获取 routes 配置 24 | const routes = await getRoutes({ appData }); 25 | // 生成项目主入口 26 | await generateEntry({ appData, routes, userConfig }); 27 | // 生成html 28 | await generateHtml({ appData, userConfig, isProduction: true }); 29 | 30 | // 执行构建; 31 | await esbuild({ 32 | format: "iife", 33 | logLevel: "error", 34 | outdir: appData.paths.absOutputPath, 35 | platform: DEFAULT_PLATFORM, 36 | bundle: true, 37 | minify: true, 38 | define: { 39 | // React 在项目中使用到了 process.env.NODE_ENV 环境变量,使用 esbuild 的 define 定义将它替换成真实的值 40 | "process.env.NODE_ENV": JSON.stringify("production"), 41 | }, 42 | entryPoints: [appData.paths.absEntryPath], 43 | external: ["esbuild"], 44 | plugins: [style()], 45 | }); 46 | }; 47 | -------------------------------------------------------------------------------- /learn/3.2mvc/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | coderduan-umi 8 | 9 | 10 |
11 | loading... 12 |
13 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /packages/coderduan-umi/src/html.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import { mkdir, writeFileSync } from "fs"; 3 | import type { AppData } from "./appData"; 4 | import { DEFAULT_OUTDIR, DEFAULT_FRAMEWORK_NAME } from "./constants"; 5 | import type { UserConfig } from "./config"; 6 | 7 | export const generateHtml = ({ 8 | appData, 9 | userConfig, 10 | isProduction = false 11 | }: { 12 | appData: AppData; 13 | userConfig: UserConfig; 14 | isProduction?: Boolean; 15 | }) => { 16 | return new Promise((resolve, reject) => { 17 | const title = userConfig.title ?? appData.pkg.name ?? "coderduan-umi"; 18 | const content = ` 19 | 20 | 21 | 22 | 23 | ${title} 24 | 25 | 26 | 27 |
28 | loading... 29 |
30 | 31 | ${isProduction ? '' : ''} 32 | 33 | 34 | `; 35 | 36 | try { 37 | const htmlPath = path.resolve(appData.paths.absOutputPath, "index.html"); 38 | mkdir(path.dirname(htmlPath), { recursive: true }, (err) => { 39 | if (err) reject(err); 40 | writeFileSync(htmlPath, content, "utf-8"); 41 | resolve({}); 42 | }); 43 | } catch (error) { 44 | reject(error); 45 | } 46 | }); 47 | }; 48 | -------------------------------------------------------------------------------- /scripts/bundleDeps.ts: -------------------------------------------------------------------------------- 1 | // 将构建入口找到 node_modules 下的某个包指定的 main 入口,然后将它编译到我们指定的路径中 2 | import minimist from "minimist"; 3 | import path from "path"; 4 | import resolve from "resolve"; 5 | import fs from "fs-extra"; 6 | import ncc from "@vercel/ncc"; 7 | import { Package } from "dts-packer"; 8 | 9 | const argv = minimist(process.argv.slice(2)); 10 | const cwd = process.cwd(); 11 | 12 | // 找到nodeModulesPath 13 | const nodeModulesPath = path.join(cwd, "node_modules"); 14 | 15 | // 某个包(eg:express) 16 | const pkg = argv._[0]; 17 | 18 | // 包的入口文件 19 | const entry = require.resolve(pkg, { 20 | paths: [nodeModulesPath], 21 | }); 22 | 23 | // 指定的路径中 24 | const target = `compiled/${pkg}`; 25 | 26 | const build = async () => { 27 | // 将这个包编译 28 | //@ts-ignore 29 | const { code } = await ncc(entry, { 30 | minify: true, 31 | target: "es5", 32 | assetBuilds: false, 33 | }); 34 | 35 | // 编译到 写入到目标文件 36 | fs.ensureDirSync(target); 37 | fs.writeFileSync(path.join(target, "index.js"), code, "utf-8"); 38 | 39 | const pkgRoot = path.dirname( 40 | resolve.sync(`${pkg}/package.json`, { 41 | basedir: cwd, 42 | }) 43 | ); 44 | if (fs.existsSync(path.join(pkgRoot, "LICENSE"))) { 45 | fs.copyFileSync( 46 | path.join(pkgRoot, "LICENSE"), 47 | path.join(target, "LICENSE") 48 | ); 49 | } 50 | fs.copyFileSync( 51 | path.join(pkgRoot, "package.json"), 52 | path.join(target, "package.json") 53 | ); 54 | 55 | new Package({ 56 | cwd: cwd, 57 | name: pkg, 58 | typesRoot: target, 59 | }); 60 | }; 61 | 62 | build(); 63 | -------------------------------------------------------------------------------- /packages/coderduan-umi/src/appData.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import { 3 | DEFAULT_ENTRY_POINT, 4 | DEFAULT_OUTDIR, 5 | DEFAULT_PORT, 6 | DEFAULT_TEMPLATE, 7 | } from "./constants"; 8 | 9 | interface Options { 10 | cwd: string; 11 | port?: number; 12 | } 13 | 14 | // app元数据类型 15 | export interface AppData { 16 | paths: { 17 | cwd: string; // 当前路径 18 | absSrcPath: string; // src 目录 绝对路径 19 | absPagesPath: string; // pages目录 绝对路径 20 | absTmpPath: string; // 临时目录 绝对路径 21 | absOutputPath: string; // 输出目录 绝对路径 22 | absEntryPath: string; // 输入目录 绝对路径 23 | absNodeModulesPath: string; // node_modules 绝对路径 24 | }; 25 | pkg: any; // package.json 信息 26 | } 27 | 28 | export const getAppData = ({ cwd, port = DEFAULT_PORT }: Options) => { 29 | return new Promise((resolve: (value: AppData) => void, reject) => { 30 | const absSrcPath = path.resolve(cwd, "src"); 31 | const absPagesPath = path.resolve(absSrcPath, "pages"); 32 | const absNodeModulesPath = path.resolve(cwd, "node_modules"); 33 | const absTmpPath = path.resolve(absNodeModulesPath, DEFAULT_TEMPLATE); 34 | const absEntryPath = path.resolve(absTmpPath, DEFAULT_ENTRY_POINT); 35 | const absOutputPath = path.resolve(cwd, DEFAULT_OUTDIR); 36 | const paths = { 37 | cwd, 38 | port, 39 | absSrcPath, 40 | absPagesPath, 41 | absTmpPath, 42 | absOutputPath, 43 | absEntryPath, 44 | absNodeModulesPath, 45 | }; 46 | const pkg = require(path.resolve(cwd, "package.json")); 47 | resolve({ paths, pkg }); 48 | }); 49 | }; 50 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/@alitajs/postcss-plugin-px2rem/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@alitajs/postcss-plugin-px2rem", 3 | "version": "0.0.1", 4 | "description": "A plugin for PostCSS that generates rem units from multi units.", 5 | "main": "index.js", 6 | "scripts": { 7 | "compile": "rm -rf lib && babel -d lib src", 8 | "compile:watch": "npm run compile -- --watch", 9 | "lint": "eslint src test", 10 | "prepublish": "npm run compile", 11 | "test": "babel-node $(npm bin)/babel-istanbul cover $(npm bin)/_mocha -- --no-timeouts", 12 | "coveralls": "cat ./coverage/lcov.info | coveralls" 13 | }, 14 | "repository": { 15 | "type": "git", 16 | "url": "https://github.com/alitajs/postcss-plugin-px2rem.git" 17 | }, 18 | "keywords": [ 19 | "px", 20 | "rem", 21 | "postcss", 22 | "plugin" 23 | ], 24 | "author": "pigcan ", 25 | "license": "MIT", 26 | "bugs": { 27 | "url": "https://github.com/ant-tool/postcss-plugin-px2rem/issues" 28 | }, 29 | "homepage": "https://github.com/ant-tool/postcss-plugin-px2rem#readme", 30 | "dependencies": { 31 | "postcss": "^5.0.21" 32 | }, 33 | "devDependencies": { 34 | "babel-cli": "^6.7.5", 35 | "babel-core": "^6.7.6", 36 | "babel-eslint": "^6.0.2", 37 | "babel-istanbul": "^0.7.0", 38 | "babel-plugin-add-module-exports": "^0.1.2", 39 | "babel-preset-es2015": "^6.6.0", 40 | "babel-preset-stage-0": "^6.5.0", 41 | "coveralls": "^2.11.9", 42 | "eslint": "^2.7.0", 43 | "eslint-config-airbnb": "^6.2.0", 44 | "expect": "^1.20.1", 45 | "mocha": "^2.4.5" 46 | }, 47 | "files": [ 48 | "lib", 49 | "index.js", 50 | "package.json", 51 | "README.md" 52 | ], 53 | "publishConfig": { 54 | "access": "public" 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /examples/app/src/layouts/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | import { useLocation, useNavigate } from "react-router-dom"; 3 | import { Page, Content, Header, Footer } from "@alita/flow"; 4 | import { useKeepOutlets } from "@coderduan-umi/keepalive"; 5 | import { Badge, NavBar, TabBar } from "antd-mobile"; 6 | import { AppOutline, UnorderedListOutline } from "antd-mobile-icons"; 7 | import "./index.css"; 8 | 9 | const Layout = () => { 10 | const { pathname } = useLocation(); 11 | const element = useKeepOutlets(); 12 | const navigate = useNavigate(); 13 | const [activeKey, setActiveKey] = useState(pathname); 14 | 15 | const tabs = [ 16 | { 17 | key: "/", 18 | title: "首页", 19 | icon: , 20 | badge: Badge.dot, 21 | }, 22 | { 23 | key: "/users", 24 | title: "我的待办", 25 | icon: , 26 | badge: "5", 27 | }, 28 | ]; 29 | 30 | const titleHash = { 31 | "/": "首页", 32 | "/users": "我的待办", 33 | }; 34 | 35 | return ( 36 | 37 | {/*
当前路由:{pathname}
*/} 38 |
39 | {titleHash[activeKey]} 40 |
41 | 42 | {element} 43 | 44 |
45 | { 47 | setActiveKey(value); 48 | navigate(value); 49 | }} 50 | activeKey={activeKey} 51 | > 52 | {tabs.map((item: any) => ( 53 | 59 | ))} 60 | 61 |
62 |
63 | ); 64 | }; 65 | export default Layout; 66 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/ws/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ws", 3 | "version": "8.8.1", 4 | "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", 5 | "keywords": [ 6 | "HyBi", 7 | "Push", 8 | "RFC-6455", 9 | "WebSocket", 10 | "WebSockets", 11 | "real-time" 12 | ], 13 | "homepage": "https://github.com/websockets/ws", 14 | "bugs": "https://github.com/websockets/ws/issues", 15 | "repository": "websockets/ws", 16 | "author": "Einar Otto Stangvik (http://2x.io)", 17 | "license": "MIT", 18 | "main": "index.js", 19 | "exports": { 20 | "import": "./wrapper.mjs", 21 | "require": "./index.js" 22 | }, 23 | "browser": "browser.js", 24 | "engines": { 25 | "node": ">=10.0.0" 26 | }, 27 | "files": [ 28 | "browser.js", 29 | "index.js", 30 | "lib/*.js", 31 | "wrapper.mjs" 32 | ], 33 | "scripts": { 34 | "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js", 35 | "integration": "mocha --throw-deprecation test/*.integration.js", 36 | "lint": "eslint --ignore-path .gitignore . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\"" 37 | }, 38 | "peerDependencies": { 39 | "bufferutil": "^4.0.1", 40 | "utf-8-validate": "^5.0.2" 41 | }, 42 | "peerDependenciesMeta": { 43 | "bufferutil": { 44 | "optional": true 45 | }, 46 | "utf-8-validate": { 47 | "optional": true 48 | } 49 | }, 50 | "devDependencies": { 51 | "benchmark": "^2.1.4", 52 | "bufferutil": "^4.0.1", 53 | "eslint": "^8.0.0", 54 | "eslint-config-prettier": "^8.1.0", 55 | "eslint-plugin-prettier": "^4.0.0", 56 | "mocha": "^8.4.0", 57 | "nyc": "^15.0.0", 58 | "prettier": "^2.0.5", 59 | "utf-8-validate": "^5.0.2" 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /packages/coderduan-umi/src/routes.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import { existsSync, readdirSync, statSync } from "fs"; 3 | import type { AppData } from "./appData"; 4 | import { DEFAULT_GLOBAL_LAYOUTS } from "./constants"; 5 | 6 | // 获取所有tsx文件 7 | const getFiles = (root: string): string[] => { 8 | if (!existsSync(root)) return []; 9 | return readdirSync(root).filter((file) => { 10 | const absFile = path.join(root, file); 11 | const fileStat = statSync(absFile); 12 | const isFile = fileStat.isFile(); 13 | if (isFile) { 14 | if (!/\.tsx?$/.test(file)) return false; 15 | } 16 | return true; 17 | }); 18 | }; 19 | 20 | // 文件转路由配置 21 | const filesToRoutes = (files: string[], pagesPath: string): IRoute[] => { 22 | return files.map((i) => { 23 | let pagePath = path.basename(i, path.extname(i)); 24 | const element = path.resolve(pagesPath, pagePath); 25 | // TODO:后续改为默认index和支持用户配置 26 | if (pagePath === "home") pagePath = ""; 27 | return { 28 | path: `${pagePath}`, 29 | element, 30 | }; 31 | }); 32 | }; 33 | 34 | export interface IRoute { 35 | element: string; 36 | path: string; 37 | routes?: IRoute[]; 38 | } 39 | 40 | // 获取路由配置 41 | export const getRoutes = ({ appData }: { appData: AppData }) => { 42 | return new Promise((resolve: (value: IRoute[]) => void) => { 43 | const files = getFiles(appData.paths.absPagesPath); 44 | const routes = filesToRoutes(files, appData.paths.absPagesPath); 45 | const layoutPtah = path.resolve( 46 | appData.paths.absSrcPath, 47 | DEFAULT_GLOBAL_LAYOUTS 48 | ); 49 | 50 | if (!existsSync(layoutPtah)) { 51 | resolve(routes); 52 | } else { 53 | resolve([ 54 | { 55 | path: "/", 56 | element: layoutPtah.replace(path.extname(layoutPtah), ""), 57 | routes: routes, 58 | }, 59 | ]); 60 | } 61 | }); 62 | }; 63 | -------------------------------------------------------------------------------- /packages/coderduan-umi/src/config.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import { existsSync } from "fs"; 3 | import { build } from "esbuild"; 4 | import { DEFAULT_CONFIG_FILE } from "./constants"; 5 | import type { AppData } from "./appData"; 6 | import type { Server } from "http"; 7 | import type { Options as ProxyOptions } from "../compiled/http-proxy-middleware"; 8 | 9 | export interface UserConfig { 10 | title: string; 11 | keepalive: any[]; 12 | proxy: { 13 | [key: string]: ProxyOptions; 14 | }; 15 | } 16 | 17 | export const getUserConfig = ({ 18 | appData, 19 | coderduanUmiServer, 20 | isProduction = false, 21 | }: { 22 | appData: AppData; 23 | coderduanUmiServer?: Server; 24 | isProduction?: Boolean; 25 | }) => { 26 | return new Promise(async (resolve: (value: UserConfig) => void, reject) => { 27 | let config = {}; 28 | const configFile = path.resolve(appData.paths.cwd, DEFAULT_CONFIG_FILE); 29 | 30 | if (existsSync(configFile)) { 31 | await build({ 32 | format: "cjs", 33 | logLevel: "error", 34 | outdir: appData.paths.absOutputPath, 35 | bundle: true, 36 | define: { 37 | "process.env.NODE_ENV": JSON.stringify(isProduction ? "production" : "development"), 38 | }, 39 | entryPoints: [configFile], 40 | external: ["esbuild"], 41 | watch: isProduction ? false : { 42 | onRebuild(error, result) { 43 | if (error) { 44 | return console.error(JSON.stringify(error)); 45 | } 46 | coderduanUmiServer?.emit("REBUILD", { appData }); 47 | }, 48 | }, 49 | }); 50 | 51 | try { 52 | const configOutputFile = path.resolve( 53 | appData.paths.absOutputPath, 54 | "coderduan-umi.config.js" 55 | ); 56 | delete require.cache[configOutputFile]; 57 | config = require(configOutputFile).default; 58 | } catch (error) { 59 | console.error("getUserConfig error", error); 60 | reject(error); 61 | } 62 | } 63 | 64 | resolve(config as UserConfig); 65 | }); 66 | }; 67 | -------------------------------------------------------------------------------- /packages/keepalive/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { createContext, useContext } from "react"; 2 | import { useOutlet, useLocation, matchPath } from "react-router-dom"; 3 | import type { FC } from "react"; 4 | 5 | export const KeepAliveContext = createContext({ 6 | keepalive: [], 7 | keepElements: [], 8 | }); 9 | 10 | const isKeepPath = (aliveList: any[], path: string) => { 11 | let isKeep = false; 12 | aliveList.map((item) => { 13 | if (item === path) { 14 | isKeep = true; 15 | } 16 | if (item instanceof RegExp && item.test(path)) { 17 | isKeep = true; 18 | } 19 | if (typeof item === "string" && item.toLowerCase() === path) { 20 | isKeep = true; 21 | } 22 | }); 23 | return isKeep; 24 | }; 25 | 26 | export function useKeepOutlets() { 27 | const location = useLocation(); 28 | const element = useOutlet(); 29 | const { keepalive, keepElements } = useContext(KeepAliveContext); 30 | const isKeep = isKeepPath(keepalive, location.pathname); 31 | if (isKeep) { 32 | keepElements.current[location.pathname] = element; 33 | } 34 | 35 | const divWrapStyle = { 36 | height: "100%", 37 | width: "100%", 38 | position: "relative", 39 | overflow: "hidden auto", 40 | }; 41 | 42 | return ( 43 | <> 44 | {Object.entries(keepElements.current).map(([pathname, element]: any) => ( 45 | 53 | ))} 54 | 61 | 62 | ); 63 | } 64 | 65 | interface KeepAliveLayoutProps { 66 | keepalive: any[]; 67 | keepElements?: any; 68 | dropByCacheKey?: (path: string) => void; 69 | } 70 | 71 | const KeepAliveLayout: FC = (props) => { 72 | const { keepalive, ...other } = props; 73 | const keepElements = React.useRef({}); 74 | function dropByCacheKey(path: string) { 75 | keepElements.current[path] = null; 76 | } 77 | return ( 78 | 82 | ); 83 | }; 84 | 85 | export default KeepAliveLayout; 86 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/commander/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "commander", 3 | "version": "9.4.0", 4 | "description": "the complete solution for node.js command-line programs", 5 | "keywords": [ 6 | "commander", 7 | "command", 8 | "option", 9 | "parser", 10 | "cli", 11 | "argument", 12 | "args", 13 | "argv" 14 | ], 15 | "author": "TJ Holowaychuk ", 16 | "license": "MIT", 17 | "repository": { 18 | "type": "git", 19 | "url": "https://github.com/tj/commander.js.git" 20 | }, 21 | "scripts": { 22 | "lint": "npm run lint:javascript && npm run lint:typescript", 23 | "lint:javascript": "eslint index.js esm.mjs \"lib/*.js\" \"tests/**/*.js\"", 24 | "lint:typescript": "eslint typings/*.ts tests/*.ts", 25 | "test": "jest && npm run test-typings", 26 | "test-esm": "node --experimental-modules ./tests/esm-imports-test.mjs", 27 | "test-typings": "tsd", 28 | "typescript-checkJS": "tsc --allowJS --checkJS index.js lib/*.js --noEmit", 29 | "test-all": "npm run test && npm run lint && npm run typescript-checkJS && npm run test-esm" 30 | }, 31 | "files": [ 32 | "index.js", 33 | "lib/*.js", 34 | "esm.mjs", 35 | "typings/index.d.ts", 36 | "package-support.json" 37 | ], 38 | "type": "commonjs", 39 | "main": "./index.js", 40 | "exports": { 41 | ".": { 42 | "types": "./typings/index.d.ts", 43 | "require": "./index.js", 44 | "import": "./esm.mjs" 45 | }, 46 | "./esm.mjs": "./esm.mjs" 47 | }, 48 | "devDependencies": { 49 | "@types/jest": "^28.1.4", 50 | "@types/node": "^16.11.15", 51 | "@typescript-eslint/eslint-plugin": "^5.30.6", 52 | "@typescript-eslint/parser": "^5.30.6", 53 | "eslint": "^8.19.0", 54 | "eslint-config-standard": "^17.0.0", 55 | "eslint-config-standard-with-typescript": "^22.0.0", 56 | "eslint-plugin-import": "^2.25.3", 57 | "eslint-plugin-jest": "^26.5.3", 58 | "eslint-plugin-n": "^15.2.4", 59 | "eslint-plugin-promise": "^6.0.0", 60 | "jest": "^28.1.2", 61 | "ts-jest": "^28.0.5", 62 | "tsd": "^0.22.0", 63 | "typescript": "^4.7.4" 64 | }, 65 | "types": "typings/index.d.ts", 66 | "jest": { 67 | "testEnvironment": "node", 68 | "collectCoverage": true, 69 | "transform": { 70 | "^.+\\.tsx?$": "ts-jest" 71 | }, 72 | "testPathIgnorePatterns": [ 73 | "/node_modules/" 74 | ] 75 | }, 76 | "engines": { 77 | "node": "^12.20.0 || >=14" 78 | }, 79 | "support": true 80 | } 81 | -------------------------------------------------------------------------------- /packages/coderduan-umi/src/entry.ts: -------------------------------------------------------------------------------- 1 | import { mkdir, writeFileSync } from "fs"; 2 | import path from "path"; 3 | import type { AppData } from "./appData"; 4 | import type { IRoute } from "./routes"; 5 | import type { UserConfig } from "./config"; 6 | 7 | let count = 1; 8 | 9 | const getRouteStr = (routes: IRoute[]) => { 10 | let routesStr = ""; 11 | let importStr = ""; 12 | routes.forEach((route) => { 13 | count += 1; 14 | importStr += `import A${count} from '${route.element}';\n`; 15 | routesStr += `\n}>`; 16 | if (route.routes) { 17 | const { routesStr: rs, importStr: is } = getRouteStr(route.routes); 18 | routesStr += rs; 19 | importStr += is; 20 | } 21 | routesStr += "\n"; 22 | }); 23 | 24 | return { routesStr, importStr }; 25 | }; 26 | 27 | const configStringify = (config: (string | RegExp)[]) => { 28 | return config.map((item) => { 29 | if (item instanceof RegExp) { 30 | return item; 31 | } 32 | return `'${item}'`; 33 | }); 34 | }; 35 | 36 | export const generateEntry = ({ 37 | appData, 38 | routes, 39 | userConfig, 40 | }: { 41 | appData: AppData; 42 | routes: IRoute[]; 43 | userConfig: UserConfig; 44 | }) => { 45 | return new Promise((resolve, reject) => { 46 | count = 0; 47 | const { routesStr, importStr } = getRouteStr(routes); 48 | const content = ` 49 | import React from "react"; 50 | import ReactDOM from "react-dom/client"; 51 | import { HashRouter, Route, Routes } from "react-router-dom"; 52 | import KeepAliveLayout from "@coderduan-umi/keepalive"; 53 | import "${path.resolve(__dirname, "hd")}" 54 | ${importStr} 55 | 56 | const App = () => { 57 | return ( 58 | 61 | 62 | 63 | ${routesStr} 64 | 65 | 66 | 67 | 68 | ); 69 | }; 70 | 71 | const root = ReactDOM.createRoot(document.getElementById("root")); 72 | root.render(React.createElement(App)); 73 | `; 74 | 75 | try { 76 | mkdir( 77 | path.dirname(appData.paths.absEntryPath), 78 | { recursive: true }, 79 | (err) => { 80 | if (err) reject(err); 81 | writeFileSync(appData.paths.absEntryPath, content, "utf-8"); 82 | resolve({}); 83 | } 84 | ); 85 | } catch (error) { 86 | reject({ error }); 87 | } 88 | }); 89 | }; 90 | -------------------------------------------------------------------------------- /packages/coderduan-umi/src/mock.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import { build } from "esbuild"; 3 | import glob from "../compiled/glob"; 4 | import type { AppData } from "./appData"; 5 | import type { Server } from "http"; 6 | 7 | function clearRequireCache(absMockPath: string) { 8 | Object.keys(require.cache).forEach((file) => { 9 | if (file.indexOf(absMockPath) > -1) { 10 | delete require.cache[file]; 11 | } 12 | }); 13 | } 14 | 15 | function normalizeConfig(config: any) { 16 | return Object.keys(config).reduce((memo: any, key) => { 17 | const handler = config[key]; 18 | const type = typeof handler; 19 | if (type !== "function" && type !== "object") { 20 | return memo; 21 | } 22 | const req = key.split(" "); 23 | const method = req[0]; 24 | const url = req[1]; 25 | if (!memo[method]) memo[method] = {}; 26 | memo[method][url] = handler; 27 | return memo; 28 | }, {}); 29 | } 30 | 31 | export const getMockConfig = ({ 32 | appData, 33 | coderduanUmiServer, 34 | }: { 35 | appData: AppData; 36 | coderduanUmiServer: Server; 37 | }) => { 38 | return new Promise(async (resolve: (value: any) => void, reject) => { 39 | let config = {}; 40 | const mockDir = path.resolve(appData.paths.cwd, "mock"); 41 | const mockFiles = glob.sync("**/*.ts", { cwd: mockDir }); 42 | const ret = mockFiles.map((memo) => { 43 | return path.join(mockDir, memo); 44 | }); 45 | const mockOutDir = path.resolve(appData.paths.absTmpPath, "mock"); 46 | await build({ 47 | format: "cjs", 48 | logLevel: "error", 49 | outdir: mockOutDir, 50 | bundle: true, 51 | define: { 52 | "process.env.NODE_ENV": JSON.stringify("development"), 53 | }, 54 | entryPoints: ret, 55 | external: ["esbuild"], 56 | watch: { 57 | onRebuild(error, result) { 58 | if (error) { 59 | return console.error(JSON.stringify(error)); 60 | } 61 | coderduanUmiServer.emit("REBUILD", { appData }); 62 | }, 63 | }, 64 | }); 65 | 66 | try { 67 | const outMockFiles = glob.sync("**/*.js", { cwd: mockOutDir }); 68 | clearRequireCache(mockOutDir); 69 | config = outMockFiles.reduce((memo, mockFile) => { 70 | memo = { 71 | ...memo, 72 | ...require(path.resolve(mockOutDir, mockFile)).default, 73 | }; 74 | return memo; 75 | }, {}); 76 | } catch (error) { 77 | console.log("getMockConfig error", error); 78 | reject(error); 79 | } 80 | resolve(normalizeConfig(config)); 81 | }); 82 | }; 83 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/postcss/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "postcss", 3 | "version": "8.4.16", 4 | "description": "Tool for transforming styles with JS plugins", 5 | "engines": { 6 | "node": "^10 || ^12 || >=14" 7 | }, 8 | "exports": { 9 | ".": { 10 | "require": "./lib/postcss.js", 11 | "import": "./lib/postcss.mjs", 12 | "types": "./lib/postcss.d.ts" 13 | }, 14 | "./lib/at-rule": "./lib/at-rule.js", 15 | "./lib/comment": "./lib/comment.js", 16 | "./lib/container": "./lib/container.js", 17 | "./lib/css-syntax-error": "./lib/css-syntax-error.js", 18 | "./lib/declaration": "./lib/declaration.js", 19 | "./lib/fromJSON": "./lib/fromJSON.js", 20 | "./lib/input": "./lib/input.js", 21 | "./lib/lazy-result": "./lib/lazy-result.js", 22 | "./lib/no-work-result": "./lib/no-work-result.js", 23 | "./lib/list": "./lib/list.js", 24 | "./lib/map-generator": "./lib/map-generator.js", 25 | "./lib/node": "./lib/node.js", 26 | "./lib/parse": "./lib/parse.js", 27 | "./lib/parser": "./lib/parser.js", 28 | "./lib/postcss": "./lib/postcss.js", 29 | "./lib/previous-map": "./lib/previous-map.js", 30 | "./lib/processor": "./lib/processor.js", 31 | "./lib/result": "./lib/result.js", 32 | "./lib/root": "./lib/root.js", 33 | "./lib/rule": "./lib/rule.js", 34 | "./lib/stringifier": "./lib/stringifier.js", 35 | "./lib/stringify": "./lib/stringify.js", 36 | "./lib/symbols": "./lib/symbols.js", 37 | "./lib/terminal-highlight": "./lib/terminal-highlight.js", 38 | "./lib/tokenize": "./lib/tokenize.js", 39 | "./lib/warn-once": "./lib/warn-once.js", 40 | "./lib/warning": "./lib/warning.js", 41 | "./package.json": "./package.json" 42 | }, 43 | "main": "./lib/postcss.js", 44 | "types": "./lib/postcss.d.ts", 45 | "keywords": [ 46 | "css", 47 | "postcss", 48 | "rework", 49 | "preprocessor", 50 | "parser", 51 | "source map", 52 | "transform", 53 | "manipulation", 54 | "transpiler" 55 | ], 56 | "funding": [ 57 | { 58 | "type": "opencollective", 59 | "url": "https://opencollective.com/postcss/" 60 | }, 61 | { 62 | "type": "tidelift", 63 | "url": "https://tidelift.com/funding/github/npm/postcss" 64 | } 65 | ], 66 | "author": "Andrey Sitnik ", 67 | "license": "MIT", 68 | "homepage": "https://postcss.org/", 69 | "repository": "postcss/postcss", 70 | "bugs": { 71 | "url": "https://github.com/postcss/postcss/issues" 72 | }, 73 | "dependencies": { 74 | "nanoid": "^3.3.4", 75 | "picocolors": "^1.0.0", 76 | "source-map-js": "^1.0.2" 77 | }, 78 | "browser": { 79 | "./lib/terminal-highlight": false, 80 | "source-map-js": false, 81 | "path": false, 82 | "url": false, 83 | "fs": false 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /packages/coderduan-umi/src/styles.ts: -------------------------------------------------------------------------------- 1 | import esbuild, { Plugin } from "esbuild"; 2 | import path from "path"; 3 | import postcss from "../compiled/postcss"; 4 | //@ts-ignore 5 | import px2rem from "../compiled/@alitajs/postcss-plugin-px2rem"; 6 | 7 | export function style(): Plugin { 8 | return { 9 | name: "style", 10 | setup({ onResolve, onLoad }) { 11 | onResolve({ filter: /\.css$/, namespace: "file" }, (args) => { 12 | const absPath = path.resolve(args.resolveDir, args.path); 13 | return { path: absPath, namespace: "style-stub" }; 14 | }); 15 | onResolve({ filter: /\.css$/, namespace: "style-stub" }, (args) => { 16 | return { path: args.path, namespace: "style-content" }; 17 | }); 18 | onResolve( 19 | { filter: /^__style_helper__$/, namespace: "style-stub" }, 20 | (args) => { 21 | return { 22 | path: args.path, 23 | namespace: "style-helper", 24 | sideEffects: false, 25 | }; 26 | } 27 | ); 28 | 29 | onLoad({ filter: /.*/, namespace: "style-helper" }, async () => ({ 30 | contents: ` 31 | export function injectStyle(text) { 32 | if (typeof document !== 'undefined') { 33 | var style = document.createElement('style') 34 | var node = document.createTextNode(text) 35 | style.appendChild(node) 36 | document.head.appendChild(style) 37 | } 38 | } 39 | `, 40 | })); 41 | 42 | onLoad({ filter: /.*/, namespace: "style-stub" }, async (args) => ({ 43 | contents: ` 44 | import { injectStyle } from "__style_helper__" 45 | import css from ${JSON.stringify(args.path)} 46 | injectStyle(css) 47 | `, 48 | })); 49 | onLoad({ filter: /.*/, namespace: "style-content" }, async (args) => { 50 | const { errors, warnings, outputFiles } = await esbuild.build({ 51 | entryPoints: [args.path], 52 | logLevel: "silent", 53 | bundle: true, 54 | write: false, 55 | charset: "utf8", 56 | minify: false, 57 | loader: { 58 | ".svg": "dataurl", 59 | ".ttf": "dataurl", 60 | }, 61 | }); 62 | 63 | if (errors.length > 0) { 64 | return { 65 | errors, 66 | warnings, 67 | contents: outputFiles![0].text, 68 | loader: "text", 69 | }; 70 | } 71 | 72 | try { 73 | // 使用postcss再处理 74 | const result = await postcss([ 75 | px2rem({ 76 | rootValue: 100, 77 | minPixelValue: 2, 78 | selectorDoubleRemList: [/.adm-/, /.ant-/], 79 | }), 80 | ]).process(outputFiles![0].text, { 81 | from: args.path, 82 | to: args.path, 83 | }); 84 | 85 | return { 86 | errors, 87 | warnings, 88 | contents: result.css, 89 | loader: "text", 90 | }; 91 | } catch (error) { 92 | return { 93 | errors, 94 | warnings, 95 | contents: outputFiles![0].text, 96 | loader: "text", 97 | }; 98 | } 99 | }); 100 | }, 101 | }; 102 | } 103 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/http-proxy-middleware/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "http-proxy-middleware", 3 | "version": "2.0.6", 4 | "description": "The one-liner node.js proxy middleware for connect, express and browser-sync", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "files": [ 8 | "dist" 9 | ], 10 | "scripts": { 11 | "clean": "rm -rf dist && rm -rf coverage", 12 | "lint": "yarn prettier && yarn eslint", 13 | "lint:fix": "yarn prettier:fix && yarn eslint:fix", 14 | "eslint": "eslint '{src,test}/**/*.ts'", 15 | "eslint:fix": "yarn eslint --fix", 16 | "prettier": "prettier --list-different \"**/*.{js,ts,md,yml,json,html}\"", 17 | "prettier:fix": "prettier --write \"**/*.{js,ts,md,yml,json,html}\"", 18 | "prebuild": "yarn clean", 19 | "build": "tsc", 20 | "pretest": "yarn build", 21 | "test": "jest", 22 | "precoverage": "yarn build", 23 | "coverage": "jest --coverage --coverageReporters=lcov", 24 | "prepare": "husky install", 25 | "prepack": "yarn build && rm dist/tsconfig.tsbuildinfo", 26 | "spellcheck": "npx --yes cspell --show-context --show-suggestions '**/*.*'" 27 | }, 28 | "repository": { 29 | "type": "git", 30 | "url": "https://github.com/chimurai/http-proxy-middleware.git" 31 | }, 32 | "keywords": [ 33 | "reverse", 34 | "proxy", 35 | "middleware", 36 | "http", 37 | "https", 38 | "connect", 39 | "express", 40 | "fastify", 41 | "polka", 42 | "browser-sync", 43 | "gulp", 44 | "grunt-contrib-connect", 45 | "websocket", 46 | "ws", 47 | "cors" 48 | ], 49 | "author": "Steven Chim", 50 | "license": "MIT", 51 | "bugs": { 52 | "url": "https://github.com/chimurai/http-proxy-middleware/issues" 53 | }, 54 | "homepage": "https://github.com/chimurai/http-proxy-middleware#readme", 55 | "devDependencies": { 56 | "@commitlint/cli": "16.2.1", 57 | "@commitlint/config-conventional": "16.2.1", 58 | "@types/express": "4.17.13", 59 | "@types/is-glob": "4.0.2", 60 | "@types/jest": "27.4.0", 61 | "@types/micromatch": "4.0.2", 62 | "@types/node": "17.0.18", 63 | "@types/supertest": "2.0.11", 64 | "@types/ws": "8.2.2", 65 | "@typescript-eslint/eslint-plugin": "5.12.0", 66 | "@typescript-eslint/parser": "5.12.0", 67 | "body-parser": "1.19.2", 68 | "browser-sync": "2.27.7", 69 | "connect": "3.7.0", 70 | "eslint": "8.9.0", 71 | "eslint-config-prettier": "8.3.0", 72 | "eslint-plugin-prettier": "4.0.0", 73 | "express": "4.17.3", 74 | "get-port": "5.1.1", 75 | "husky": "7.0.4", 76 | "jest": "27.5.1", 77 | "lint-staged": "12.3.4", 78 | "mockttp": "2.6.0", 79 | "open": "8.4.0", 80 | "prettier": "2.5.1", 81 | "supertest": "6.2.2", 82 | "ts-jest": "27.1.3", 83 | "typescript": "4.5.5", 84 | "ws": "8.5.0" 85 | }, 86 | "dependencies": { 87 | "@types/http-proxy": "^1.17.8", 88 | "http-proxy": "^1.18.1", 89 | "is-glob": "^4.0.1", 90 | "is-plain-obj": "^3.0.0", 91 | "micromatch": "^4.0.2" 92 | }, 93 | "peerDependencies": { 94 | "@types/express": "^4.17.13" 95 | }, 96 | "peerDependenciesMeta": { 97 | "@types/express": { 98 | "optional": true 99 | } 100 | }, 101 | "engines": { 102 | "node": ">=12.0.0" 103 | }, 104 | "commitlint": { 105 | "extends": [ 106 | "@commitlint/config-conventional" 107 | ] 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/glob/index.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for Glob 7.2 2 | // Project: https://github.com/isaacs/node-glob 3 | // Definitions by: vvakame 4 | // voy 5 | // Klaus Meinhardt 6 | // Piotr Błażejewicz 7 | // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped 8 | 9 | /// 10 | 11 | import events = require('events'); 12 | import minimatch = require('./minimatch'); 13 | import fs = require('fs'); 14 | 15 | declare function G(pattern: string, cb: (err: Error | null, matches: string[]) => void): G.IGlob; 16 | declare function G(pattern: string, options: G.IOptions, cb: (err: Error | null, matches: string[]) => void): G.IGlob; 17 | 18 | declare namespace G { 19 | function __promisify__(pattern: string, options?: IOptions): Promise; 20 | 21 | function sync(pattern: string, options?: IOptions): string[]; 22 | 23 | function hasMagic(pattern: string, options?: IOptions): boolean; 24 | 25 | let glob: typeof G; 26 | let Glob: IGlobStatic; 27 | let GlobSync: IGlobSyncStatic; 28 | 29 | interface IOptions extends minimatch.IOptions { 30 | cwd?: string | undefined; 31 | root?: string | undefined; 32 | dot?: boolean | undefined; 33 | nomount?: boolean | undefined; 34 | mark?: boolean | undefined; 35 | nosort?: boolean | undefined; 36 | stat?: boolean | undefined; 37 | silent?: boolean | undefined; 38 | strict?: boolean | undefined; 39 | cache?: { [path: string]: boolean | 'DIR' | 'FILE' | ReadonlyArray } | undefined; 40 | statCache?: { [path: string]: false | { isDirectory(): boolean} | undefined } | undefined; 41 | symlinks?: { [path: string]: boolean | undefined } | undefined; 42 | realpathCache?: { [path: string]: string } | undefined; 43 | sync?: boolean | undefined; 44 | nounique?: boolean | undefined; 45 | nonull?: boolean | undefined; 46 | debug?: boolean | undefined; 47 | nobrace?: boolean | undefined; 48 | noglobstar?: boolean | undefined; 49 | noext?: boolean | undefined; 50 | nocase?: boolean | undefined; 51 | matchBase?: any; 52 | nodir?: boolean | undefined; 53 | ignore?: string | ReadonlyArray | undefined; 54 | follow?: boolean | undefined; 55 | realpath?: boolean | undefined; 56 | nonegate?: boolean | undefined; 57 | nocomment?: boolean | undefined; 58 | absolute?: boolean | undefined; 59 | fs?: typeof fs; 60 | } 61 | 62 | interface IGlobStatic extends events.EventEmitter { 63 | new (pattern: string, cb?: (err: Error | null, matches: string[]) => void): IGlob; 64 | new (pattern: string, options: IOptions, cb?: (err: Error | null, matches: string[]) => void): IGlob; 65 | prototype: IGlob; 66 | } 67 | 68 | interface IGlobSyncStatic { 69 | new (pattern: string, options?: IOptions): IGlobBase; 70 | prototype: IGlobBase; 71 | } 72 | 73 | interface IGlobBase { 74 | minimatch: minimatch.IMinimatch; 75 | options: IOptions; 76 | aborted: boolean; 77 | cache: { [path: string]: boolean | 'DIR' | 'FILE' | ReadonlyArray }; 78 | statCache: { [path: string]: false | { isDirectory(): boolean; } | undefined }; 79 | symlinks: { [path: string]: boolean | undefined }; 80 | realpathCache: { [path: string]: string }; 81 | found: string[]; 82 | } 83 | 84 | interface IGlob extends IGlobBase, events.EventEmitter { 85 | pause(): void; 86 | resume(): void; 87 | abort(): void; 88 | } 89 | } 90 | 91 | export = G; 92 | -------------------------------------------------------------------------------- /examples/app/src/pages/home.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | import { Button, Grid, List, Space, Swiper, Image, Toast } from "antd-mobile"; 3 | import "./home.css"; 4 | 5 | const demoSrc = 6 | "https://images.unsplash.com/photo-1567945716310-4745a6b7844b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=300&q=60"; 7 | 8 | const users = [ 9 | { 10 | id: "1", 11 | avatar: 12 | "https://images.unsplash.com/photo-1548532928-b34e3be62fc6?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ", 13 | name: "Novalee Spicer", 14 | description: "Deserunt dolor ea eaque eos", 15 | }, 16 | { 17 | id: "2", 18 | avatar: 19 | "https://images.unsplash.com/photo-1493666438817-866a91353ca9?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&s=b616b2c5b373a80ffc9636ba24f7a4a9", 20 | name: "Sara Koivisto", 21 | description: "Animi eius expedita, explicabo", 22 | }, 23 | { 24 | id: "3", 25 | avatar: 26 | "https://images.unsplash.com/photo-1542624937-8d1e9f53c1b9?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ", 27 | name: "Marco Gregg", 28 | description: "Ab animi cumque eveniet ex harum nam odio omnis", 29 | }, 30 | { 31 | id: "4", 32 | avatar: 33 | "https://images.unsplash.com/photo-1546967191-fdfb13ed6b1e?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ", 34 | name: "Edith Koenig", 35 | description: "Commodi earum exercitationem id numquam vitae", 36 | }, 37 | ]; 38 | 39 | const colors = [ 40 | "#ace0ff", 41 | "#bcffbd", 42 | "#e4fabd", 43 | "#ffcfac", 44 | "#ffcabd", 45 | "#ffc0c0", 46 | ]; 47 | 48 | const items = colors.map((color, index) => ( 49 | 50 |
{ 62 | Toast.show(`你点击了卡片 ${index + 1}`); 63 | }} 64 | > 65 | {index + 1} 66 |
67 |
68 | )); 69 | 70 | const grids = colors.map((color) => ( 71 | 72 | 73 | 80 |
89 | {color} 90 |
91 |
92 |
93 | )); 94 | 95 | const Hello = () => { 96 | const [text, setText] = useState("Hello coderduan-umi~"); 97 | const [count, setCount] = useState(0); 98 | return ( 99 | <> 100 | {items} 101 | 102 | 103 | {grids} 104 | 105 | 106 | {users.map((user) => ( 107 | 117 | } 118 | description={user.description} 119 | > 120 | {user.name} 121 | 122 | ))} 123 | 124 | 125 | ); 126 | }; 127 | export default Hello; 128 | -------------------------------------------------------------------------------- /packages/coderduan-umi/src/hd.ts: -------------------------------------------------------------------------------- 1 | if (typeof document !== "undefined") { 2 | const win = window as any; 3 | const baseFontSize = win.alitaBaseFontSize || 100; 4 | const psdWidth = win.alitaPsdWidth || 750; 5 | const _baseFontSize = baseFontSize || 100; 6 | const _psdWidth = psdWidth || 750; 7 | 8 | const doc = win.document; 9 | const docEl = doc.documentElement; 10 | 11 | let lastWidth = docEl.clientWidth; 12 | let lastHeight = docEl.clientHeight; 13 | 14 | // 为了消除安卓dpr乱标的比例 15 | let rate = 1; 16 | // 非淘宝高清方案,默认的 initial-scale 为 1 17 | let scale = 1; 18 | 19 | // 部分安卓机,需要延迟获取屏幕转向和宽高 20 | let timeoutNum: any; 21 | // 有些兼容环境下, fontSize为100px的时候, 结果1rem=86px; 需要纠正viewport; 22 | docEl.style.fontSize = `${_baseFontSize}px`; 23 | const div = doc.createElement("div"); 24 | div.setAttribute("style", "width: 1rem;display:none"); 25 | docEl.appendChild(div); 26 | const trueWidth = win.getComputedStyle(div).width; 27 | docEl.removeChild(div); 28 | // 如果1rem的真实px跟html.fontSize不符. 那么就要加一个rate缩放了; 29 | if (trueWidth !== docEl.style.fontSize) { 30 | const trueWidthVal = parseInt(trueWidth, 10); 31 | rate = _baseFontSize / trueWidthVal; 32 | scale = scale * rate; 33 | } 34 | const getViewPort = (str?: string) => { 35 | if (!str) return {}; 36 | const arr = str.split(","); 37 | const hashArr = {}; 38 | arr.forEach((s) => { 39 | const ss = s.split("="); 40 | // @ts-ignore 41 | hashArr[ss[0].replace(/(^\s*)|(\s*$)/g, "")] = ss[1]; 42 | }); 43 | return hashArr; 44 | }; 45 | let metaEl = doc.querySelector('meta[name="viewport"]'); 46 | if (!metaEl) { 47 | metaEl = doc.createElement("meta"); 48 | metaEl.setAttribute("name", "viewport"); 49 | doc.head.appendChild(metaEl); 50 | } 51 | // 如果是在 iframe 中打开 52 | if (window != top) { 53 | const metaStr = metaEl?.getAttribute("content") || ""; 54 | const viewport = getViewPort(metaStr); 55 | // @ts-ignore 56 | const initScale = viewport["initial-scale"] || "1.0"; 57 | // 把 initial-scale 换成两位数的整数,便于计算。 58 | const initScaleNum = parseInt(`${parseFloat(initScale) * 10}`, 10); 59 | scale = initScaleNum / 10; 60 | } 61 | metaEl.setAttribute( 62 | "content", 63 | `width=device-width,user-scalable=no,initial-scale=${scale},maximum-scale=${scale},minimum-scale=${scale},viewport-fit=cover` 64 | ); 65 | 66 | // width/750*100, 为了统一rem为0.01rem = 1px 67 | const setFontSize = () => { 68 | // 多次触发 resize 的情况,比如转动屏幕,有些手机会改变两次,有些只有一次 69 | if (timeoutNum) clearTimeout(timeoutNum); 70 | // 部分安卓机,转屏幕时直接获取 clientHeight 值异常 71 | timeoutNum = setTimeout(() => { 72 | const currentWidth = docEl.clientWidth; 73 | const currentHeight = docEl.clientHeight; 74 | 75 | // 如果只有高度变化了,认为是键盘弹起事件,不做fontsize计算 76 | if (currentWidth === lastWidth && currentHeight !== lastHeight) { 77 | lastWidth = currentWidth; 78 | lastHeight = currentHeight; 79 | return; 80 | } 81 | 82 | lastWidth = currentWidth; 83 | lastHeight = currentHeight; 84 | 85 | const trueClient = 86 | currentHeight > currentWidth ? currentWidth : currentHeight; 87 | 88 | const newFontSize = `${ 89 | (_baseFontSize / _psdWidth) * trueClient * rate 90 | }px`; 91 | // 如果计算值和当前值相同,不需要重新设置 92 | if (newFontSize === docEl.style.fontSize) return; 93 | docEl.style.fontSize = newFontSize; 94 | }, 300); 95 | }; 96 | // 延迟执行会导致,首次页面闪屏,直接设置 97 | // setFontSize(); 98 | const trueClient = 99 | docEl.clientHeight > docEl.clientWidth 100 | ? docEl.clientWidth 101 | : docEl.clientHeight; 102 | const newFontSize = `${(_baseFontSize / _psdWidth) * trueClient * rate}px`; 103 | docEl.style.fontSize = newFontSize; 104 | 105 | win.addEventListener("resize", setFontSize); 106 | 107 | // hd solution for antd-mobile@2 108 | // ref: https://mobile.ant.design/docs/react/upgrade-notes-cn#%E9%AB%98%E6%B8%85%E6%96%B9%E6%A1%88 109 | // @ts-ignore 110 | document.documentElement.setAttribute("data-scale", true); 111 | } 112 | -------------------------------------------------------------------------------- /packages/coderduan-umi/src/dev.ts: -------------------------------------------------------------------------------- 1 | import express from "../compiled/express"; 2 | import { build } from "esbuild"; 3 | import path from "path"; 4 | import fs from "fs"; 5 | import portfinder from "../compiled/portfinder"; 6 | import { createServer } from "http"; 7 | import { createProxyMiddleware } from "../compiled/http-proxy-middleware"; 8 | import { createWebSocketServer } from "./server"; 9 | import { style } from "./styles"; 10 | import { 11 | DEFAULT_OUTDIR, 12 | DEFAULT_PLATFORM, 13 | DEFAULT_HOST, 14 | DEFAULT_PORT, 15 | } from "./constants"; 16 | import { getAppData } from "./appData"; 17 | import type { AppData } from "./appData"; 18 | import { getRoutes } from "./routes"; 19 | import { generateEntry } from "./entry"; 20 | import { generateHtml } from "./html"; 21 | import { getUserConfig } from "./config"; 22 | import { getMockConfig } from "./mock"; 23 | 24 | export const dev = async () => { 25 | const cwd = process.cwd(); 26 | const app = express(); 27 | const port = await portfinder.getPortPromise({ port: DEFAULT_PORT }); 28 | const output = path.resolve(cwd, DEFAULT_OUTDIR); 29 | 30 | app.get("/", (req, res, next) => { 31 | res.set("Content-Type", "text/html"); 32 | const htmlPath = path.join(output, "index.html"); 33 | if (fs.existsSync(htmlPath)) { 34 | fs.createReadStream(htmlPath).on("error", next).pipe(res); 35 | } else { 36 | next(); 37 | } 38 | }); 39 | 40 | app.use(`/${DEFAULT_OUTDIR}`, express.static(output)); 41 | app.use("/coderduan-umi", express.static(path.resolve(__dirname, "client"))); 42 | 43 | const coderduanUmiServer = createServer(app); 44 | const ws = createWebSocketServer(coderduanUmiServer); 45 | 46 | function sendMessage(type: string, data?: any) { 47 | ws.send(JSON.stringify({ type, data })); 48 | } 49 | 50 | const buildMain = async ({ appData }: { appData: AppData }) => { 51 | // 获取用户数据 52 | const userConfig = await getUserConfig({ appData, coderduanUmiServer }); 53 | const mockConfig = await getMockConfig({ appData, coderduanUmiServer }); 54 | 55 | app.use((req, res, next) => { 56 | const result = mockConfig?.[req.method]?.[req.url]; 57 | const resultType = Object.prototype.toString.call(result); 58 | if ( 59 | resultType === "[object String]" || 60 | resultType === "[object Array]" || 61 | resultType === "[object Object]" 62 | ) { 63 | res.json(result); 64 | } else if (resultType === "[object Function]") { 65 | result(req, res); 66 | } else { 67 | next(); 68 | } 69 | }); 70 | 71 | // 获取 routes 配置 72 | const routes = await getRoutes({ appData }); 73 | // 生成项目主入口 74 | await generateEntry({ appData, routes, userConfig }); 75 | // 生成html 76 | await generateHtml({ appData, userConfig }); 77 | 78 | if (userConfig.proxy) { 79 | Object.keys(userConfig.proxy).forEach((key) => { 80 | const proxyConfig = userConfig.proxy![key]; 81 | const target = proxyConfig.target; 82 | if (target) { 83 | app.use(key, createProxyMiddleware(key, userConfig.proxy![key])); 84 | } 85 | }); 86 | } 87 | }; 88 | 89 | coderduanUmiServer.on("REBUILD", async ({ appData }) => { 90 | await buildMain({ appData }); 91 | sendMessage("reload"); 92 | }); 93 | 94 | coderduanUmiServer.listen(port, async () => { 95 | console.log(`App listening at http://${DEFAULT_HOST}:${port}`); 96 | try { 97 | // 生命周期 98 | 99 | // 获取项目元信息 100 | const appData = await getAppData({ cwd, port }); 101 | 102 | buildMain({ appData }); 103 | 104 | // 执行构建; 105 | await build({ 106 | format: "iife", 107 | logLevel: "error", 108 | outdir: appData.paths.absOutputPath, 109 | platform: DEFAULT_PLATFORM, 110 | bundle: true, 111 | define: { 112 | // React 在项目中使用到了 process.env.NODE_ENV 环境变量,使用 esbuild 的 define 定义将它替换成真实的值 113 | "process.env.NODE_ENV": JSON.stringify("development"), 114 | }, 115 | entryPoints: [appData.paths.absEntryPath], 116 | external: ["esbuild"], 117 | plugins: [style()], 118 | watch: { 119 | onRebuild(error, result) { 120 | if (error) { 121 | return console.error(JSON.stringify(error)); 122 | } 123 | sendMessage("reload"); 124 | }, 125 | }, 126 | }); 127 | // [Issues](https://github.com/evanw/esbuild/issues/805) 128 | // esbuild serve 不能响应 onRebuild 129 | } catch (error) { 130 | console.log(error); 131 | process.exit(1); 132 | } 133 | }); 134 | }; 135 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/express/index.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for Express 4.17 2 | // Project: http://expressjs.com 3 | // Definitions by: Boris Yankov 4 | // China Medical University Hospital 5 | // Puneet Arora 6 | // Dylan Frankland 7 | // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped 8 | 9 | /* =================== USAGE =================== 10 | 11 | import express = require('./express'); 12 | var app = express(); 13 | 14 | =============================================== */ 15 | 16 | /// 17 | /// 18 | 19 | import * as bodyParser from './body-parser'; 20 | import * as serveStatic from './serve-static'; 21 | import * as core from './express-serve-static-core'; 22 | import * as qs from './qs'; 23 | 24 | /** 25 | * Creates an Express application. The express() function is a top-level function exported by the express module. 26 | */ 27 | declare function e(): core.Express; 28 | 29 | declare namespace e { 30 | /** 31 | * This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser. 32 | * @since 4.16.0 33 | */ 34 | var json: typeof bodyParser.json; 35 | 36 | /** 37 | * This is a built-in middleware function in Express. It parses incoming requests with Buffer payloads and is based on body-parser. 38 | * @since 4.17.0 39 | */ 40 | var raw: typeof bodyParser.raw; 41 | 42 | /** 43 | * This is a built-in middleware function in Express. It parses incoming requests with text payloads and is based on body-parser. 44 | * @since 4.17.0 45 | */ 46 | var text: typeof bodyParser.text; 47 | 48 | /** 49 | * These are the exposed prototypes. 50 | */ 51 | var application: Application; 52 | var request: Request; 53 | var response: Response; 54 | 55 | /** 56 | * This is a built-in middleware function in Express. It serves static files and is based on serve-static. 57 | */ 58 | var static: serveStatic.RequestHandlerConstructor; 59 | 60 | /** 61 | * This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser. 62 | * @since 4.16.0 63 | */ 64 | var urlencoded: typeof bodyParser.urlencoded; 65 | 66 | /** 67 | * This is a built-in middleware function in Express. It parses incoming request query parameters. 68 | */ 69 | export function query(options: qs.IParseOptions | typeof qs.parse): Handler; 70 | 71 | export function Router(options?: RouterOptions): core.Router; 72 | 73 | interface RouterOptions { 74 | /** 75 | * Enable case sensitivity. 76 | */ 77 | caseSensitive?: boolean | undefined; 78 | 79 | /** 80 | * Preserve the req.params values from the parent router. 81 | * If the parent and the child have conflicting param names, the child’s value take precedence. 82 | * 83 | * @default false 84 | * @since 4.5.0 85 | */ 86 | mergeParams?: boolean | undefined; 87 | 88 | /** 89 | * Enable strict routing. 90 | */ 91 | strict?: boolean | undefined; 92 | } 93 | 94 | interface Application extends core.Application {} 95 | interface CookieOptions extends core.CookieOptions {} 96 | interface Errback extends core.Errback {} 97 | interface ErrorRequestHandler< 98 | P = core.ParamsDictionary, 99 | ResBody = any, 100 | ReqBody = any, 101 | ReqQuery = core.Query, 102 | Locals extends Record = Record 103 | > extends core.ErrorRequestHandler {} 104 | interface Express extends core.Express {} 105 | interface Handler extends core.Handler {} 106 | interface IRoute extends core.IRoute {} 107 | interface IRouter extends core.IRouter {} 108 | interface IRouterHandler extends core.IRouterHandler {} 109 | interface IRouterMatcher extends core.IRouterMatcher {} 110 | interface MediaType extends core.MediaType {} 111 | interface NextFunction extends core.NextFunction {} 112 | interface Request< 113 | P = core.ParamsDictionary, 114 | ResBody = any, 115 | ReqBody = any, 116 | ReqQuery = core.Query, 117 | Locals extends Record = Record 118 | > extends core.Request {} 119 | interface RequestHandler< 120 | P = core.ParamsDictionary, 121 | ResBody = any, 122 | ReqBody = any, 123 | ReqQuery = core.Query, 124 | Locals extends Record = Record 125 | > extends core.RequestHandler {} 126 | interface RequestParamHandler extends core.RequestParamHandler {} 127 | export interface Response = Record> 128 | extends core.Response {} 129 | interface Router extends core.Router {} 130 | interface Send extends core.Send {} 131 | } 132 | 133 | export = e; 134 | -------------------------------------------------------------------------------- /tsconfig.base.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "commonjs" /* Specify what module code is generated. */, 29 | // "rootDir": "./", /* Specify the root folder within your source files. */ 30 | // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 38 | // "resolveJsonModule": true, /* Enable importing .json files. */ 39 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 40 | 41 | /* JavaScript Support */ 42 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 43 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 44 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 45 | 46 | /* Emit */ 47 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 48 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 49 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 50 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 51 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 52 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 53 | // "removeComments": true, /* Disable emitting comments. */ 54 | // "noEmit": true, /* Disable emitting files from a compilation. */ 55 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 56 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 57 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 58 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 59 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 60 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 61 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 62 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 63 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 64 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 65 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 66 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 67 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 68 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 69 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 70 | 71 | /* Interop Constraints */ 72 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 73 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 74 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, 75 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 76 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, 77 | 78 | /* Type Checking */ 79 | "strict": true /* Enable all strict type-checking options. */, 80 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 81 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 82 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 83 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 84 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 85 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 86 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 87 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 88 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 89 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 90 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 91 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 92 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 93 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 94 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 95 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 96 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 97 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 98 | 99 | /* Completeness */ 100 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 101 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/ws/index.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for ws 8.5 2 | // Project: https://github.com/websockets/ws 3 | // Definitions by: Paul Loyd 4 | // Margus Lamp 5 | // Philippe D'Alva 6 | // reduckted 7 | // teidesu 8 | // Bartosz Wojtkowiak 9 | // Kyle Hensel 10 | // Samuel Skeen 11 | // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped 12 | 13 | /// 14 | 15 | import { EventEmitter } from 'events'; 16 | import { 17 | Agent, 18 | ClientRequest, 19 | ClientRequestArgs, 20 | IncomingMessage, 21 | OutgoingHttpHeaders, 22 | Server as HTTPServer, 23 | } from "http"; 24 | import { Server as HTTPSServer } from 'https'; 25 | import { Duplex, DuplexOptions } from 'stream'; 26 | import { SecureContextOptions } from 'tls'; 27 | import { URL } from 'url'; 28 | import { ZlibOptions } from 'zlib'; 29 | 30 | // WebSocket socket. 31 | declare class WebSocket extends EventEmitter { 32 | /** The connection is not yet open. */ 33 | static readonly CONNECTING: 0; 34 | /** The connection is open and ready to communicate. */ 35 | static readonly OPEN: 1; 36 | /** The connection is in the process of closing. */ 37 | static readonly CLOSING: 2; 38 | /** The connection is closed. */ 39 | static readonly CLOSED: 3; 40 | 41 | binaryType: "nodebuffer" | "arraybuffer" | "fragments"; 42 | readonly bufferedAmount: number; 43 | readonly extensions: string; 44 | /** Indicates whether the websocket is paused */ 45 | readonly isPaused: boolean; 46 | readonly protocol: string; 47 | /** The current state of the connection */ 48 | readonly readyState: 49 | | typeof WebSocket.CONNECTING 50 | | typeof WebSocket.OPEN 51 | | typeof WebSocket.CLOSING 52 | | typeof WebSocket.CLOSED; 53 | readonly url: string; 54 | 55 | /** The connection is not yet open. */ 56 | readonly CONNECTING: 0; 57 | /** The connection is open and ready to communicate. */ 58 | readonly OPEN: 1; 59 | /** The connection is in the process of closing. */ 60 | readonly CLOSING: 2; 61 | /** The connection is closed. */ 62 | readonly CLOSED: 3; 63 | 64 | onopen: ((event: WebSocket.Event) => void) | null; 65 | onerror: ((event: WebSocket.ErrorEvent) => void) | null; 66 | onclose: ((event: WebSocket.CloseEvent) => void) | null; 67 | onmessage: ((event: WebSocket.MessageEvent) => void) | null; 68 | 69 | constructor(address: null); 70 | constructor(address: string | URL, options?: WebSocket.ClientOptions | ClientRequestArgs); 71 | constructor( 72 | address: string | URL, 73 | protocols?: string | string[], 74 | options?: WebSocket.ClientOptions | ClientRequestArgs, 75 | ); 76 | 77 | close(code?: number, data?: string | Buffer): void; 78 | ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void; 79 | pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void; 80 | send(data: any, cb?: (err?: Error) => void): void; 81 | send( 82 | data: any, 83 | options: { mask?: boolean | undefined; binary?: boolean | undefined; compress?: boolean | undefined; fin?: boolean | undefined }, 84 | cb?: (err?: Error) => void, 85 | ): void; 86 | terminate(): void; 87 | 88 | /** 89 | * Pause the websocket causing it to stop emitting events. Some events can still be 90 | * emitted after this is called, until all buffered data is consumed. This method 91 | * is a noop if the ready state is `CONNECTING` or `CLOSED`. 92 | */ 93 | pause(): void; 94 | /** 95 | * Make a paused socket resume emitting events. This method is a noop if the ready 96 | * state is `CONNECTING` or `CLOSED`. 97 | */ 98 | resume(): void; 99 | 100 | // HTML5 WebSocket events 101 | addEventListener( 102 | method: "message", 103 | cb: (event: WebSocket.MessageEvent) => void, 104 | options?: WebSocket.EventListenerOptions, 105 | ): void; 106 | addEventListener( 107 | method: "close", 108 | cb: (event: WebSocket.CloseEvent) => void, 109 | options?: WebSocket.EventListenerOptions, 110 | ): void; 111 | addEventListener( 112 | method: "error", 113 | cb: (event: WebSocket.ErrorEvent) => void, 114 | options?: WebSocket.EventListenerOptions, 115 | ): void; 116 | addEventListener( 117 | method: "open", 118 | cb: (event: WebSocket.Event) => void, 119 | options?: WebSocket.EventListenerOptions, 120 | ): void; 121 | 122 | removeEventListener(method: "message", cb: (event: WebSocket.MessageEvent) => void): void; 123 | removeEventListener(method: "close", cb: (event: WebSocket.CloseEvent) => void): void; 124 | removeEventListener(method: "error", cb: (event: WebSocket.ErrorEvent) => void): void; 125 | removeEventListener(method: "open", cb: (event: WebSocket.Event) => void): void; 126 | 127 | // Events 128 | on(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this; 129 | on(event: "error", listener: (this: WebSocket, err: Error) => void): this; 130 | on(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this; 131 | on(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this; 132 | on(event: "open", listener: (this: WebSocket) => void): this; 133 | on(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this; 134 | on( 135 | event: "unexpected-response", 136 | listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void, 137 | ): this; 138 | on(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this; 139 | 140 | once(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this; 141 | once(event: "error", listener: (this: WebSocket, err: Error) => void): this; 142 | once(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this; 143 | once(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this; 144 | once(event: "open", listener: (this: WebSocket) => void): this; 145 | once(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this; 146 | once( 147 | event: "unexpected-response", 148 | listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void, 149 | ): this; 150 | once(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this; 151 | 152 | off(event: "close", listener: (this: WebSocket, code: number, reason: Buffer) => void): this; 153 | off(event: "error", listener: (this: WebSocket, err: Error) => void): this; 154 | off(event: "upgrade", listener: (this: WebSocket, request: IncomingMessage) => void): this; 155 | off(event: "message", listener: (this: WebSocket, data: WebSocket.RawData, isBinary: boolean) => void): this; 156 | off(event: "open", listener: (this: WebSocket) => void): this; 157 | off(event: "ping" | "pong", listener: (this: WebSocket, data: Buffer) => void): this; 158 | off( 159 | event: "unexpected-response", 160 | listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void, 161 | ): this; 162 | off(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this; 163 | 164 | addListener(event: "close", listener: (code: number, reason: Buffer) => void): this; 165 | addListener(event: "error", listener: (err: Error) => void): this; 166 | addListener(event: "upgrade", listener: (request: IncomingMessage) => void): this; 167 | addListener(event: "message", listener: (data: WebSocket.RawData, isBinary: boolean) => void): this; 168 | addListener(event: "open", listener: () => void): this; 169 | addListener(event: "ping" | "pong", listener: (data: Buffer) => void): this; 170 | addListener( 171 | event: "unexpected-response", 172 | listener: (request: ClientRequest, response: IncomingMessage) => void, 173 | ): this; 174 | addListener(event: string | symbol, listener: (...args: any[]) => void): this; 175 | 176 | removeListener(event: "close", listener: (code: number, reason: Buffer) => void): this; 177 | removeListener(event: "error", listener: (err: Error) => void): this; 178 | removeListener(event: "upgrade", listener: (request: IncomingMessage) => void): this; 179 | removeListener(event: "message", listener: (data: WebSocket.RawData, isBinary: boolean) => void): this; 180 | removeListener(event: "open", listener: () => void): this; 181 | removeListener(event: "ping" | "pong", listener: (data: Buffer) => void): this; 182 | removeListener( 183 | event: "unexpected-response", 184 | listener: (request: ClientRequest, response: IncomingMessage) => void, 185 | ): this; 186 | removeListener(event: string | symbol, listener: (...args: any[]) => void): this; 187 | } 188 | 189 | declare const WebSocketAlias: typeof WebSocket; 190 | interface WebSocketAlias extends WebSocket {} // tslint:disable-line no-empty-interface 191 | 192 | declare namespace WebSocket { 193 | /** 194 | * Data represents the raw message payload received over the WebSocket. 195 | */ 196 | type RawData = Buffer | ArrayBuffer | Buffer[]; 197 | 198 | /** 199 | * Data represents the message payload received over the WebSocket. 200 | */ 201 | type Data = string | Buffer | ArrayBuffer | Buffer[]; 202 | 203 | /** 204 | * CertMeta represents the accepted types for certificate & key data. 205 | */ 206 | type CertMeta = string | string[] | Buffer | Buffer[]; 207 | 208 | /** 209 | * VerifyClientCallbackSync is a synchronous callback used to inspect the 210 | * incoming message. The return value (boolean) of the function determines 211 | * whether or not to accept the handshake. 212 | */ 213 | type VerifyClientCallbackSync = (info: { origin: string; secure: boolean; req: IncomingMessage }) => boolean; 214 | 215 | /** 216 | * VerifyClientCallbackAsync is an asynchronous callback used to inspect the 217 | * incoming message. The return value (boolean) of the function determines 218 | * whether or not to accept the handshake. 219 | */ 220 | type VerifyClientCallbackAsync = ( 221 | info: { origin: string; secure: boolean; req: IncomingMessage }, 222 | callback: (res: boolean, code?: number, message?: string, headers?: OutgoingHttpHeaders) => void, 223 | ) => void; 224 | 225 | interface ClientOptions extends SecureContextOptions { 226 | protocol?: string | undefined; 227 | followRedirects?: boolean | undefined; 228 | generateMask?(mask: Buffer): void; 229 | handshakeTimeout?: number | undefined; 230 | maxRedirects?: number | undefined; 231 | perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined; 232 | localAddress?: string | undefined; 233 | protocolVersion?: number | undefined; 234 | headers?: { [key: string]: string } | undefined; 235 | origin?: string | undefined; 236 | agent?: Agent | undefined; 237 | host?: string | undefined; 238 | family?: number | undefined; 239 | checkServerIdentity?(servername: string, cert: CertMeta): boolean; 240 | rejectUnauthorized?: boolean | undefined; 241 | maxPayload?: number | undefined; 242 | skipUTF8Validation?: boolean | undefined; 243 | } 244 | 245 | interface PerMessageDeflateOptions { 246 | serverNoContextTakeover?: boolean | undefined; 247 | clientNoContextTakeover?: boolean | undefined; 248 | serverMaxWindowBits?: number | undefined; 249 | clientMaxWindowBits?: number | undefined; 250 | zlibDeflateOptions?: { 251 | flush?: number | undefined; 252 | finishFlush?: number | undefined; 253 | chunkSize?: number | undefined; 254 | windowBits?: number | undefined; 255 | level?: number | undefined; 256 | memLevel?: number | undefined; 257 | strategy?: number | undefined; 258 | dictionary?: Buffer | Buffer[] | DataView | undefined; 259 | info?: boolean | undefined; 260 | } | undefined; 261 | zlibInflateOptions?: ZlibOptions | undefined; 262 | threshold?: number | undefined; 263 | concurrencyLimit?: number | undefined; 264 | } 265 | 266 | interface Event { 267 | type: string; 268 | target: WebSocket; 269 | } 270 | 271 | interface ErrorEvent { 272 | error: any; 273 | message: string; 274 | type: string; 275 | target: WebSocket; 276 | } 277 | 278 | interface CloseEvent { 279 | wasClean: boolean; 280 | code: number; 281 | reason: string; 282 | type: string; 283 | target: WebSocket; 284 | } 285 | 286 | interface MessageEvent { 287 | data: Data; 288 | type: string; 289 | target: WebSocket; 290 | } 291 | 292 | interface EventListenerOptions { 293 | once?: boolean | undefined; 294 | } 295 | 296 | interface ServerOptions { 297 | host?: string | undefined; 298 | port?: number | undefined; 299 | backlog?: number | undefined; 300 | server?: HTTPServer | HTTPSServer | undefined; 301 | verifyClient?: VerifyClientCallbackAsync | VerifyClientCallbackSync | undefined; 302 | handleProtocols?: (protocols: Set, request: IncomingMessage) => string | false; 303 | path?: string | undefined; 304 | noServer?: boolean | undefined; 305 | clientTracking?: boolean | undefined; 306 | perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined; 307 | maxPayload?: number | undefined; 308 | skipUTF8Validation?: boolean | undefined; 309 | WebSocket?: typeof WebSocket.WebSocket | undefined; 310 | } 311 | 312 | interface AddressInfo { 313 | address: string; 314 | family: string; 315 | port: number; 316 | } 317 | 318 | // WebSocket Server 319 | class Server extends EventEmitter { 320 | options: ServerOptions; 321 | path: string; 322 | clients: Set; 323 | 324 | constructor(options?: ServerOptions, callback?: () => void); 325 | 326 | address(): AddressInfo | string; 327 | close(cb?: (err?: Error) => void): void; 328 | handleUpgrade( 329 | request: IncomingMessage, 330 | socket: Duplex, 331 | upgradeHead: Buffer, 332 | callback: (client: T, request: IncomingMessage) => void, 333 | ): void; 334 | shouldHandle(request: IncomingMessage): boolean | Promise; 335 | 336 | // Events 337 | on(event: "connection", cb: (this: Server, socket: T, request: IncomingMessage) => void): this; 338 | on(event: "error", cb: (this: Server, error: Error) => void): this; 339 | on(event: "headers", cb: (this: Server, headers: string[], request: IncomingMessage) => void): this; 340 | on(event: "close" | "listening", cb: (this: Server) => void): this; 341 | on(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this; 342 | 343 | once(event: "connection", cb: (this: Server, socket: T, request: IncomingMessage) => void): this; 344 | once(event: "error", cb: (this: Server, error: Error) => void): this; 345 | once(event: "headers", cb: (this: Server, headers: string[], request: IncomingMessage) => void): this; 346 | once(event: "close" | "listening", cb: (this: Server) => void): this; 347 | once(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this; 348 | 349 | off(event: "connection", cb: (this: Server, socket: T, request: IncomingMessage) => void): this; 350 | off(event: "error", cb: (this: Server, error: Error) => void): this; 351 | off(event: "headers", cb: (this: Server, headers: string[], request: IncomingMessage) => void): this; 352 | off(event: "close" | "listening", cb: (this: Server) => void): this; 353 | off(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this; 354 | 355 | addListener(event: "connection", cb: (client: T, request: IncomingMessage) => void): this; 356 | addListener(event: "error", cb: (err: Error) => void): this; 357 | addListener(event: "headers", cb: (headers: string[], request: IncomingMessage) => void): this; 358 | addListener(event: "close" | "listening", cb: () => void): this; 359 | addListener(event: string | symbol, listener: (...args: any[]) => void): this; 360 | 361 | removeListener(event: "connection", cb: (client: T) => void): this; 362 | removeListener(event: "error", cb: (err: Error) => void): this; 363 | removeListener(event: "headers", cb: (headers: string[], request: IncomingMessage) => void): this; 364 | removeListener(event: "close" | "listening", cb: () => void): this; 365 | removeListener(event: string | symbol, listener: (...args: any[]) => void): this; 366 | } 367 | 368 | const WebSocketServer: typeof Server; 369 | interface WebSocketServer extends Server {} // tslint:disable-line no-empty-interface 370 | const WebSocket: typeof WebSocketAlias; 371 | interface WebSocket extends WebSocketAlias {} // tslint:disable-line no-empty-interface 372 | 373 | // WebSocket stream 374 | function createWebSocketStream(websocket: WebSocket, options?: DuplexOptions): Duplex; 375 | } 376 | 377 | export = WebSocket; 378 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/commander/typings/index.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for commander 2 | // Original definitions by: Alan Agius , Marcelo Dezem , vvakame , Jules Randolph 3 | 4 | // Using method rather than property for method-signature-style, to document method overloads separately. Allow either. 5 | /* eslint-disable @typescript-eslint/method-signature-style */ 6 | /* eslint-disable @typescript-eslint/no-explicit-any */ 7 | 8 | export class CommanderError extends Error { 9 | code: string; 10 | exitCode: number; 11 | message: string; 12 | nestedError?: string; 13 | 14 | /** 15 | * Constructs the CommanderError class 16 | * @param exitCode - suggested exit code which could be used with process.exit 17 | * @param code - an id string representing the error 18 | * @param message - human-readable description of the error 19 | * @constructor 20 | */ 21 | constructor(exitCode: number, code: string, message: string); 22 | } 23 | 24 | export class InvalidArgumentError extends CommanderError { 25 | /** 26 | * Constructs the InvalidArgumentError class 27 | * @param message - explanation of why argument is invalid 28 | * @constructor 29 | */ 30 | constructor(message: string); 31 | } 32 | export { InvalidArgumentError as InvalidOptionArgumentError }; // deprecated old name 33 | 34 | export interface ErrorOptions { // optional parameter for error() 35 | /** an id string representing the error */ 36 | code?: string; 37 | /** suggested exit code which could be used with process.exit */ 38 | exitCode?: number; 39 | } 40 | 41 | export class Argument { 42 | description: string; 43 | required: boolean; 44 | variadic: boolean; 45 | 46 | /** 47 | * Initialize a new command argument with the given name and description. 48 | * The default is that the argument is required, and you can explicitly 49 | * indicate this with <> around the name. Put [] around the name for an optional argument. 50 | */ 51 | constructor(arg: string, description?: string); 52 | 53 | /** 54 | * Return argument name. 55 | */ 56 | name(): string; 57 | 58 | /** 59 | * Set the default value, and optionally supply the description to be displayed in the help. 60 | */ 61 | default(value: unknown, description?: string): this; 62 | 63 | /** 64 | * Set the custom handler for processing CLI command arguments into argument values. 65 | */ 66 | argParser(fn: (value: string, previous: T) => T): this; 67 | 68 | /** 69 | * Only allow argument value to be one of choices. 70 | */ 71 | choices(values: readonly string[]): this; 72 | 73 | /** 74 | * Make argument required. 75 | */ 76 | argRequired(): this; 77 | 78 | /** 79 | * Make argument optional. 80 | */ 81 | argOptional(): this; 82 | } 83 | 84 | export class Option { 85 | flags: string; 86 | description: string; 87 | 88 | required: boolean; // A value must be supplied when the option is specified. 89 | optional: boolean; // A value is optional when the option is specified. 90 | variadic: boolean; 91 | mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line. 92 | optionFlags: string; 93 | short?: string; 94 | long?: string; 95 | negate: boolean; 96 | defaultValue?: any; 97 | defaultValueDescription?: string; 98 | parseArg?: (value: string, previous: T) => T; 99 | hidden: boolean; 100 | argChoices?: string[]; 101 | 102 | constructor(flags: string, description?: string); 103 | 104 | /** 105 | * Set the default value, and optionally supply the description to be displayed in the help. 106 | */ 107 | default(value: unknown, description?: string): this; 108 | 109 | /** 110 | * Preset to use when option used without option-argument, especially optional but also boolean and negated. 111 | * The custom processing (parseArg) is called. 112 | * 113 | * @example 114 | * ```ts 115 | * new Option('--color').default('GREYSCALE').preset('RGB'); 116 | * new Option('--donate [amount]').preset('20').argParser(parseFloat); 117 | * ``` 118 | */ 119 | preset(arg: unknown): this; 120 | 121 | /** 122 | * Add option name(s) that conflict with this option. 123 | * An error will be displayed if conflicting options are found during parsing. 124 | * 125 | * @example 126 | * ```ts 127 | * new Option('--rgb').conflicts('cmyk'); 128 | * new Option('--js').conflicts(['ts', 'jsx']); 129 | * ``` 130 | */ 131 | conflicts(names: string | string[]): this; 132 | 133 | /** 134 | * Specify implied option values for when this option is set and the implied options are not. 135 | * 136 | * The custom processing (parseArg) is not called on the implied values. 137 | * 138 | * @example 139 | * program 140 | * .addOption(new Option('--log', 'write logging information to file')) 141 | * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' })); 142 | */ 143 | implies(optionValues: OptionValues): this; 144 | 145 | /** 146 | * Set environment variable to check for option value. 147 | * Priority order of option values is default < env < cli 148 | */ 149 | env(name: string): this; 150 | 151 | /** 152 | * Calculate the full description, including defaultValue etc. 153 | */ 154 | fullDescription(): string; 155 | 156 | /** 157 | * Set the custom handler for processing CLI option arguments into option values. 158 | */ 159 | argParser(fn: (value: string, previous: T) => T): this; 160 | 161 | /** 162 | * Whether the option is mandatory and must have a value after parsing. 163 | */ 164 | makeOptionMandatory(mandatory?: boolean): this; 165 | 166 | /** 167 | * Hide option in help. 168 | */ 169 | hideHelp(hide?: boolean): this; 170 | 171 | /** 172 | * Only allow option value to be one of choices. 173 | */ 174 | choices(values: readonly string[]): this; 175 | 176 | /** 177 | * Return option name. 178 | */ 179 | name(): string; 180 | 181 | /** 182 | * Return option name, in a camelcase format that can be used 183 | * as a object attribute key. 184 | */ 185 | attributeName(): string; 186 | 187 | /** 188 | * Return whether a boolean option. 189 | * 190 | * Options are one of boolean, negated, required argument, or optional argument. 191 | */ 192 | isBoolean(): boolean; 193 | } 194 | 195 | export class Help { 196 | /** output helpWidth, long lines are wrapped to fit */ 197 | helpWidth?: number; 198 | sortSubcommands: boolean; 199 | sortOptions: boolean; 200 | 201 | constructor(); 202 | 203 | /** Get the command term to show in the list of subcommands. */ 204 | subcommandTerm(cmd: Command): string; 205 | /** Get the command summary to show in the list of subcommands. */ 206 | subcommandDescription(cmd: Command): string; 207 | /** Get the option term to show in the list of options. */ 208 | optionTerm(option: Option): string; 209 | /** Get the option description to show in the list of options. */ 210 | optionDescription(option: Option): string; 211 | /** Get the argument term to show in the list of arguments. */ 212 | argumentTerm(argument: Argument): string; 213 | /** Get the argument description to show in the list of arguments. */ 214 | argumentDescription(argument: Argument): string; 215 | 216 | /** Get the command usage to be displayed at the top of the built-in help. */ 217 | commandUsage(cmd: Command): string; 218 | /** Get the description for the command. */ 219 | commandDescription(cmd: Command): string; 220 | 221 | /** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */ 222 | visibleCommands(cmd: Command): Command[]; 223 | /** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */ 224 | visibleOptions(cmd: Command): Option[]; 225 | /** Get an array of the arguments which have descriptions. */ 226 | visibleArguments(cmd: Command): Argument[]; 227 | 228 | /** Get the longest command term length. */ 229 | longestSubcommandTermLength(cmd: Command, helper: Help): number; 230 | /** Get the longest option term length. */ 231 | longestOptionTermLength(cmd: Command, helper: Help): number; 232 | /** Get the longest argument term length. */ 233 | longestArgumentTermLength(cmd: Command, helper: Help): number; 234 | /** Calculate the pad width from the maximum term length. */ 235 | padWidth(cmd: Command, helper: Help): number; 236 | 237 | /** 238 | * Wrap the given string to width characters per line, with lines after the first indented. 239 | * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted. 240 | */ 241 | wrap(str: string, width: number, indent: number, minColumnWidth?: number): string; 242 | 243 | /** Generate the built-in help text. */ 244 | formatHelp(cmd: Command, helper: Help): string; 245 | } 246 | export type HelpConfiguration = Partial; 247 | 248 | export interface ParseOptions { 249 | from: 'node' | 'electron' | 'user'; 250 | } 251 | export interface HelpContext { // optional parameter for .help() and .outputHelp() 252 | error: boolean; 253 | } 254 | export interface AddHelpTextContext { // passed to text function used with .addHelpText() 255 | error: boolean; 256 | command: Command; 257 | } 258 | export interface OutputConfiguration { 259 | writeOut?(str: string): void; 260 | writeErr?(str: string): void; 261 | getOutHelpWidth?(): number; 262 | getErrHelpWidth?(): number; 263 | outputError?(str: string, write: (str: string) => void): void; 264 | 265 | } 266 | 267 | export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll'; 268 | export type HookEvent = 'preSubcommand' | 'preAction' | 'postAction'; 269 | export type OptionValueSource = 'default' | 'env' | 'config' | 'cli'; 270 | 271 | export interface OptionValues { 272 | [key: string]: any; 273 | } 274 | 275 | export class Command { 276 | args: string[]; 277 | processedArgs: any[]; 278 | commands: Command[]; 279 | parent: Command | null; 280 | 281 | constructor(name?: string); 282 | 283 | /** 284 | * Set the program version to `str`. 285 | * 286 | * This method auto-registers the "-V, --version" flag 287 | * which will print the version number when passed. 288 | * 289 | * You can optionally supply the flags and description to override the defaults. 290 | */ 291 | version(str: string, flags?: string, description?: string): this; 292 | 293 | /** 294 | * Define a command, implemented using an action handler. 295 | * 296 | * @remarks 297 | * The command description is supplied using `.description`, not as a parameter to `.command`. 298 | * 299 | * @example 300 | * ```ts 301 | * program 302 | * .command('clone [destination]') 303 | * .description('clone a repository into a newly created directory') 304 | * .action((source, destination) => { 305 | * console.log('clone command called'); 306 | * }); 307 | * ``` 308 | * 309 | * @param nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` 310 | * @param opts - configuration options 311 | * @returns new command 312 | */ 313 | command(nameAndArgs: string, opts?: CommandOptions): ReturnType; 314 | /** 315 | * Define a command, implemented in a separate executable file. 316 | * 317 | * @remarks 318 | * The command description is supplied as the second parameter to `.command`. 319 | * 320 | * @example 321 | * ```ts 322 | * program 323 | * .command('start ', 'start named service') 324 | * .command('stop [service]', 'stop named service, or all if no name supplied'); 325 | * ``` 326 | * 327 | * @param nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` 328 | * @param description - description of executable command 329 | * @param opts - configuration options 330 | * @returns `this` command for chaining 331 | */ 332 | command(nameAndArgs: string, description: string, opts?: ExecutableCommandOptions): this; 333 | 334 | /** 335 | * Factory routine to create a new unattached command. 336 | * 337 | * See .command() for creating an attached subcommand, which uses this routine to 338 | * create the command. You can override createCommand to customise subcommands. 339 | */ 340 | createCommand(name?: string): Command; 341 | 342 | /** 343 | * Add a prepared subcommand. 344 | * 345 | * See .command() for creating an attached subcommand which inherits settings from its parent. 346 | * 347 | * @returns `this` command for chaining 348 | */ 349 | addCommand(cmd: Command, opts?: CommandOptions): this; 350 | 351 | /** 352 | * Factory routine to create a new unattached argument. 353 | * 354 | * See .argument() for creating an attached argument, which uses this routine to 355 | * create the argument. You can override createArgument to return a custom argument. 356 | */ 357 | createArgument(name: string, description?: string): Argument; 358 | 359 | /** 360 | * Define argument syntax for command. 361 | * 362 | * The default is that the argument is required, and you can explicitly 363 | * indicate this with <> around the name. Put [] around the name for an optional argument. 364 | * 365 | * @example 366 | * ``` 367 | * program.argument(''); 368 | * program.argument('[output-file]'); 369 | * ``` 370 | * 371 | * @returns `this` command for chaining 372 | */ 373 | argument(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this; 374 | argument(name: string, description?: string, defaultValue?: unknown): this; 375 | 376 | /** 377 | * Define argument syntax for command, adding a prepared argument. 378 | * 379 | * @returns `this` command for chaining 380 | */ 381 | addArgument(arg: Argument): this; 382 | 383 | /** 384 | * Define argument syntax for command, adding multiple at once (without descriptions). 385 | * 386 | * See also .argument(). 387 | * 388 | * @example 389 | * ``` 390 | * program.arguments(' [env]'); 391 | * ``` 392 | * 393 | * @returns `this` command for chaining 394 | */ 395 | arguments(names: string): this; 396 | 397 | /** 398 | * Override default decision whether to add implicit help command. 399 | * 400 | * @example 401 | * ``` 402 | * addHelpCommand() // force on 403 | * addHelpCommand(false); // force off 404 | * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details 405 | * ``` 406 | * 407 | * @returns `this` command for chaining 408 | */ 409 | addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this; 410 | 411 | /** 412 | * Add hook for life cycle event. 413 | */ 414 | hook(event: HookEvent, listener: (thisCommand: Command, actionCommand: Command) => void | Promise): this; 415 | 416 | /** 417 | * Register callback to use as replacement for calling process.exit. 418 | */ 419 | exitOverride(callback?: (err: CommanderError) => never | void): this; 420 | 421 | /** 422 | * Display error message and exit (or call exitOverride). 423 | */ 424 | error(message: string, errorOptions?: ErrorOptions): never; 425 | 426 | /** 427 | * You can customise the help with a subclass of Help by overriding createHelp, 428 | * or by overriding Help properties using configureHelp(). 429 | */ 430 | createHelp(): Help; 431 | 432 | /** 433 | * You can customise the help by overriding Help properties using configureHelp(), 434 | * or with a subclass of Help by overriding createHelp(). 435 | */ 436 | configureHelp(configuration: HelpConfiguration): this; 437 | /** Get configuration */ 438 | configureHelp(): HelpConfiguration; 439 | 440 | /** 441 | * The default output goes to stdout and stderr. You can customise this for special 442 | * applications. You can also customise the display of errors by overriding outputError. 443 | * 444 | * The configuration properties are all functions: 445 | * ``` 446 | * // functions to change where being written, stdout and stderr 447 | * writeOut(str) 448 | * writeErr(str) 449 | * // matching functions to specify width for wrapping help 450 | * getOutHelpWidth() 451 | * getErrHelpWidth() 452 | * // functions based on what is being written out 453 | * outputError(str, write) // used for displaying errors, and not used for displaying help 454 | * ``` 455 | */ 456 | configureOutput(configuration: OutputConfiguration): this; 457 | /** Get configuration */ 458 | configureOutput(): OutputConfiguration; 459 | 460 | /** 461 | * Copy settings that are useful to have in common across root command and subcommands. 462 | * 463 | * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.) 464 | */ 465 | copyInheritedSettings(sourceCommand: Command): this; 466 | 467 | /** 468 | * Display the help or a custom message after an error occurs. 469 | */ 470 | showHelpAfterError(displayHelp?: boolean | string): this; 471 | 472 | /** 473 | * Display suggestion of similar commands for unknown commands, or options for unknown options. 474 | */ 475 | showSuggestionAfterError(displaySuggestion?: boolean): this; 476 | 477 | /** 478 | * Register callback `fn` for the command. 479 | * 480 | * @example 481 | * ``` 482 | * program 483 | * .command('serve') 484 | * .description('start service') 485 | * .action(function() { 486 | * // do work here 487 | * }); 488 | * ``` 489 | * 490 | * @returns `this` command for chaining 491 | */ 492 | action(fn: (...args: any[]) => void | Promise): this; 493 | 494 | /** 495 | * Define option with `flags`, `description` and optional 496 | * coercion `fn`. 497 | * 498 | * The `flags` string contains the short and/or long flags, 499 | * separated by comma, a pipe or space. The following are all valid 500 | * all will output this way when `--help` is used. 501 | * 502 | * "-p, --pepper" 503 | * "-p|--pepper" 504 | * "-p --pepper" 505 | * 506 | * @example 507 | * ``` 508 | * // simple boolean defaulting to false 509 | * program.option('-p, --pepper', 'add pepper'); 510 | * 511 | * --pepper 512 | * program.pepper 513 | * // => Boolean 514 | * 515 | * // simple boolean defaulting to true 516 | * program.option('-C, --no-cheese', 'remove cheese'); 517 | * 518 | * program.cheese 519 | * // => true 520 | * 521 | * --no-cheese 522 | * program.cheese 523 | * // => false 524 | * 525 | * // required argument 526 | * program.option('-C, --chdir ', 'change the working directory'); 527 | * 528 | * --chdir /tmp 529 | * program.chdir 530 | * // => "/tmp" 531 | * 532 | * // optional argument 533 | * program.option('-c, --cheese [type]', 'add cheese [marble]'); 534 | * ``` 535 | * 536 | * @returns `this` command for chaining 537 | */ 538 | option(flags: string, description?: string, defaultValue?: string | boolean | string[]): this; 539 | option(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this; 540 | /** @deprecated since v7, instead use choices or a custom function */ 541 | option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this; 542 | 543 | /** 544 | * Define a required option, which must have a value after parsing. This usually means 545 | * the option must be specified on the command line. (Otherwise the same as .option().) 546 | * 547 | * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. 548 | */ 549 | requiredOption(flags: string, description?: string, defaultValue?: string | boolean | string[]): this; 550 | requiredOption(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this; 551 | /** @deprecated since v7, instead use choices or a custom function */ 552 | requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this; 553 | 554 | /** 555 | * Factory routine to create a new unattached option. 556 | * 557 | * See .option() for creating an attached option, which uses this routine to 558 | * create the option. You can override createOption to return a custom option. 559 | */ 560 | 561 | createOption(flags: string, description?: string): Option; 562 | 563 | /** 564 | * Add a prepared Option. 565 | * 566 | * See .option() and .requiredOption() for creating and attaching an option in a single call. 567 | */ 568 | addOption(option: Option): this; 569 | 570 | /** 571 | * Whether to store option values as properties on command object, 572 | * or store separately (specify false). In both cases the option values can be accessed using .opts(). 573 | * 574 | * @returns `this` command for chaining 575 | */ 576 | storeOptionsAsProperties(): this & T; 577 | storeOptionsAsProperties(storeAsProperties: true): this & T; 578 | storeOptionsAsProperties(storeAsProperties?: boolean): this; 579 | 580 | /** 581 | * Retrieve option value. 582 | */ 583 | getOptionValue(key: string): any; 584 | 585 | /** 586 | * Store option value. 587 | */ 588 | setOptionValue(key: string, value: unknown): this; 589 | 590 | /** 591 | * Store option value and where the value came from. 592 | */ 593 | setOptionValueWithSource(key: string, value: unknown, source: OptionValueSource): this; 594 | 595 | /** 596 | * Retrieve option value source. 597 | */ 598 | getOptionValueSource(key: string): OptionValueSource; 599 | 600 | /** 601 | * Alter parsing of short flags with optional values. 602 | * 603 | * @example 604 | * ``` 605 | * // for `.option('-f,--flag [value]'): 606 | * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour 607 | * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` 608 | * ``` 609 | * 610 | * @returns `this` command for chaining 611 | */ 612 | combineFlagAndOptionalValue(combine?: boolean): this; 613 | 614 | /** 615 | * Allow unknown options on the command line. 616 | * 617 | * @returns `this` command for chaining 618 | */ 619 | allowUnknownOption(allowUnknown?: boolean): this; 620 | 621 | /** 622 | * Allow excess command-arguments on the command line. Pass false to make excess arguments an error. 623 | * 624 | * @returns `this` command for chaining 625 | */ 626 | allowExcessArguments(allowExcess?: boolean): this; 627 | 628 | /** 629 | * Enable positional options. Positional means global options are specified before subcommands which lets 630 | * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions. 631 | * 632 | * The default behaviour is non-positional and global options may appear anywhere on the command line. 633 | * 634 | * @returns `this` command for chaining 635 | */ 636 | enablePositionalOptions(positional?: boolean): this; 637 | 638 | /** 639 | * Pass through options that come after command-arguments rather than treat them as command-options, 640 | * so actual command-options come before command-arguments. Turning this on for a subcommand requires 641 | * positional options to have been enabled on the program (parent commands). 642 | * 643 | * The default behaviour is non-positional and options may appear before or after command-arguments. 644 | * 645 | * @returns `this` command for chaining 646 | */ 647 | passThroughOptions(passThrough?: boolean): this; 648 | 649 | /** 650 | * Parse `argv`, setting options and invoking commands when defined. 651 | * 652 | * The default expectation is that the arguments are from node and have the application as argv[0] 653 | * and the script being run in argv[1], with user parameters after that. 654 | * 655 | * @example 656 | * ``` 657 | * program.parse(process.argv); 658 | * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions 659 | * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] 660 | * ``` 661 | * 662 | * @returns `this` command for chaining 663 | */ 664 | parse(argv?: readonly string[], options?: ParseOptions): this; 665 | 666 | /** 667 | * Parse `argv`, setting options and invoking commands when defined. 668 | * 669 | * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. 670 | * 671 | * The default expectation is that the arguments are from node and have the application as argv[0] 672 | * and the script being run in argv[1], with user parameters after that. 673 | * 674 | * @example 675 | * ``` 676 | * program.parseAsync(process.argv); 677 | * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions 678 | * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] 679 | * ``` 680 | * 681 | * @returns Promise 682 | */ 683 | parseAsync(argv?: readonly string[], options?: ParseOptions): Promise; 684 | 685 | /** 686 | * Parse options from `argv` removing known options, 687 | * and return argv split into operands and unknown arguments. 688 | * 689 | * argv => operands, unknown 690 | * --known kkk op => [op], [] 691 | * op --known kkk => [op], [] 692 | * sub --unknown uuu op => [sub], [--unknown uuu op] 693 | * sub -- --unknown uuu op => [sub --unknown uuu op], [] 694 | */ 695 | parseOptions(argv: string[]): ParseOptionsResult; 696 | 697 | /** 698 | * Return an object containing local option values as key-value pairs 699 | */ 700 | opts(): T; 701 | 702 | /** 703 | * Return an object containing merged local and global option values as key-value pairs. 704 | */ 705 | optsWithGlobals(): T; 706 | 707 | /** 708 | * Set the description. 709 | * 710 | * @returns `this` command for chaining 711 | */ 712 | 713 | description(str: string): this; 714 | /** @deprecated since v8, instead use .argument to add command argument with description */ 715 | description(str: string, argsDescription: {[argName: string]: string}): this; 716 | /** 717 | * Get the description. 718 | */ 719 | description(): string; 720 | 721 | /** 722 | * Set the summary. Used when listed as subcommand of parent. 723 | * 724 | * @returns `this` command for chaining 725 | */ 726 | 727 | summary(str: string): this; 728 | /** 729 | * Get the summary. 730 | */ 731 | summary(): string; 732 | 733 | /** 734 | * Set an alias for the command. 735 | * 736 | * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. 737 | * 738 | * @returns `this` command for chaining 739 | */ 740 | alias(alias: string): this; 741 | /** 742 | * Get alias for the command. 743 | */ 744 | alias(): string; 745 | 746 | /** 747 | * Set aliases for the command. 748 | * 749 | * Only the first alias is shown in the auto-generated help. 750 | * 751 | * @returns `this` command for chaining 752 | */ 753 | aliases(aliases: readonly string[]): this; 754 | /** 755 | * Get aliases for the command. 756 | */ 757 | aliases(): string[]; 758 | 759 | /** 760 | * Set the command usage. 761 | * 762 | * @returns `this` command for chaining 763 | */ 764 | usage(str: string): this; 765 | /** 766 | * Get the command usage. 767 | */ 768 | usage(): string; 769 | 770 | /** 771 | * Set the name of the command. 772 | * 773 | * @returns `this` command for chaining 774 | */ 775 | name(str: string): this; 776 | /** 777 | * Get the name of the command. 778 | */ 779 | name(): string; 780 | 781 | /** 782 | * Set the name of the command from script filename, such as process.argv[1], 783 | * or require.main.filename, or __filename. 784 | * 785 | * (Used internally and public although not documented in README.) 786 | * 787 | * @example 788 | * ```ts 789 | * program.nameFromFilename(require.main.filename); 790 | * ``` 791 | * 792 | * @returns `this` command for chaining 793 | */ 794 | nameFromFilename(filename: string): this; 795 | 796 | /** 797 | * Set the directory for searching for executable subcommands of this command. 798 | * 799 | * @example 800 | * ```ts 801 | * program.executableDir(__dirname); 802 | * // or 803 | * program.executableDir('subcommands'); 804 | * ``` 805 | * 806 | * @returns `this` command for chaining 807 | */ 808 | executableDir(path: string): this; 809 | /** 810 | * Get the executable search directory. 811 | */ 812 | executableDir(): string; 813 | 814 | /** 815 | * Output help information for this command. 816 | * 817 | * Outputs built-in help, and custom text added using `.addHelpText()`. 818 | * 819 | */ 820 | outputHelp(context?: HelpContext): void; 821 | /** @deprecated since v7 */ 822 | outputHelp(cb?: (str: string) => string): void; 823 | 824 | /** 825 | * Return command help documentation. 826 | */ 827 | helpInformation(context?: HelpContext): string; 828 | 829 | /** 830 | * You can pass in flags and a description to override the help 831 | * flags and help description for your command. Pass in false 832 | * to disable the built-in help option. 833 | */ 834 | helpOption(flags?: string | boolean, description?: string): this; 835 | 836 | /** 837 | * Output help information and exit. 838 | * 839 | * Outputs built-in help, and custom text added using `.addHelpText()`. 840 | */ 841 | help(context?: HelpContext): never; 842 | /** @deprecated since v7 */ 843 | help(cb?: (str: string) => string): never; 844 | 845 | /** 846 | * Add additional text to be displayed with the built-in help. 847 | * 848 | * Position is 'before' or 'after' to affect just this command, 849 | * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands. 850 | */ 851 | addHelpText(position: AddHelpTextPosition, text: string): this; 852 | addHelpText(position: AddHelpTextPosition, text: (context: AddHelpTextContext) => string): this; 853 | 854 | /** 855 | * Add a listener (callback) for when events occur. (Implemented using EventEmitter.) 856 | */ 857 | on(event: string | symbol, listener: (...args: any[]) => void): this; 858 | } 859 | 860 | export interface CommandOptions { 861 | hidden?: boolean; 862 | isDefault?: boolean; 863 | /** @deprecated since v7, replaced by hidden */ 864 | noHelp?: boolean; 865 | } 866 | export interface ExecutableCommandOptions extends CommandOptions { 867 | executableFile?: string; 868 | } 869 | 870 | export interface ParseOptionsResult { 871 | operands: string[]; 872 | unknown: string[]; 873 | } 874 | 875 | export function createCommand(name?: string): Command; 876 | export function createOption(flags: string, description?: string): Option; 877 | export function createArgument(name: string, description?: string): Argument; 878 | 879 | export const program: Command; 880 | -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/commander/index.js: -------------------------------------------------------------------------------- 1 | (function(){var t={81:function(t){"use strict";t.exports=require("child_process")},361:function(t){"use strict";t.exports=require("events")},147:function(t){"use strict";t.exports=require("fs")},17:function(t){"use strict";t.exports=require("path")},282:function(t){"use strict";t.exports=require("process")},978:function(t,e,i){const{Argument:n}=i(840);const{Command:s}=i(423);const{CommanderError:r,InvalidArgumentError:o}=i(234);const{Help:a}=i(627);const{Option:h}=i(277);e=t.exports=new s;e.program=e;e.Argument=n;e.Command=s;e.CommanderError=r;e.Help=a;e.InvalidArgumentError=o;e.InvalidOptionArgumentError=o;e.Option=h},840:function(t,e,i){const{InvalidArgumentError:n}=i(234);class Argument{constructor(t,e){this.description=e||"";this.variadic=false;this.parseArg=undefined;this.defaultValue=undefined;this.defaultValueDescription=undefined;this.argChoices=undefined;switch(t[0]){case"<":this.required=true;this._name=t.slice(1,-1);break;case"[":this.required=false;this._name=t.slice(1,-1);break;default:this.required=true;this._name=t;break}if(this._name.length>3&&this._name.slice(-3)==="..."){this.variadic=true;this._name=this._name.slice(0,-3)}}name(){return this._name}_concatValue(t,e){if(e===this.defaultValue||!Array.isArray(e)){return[t]}return e.concat(t)}default(t,e){this.defaultValue=t;this.defaultValueDescription=e;return this}argParser(t){this.parseArg=t;return this}choices(t){this.argChoices=t.slice();this.parseArg=(t,e)=>{if(!this.argChoices.includes(t)){throw new n(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(t,e)}return t};return this}argRequired(){this.required=true;return this}argOptional(){this.required=false;return this}}function humanReadableArgName(t){const e=t.name()+(t.variadic===true?"...":"");return t.required?"<"+e+">":"["+e+"]"}e.Argument=Argument;e.humanReadableArgName=humanReadableArgName},423:function(t,e,i){const n=i(361).EventEmitter;const s=i(81);const r=i(17);const o=i(147);const a=i(282);const{Argument:h,humanReadableArgName:l}=i(840);const{CommanderError:u}=i(234);const{Help:c}=i(627);const{Option:p,splitOptionFlags:m,DualOptions:d}=i(277);const{suggestSimilar:f}=i(176);class Command extends n{constructor(t){super();this.commands=[];this.options=[];this.parent=null;this._allowUnknownOption=false;this._allowExcessArguments=true;this._args=[];this.args=[];this.rawArgs=[];this.processedArgs=[];this._scriptPath=null;this._name=t||"";this._optionValues={};this._optionValueSources={};this._storeOptionsAsProperties=false;this._actionHandler=null;this._executableHandler=false;this._executableFile=null;this._executableDir=null;this._defaultCommandName=null;this._exitCallback=null;this._aliases=[];this._combineFlagAndOptionalValue=true;this._description="";this._summary="";this._argsDescription=undefined;this._enablePositionalOptions=false;this._passThroughOptions=false;this._lifeCycleHooks={};this._showHelpAfterError=false;this._showSuggestionAfterError=true;this._outputConfiguration={writeOut:t=>a.stdout.write(t),writeErr:t=>a.stderr.write(t),getOutHelpWidth:()=>a.stdout.isTTY?a.stdout.columns:undefined,getErrHelpWidth:()=>a.stderr.isTTY?a.stderr.columns:undefined,outputError:(t,e)=>e(t)};this._hidden=false;this._hasHelpOption=true;this._helpFlags="-h, --help";this._helpDescription="display help for command";this._helpShortFlag="-h";this._helpLongFlag="--help";this._addImplicitHelpCommand=undefined;this._helpCommandName="help";this._helpCommandnameAndArgs="help [command]";this._helpCommandDescription="display help for command";this._helpConfiguration={}}copyInheritedSettings(t){this._outputConfiguration=t._outputConfiguration;this._hasHelpOption=t._hasHelpOption;this._helpFlags=t._helpFlags;this._helpDescription=t._helpDescription;this._helpShortFlag=t._helpShortFlag;this._helpLongFlag=t._helpLongFlag;this._helpCommandName=t._helpCommandName;this._helpCommandnameAndArgs=t._helpCommandnameAndArgs;this._helpCommandDescription=t._helpCommandDescription;this._helpConfiguration=t._helpConfiguration;this._exitCallback=t._exitCallback;this._storeOptionsAsProperties=t._storeOptionsAsProperties;this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue;this._allowExcessArguments=t._allowExcessArguments;this._enablePositionalOptions=t._enablePositionalOptions;this._showHelpAfterError=t._showHelpAfterError;this._showSuggestionAfterError=t._showSuggestionAfterError;return this}command(t,e,i){let n=e;let s=i;if(typeof n==="object"&&n!==null){s=n;n=null}s=s||{};const[,r,o]=t.match(/([^ ]+) *(.*)/);const a=this.createCommand(r);if(n){a.description(n);a._executableHandler=true}if(s.isDefault)this._defaultCommandName=a._name;a._hidden=!!(s.noHelp||s.hidden);a._executableFile=s.executableFile||null;if(o)a.arguments(o);this.commands.push(a);a.parent=this;a.copyInheritedSettings(this);if(n)return this;return a}createCommand(t){return new Command(t)}createHelp(){return Object.assign(new c,this.configureHelp())}configureHelp(t){if(t===undefined)return this._helpConfiguration;this._helpConfiguration=t;return this}configureOutput(t){if(t===undefined)return this._outputConfiguration;Object.assign(this._outputConfiguration,t);return this}showHelpAfterError(t=true){if(typeof t!=="string")t=!!t;this._showHelpAfterError=t;return this}showSuggestionAfterError(t=true){this._showSuggestionAfterError=!!t;return this}addCommand(t,e){if(!t._name){throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`)}e=e||{};if(e.isDefault)this._defaultCommandName=t._name;if(e.noHelp||e.hidden)t._hidden=true;this.commands.push(t);t.parent=this;return this}createArgument(t,e){return new h(t,e)}argument(t,e,i,n){const s=this.createArgument(t,e);if(typeof i==="function"){s.default(n).argParser(i)}else{s.default(i)}this.addArgument(s);return this}arguments(t){t.split(/ +/).forEach((t=>{this.argument(t)}));return this}addArgument(t){const e=this._args.slice(-1)[0];if(e&&e.variadic){throw new Error(`only the last argument can be variadic '${e.name()}'`)}if(t.required&&t.defaultValue!==undefined&&t.parseArg===undefined){throw new Error(`a default value for a required argument is never used: '${t.name()}'`)}this._args.push(t);return this}addHelpCommand(t,e){if(t===false){this._addImplicitHelpCommand=false}else{this._addImplicitHelpCommand=true;if(typeof t==="string"){this._helpCommandName=t.split(" ")[0];this._helpCommandnameAndArgs=t}this._helpCommandDescription=e||this._helpCommandDescription}return this}_hasImplicitHelpCommand(){if(this._addImplicitHelpCommand===undefined){return this.commands.length&&!this._actionHandler&&!this._findCommand("help")}return this._addImplicitHelpCommand}hook(t,e){const i=["preSubcommand","preAction","postAction"];if(!i.includes(t)){throw new Error(`Unexpected value for event passed to hook : '${t}'.\nExpecting one of '${i.join("', '")}'`)}if(this._lifeCycleHooks[t]){this._lifeCycleHooks[t].push(e)}else{this._lifeCycleHooks[t]=[e]}return this}exitOverride(t){if(t){this._exitCallback=t}else{this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync"){throw t}else{}}}return this}_exit(t,e,i){if(this._exitCallback){this._exitCallback(new u(t,e,i))}a.exit(t)}action(t){const listener=e=>{const i=this._args.length;const n=e.slice(0,i);if(this._storeOptionsAsProperties){n[i]=this}else{n[i]=this.opts()}n.push(this);return t.apply(this,n)};this._actionHandler=listener;return this}createOption(t,e){return new p(t,e)}addOption(t){const e=t.name();const i=t.attributeName();if(t.negate){const e=t.long.replace(/^--no-/,"--");if(!this._findOption(e)){this.setOptionValueWithSource(i,t.defaultValue===undefined?true:t.defaultValue,"default")}}else if(t.defaultValue!==undefined){this.setOptionValueWithSource(i,t.defaultValue,"default")}this.options.push(t);const handleOptionValue=(e,n,s)=>{if(e==null&&t.presetArg!==undefined){e=t.presetArg}const r=this.getOptionValue(i);if(e!==null&&t.parseArg){try{e=t.parseArg(e,r)}catch(t){if(t.code==="commander.invalidArgument"){const e=`${n} ${t.message}`;this.error(e,{exitCode:t.exitCode,code:t.code})}throw t}}else if(e!==null&&t.variadic){e=t._concatValue(e,r)}if(e==null){if(t.negate){e=false}else if(t.isBoolean()||t.optional){e=true}else{e=""}}this.setOptionValueWithSource(i,e,s)};this.on("option:"+e,(e=>{const i=`error: option '${t.flags}' argument '${e}' is invalid.`;handleOptionValue(e,i,"cli")}));if(t.envVar){this.on("optionEnv:"+e,(e=>{const i=`error: option '${t.flags}' value '${e}' from env '${t.envVar}' is invalid.`;handleOptionValue(e,i,"env")}))}return this}_optionEx(t,e,i,n,s){if(typeof e==="object"&&e instanceof p){throw new Error("To add an Option object use addOption() instead of option() or requiredOption()")}const r=this.createOption(e,i);r.makeOptionMandatory(!!t.mandatory);if(typeof n==="function"){r.default(s).argParser(n)}else if(n instanceof RegExp){const t=n;n=(e,i)=>{const n=t.exec(e);return n?n[0]:i};r.default(s).argParser(n)}else{r.default(n)}return this.addOption(r)}option(t,e,i,n){return this._optionEx({},t,e,i,n)}requiredOption(t,e,i,n){return this._optionEx({mandatory:true},t,e,i,n)}combineFlagAndOptionalValue(t=true){this._combineFlagAndOptionalValue=!!t;return this}allowUnknownOption(t=true){this._allowUnknownOption=!!t;return this}allowExcessArguments(t=true){this._allowExcessArguments=!!t;return this}enablePositionalOptions(t=true){this._enablePositionalOptions=!!t;return this}passThroughOptions(t=true){this._passThroughOptions=!!t;if(!!this.parent&&t&&!this.parent._enablePositionalOptions){throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)")}return this}storeOptionsAsProperties(t=true){this._storeOptionsAsProperties=!!t;if(this.options.length){throw new Error("call .storeOptionsAsProperties() before adding options")}return this}getOptionValue(t){if(this._storeOptionsAsProperties){return this[t]}return this._optionValues[t]}setOptionValue(t,e){if(this._storeOptionsAsProperties){this[t]=e}else{this._optionValues[t]=e}return this}setOptionValueWithSource(t,e,i){this.setOptionValue(t,e);this._optionValueSources[t]=i;return this}getOptionValueSource(t){return this._optionValueSources[t]}_prepareUserArgs(t,e){if(t!==undefined&&!Array.isArray(t)){throw new Error("first parameter to parse must be array or undefined")}e=e||{};if(t===undefined){t=a.argv;if(a.versions&&a.versions.electron){e.from="electron"}}this.rawArgs=t.slice();let i;switch(e.from){case undefined:case"node":this._scriptPath=t[1];i=t.slice(2);break;case"electron":if(a.defaultApp){this._scriptPath=t[1];i=t.slice(2)}else{i=t.slice(1)}break;case"user":i=t.slice(0);break;default:throw new Error(`unexpected parse option { from: '${e.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);this._name=this._name||"program";return i}parse(t,e){const i=this._prepareUserArgs(t,e);this._parseCommand([],i);return this}async parseAsync(t,e){const i=this._prepareUserArgs(t,e);await this._parseCommand([],i);return this}_executeSubCommand(t,e){e=e.slice();let i=false;const n=[".js",".ts",".tsx",".mjs",".cjs"];function findFile(t,e){const i=r.resolve(t,e);if(o.existsSync(i))return i;if(n.includes(r.extname(e)))return undefined;const s=n.find((t=>o.existsSync(`${i}${t}`)));if(s)return`${i}${s}`;return undefined}this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();let h=t._executableFile||`${this._name}-${t._name}`;let l=this._executableDir||"";if(this._scriptPath){let t;try{t=o.realpathSync(this._scriptPath)}catch(e){t=this._scriptPath}l=r.resolve(r.dirname(t),l)}if(l){let e=findFile(l,h);if(!e&&!t._executableFile&&this._scriptPath){const i=r.basename(this._scriptPath,r.extname(this._scriptPath));if(i!==this._name){e=findFile(l,`${i}-${t._name}`)}}h=e||h}i=n.includes(r.extname(h));let c;if(a.platform!=="win32"){if(i){e.unshift(h);e=incrementNodeInspectorPort(a.execArgv).concat(e);c=s.spawn(a.argv[0],e,{stdio:"inherit"})}else{c=s.spawn(h,e,{stdio:"inherit"})}}else{e.unshift(h);e=incrementNodeInspectorPort(a.execArgv).concat(e);c=s.spawn(a.execPath,e,{stdio:"inherit"})}if(!c.killed){const t=["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"];t.forEach((t=>{a.on(t,(()=>{if(c.killed===false&&c.exitCode===null){c.kill(t)}}))}))}const p=this._exitCallback;if(!p){c.on("close",a.exit.bind(a))}else{c.on("close",(()=>{p(new u(a.exitCode||0,"commander.executeSubCommandAsync","(close)"))}))}c.on("error",(e=>{if(e.code==="ENOENT"){const e=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory";const i=`'${h}' does not exist\n - if '${t._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${e}`;throw new Error(i)}else if(e.code==="EACCES"){throw new Error(`'${h}' not executable`)}if(!p){a.exit(1)}else{const t=new u(1,"commander.executeSubCommandAsync","(error)");t.nestedError=e;p(t)}}));this.runningCommand=c}_dispatchSubcommand(t,e,i){const n=this._findCommand(t);if(!n)this.help({error:true});let s;s=this._chainOrCallSubCommandHook(s,n,"preSubcommand");s=this._chainOrCall(s,(()=>{if(n._executableHandler){this._executeSubCommand(n,e.concat(i))}else{return n._parseCommand(e,i)}}));return s}_checkNumberOfArguments(){this._args.forEach(((t,e)=>{if(t.required&&this.args[e]==null){this.missingArgument(t.name())}}));if(this._args.length>0&&this._args[this._args.length-1].variadic){return}if(this.args.length>this._args.length){this._excessArguments(this.args)}}_processArguments(){const myParseArg=(t,e,i)=>{let n=e;if(e!==null&&t.parseArg){try{n=t.parseArg(e,i)}catch(i){if(i.code==="commander.invalidArgument"){const n=`error: command-argument value '${e}' is invalid for argument '${t.name()}'. ${i.message}`;this.error(n,{exitCode:i.exitCode,code:i.code})}throw i}}return n};this._checkNumberOfArguments();const t=[];this._args.forEach(((e,i)=>{let n=e.defaultValue;if(e.variadic){if(imyParseArg(e,i,t)),e.defaultValue)}}else if(n===undefined){n=[]}}else if(ie()))}return e()}_chainOrCallHooks(t,e){let i=t;const n=[];getCommandAndParents(this).reverse().filter((t=>t._lifeCycleHooks[e]!==undefined)).forEach((t=>{t._lifeCycleHooks[e].forEach((e=>{n.push({hookedCommand:t,callback:e})}))}));if(e==="postAction"){n.reverse()}n.forEach((t=>{i=this._chainOrCall(i,(()=>t.callback(t.hookedCommand,this)))}));return i}_chainOrCallSubCommandHook(t,e,i){let n=t;if(this._lifeCycleHooks[i]!==undefined){this._lifeCycleHooks[i].forEach((t=>{n=this._chainOrCall(n,(()=>t(this,e)))}))}return n}_parseCommand(t,e){const i=this.parseOptions(e);this._parseOptionsEnv();this._parseOptionsImplied();t=t.concat(i.operands);e=i.unknown;this.args=t.concat(e);if(t&&this._findCommand(t[0])){return this._dispatchSubcommand(t[0],t.slice(1),e)}if(this._hasImplicitHelpCommand()&&t[0]===this._helpCommandName){if(t.length===1){this.help()}return this._dispatchSubcommand(t[1],[],[this._helpLongFlag])}if(this._defaultCommandName){outputHelpIfRequested(this,e);return this._dispatchSubcommand(this._defaultCommandName,t,e)}if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName){this.help({error:true})}outputHelpIfRequested(this,i.unknown);this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();const checkForUnknownOptions=()=>{if(i.unknown.length>0){this.unknownOption(i.unknown[0])}};const n=`command:${this.name()}`;if(this._actionHandler){checkForUnknownOptions();this._processArguments();let i;i=this._chainOrCallHooks(i,"preAction");i=this._chainOrCall(i,(()=>this._actionHandler(this.processedArgs)));if(this.parent){i=this._chainOrCall(i,(()=>{this.parent.emit(n,t,e)}))}i=this._chainOrCallHooks(i,"postAction");return i}if(this.parent&&this.parent.listenerCount(n)){checkForUnknownOptions();this._processArguments();this.parent.emit(n,t,e)}else if(t.length){if(this._findCommand("*")){return this._dispatchSubcommand("*",t,e)}if(this.listenerCount("command:*")){this.emit("command:*",t,e)}else if(this.commands.length){this.unknownCommand()}else{checkForUnknownOptions();this._processArguments()}}else if(this.commands.length){checkForUnknownOptions();this.help({error:true})}else{checkForUnknownOptions();this._processArguments()}}_findCommand(t){if(!t)return undefined;return this.commands.find((e=>e._name===t||e._aliases.includes(t)))}_findOption(t){return this.options.find((e=>e.is(t)))}_checkForMissingMandatoryOptions(){for(let t=this;t;t=t.parent){t.options.forEach((e=>{if(e.mandatory&&t.getOptionValue(e.attributeName())===undefined){t.missingMandatoryOptionValue(e)}}))}}_checkForConflictingLocalOptions(){const t=this.options.filter((t=>{const e=t.attributeName();if(this.getOptionValue(e)===undefined){return false}return this.getOptionValueSource(e)!=="default"}));const e=t.filter((t=>t.conflictsWith.length>0));e.forEach((e=>{const i=t.find((t=>e.conflictsWith.includes(t.attributeName())));if(i){this._conflictingOption(e,i)}}))}_checkForConflictingOptions(){for(let t=this;t;t=t.parent){t._checkForConflictingLocalOptions()}}parseOptions(t){const e=[];const i=[];let n=e;const s=t.slice();function maybeOption(t){return t.length>1&&t[0]==="-"}let r=null;while(s.length){const t=s.shift();if(t==="--"){if(n===i)n.push(t);n.push(...s);break}if(r&&!maybeOption(t)){this.emit(`option:${r.name()}`,t);continue}r=null;if(maybeOption(t)){const e=this._findOption(t);if(e){if(e.required){const t=s.shift();if(t===undefined)this.optionMissingArgument(e);this.emit(`option:${e.name()}`,t)}else if(e.optional){let t=null;if(s.length>0&&!maybeOption(s[0])){t=s.shift()}this.emit(`option:${e.name()}`,t)}else{this.emit(`option:${e.name()}`)}r=e.variadic?e:null;continue}}if(t.length>2&&t[0]==="-"&&t[1]!=="-"){const e=this._findOption(`-${t[1]}`);if(e){if(e.required||e.optional&&this._combineFlagAndOptionalValue){this.emit(`option:${e.name()}`,t.slice(2))}else{this.emit(`option:${e.name()}`);s.unshift(`-${t.slice(2)}`)}continue}}if(/^--[^=]+=/.test(t)){const e=t.indexOf("=");const i=this._findOption(t.slice(0,e));if(i&&(i.required||i.optional)){this.emit(`option:${i.name()}`,t.slice(e+1));continue}}if(maybeOption(t)){n=i}if((this._enablePositionalOptions||this._passThroughOptions)&&e.length===0&&i.length===0){if(this._findCommand(t)){e.push(t);if(s.length>0)i.push(...s);break}else if(t===this._helpCommandName&&this._hasImplicitHelpCommand()){e.push(t);if(s.length>0)e.push(...s);break}else if(this._defaultCommandName){i.push(t);if(s.length>0)i.push(...s);break}}if(this._passThroughOptions){n.push(t);if(s.length>0)n.push(...s);break}n.push(t)}return{operands:e,unknown:i}}opts(){if(this._storeOptionsAsProperties){const t={};const e=this.options.length;for(let i=0;iObject.assign(t,e.opts())),{})}error(t,e){this._outputConfiguration.outputError(`${t}\n`,this._outputConfiguration.writeErr);if(typeof this._showHelpAfterError==="string"){this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`)}else if(this._showHelpAfterError){this._outputConfiguration.writeErr("\n");this.outputHelp({error:true})}const i=e||{};const n=i.exitCode||1;const s=i.code||"commander.error";this._exit(n,s,t)}_parseOptionsEnv(){this.options.forEach((t=>{if(t.envVar&&t.envVar in a.env){const e=t.attributeName();if(this.getOptionValue(e)===undefined||["default","config","env"].includes(this.getOptionValueSource(e))){if(t.required||t.optional){this.emit(`optionEnv:${t.name()}`,a.env[t.envVar])}else{this.emit(`optionEnv:${t.name()}`)}}}}))}_parseOptionsImplied(){const t=new d(this.options);const hasCustomOptionValue=t=>this.getOptionValue(t)!==undefined&&!["default","implied"].includes(this.getOptionValueSource(t));this.options.filter((e=>e.implied!==undefined&&hasCustomOptionValue(e.attributeName())&&t.valueFromOption(this.getOptionValue(e.attributeName()),e))).forEach((t=>{Object.keys(t.implied).filter((t=>!hasCustomOptionValue(t))).forEach((e=>{this.setOptionValueWithSource(e,t.implied[e],"implied")}))}))}missingArgument(t){const e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){const e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){const e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){const findBestOptionFromValue=t=>{const e=t.attributeName();const i=this.getOptionValue(e);const n=this.options.find((t=>t.negate&&e===t.attributeName()));const s=this.options.find((t=>!t.negate&&e===t.attributeName()));if(n&&(n.presetArg===undefined&&i===false||n.presetArg!==undefined&&i===n.presetArg)){return n}return s||t};const getErrorMessage=t=>{const e=findBestOptionFromValue(t);const i=e.attributeName();const n=this.getOptionValueSource(i);if(n==="env"){return`environment variable '${e.envVar}'`}return`option '${e.flags}'`};const i=`error: ${getErrorMessage(t)} cannot be used with ${getErrorMessage(e)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let i=[];let n=this;do{const t=n.createHelp().visibleOptions(n).filter((t=>t.long)).map((t=>t.long));i=i.concat(t);n=n.parent}while(n&&!n._enablePositionalOptions);e=f(t,i)}const i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;const e=this._args.length;const i=e===1?"":"s";const n=this.parent?` for '${this.name()}'`:"";const s=`error: too many arguments${n}. Expected ${e} argument${i} but got ${t.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){const t=this.args[0];let e="";if(this._showSuggestionAfterError){const i=[];this.createHelp().visibleCommands(this).forEach((t=>{i.push(t.name());if(t.alias())i.push(t.alias())}));e=f(t,i)}const i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"})}version(t,e,i){if(t===undefined)return this._version;this._version=t;e=e||"-V, --version";i=i||"output the version number";const n=this.createOption(e,i);this._versionOptionName=n.attributeName();this.options.push(n);this.on("option:"+n.name(),(()=>{this._outputConfiguration.writeOut(`${t}\n`);this._exit(0,"commander.version",t)}));return this}description(t,e){if(t===undefined&&e===undefined)return this._description;this._description=t;if(e){this._argsDescription=e}return this}summary(t){if(t===undefined)return this._summary;this._summary=t;return this}alias(t){if(t===undefined)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler){e=this.commands[this.commands.length-1]}if(t===e._name)throw new Error("Command alias can't be the same as its name");e._aliases.push(t);return this}aliases(t){if(t===undefined)return this._aliases;t.forEach((t=>this.alias(t)));return this}usage(t){if(t===undefined){if(this._usage)return this._usage;const t=this._args.map((t=>l(t)));return[].concat(this.options.length||this._hasHelpOption?"[options]":[],this.commands.length?"[command]":[],this._args.length?t:[]).join(" ")}this._usage=t;return this}name(t){if(t===undefined)return this._name;this._name=t;return this}nameFromFilename(t){this._name=r.basename(t,r.extname(t));return this}executableDir(t){if(t===undefined)return this._executableDir;this._executableDir=t;return this}helpInformation(t){const e=this.createHelp();if(e.helpWidth===undefined){e.helpWidth=t&&t.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()}return e.formatHelp(this,e)}_getHelpContext(t){t=t||{};const e={error:!!t.error};let i;if(e.error){i=t=>this._outputConfiguration.writeErr(t)}else{i=t=>this._outputConfiguration.writeOut(t)}e.write=t.write||i;e.command=this;return e}outputHelp(t){let e;if(typeof t==="function"){e=t;t=undefined}const i=this._getHelpContext(t);getCommandAndParents(this).reverse().forEach((t=>t.emit("beforeAllHelp",i)));this.emit("beforeHelp",i);let n=this.helpInformation(i);if(e){n=e(n);if(typeof n!=="string"&&!Buffer.isBuffer(n)){throw new Error("outputHelp callback must return a string or a Buffer")}}i.write(n);this.emit(this._helpLongFlag);this.emit("afterHelp",i);getCommandAndParents(this).forEach((t=>t.emit("afterAllHelp",i)))}helpOption(t,e){if(typeof t==="boolean"){this._hasHelpOption=t;return this}this._helpFlags=t||this._helpFlags;this._helpDescription=e||this._helpDescription;const i=m(this._helpFlags);this._helpShortFlag=i.shortFlag;this._helpLongFlag=i.longFlag;return this}help(t){this.outputHelp(t);let e=a.exitCode||0;if(e===0&&t&&typeof t!=="function"&&t.error){e=1}this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){const i=["beforeAll","before","after","afterAll"];if(!i.includes(t)){throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${i.join("', '")}'`)}const n=`${t}Help`;this.on(n,(t=>{let i;if(typeof e==="function"){i=e({error:t.error,command:t.command})}else{i=e}if(i){t.write(`${i}\n`)}}));return this}}function outputHelpIfRequested(t,e){const i=t._hasHelpOption&&e.find((e=>e===t._helpLongFlag||e===t._helpShortFlag));if(i){t.outputHelp();t._exit(0,"commander.helpDisplayed","(outputHelp)")}}function incrementNodeInspectorPort(t){return t.map((t=>{if(!t.startsWith("--inspect")){return t}let e;let i="127.0.0.1";let n="9229";let s;if((s=t.match(/^(--inspect(-brk)?)$/))!==null){e=s[1]}else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null){e=s[1];if(/^\d+$/.test(s[3])){n=s[3]}else{i=s[3]}}else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null){e=s[1];i=s[3];n=s[4]}if(e&&n!=="0"){return`${e}=${i}:${parseInt(n)+1}`}return t}))}function getCommandAndParents(t){const e=[];for(let i=t;i;i=i.parent){e.push(i)}return e}e.Command=Command},234:function(t,e){class CommanderError extends Error{constructor(t,e,i){super(i);Error.captureStackTrace(this,this.constructor);this.name=this.constructor.name;this.code=e;this.exitCode=t;this.nestedError=undefined}}class InvalidArgumentError extends CommanderError{constructor(t){super(1,"commander.invalidArgument",t);Error.captureStackTrace(this,this.constructor);this.name=this.constructor.name}}e.CommanderError=CommanderError;e.InvalidArgumentError=InvalidArgumentError},627:function(t,e,i){const{humanReadableArgName:n}=i(840);class Help{constructor(){this.helpWidth=undefined;this.sortSubcommands=false;this.sortOptions=false}visibleCommands(t){const e=t.commands.filter((t=>!t._hidden));if(t._hasImplicitHelpCommand()){const[,i,n]=t._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);const s=t.createCommand(i).helpOption(false);s.description(t._helpCommandDescription);if(n)s.arguments(n);e.push(s)}if(this.sortSubcommands){e.sort(((t,e)=>t.name().localeCompare(e.name())))}return e}visibleOptions(t){const e=t.options.filter((t=>!t.hidden));const i=t._hasHelpOption&&t._helpShortFlag&&!t._findOption(t._helpShortFlag);const n=t._hasHelpOption&&!t._findOption(t._helpLongFlag);if(i||n){let s;if(!i){s=t.createOption(t._helpLongFlag,t._helpDescription)}else if(!n){s=t.createOption(t._helpShortFlag,t._helpDescription)}else{s=t.createOption(t._helpFlags,t._helpDescription)}e.push(s)}if(this.sortOptions){const getSortKey=t=>t.short?t.short.replace(/^-/,""):t.long.replace(/^--/,"");e.sort(((t,e)=>getSortKey(t).localeCompare(getSortKey(e))))}return e}visibleArguments(t){if(t._argsDescription){t._args.forEach((e=>{e.description=e.description||t._argsDescription[e.name()]||""}))}if(t._args.find((t=>t.description))){return t._args}return[]}subcommandTerm(t){const e=t._args.map((t=>n(t))).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce(((t,i)=>Math.max(t,e.subcommandTerm(i).length)),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce(((t,i)=>Math.max(t,e.optionTerm(i).length)),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce(((t,i)=>Math.max(t,e.argumentTerm(i).length)),0)}commandUsage(t){let e=t._name;if(t._aliases[0]){e=e+"|"+t._aliases[0]}let i="";for(let e=t.parent;e;e=e.parent){i=e.name()+" "+i}return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){const e=[];if(t.argChoices){e.push(`choices: ${t.argChoices.map((t=>JSON.stringify(t))).join(", ")}`)}if(t.defaultValue!==undefined){const i=t.required||t.optional||t.isBoolean()&&typeof t.defaultValue==="boolean";if(i){e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`)}}if(t.presetArg!==undefined&&t.optional){e.push(`preset: ${JSON.stringify(t.presetArg)}`)}if(t.envVar!==undefined){e.push(`env: ${t.envVar}`)}if(e.length>0){return`${t.description} (${e.join(", ")})`}return t.description}argumentDescription(t){const e=[];if(t.argChoices){e.push(`choices: ${t.argChoices.map((t=>JSON.stringify(t))).join(", ")}`)}if(t.defaultValue!==undefined){e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`)}if(e.length>0){const i=`(${e.join(", ")})`;if(t.description){return`${t.description} ${i}`}return i}return t.description}formatHelp(t,e){const i=e.padWidth(t,e);const n=e.helpWidth||80;const s=2;const r=2;function formatItem(t,o){if(o){const a=`${t.padEnd(i+r)}${o}`;return e.wrap(a,n-s,i+r)}return t}function formatList(t){return t.join("\n").replace(/^/gm," ".repeat(s))}let o=[`Usage: ${e.commandUsage(t)}`,""];const a=e.commandDescription(t);if(a.length>0){o=o.concat([a,""])}const h=e.visibleArguments(t).map((t=>formatItem(e.argumentTerm(t),e.argumentDescription(t))));if(h.length>0){o=o.concat(["Arguments:",formatList(h),""])}const l=e.visibleOptions(t).map((t=>formatItem(e.optionTerm(t),e.optionDescription(t))));if(l.length>0){o=o.concat(["Options:",formatList(l),""])}const u=e.visibleCommands(t).map((t=>formatItem(e.subcommandTerm(t),e.subcommandDescription(t))));if(u.length>0){o=o.concat(["Commands:",formatList(u),""])}return o.join("\n")}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}wrap(t,e,i,n=40){if(t.match(/[\n]\s+/))return t;const s=e-i;if(s{if(t.slice(-1)==="\n"){t=t.slice(0,t.length-1)}return(e>0?a:"")+t.trimRight()})).join("\n")}}e.Help=Help},277:function(t,e,i){const{InvalidArgumentError:n}=i(234);class Option{constructor(t,e){this.flags=t;this.description=e||"";this.required=t.includes("<");this.optional=t.includes("[");this.variadic=/\w\.\.\.[>\]]$/.test(t);this.mandatory=false;const i=splitOptionFlags(t);this.short=i.shortFlag;this.long=i.longFlag;this.negate=false;if(this.long){this.negate=this.long.startsWith("--no-")}this.defaultValue=undefined;this.defaultValueDescription=undefined;this.presetArg=undefined;this.envVar=undefined;this.parseArg=undefined;this.hidden=false;this.argChoices=undefined;this.conflictsWith=[];this.implied=undefined}default(t,e){this.defaultValue=t;this.defaultValueDescription=e;return this}preset(t){this.presetArg=t;return this}conflicts(t){this.conflictsWith=this.conflictsWith.concat(t);return this}implies(t){this.implied=Object.assign(this.implied||{},t);return this}env(t){this.envVar=t;return this}argParser(t){this.parseArg=t;return this}makeOptionMandatory(t=true){this.mandatory=!!t;return this}hideHelp(t=true){this.hidden=!!t;return this}_concatValue(t,e){if(e===this.defaultValue||!Array.isArray(e)){return[t]}return e.concat(t)}choices(t){this.argChoices=t.slice();this.parseArg=(t,e)=>{if(!this.argChoices.includes(t)){throw new n(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(t,e)}return t};return this}name(){if(this.long){return this.long.replace(/^--/,"")}return this.short.replace(/^-/,"")}attributeName(){return camelcase(this.name().replace(/^no-/,""))}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class DualOptions{constructor(t){this.positiveOptions=new Map;this.negativeOptions=new Map;this.dualOptions=new Set;t.forEach((t=>{if(t.negate){this.negativeOptions.set(t.attributeName(),t)}else{this.positiveOptions.set(t.attributeName(),t)}}));this.negativeOptions.forEach(((t,e)=>{if(this.positiveOptions.has(e)){this.dualOptions.add(e)}}))}valueFromOption(t,e){const i=e.attributeName();if(!this.dualOptions.has(i))return true;const n=this.negativeOptions.get(i).presetArg;const s=n!==undefined?n:false;return e.negate===(s===t)}}function camelcase(t){return t.split("-").reduce(((t,e)=>t+e[0].toUpperCase()+e.slice(1)))}function splitOptionFlags(t){let e;let i;const n=t.split(/[ |,]+/);if(n.length>1&&!/^[[<]/.test(n[1]))e=n.shift();i=n.shift();if(!e&&/^-[^-]$/.test(i)){e=i;i=undefined}return{shortFlag:e,longFlag:i}}e.Option=Option;e.splitOptionFlags=splitOptionFlags;e.DualOptions=DualOptions},176:function(t,e){const i=3;function editDistance(t,e){if(Math.abs(t.length-e.length)>i)return Math.max(t.length,e.length);const n=[];for(let e=0;e<=t.length;e++){n[e]=[e]}for(let t=0;t<=e.length;t++){n[0][t]=t}for(let i=1;i<=e.length;i++){for(let s=1;s<=t.length;s++){let r=1;if(t[s-1]===e[i-1]){r=0}else{r=1}n[s][i]=Math.min(n[s-1][i]+1,n[s][i-1]+1,n[s-1][i-1]+r);if(s>1&&i>1&&t[s-1]===e[i-2]&&t[s-2]===e[i-1]){n[s][i]=Math.min(n[s][i],n[s-2][i-2]+1)}}}return n[t.length][e.length]}function suggestSimilar(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));const n=t.startsWith("--");if(n){t=t.slice(2);e=e.map((t=>t.slice(2)))}let s=[];let r=i;const o=.4;e.forEach((e=>{if(e.length<=1)return;const i=editDistance(t,e);const n=Math.max(t.length,e.length);const a=(n-i)/n;if(a>o){if(it.localeCompare(e)));if(n){s=s.map((t=>`--${t}`))}if(s.length>1){return`\n(Did you mean one of ${s.join(", ")}?)`}if(s.length===1){return`\n(Did you mean ${s[0]}?)`}return""}e.suggestSimilar=suggestSimilar}};var e={};function __nccwpck_require__(i){var n=e[i];if(n!==undefined){return n.exports}var s=e[i]={exports:{}};var r=true;try{t[i](s,s.exports,__nccwpck_require__);r=false}finally{if(r)delete e[i]}return s.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var i=__nccwpck_require__(978);module.exports=i})(); -------------------------------------------------------------------------------- /packages/coderduan-umi/compiled/glob/index.js: -------------------------------------------------------------------------------- 1 | (function(){var t={218:function(t){"use strict";t.exports=balanced;function balanced(t,e,r){if(t instanceof RegExp)t=maybeMatch(t,r);if(e instanceof RegExp)e=maybeMatch(e,r);var i=range(t,e,r);return i&&{start:i[0],end:i[1],pre:r.slice(0,i[0]),body:r.slice(i[0]+t.length,i[1]),post:r.slice(i[1]+e.length)}}function maybeMatch(t,e){var r=e.match(t);return r?r[0]:null}balanced.range=range;function range(t,e,r){var i,n,s,a,o;var c=r.indexOf(t);var l=r.indexOf(e,c+1);var h=c;if(c>=0&&l>0){if(t===e){return[c,l]}i=[];s=r.length;while(h>=0&&!o){if(h==c){i.push(h);c=r.indexOf(t,h+1)}else if(i.length==1){o=[i.pop(),l]}else{n=i.pop();if(n=0?c:l}if(i.length){o=[s,a]}}return o}},847:function(t,e,r){var i=r(218);t.exports=expandTop;var n="\0SLASH"+Math.random()+"\0";var s="\0OPEN"+Math.random()+"\0";var a="\0CLOSE"+Math.random()+"\0";var o="\0COMMA"+Math.random()+"\0";var c="\0PERIOD"+Math.random()+"\0";function numeric(t){return parseInt(t,10)==t?parseInt(t,10):t.charCodeAt(0)}function escapeBraces(t){return t.split("\\\\").join(n).split("\\{").join(s).split("\\}").join(a).split("\\,").join(o).split("\\.").join(c)}function unescapeBraces(t){return t.split(n).join("\\").split(s).join("{").split(a).join("}").split(o).join(",").split(c).join(".")}function parseCommaParts(t){if(!t)return[""];var e=[];var r=i("{","}",t);if(!r)return t.split(",");var n=r.pre;var s=r.body;var a=r.post;var o=n.split(",");o[o.length-1]+="{"+s+"}";var c=parseCommaParts(a);if(a.length){o[o.length-1]+=c.shift();o.push.apply(o,c)}e.push.apply(e,o);return e}function expandTop(t){if(!t)return[];if(t.substr(0,2)==="{}"){t="\\{\\}"+t.substr(2)}return expand(escapeBraces(t),true).map(unescapeBraces)}function embrace(t){return"{"+t+"}"}function isPadded(t){return/^-?0\d/.test(t)}function lte(t,e){return t<=e}function gte(t,e){return t>=e}function expand(t,e){var r=[];var n=i("{","}",t);if(!n)return[t];var s=n.pre;var o=n.post.length?expand(n.post,false):[""];if(/\$$/.test(n.pre)){for(var c=0;c=0;if(!p&&!v){if(n.post.match(/,.*\}/)){t=n.pre+"{"+n.body+a+n.post;return expand(t)}return[t]}var d;if(p){d=n.body.split(/\.\./)}else{d=parseCommaParts(n.body);if(d.length===1){d=expand(d[0],false).map(embrace);if(d.length===1){return o.map((function(t){return n.pre+d[0]+t}))}}}var b;if(p){var g=numeric(d[0]);var y=numeric(d[1]);var _=Math.max(d[0].length,d[1].length);var w=d.length==3?Math.abs(numeric(d[2])):1;var k=lte;var E=y0){var G=new Array(x+1).join("0");if(O<0)A="-"+G+A.slice(1);else A=G+A}}}b.push(A)}}else{b=[];for(var j=0;j=t.length){if(e)e[a]=t;return r(null,t)}c.lastIndex=u;var i=c.exec(t);d=p;p+=i[0];v=d+i[1];u=c.lastIndex;if(h[v]||e&&e[v]===v){return process.nextTick(LOOP)}if(e&&Object.prototype.hasOwnProperty.call(e,v)){return gotResolvedLink(e[v])}return s.lstat(v,gotStat)}function gotStat(t,i){if(t)return r(t);if(!i.isSymbolicLink()){h[v]=true;if(e)e[v]=v;return process.nextTick(LOOP)}if(!n){var a=i.dev.toString(32)+":"+i.ino.toString(32);if(o.hasOwnProperty(a)){return gotTarget(null,o[a],v)}}s.stat(v,(function(t){if(t)return r(t);s.readlink(v,(function(t,e){if(!n)o[a]=e;gotTarget(t,e)}))}))}function gotTarget(t,n,s){if(t)return r(t);var a=i.resolve(d,n);if(e)e[s]=a;gotResolvedLink(a)}function gotResolvedLink(e){t=i.resolve(e,t.slice(u));start()}}},945:function(t,e,r){e.setopts=setopts;e.ownProp=ownProp;e.makeAbs=makeAbs;e.finish=finish;e.mark=mark;e.isIgnored=isIgnored;e.childrenIgnored=childrenIgnored;function ownProp(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var i=r(147);var n=r(17);var s=r(373);var a=r(17).isAbsolute;var o=s.Minimatch;function alphasort(t,e){return t.localeCompare(e,"en")}function setupIgnores(t,e){t.ignore=e.ignore||[];if(!Array.isArray(t.ignore))t.ignore=[t.ignore];if(t.ignore.length){t.ignore=t.ignore.map(ignoreMap)}}function ignoreMap(t){var e=null;if(t.slice(-3)==="/**"){var r=t.replace(/(\/\*\*)+$/,"");e=new o(r,{dot:true})}return{matcher:new o(t,{dot:true}),gmatcher:e}}function setopts(t,e,r){if(!r)r={};if(r.matchBase&&-1===e.indexOf("/")){if(r.noglobstar){throw new Error("base matching requires globstar")}e="**/"+e}t.silent=!!r.silent;t.pattern=e;t.strict=r.strict!==false;t.realpath=!!r.realpath;t.realpathCache=r.realpathCache||Object.create(null);t.follow=!!r.follow;t.dot=!!r.dot;t.mark=!!r.mark;t.nodir=!!r.nodir;if(t.nodir)t.mark=true;t.sync=!!r.sync;t.nounique=!!r.nounique;t.nonull=!!r.nonull;t.nosort=!!r.nosort;t.nocase=!!r.nocase;t.stat=!!r.stat;t.noprocess=!!r.noprocess;t.absolute=!!r.absolute;t.fs=r.fs||i;t.maxLength=r.maxLength||Infinity;t.cache=r.cache||Object.create(null);t.statCache=r.statCache||Object.create(null);t.symlinks=r.symlinks||Object.create(null);setupIgnores(t,r);t.changedCwd=false;var s=process.cwd();if(!ownProp(r,"cwd"))t.cwd=n.resolve(s);else{t.cwd=n.resolve(r.cwd);t.changedCwd=t.cwd!==s}t.root=r.root||n.resolve(t.cwd,"/");t.root=n.resolve(t.root);t.cwdAbs=a(t.cwd)?t.cwd:makeAbs(t,t.cwd);t.nomount=!!r.nomount;if(process.platform==="win32"){t.root=t.root.replace(/\\/g,"/");t.cwd=t.cwd.replace(/\\/g,"/");t.cwdAbs=t.cwdAbs.replace(/\\/g,"/")}r.nonegate=true;r.nocomment=true;r.allowWindowsEscape=true;t.minimatch=new o(e,r);t.options=t.minimatch.options}function finish(t){var e=t.nounique;var r=e?[]:Object.create(null);for(var i=0,n=t.matches.length;i1)return true;for(var s=0;sthis.maxLength)return e();if(!this.stat&&d(this.cache,r)){var n=this.cache[r];if(Array.isArray(n))n="DIR";if(!i||n==="DIR")return e(null,n);if(i&&n==="FILE")return e()}var s;var a=this.statCache[r];if(a!==undefined){if(a===false)return e(null,a);else{var o=a.isDirectory()?"DIR":"FILE";if(i&&o==="FILE")return e();else return e(null,o,a)}}var c=this;var l=b("stat\0"+r,lstatcb_);if(l)c.fs.lstat(r,l);function lstatcb_(i,n){if(n&&n.isSymbolicLink()){return c.fs.stat(r,(function(i,s){if(i)c._stat2(t,r,null,n,e);else c._stat2(t,r,i,s,e)}))}else{c._stat2(t,r,i,n,e)}}};Glob.prototype._stat2=function(t,e,r,i,n){if(r&&(r.code==="ENOENT"||r.code==="ENOTDIR")){this.statCache[e]=false;return n()}var s=t.slice(-1)==="/";this.statCache[e]=i;if(e.slice(-1)==="/"&&i&&!i.isDirectory())return n(null,false,i);var a=true;if(i)a=i.isDirectory()?"DIR":"FILE";this.cache[e]=this.cache[e]||a;if(s&&a==="FILE")return n();return n(null,a,i)}},407:function(t,e,r){t.exports=globSync;globSync.GlobSync=GlobSync;var i=r(981);var n=r(373);var s=n.Minimatch;var a=r(529).Glob;var o=r(837);var c=r(17);var l=r(491);var h=r(17).isAbsolute;var u=r(945);var p=u.setopts;var v=u.ownProp;var d=u.childrenIgnored;var b=u.isIgnored;function globSync(t,e){if(typeof e==="function"||arguments.length===3)throw new TypeError("callback provided to sync glob\n"+"See: https://github.com/isaacs/node-glob/issues/167");return new GlobSync(t,e).found}function GlobSync(t,e){if(!t)throw new Error("must provide pattern");if(typeof e==="function"||arguments.length===3)throw new TypeError("callback provided to sync glob\n"+"See: https://github.com/isaacs/node-glob/issues/167");if(!(this instanceof GlobSync))return new GlobSync(t,e);p(this,t,e);if(this.noprocess)return this;var r=this.minimatch.set.length;this.matches=new Array(r);for(var i=0;ithis.maxLength)return false;if(!this.stat&&v(this.cache,e)){var i=this.cache[e];if(Array.isArray(i))i="DIR";if(!r||i==="DIR")return i;if(r&&i==="FILE")return false}var n;var s=this.statCache[e];if(!s){var a;try{a=this.fs.lstatSync(e)}catch(t){if(t&&(t.code==="ENOENT"||t.code==="ENOTDIR")){this.statCache[e]=false;return false}}if(a&&a.isSymbolicLink()){try{s=this.fs.statSync(e)}catch(t){s=a}}else{s=a}}this.statCache[e]=s;var i=true;if(s)i=s.isDirectory()?"DIR":"FILE";this.cache[e]=this.cache[e]||i;if(r&&i==="FILE")return false;return i};GlobSync.prototype._mark=function(t){return u.mark(this,t)};GlobSync.prototype._makeAbs=function(t){return u.makeAbs(this,t)}},143:function(t,e,r){var i=r(270);var n=Object.create(null);var s=r(852);t.exports=i(inflight);function inflight(t,e){if(n[t]){n[t].push(e);return null}else{n[t]=[e];return makeres(t)}}function makeres(t){return s((function RES(){var e=n[t];var r=e.length;var i=slice(arguments);try{for(var s=0;sr){e.splice(0,r);process.nextTick((function(){RES.apply(null,i)}))}else{delete n[t]}}}))}function slice(t){var e=t.length;var r=[];for(var i=0;i{assertValidPattern(e);if(!r.nocomment&&e.charAt(0)==="#"){return false}return new Minimatch(e,r).match(t)};t.exports=i;const n=r(445);i.sep=n.sep;const s=Symbol("globstar **");i.GLOBSTAR=s;const a=r(847);const o={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}};const c="[^/]";const l=c+"*?";const h="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";const u="(?:(?!(?:\\/|^)\\.).)*?";const charSet=t=>t.split("").reduce(((t,e)=>{t[e]=true;return t}),{});const p=charSet("().*{}+?[]^$\\!");const v=charSet("[.(");const d=/\/+/;i.filter=(t,e={})=>(r,n,s)=>i(r,t,e);const ext=(t,e={})=>{const r={};Object.keys(t).forEach((e=>r[e]=t[e]));Object.keys(e).forEach((t=>r[t]=e[t]));return r};i.defaults=t=>{if(!t||typeof t!=="object"||!Object.keys(t).length){return i}const e=i;const m=(r,i,n)=>e(r,i,ext(t,n));m.Minimatch=class Minimatch extends e.Minimatch{constructor(e,r){super(e,ext(t,r))}};m.Minimatch.defaults=r=>e.defaults(ext(t,r)).Minimatch;m.filter=(r,i)=>e.filter(r,ext(t,i));m.defaults=r=>e.defaults(ext(t,r));m.makeRe=(r,i)=>e.makeRe(r,ext(t,i));m.braceExpand=(r,i)=>e.braceExpand(r,ext(t,i));m.match=(r,i,n)=>e.match(r,i,ext(t,n));return m};i.braceExpand=(t,e)=>braceExpand(t,e);const braceExpand=(t,e={})=>{assertValidPattern(t);if(e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)){return[t]}return a(t)};const b=1024*64;const assertValidPattern=t=>{if(typeof t!=="string"){throw new TypeError("invalid pattern")}if(t.length>b){throw new TypeError("pattern is too long")}};const g=Symbol("subparse");i.makeRe=(t,e)=>new Minimatch(t,e||{}).makeRe();i.match=(t,e,r={})=>{const i=new Minimatch(e,r);t=t.filter((t=>i.match(t)));if(i.options.nonull&&!t.length){t.push(e)}return t};const globUnescape=t=>t.replace(/\\(.)/g,"$1");const regExpEscape=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");class Minimatch{constructor(t,e){assertValidPattern(t);if(!e)e={};this.options=e;this.set=[];this.pattern=t;this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===false;if(this.windowsPathsNoEscape){this.pattern=this.pattern.replace(/\\/g,"/")}this.regexp=null;this.negate=false;this.comment=false;this.empty=false;this.partial=!!e.partial;this.make()}debug(){}make(){const t=this.pattern;const e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=true;return}if(!t){this.empty=true;return}this.parseNegate();let r=this.globSet=this.braceExpand();if(e.debug)this.debug=(...t)=>console.error(...t);this.debug(this.pattern,r);r=this.globParts=r.map((t=>t.split(d)));this.debug(this.pattern,r);r=r.map(((t,e,r)=>t.map(this.parse,this)));this.debug(this.pattern,r);r=r.filter((t=>t.indexOf(false)===-1));this.debug(this.pattern,r);this.set=r}parseNegate(){if(this.options.nonegate)return;const t=this.pattern;let e=false;let r=0;for(let i=0;i>> no match, partial?",t,u,e,p);if(u===o)return true}return false}var d;if(typeof l==="string"){d=h===l;this.debug("string match",l,h,d)}else{d=h.match(l);this.debug("pattern match",l,h,d)}if(!d)return false}if(n===o&&a===c){return true}else if(n===o){return r}else if(a===c){return n===o-1&&t[n]===""}throw new Error("wtf?")}braceExpand(){return braceExpand(this.pattern,this.options)}parse(t,e){assertValidPattern(t);const r=this.options;if(t==="**"){if(!r.noglobstar)return s;else t="*"}if(t==="")return"";let i="";let n=!!r.nocase;let a=false;const h=[];const u=[];let d;let b=false;let y=-1;let _=-1;let w;let k;let E;const S=t.charAt(0)==="."?"":r.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)";const clearStateChar=()=>{if(d){switch(d){case"*":i+=l;n=true;break;case"?":i+=c;n=true;break;default:i+="\\"+d;break}this.debug("clearStateChar %j %j",d,i);d=false}};for(let e=0,s;e{if(!r){r="\\"}return e+e+r+"|"}));this.debug("tail=%j\n %s",t,t,k,i);const e=k.type==="*"?l:k.type==="?"?c:"\\"+k.type;n=true;i=i.slice(0,k.reStart)+e+"\\("+t}clearStateChar();if(a){i+="\\\\"}const O=v[i.charAt(0)];for(let t=u.length-1;t>-1;t--){const r=u[t];const n=i.slice(0,r.reStart);const s=i.slice(r.reStart,r.reEnd-8);let a=i.slice(r.reEnd);const o=i.slice(r.reEnd-8,r.reEnd)+a;const c=n.split("(").length-1;let l=a;for(let t=0;t{t=t.map((t=>typeof t==="string"?regExpEscape(t):t===s?s:t._src)).reduce(((t,e)=>{if(!(t[t.length-1]===s&&e===s)){t.push(e)}return t}),[]);t.forEach(((e,i)=>{if(e!==s||t[i-1]===s){return}if(i===0){if(t.length>1){t[i+1]="(?:\\/|"+r+"\\/)?"+t[i+1]}else{t[i]=r}}else if(i===t.length-1){t[i-1]+="(?:\\/|"+r+")?"}else{t[i-1]+="(?:\\/|\\/"+r+"\\/)"+t[i+1];t[i+1]=s}}));return t.filter((t=>t!==s)).join("/")})).join("|");n="^(?:"+n+")$";if(this.negate)n="^(?!"+n+").*$";try{this.regexp=new RegExp(n,i)}catch(t){this.regexp=false}return this.regexp}match(t,e=this.partial){this.debug("match",t,this.pattern);if(this.comment)return false;if(this.empty)return t==="";if(t==="/"&&e)return true;const r=this.options;if(n.sep!=="/"){t=t.split(n.sep).join("/")}t=t.split(d);this.debug(this.pattern,"split",t);const i=this.set;this.debug(this.pattern,"set",i);let s;for(let e=t.length-1;e>=0;e--){s=t[e];if(s)break}for(let n=0;n