UNPKG

tsdk

Version:

Type-safe API development and code share tool for TypeScript projects.

218 lines (217 loc) 12.2 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.syncSharedFiles = exports.syncAddtionShareFiles = exports.syncAPIConf = exports.syncEntityFiles = exports.syncExtFiles = exports.copySDK = exports.copyShared = exports.copySnippet = exports.addDepsIfNone = exports.copyTsdkConfig = exports.syncFiles = void 0; const child_process_1 = require("child_process"); const glob = require("fast-glob"); const fs_extra_1 = __importDefault(require("fs-extra")); const path_1 = __importDefault(require("path")); const config_1 = require("./config"); const get_pkg_manager_1 = require("./get-pkg-manager"); const symbols_1 = __importDefault(require("./symbols")); const transform_import_path_1 = require("./transform-import-path"); function syncFiles() { return __awaiter(this, arguments, void 0, function* (noOverwrite = false) { yield copySDK(noOverwrite); yield (0, config_1.parseDeps)(); yield syncAddtionShareFiles(); yield syncAPIConf(); yield syncEntityFiles(); yield syncSharedFiles(); }); } exports.syncFiles = syncFiles; function copyTsdkConfig() { return __awaiter(this, void 0, void 0, function* () { // copy tsdk.config.js and remove packages/fe-sdk/tsdk.config.js yield fs_extra_1.default.copy(path_1.default.join(__dirname, '../fe-sdk-template', './config/tsdk.config.js'), path_1.default.join(process.cwd(), 'tsdk.config.js'), { overwrite: false }); }); } exports.copyTsdkConfig = copyTsdkConfig; function addDepsIfNone() { return __awaiter(this, void 0, void 0, function* () { const cwd = process.cwd(); const pkgPath = path_1.default.resolve(cwd, 'package.json'); const content = yield fs_extra_1.default.readFile(pkgPath, 'utf8'); const contentJSON = JSON.parse(content); const npmCMDs = yield (0, get_pkg_manager_1.getNpmCommand)(cwd); let needRunInstall = false; yield Promise.all([ ['zod', '^3'], ['change-case', '^4.1.2'], ].map((_a) => __awaiter(this, [_a], void 0, function* ([i, version]) { if (!contentJSON.dependencies[i]) { contentJSON.dependencies[i] = version; yield fs_extra_1.default.writeFile(pkgPath, JSON.stringify(contentJSON, null, 2)); needRunInstall = true; console.log(''); console.log(symbols_1.default.warning, `\`tsdk\` depends on \`${i}\`, so automatic add \`${i}\` to dependencies`); console.log(symbols_1.default.info, `You can run \`${npmCMDs.installCmd}\` to install new dependencies`); console.log(''); } return 1; }))); if (needRunInstall) { (0, child_process_1.execSync)(`${npmCMDs.installCmd}`); } }); } exports.addDepsIfNone = addDepsIfNone; function copySnippet() { return __awaiter(this, void 0, void 0, function* () { yield fs_extra_1.default.copy(path_1.default.join(__dirname, '../fe-sdk-template', './config/.vscode'), path_1.default.resolve(process.cwd(), config_1.config.monorepoRoot || './', '.vscode'), { overwrite: false }); }); } exports.copySnippet = copySnippet; function copyShared() { return __awaiter(this, void 0, void 0, function* () { yield fs_extra_1.default.copy(path_1.default.join(__dirname, '../fe-sdk-template', './src/shared/'), path_1.default.join(process.cwd(), config_1.config.baseDir, 'shared'), { overwrite: false }); }); } exports.copyShared = copyShared; function reconfigPkg() { return __awaiter(this, void 0, void 0, function* () { var _a, _b, _c; // rename package name const pkgPath = path_1.default.resolve(process.cwd(), config_1.config.packageDir, config_1.packageFolder, 'package.json'); const [content] = yield Promise.all([fs_extra_1.default.readFile(pkgPath, 'utf-8')]); const pkgContent = JSON.parse(content); pkgContent.name = config_1.config.packageName; if ((_a = (Array.isArray(config_1.config.entityLibName) ? config_1.config.entityLibName : [config_1.config.entityLibName || 'typeorm'])) === null || _a === void 0 ? void 0 : _a.find((item) => item === 'kysely')) { pkgContent.dependencies.kysely = '^0.27.5'; } const dataHookLib = (_b = config_1.config.dataHookLib) === null || _b === void 0 ? void 0 : _b.toLowerCase(); if (dataHookLib === 'swr') { pkgContent.dependencies.swr = '^2.3.0'; } else if (dataHookLib === 'reactquery') { pkgContent.dependencies['@tanstack/react-query'] = '^5.56.2'; } if (config_1.config.dependencies) { pkgContent.dependencies = Object.assign(Object.assign({}, pkgContent.dependencies), config_1.config.dependencies); } if (config_1.config.devDependencies) { pkgContent.devDependencies = Object.assign(Object.assign({}, pkgContent.devDependencies), config_1.config.devDependencies); } if (config_1.config.scripts) { pkgContent.scripts = Object.assign(Object.assign({}, pkgContent.scripts), config_1.config.scripts); } yield Promise.all([fs_extra_1.default.writeFile(pkgPath, JSON.stringify(pkgContent, null, 2))]); yield Promise.all([copyShared(), copySnippet()]); const content2 = yield fs_extra_1.default.readFile('./package.json', 'utf-8'); const pkgJSON = JSON.parse(content2); pkgJSON.scripts = Object.assign(Object.assign({}, (pkgJSON.scripts || {})), { 'sync-sdk': ((_c = pkgJSON.scripts) === null || _c === void 0 ? void 0 : _c['sync-sdk']) || `tsdk --sync` }); yield fs_extra_1.default.writeFile('./package.json', JSON.stringify(pkgJSON, null, 2)); }); } function copySDK(noOverwrite) { return __awaiter(this, void 0, void 0, function* () { console.log(symbols_1.default.bullet, `init ${config_1.ensureDir}`); if (!config_1.isConfigExist) { yield copyTsdkConfig(); } const existPath = path_1.default.resolve(process.cwd(), config_1.config.packageDir, config_1.packageFolder, `package.json`); const isExist = yield fs_extra_1.default.pathExists(existPath); if (isExist && noOverwrite) { yield reconfigPkg(); console.log(symbols_1.default.info, `skip init sdk: \`${path_1.default.resolve(process.cwd(), config_1.config.packageDir, config_1.packageFolder)}\` already exist`); return; } yield fs_extra_1.default.ensureDir(config_1.ensureDir); console.log(symbols_1.default.success, `mkdir -p ${config_1.ensureDir}`); yield fs_extra_1.default.copy(path_1.default.join(__dirname, '../fe-sdk-template'), path_1.default.resolve(process.cwd(), config_1.config.packageDir, config_1.packageFolder), { overwrite: true }); yield reconfigPkg(); yield Promise.all(['config'].map((folder) => { return fs_extra_1.default.remove(path_1.default.join(config_1.ensureDir, folder)); })); console.log(symbols_1.default.success, `init ${config_1.ensureDir}`); }); } exports.copySDK = copySDK; /** sync files base extension config */ function syncExtFiles(ext_1) { return __awaiter(this, arguments, void 0, function* (ext, isEntity = false) { console.log(symbols_1.default.bullet, `sync *.${ext}.ts files`); const pattern = path_1.default .join(`${path_1.default.join(...config_1.config.baseDir.split('/'))}`, `**`, `*.${ext}.ts`) .replace(/\\/g, '/'); const files = yield glob(pattern); files.sort(); const indexContentMap = {}; yield Promise.all(files.map((file, idx) => __awaiter(this, void 0, void 0, function* () { const filePath = path_1.default.join(config_1.ensureDir, file.replace(`${config_1.config.baseDir}/`, 'src/')); const content = yield (0, transform_import_path_1.transformImportPath)(file, isEntity); yield fs_extra_1.default.ensureDir(path_1.default.dirname(filePath)); let fromPath = path_1.default.relative(`${config_1.ensureDir}/src/`.replace(/\\/g, '/'), filePath.replace('.ts', '')); fromPath = path_1.default.normalize(fromPath); fromPath = fromPath.startsWith('.') ? fromPath : './' + fromPath; indexContentMap[file] = `export * from '${fromPath.replace(/\\/g, '/')}';\n`; return fs_extra_1.default.writeFile(filePath, content); }))); const indexContent = files.length > 0 ? files.map((file) => indexContentMap[file]).join('') : (0, config_1.getDefaultContent)(); yield fs_extra_1.default.writeFile(path_1.default.join(config_1.ensureDir, `src/${ext}-refs.ts`), `${config_1.comment}${indexContent}`); }); } exports.syncExtFiles = syncExtFiles; /** sync entity files */ function syncEntityFiles() { return __awaiter(this, void 0, void 0, function* () { return syncExtFiles(config_1.config.entityExt, true); }); } exports.syncEntityFiles = syncEntityFiles; /** sync apiconf files */ function syncAPIConf() { return __awaiter(this, void 0, void 0, function* () { return syncExtFiles(config_1.config.apiconfExt); }); } exports.syncAPIConf = syncAPIConf; /** sync apiconf files */ function syncAddtionShareFiles() { return __awaiter(this, void 0, void 0, function* () { return syncExtFiles(config_1.config.shareExt || 'shared'); }); } exports.syncAddtionShareFiles = syncAddtionShareFiles; /** sync shared files */ function syncSharedFiles() { return __awaiter(this, void 0, void 0, function* () { console.log(symbols_1.default.bullet, `sync shared files`); const files = yield glob([ ...config_1.config.sharedDirs.map((i) => path_1.default.join(i, `**/*.*`).replace(/\\/g, '/')), path_1.default.join(config_1.config.baseDir, `**/*.${config_1.config.shareExt || 'shared'}.*`).replace(/\\/g, '/'), ]); files.sort(); const indexContentMap = {}; yield Promise.all(files.map((file) => __awaiter(this, void 0, void 0, function* () { const filePath = path_1.default.join(config_1.ensureDir, file.replace(`${config_1.config.baseDir}/`, 'src/')); const content = yield (0, transform_import_path_1.transformImportPath)(file); yield fs_extra_1.default.ensureDir(path_1.default.dirname(filePath)); let fromPath = path_1.default.relative(`${config_1.ensureDir}/src/`.replace(/\\/g, '/'), filePath.replace('.ts', '')); fromPath = path_1.default.normalize(fromPath); fromPath = fromPath.startsWith('.') ? fromPath : './' + fromPath; if (fromPath.indexOf('tsdk-types') < 0 && filePath.endsWith('.ts')) { indexContentMap[file] = `export * from '${fromPath.replace(/\\/g, '/')}';\n`; } return fs_extra_1.default.writeFile(filePath, content); }))); const indexContent = files.map((file) => indexContentMap[file]).join('\n'); yield fs_extra_1.default.writeFile(path_1.default.join(config_1.ensureDir, `src`, `shared-refs.ts`), `${config_1.comment}${indexContent}`); console.log(symbols_1.default.success, `sync shared files`); }); } exports.syncSharedFiles = syncSharedFiles;