UNPKG

@nestia/sdk

Version:

Nestia SDK and Swagger generator

277 lines 13.8 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.ConfigAnalyzer = void 0; /// <reference path="../typings/get-function-location.d.ts" /> const common_1 = require("@nestjs/common"); const constants_1 = require("@nestjs/common/constants"); const fs_1 = __importDefault(require("fs")); const get_function_location_1 = __importDefault(require("get-function-location")); const path_1 = __importDefault(require("path")); const tstl_1 = require("tstl"); const url_1 = require("url"); const SdkGenerator_1 = require("../generates/SdkGenerator"); const ArrayUtil_1 = require("../utils/ArrayUtil"); const EmittedJavaScriptPatcher_1 = require("../utils/EmittedJavaScriptPatcher"); const MapUtil_1 = require("../utils/MapUtil"); const SourceFinder_1 = require("../utils/SourceFinder"); const TsConfigReader_1 = require("../utils/TsConfigReader"); const TtscExecutor_1 = require("../utils/TtscExecutor"); var ConfigAnalyzer; (function (ConfigAnalyzer) { ConfigAnalyzer.input = (config) => __awaiter(this, void 0, void 0, function* () { return MapUtil_1.MapUtil.take(memory, config, () => __awaiter(this, void 0, void 0, function* () { var _a; if (typeof config.input === "function") return ConfigAnalyzer.application(yield config.input()); const sources = yield SourceFinder_1.SourceFinder.find({ include: Array.isArray(config.input) ? config.input : typeof config.input === "object" ? config.input.include : [config.input], exclude: typeof config.input === "object" && !Array.isArray(config.input) ? ((_a = config.input.exclude) !== null && _a !== void 0 ? _a : []) : [], filter: filter(config), }); const runtime = yield RuntimeCompiler.compile(sources); const controllers = []; for (const file of sources) { const external = yield dynamicImport((0, url_1.pathToFileURL)(runtime.output(file)).href); for (const key in external) { const instance = external[key]; if (typeof instance !== "function") continue; if (Reflect.getMetadata("path", instance) !== undefined) controllers.push({ class: instance, location: file, prefixes: [], }); } } return { controllers, }; })); }); ConfigAnalyzer.application = (app) => __awaiter(this, void 0, void 0, function* () { var _a, _b, _c, _d; var _e, _f, _g, _h; const container = app.container; const modules = [...container.getModules().values()].filter((m) => !!m.controllers.size); const unique = new tstl_1.HashMap(); for (const m of modules) { const path = (_f = (_e = Reflect.getMetadata(constants_1.MODULE_PATH + container.getModules().applicationId, m.metatype)) !== null && _e !== void 0 ? _e : Reflect.getMetadata(constants_1.MODULE_PATH, m.metatype)) !== null && _f !== void 0 ? _f : ""; for (const controller of [...m.controllers.keys()]) if (typeof controller === "function") unique.take(controller, () => new Set()).add(path); } const controllers = []; for (const it of unique) { const file = (_g = (_a = (yield (0, get_function_location_1.default)(it.first))) === null || _a === void 0 ? void 0 : _a.source) !== null && _g !== void 0 ? _g : null; if (file === null) continue; const location = normalize_file(file); if (location.length === 0) continue; controllers.push({ class: it.first, prefixes: Array.from(it.second), location, }); } const versioning = (_b = app.config) === null || _b === void 0 ? void 0 : _b.versioningOptions; return { controllers, globalPrefix: typeof ((_c = app.config) === null || _c === void 0 ? void 0 : _c.globalPrefix) === "string" ? { prefix: app.config.globalPrefix, exclude: (_h = (_d = app.config.globalPrefixOptions) === null || _d === void 0 ? void 0 : _d.exclude) !== null && _h !== void 0 ? _h : [], } : undefined, versioning: versioning === undefined || versioning.type !== common_1.VersioningType.URI ? undefined : { prefix: versioning.prefix === undefined || versioning.prefix === false ? "v" : versioning.prefix, defaultVersion: versioning.defaultVersion, }, }; }); })(ConfigAnalyzer || (exports.ConfigAnalyzer = ConfigAnalyzer = {})); const memory = new Map(); class RuntimeCompiler { constructor(cwd, outDir) { this.cwd = cwd; this.outDir = outDir; } static compile(sources) { return __awaiter(this, void 0, void 0, function* () { var _a; const cwd = process.cwd(); const runtimeRoot = path_1.default.join(cwd, "node_modules", ".nestia", "runtime"); yield fs_1.default.promises.mkdir(runtimeRoot, { recursive: true }); ensureRuntimeCleanup(runtimeRoot); const outDir = yield fs_1.default.promises.mkdtemp(path_1.default.join(runtimeRoot, "run-")); const project = path_1.default.join(cwd, `.nestia.runtime.${process.pid}.${Date.now()}.json`); const relative = (file) => path_1.default.relative(cwd, file).split("\\").join("/"); yield fs_1.default.promises.writeFile(project, JSON.stringify({ extends: normalizeProjectPath(process.env.NESTIA_PROJECT), compilerOptions: { noEmit: false, noUnusedLocals: false, noUnusedParameters: false, outDir, plugins: yield runtimePlugins(cwd), rootDir: ".", }, include: sources.map(relative), }, null, 2), "utf8"); try { TtscExecutor_1.TtscExecutor.run({ cwd, env: sdkTransformEnv(), project, }); } catch (error) { const output = error instanceof Error && "stderr" in error ? String((_a = error.stderr) !== null && _a !== void 0 ? _a : "") : ""; throw new Error(output || `Failed to compile Nestia runtime inputs.`); } finally { yield fs_1.default.promises.rm(project, { force: true }); } yield EmittedJavaScriptPatcher_1.EmittedJavaScriptPatcher.importMetaUrl(outDir); return new RuntimeCompiler(cwd, outDir); }); } output(source) { const relative = path_1.default.relative(this.cwd, source); const emitted = path_1.default.join(this.outDir, replaceExtension(relative, ".js")); return emitted; } } const RUNTIME_ROOTS = new Set(); let RUNTIME_CLEANUP_REGISTERED = false; const ensureRuntimeCleanup = (runtimeRoot) => { RUNTIME_ROOTS.add(runtimeRoot); if (RUNTIME_CLEANUP_REGISTERED === true) return; RUNTIME_CLEANUP_REGISTERED = true; const sweep = () => { for (const location of RUNTIME_ROOTS) fs_1.default.rmSync(location, { force: true, recursive: true }); }; process.once("exit", sweep); // process.once("exit", …) does not fire on SIGINT/SIGTERM. Without these // handlers a Ctrl-C during codegen leaves `run-*` mkdtemp directories // behind under node_modules/.nestia/runtime/ until a subsequent clean exit. // The module-level RUNTIME_CLEANUP_REGISTERED flag above guards against // re-entrancy within this module; we deliberately do NOT gate on // `process.listenerCount(signal) > 0` because NestiaConfigLoader's parallel // sweep registers first, and that gate would skip our registration — // leaving RUNTIME_ROOTS unswept on Ctrl-C while config-loader cleans up. // Windows note: `process.kill(pid, "SIGINT")` calls TerminateProcess // rather than re-raising through the listener queue, so the handler // cascade documented above only holds on POSIX. On Windows, whichever // module registers FIRST runs its sweep and the second is skipped — // RUNTIME_ROOTS cleanup is best-effort there. SIGHUP is a no-op for // most common code paths on Windows (Node fires it on console-close // and exits within seconds). const onSignal = (signal) => { sweep(); process.kill(process.pid, signal); }; for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) { process.once(signal, onSignal); } }; const sdkTransformEnv = () => process.env.NESTIA_SDK_TRANSFORM === undefined ? { NESTIA_SDK_TRANSFORM: "1" } : {}; const runtimePlugins = (cwd) => __awaiter(void 0, void 0, void 0, function* () { const plugins = yield readProjectPlugins(cwd); const typia = plugins.find((p) => isTransform(p, "typia")); const core = plugins.find((p) => isTransform(p, "@nestia/core")); return [ Object.assign(Object.assign({}, (typia !== null && typia !== void 0 ? typia : {})), { transform: "typia/lib/transform", enabled: false }), normalizeRuntimePlugin(Object.assign(Object.assign({}, (core !== null && core !== void 0 ? core : {})), { transform: "@nestia/core/native/transform.cjs" })), ]; }); const readProjectPlugins = (cwd) => __awaiter(void 0, void 0, void 0, function* () { const project = normalizeProjectPath(process.env.NESTIA_PROJECT); const file = path_1.default.isAbsolute(project) ? project : path_1.default.join(cwd, project); const config = yield TsConfigReader_1.TsConfigReader.read(file); const options = config.compilerOptions; return Array.isArray(options === null || options === void 0 ? void 0 : options.plugins) ? options.plugins .filter((p) => typeof p === "object" && p !== null) .map((p) => (Object.assign({}, p))) : []; }); const normalizeRuntimePlugin = (plugin) => { const output = Object.assign({}, plugin); if (output.enabled === false) delete output.enabled; return output; }; const isTransform = (plugin, name) => typeof plugin.transform === "string" && plugin.transform.includes(name); const replaceExtension = (file, extension) => file.replace(/\.[cm]?tsx?$/i, (matched) => matched.toLowerCase() === ".mts" ? ".mjs" : matched.toLowerCase() === ".cts" ? ".cjs" : extension); const normalizeProjectPath = (project) => { const next = project !== null && project !== void 0 ? project : "tsconfig.json"; return path_1.default.isAbsolute(next) || next.startsWith(".") ? next : `./${next}`; }; const normalize_file = (str) => str.substring(str.startsWith("file:///") ? process.cwd()[0] === "/" ? 7 : 8 : str.startsWith("file://") ? 7 : 0); const filter = (config) => (location) => __awaiter(void 0, void 0, void 0, function* () { return SourceFinder_1.SourceFinder.isTypeScriptSource(location) && (config.output === undefined || (location.indexOf(path_1.default.join(config.output, "functional")) === -1 && (yield (yield bundler.get(config.output))(location))) === false); }); const dynamicImport = Function("specifier", "return import(specifier);"); const bundler = new tstl_1.Singleton((output) => __awaiter(void 0, void 0, void 0, function* () { const assets = yield fs_1.default.promises.readdir(SdkGenerator_1.SdkGenerator.BUNDLE_PATH); const tuples = yield ArrayUtil_1.ArrayUtil.asyncMap(assets, (file) => __awaiter(void 0, void 0, void 0, function* () { const relative = path_1.default.join(output, file); const location = path_1.default.join(SdkGenerator_1.SdkGenerator.BUNDLE_PATH, file); const stats = yield fs_1.default.promises.stat(location); return new tstl_1.Pair(relative, stats.isDirectory()); })); return (file) => __awaiter(void 0, void 0, void 0, function* () { for (const it of tuples) if (it.second === false && file === it.first) return true; else if (it.second === true && file.indexOf(it.first) === 0) return true; return false; }); })); //# sourceMappingURL=ConfigAnalyzer.js.map