@nestia/migrate 14.0.2 → 14.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/lib/_virtual/_rolldown/runtime.mjs +6 -1
  2. package/lib/bundles/NEST_TEMPLATE.js +1 -1
  3. package/lib/bundles/NEST_TEMPLATE.mjs +1 -1
  4. package/lib/bundles/SDK_TEMPLATE.js +1 -1
  5. package/lib/bundles/SDK_TEMPLATE.mjs +1 -1
  6. package/lib/executable/NestiaMigrateCommander.d.ts +4 -2
  7. package/lib/executable/NestiaMigrateCommander.js +5 -3
  8. package/lib/executable/NestiaMigrateCommander.js.map +1 -1
  9. package/lib/executable/NestiaMigrateCommander.mjs +2 -2
  10. package/lib/executable/NestiaMigrateInquirer.d.ts +6 -4
  11. package/lib/executable/NestiaMigrateInquirer.js +16 -13
  12. package/lib/executable/NestiaMigrateInquirer.js.map +1 -1
  13. package/lib/executable/NestiaMigrateInquirer.mjs +4 -3
  14. package/lib/executable/TemplateBundleCache.d.ts +23 -0
  15. package/lib/executable/TemplateBundleCache.js +60 -0
  16. package/lib/executable/TemplateBundleCache.js.map +1 -0
  17. package/lib/executable/TemplateBundleCache.mjs +39 -0
  18. package/lib/executable/TemplateBundleCache.mjs.map +1 -0
  19. package/lib/executable/bundle.d.ts +1 -0
  20. package/lib/executable/bundle.js +404 -0
  21. package/lib/executable/bundle.js.map +1 -0
  22. package/lib/executable/bundle.mjs +324 -0
  23. package/lib/executable/bundle.mjs.map +1 -0
  24. package/lib/package.mjs +55 -0
  25. package/lib/package.mjs.map +1 -0
  26. package/package.json +3 -3
  27. package/src/bundles/NEST_TEMPLATE.ts +1 -1
  28. package/src/bundles/SDK_TEMPLATE.ts +1 -1
  29. package/src/executable/NestiaMigrateCommander.ts +5 -3
  30. package/src/executable/NestiaMigrateInquirer.ts +9 -6
  31. package/src/executable/TemplateBundleCache.ts +65 -0
  32. package/src/executable/{bundle.js → bundle.ts} +110 -43
@@ -0,0 +1,324 @@
1
+ import { __require } from "../_virtual/_rolldown/runtime.mjs";
2
+ import { run } from "./TemplateBundleCache.mjs";
3
+ import { require_package } from "../package.mjs";
4
+ import fs from "node:fs";
5
+ import cp from "node:child_process";
6
+ //#region src/executable/bundle.ts
7
+ const { version } = require_package();
8
+ const ROOT = `${__dirname}/../..`;
9
+ const ASSETS = `${ROOT}/assets`;
10
+ const CATALOGS = __require("js-yaml").load(fs.readFileSync(`${__dirname}/../../../../pnpm-lock.yaml`, "utf8")).catalogs;
11
+ const TYPIA = CATALOGS.samchon;
12
+ const TYPESCRIPT = CATALOGS.typescript ?? {};
13
+ const update = (content, options = {}) => {
14
+ const parsed = JSON.parse(content);
15
+ for (const record of [parsed.dependencies ?? {}, parsed.devDependencies ?? {}]) for (const key of Object.keys(record)) {
16
+ const current = record[key];
17
+ if (typeof current === "string" && (current.startsWith("catalog:") || current.startsWith("workspace:"))) continue;
18
+ if (key.startsWith("@nestia/") || key === "nestia") record[key] = `^${version}`;
19
+ else {
20
+ const catalog = TYPIA[key] ?? TYPESCRIPT[key];
21
+ if (catalog) record[key] = catalog.specifier;
22
+ }
23
+ }
24
+ migratePackageJson(parsed);
25
+ if (options.sdkAggregate) {
26
+ parsed.devDependencies ??= {};
27
+ parsed.devDependencies["@nestia/core"] = `^${version}`;
28
+ }
29
+ return JSON.stringify(parsed, null, 2);
30
+ };
31
+ const migratePackageJson = (parsed) => {
32
+ if (parsed.scripts) {
33
+ for (const [key, value] of Object.entries(parsed.scripts)) if (typeof value === "string") parsed.scripts[key] = normalizeScript(value);
34
+ }
35
+ const devDependencies = parsed.devDependencies;
36
+ if (devDependencies) {
37
+ const usesTypeScript = typeof devDependencies.typescript === "string" && devDependencies.typescript.startsWith("catalog:") === false;
38
+ delete devDependencies["typescript-transform-paths"];
39
+ if (usesTypeScript && TYPESCRIPT.ttsc) devDependencies.ttsc ??= TYPESCRIPT.ttsc.specifier;
40
+ }
41
+ };
42
+ const updateWorkspaceCatalog = (content) => {
43
+ const replace = (line) => {
44
+ const match = line.match(/^(\s+(?:"([^"]+)"|'([^']+)'|([^:\s]+)): (?:&[A-Za-z0-9_-]+ )?)\S[^\r\n]*(\r?)$/);
45
+ if (match === null) return line;
46
+ const name = match[2] ?? match[3] ?? match[4];
47
+ const specifier = name === "nestia" || name.startsWith("@nestia/") ? `^${version}` : TYPIA[name]?.specifier ?? TYPESCRIPT[name]?.specifier;
48
+ if (typeof specifier !== "string") return line;
49
+ return `${match[1]}${specifier}${match[5]}`;
50
+ };
51
+ return content.split("\n").map(replace).join("\n");
52
+ };
53
+ const trimTemplateDependencies = (parsed) => {
54
+ if (parsed.dependencies) {
55
+ delete parsed.dependencies.commander;
56
+ delete parsed.dependencies.inquirer;
57
+ }
58
+ if (parsed.devDependencies) {
59
+ delete parsed.devDependencies["@types/inquirer"];
60
+ delete parsed.devDependencies.commander;
61
+ delete parsed.devDependencies.inquirer;
62
+ }
63
+ };
64
+ const normalizeScript = (script) => script.replace(/(^|[^A-Za-z0-9_-])tsc(?=$|[^A-Za-z0-9_-])/g, "$1ttsc");
65
+ const ARGUMENT_PARSER = `import { createInterface } from "node:readline/promises";
66
+
67
+ export namespace ArgumentParser {
68
+ export interface Command {
69
+ option: (flags: string, description?: string) => Command;
70
+ }
71
+
72
+ export interface Prompt {
73
+ select: (
74
+ name: string,
75
+ ) => (
76
+ message: string,
77
+ ) => <Choice extends string>(choices: Choice[]) => Promise<Choice>;
78
+ boolean: (name: string) => (message: string) => Promise<boolean>;
79
+ number: (name: string) => (message: string) => Promise<number>;
80
+ }
81
+
82
+ export const parse = async <T>(
83
+ inquiry: (
84
+ command: Command,
85
+ prompt: Prompt,
86
+ action: (closure: (options: Partial<T>) => Promise<T>) => Promise<T>,
87
+ ) => Promise<T>,
88
+ ): Promise<T> => {
89
+ const command: Command = {
90
+ option: (_flags: string, _description?: string): Command => command,
91
+ };
92
+ const action = (closure: (options: Partial<T>) => Promise<T>) =>
93
+ closure(parseArguments() as Partial<T>);
94
+ return inquiry(
95
+ command,
96
+ { select, boolean, number },
97
+ action,
98
+ );
99
+ };
100
+
101
+ const select =
102
+ (_name: string) =>
103
+ (message: string) =>
104
+ async <Choice extends string>(choices: Choice[]): Promise<Choice> => {
105
+ const answer: string = await ask(\`\${message} (\${choices.join("/")})\`);
106
+ return (choices.find((choice) => choice === answer) ?? choices[0])!;
107
+ };
108
+
109
+ const boolean = (_name: string) => async (message: string) =>
110
+ /^(true|t|yes|y|1)$/i.test(await ask(\`\${message} [y/N]\`));
111
+
112
+ const number = (_name: string) => async (message: string) =>
113
+ Number(await ask(message));
114
+
115
+ const ask = async (message: string): Promise<string> => {
116
+ const reader = createInterface({
117
+ input: process.stdin,
118
+ output: process.stdout,
119
+ });
120
+ try {
121
+ return (await reader.question(\`\${message}: \`)).trim();
122
+ } finally {
123
+ reader.close();
124
+ }
125
+ };
126
+
127
+ const parseArguments = (): Record<string, string | string[] | boolean> => {
128
+ const output: Record<string, string | string[] | boolean> = {};
129
+ const args: string[] = process.argv.slice(2);
130
+ for (let i = 0; i < args.length; ++i) {
131
+ const raw: string = args[i]!;
132
+ if (raw.startsWith("--") === false) continue;
133
+
134
+ const equal: number = raw.indexOf("=");
135
+ const name: string = toCamelCase(
136
+ raw.slice(2, equal === -1 ? undefined : equal),
137
+ );
138
+ if (equal !== -1) {
139
+ assign(output, name, raw.slice(equal + 1));
140
+ continue;
141
+ }
142
+
143
+ const values: string[] = [];
144
+ while (i + 1 < args.length && args[i + 1]!.startsWith("--") === false)
145
+ values.push(args[++i]!);
146
+ assign(
147
+ output,
148
+ name,
149
+ values.length === 0 ? true : values.length === 1 ? values[0]! : values,
150
+ );
151
+ }
152
+ return output;
153
+ };
154
+
155
+ const assign = (
156
+ output: Record<string, string | string[] | boolean>,
157
+ name: string,
158
+ value: string | string[] | boolean,
159
+ ): void => {
160
+ const current: string | string[] | boolean | undefined = output[name];
161
+ if (current === undefined) output[name] = value;
162
+ else
163
+ output[name] = [
164
+ ...(Array.isArray(current) ? current : [String(current)]),
165
+ ...(Array.isArray(value) ? value : [String(value)]),
166
+ ];
167
+ };
168
+
169
+ const toCamelCase = (str: string): string =>
170
+ str.replace(/-([a-z])/g, (_matched, letter: string) =>
171
+ letter.toUpperCase(),
172
+ );
173
+ }
174
+ `;
175
+ const updateTsConfig = (content) => {
176
+ content = content.replace(/^\s*\{\s*"transform":\s*"typescript-transform-paths"\s*\},\r?\n/gm, "");
177
+ content = content.replace(/^\s*\{\s*"transform":\s*"typia\/lib\/transform"(?:,\s*"enabled":\s*false)?\s*\},?\r?\n/gm, "");
178
+ content = content.replace(/^\s*\{\s*"transform":\s*"@nestia\/core\/lib\/transform"\s*\},?\r?\n/gm, "");
179
+ content = content.replace(/^\s*\{\s*"transform":\s*"@nestia\/core\/native\/transform\.cjs"\s*\},?\r?\n/gm, "");
180
+ content = content.replace(/^\s*\{\s*"transform":\s*"@nestia\/sdk\/lib\/transform"\s*\},\r?\n/gm, "");
181
+ return content;
182
+ };
183
+ const bundle = async ({ mode, repository, revision, exceptions, transform }) => {
184
+ const template = `${`${`${__dirname}/../..`}/assets`}/${mode}`;
185
+ const clone = async () => {
186
+ if (fs.existsSync(template)) await fs.promises.rm(template, { recursive: true });
187
+ else try {
188
+ await fs.promises.mkdir(ASSETS);
189
+ } catch {}
190
+ await fs.promises.mkdir(template, { recursive: true });
191
+ cp.execFileSync("git", ["init", "--quiet"], { cwd: template });
192
+ cp.execFileSync("git", [
193
+ "fetch",
194
+ "--quiet",
195
+ "--depth=1",
196
+ "--no-auto-maintenance",
197
+ `https://github.com/samchon/${repository}`,
198
+ revision
199
+ ], { cwd: template });
200
+ cp.execFileSync("git", [
201
+ "-c",
202
+ "core.autocrlf=false",
203
+ "checkout",
204
+ "--quiet",
205
+ "--detach",
206
+ revision
207
+ ], {
208
+ cwd: template,
209
+ stdio: "pipe"
210
+ });
211
+ for (const location of exceptions ?? []) await fs.promises.rm(`${template}/${location}`, { recursive: true });
212
+ };
213
+ const iterate = (collection) => async (location) => {
214
+ const directory = await fs.promises.readdir(location);
215
+ for (const file of directory) {
216
+ const absolute = location + "/" + file;
217
+ if ((await fs.promises.stat(absolute)).isDirectory()) await iterate(collection)(absolute);
218
+ else {
219
+ const content = await fs.promises.readFile(absolute, "utf-8");
220
+ collection[(() => {
221
+ const str = absolute.replace(template, "");
222
+ return str[0] === "/" ? str.substring(1) : str;
223
+ })()] = content;
224
+ }
225
+ }
226
+ };
227
+ const archive = async (collection) => {
228
+ const name = `${mode.toUpperCase()}_TEMPLATE`;
229
+ const content = `export const ${name}: Record<string, string> = ${JSON.stringify(collection, null, 2)}`;
230
+ try {
231
+ await fs.promises.mkdir(`${ROOT}/src/bundles`);
232
+ } catch {}
233
+ await fs.promises.writeFile(`${ROOT}/src/bundles/${name}.ts`, content, "utf8");
234
+ };
235
+ const collection = {};
236
+ await clone();
237
+ await iterate(collection)(template);
238
+ if (transform) for (const [key, value] of Object.entries(collection)) collection[key] = await writeTransformedAsset(template, key, transform(key, value));
239
+ await archive(collection);
240
+ };
241
+ const writeTransformedAsset = async (template, key, value) => {
242
+ await fs.promises.writeFile(`${template}/${key}`, value, "utf8");
243
+ return value;
244
+ };
245
+ /**
246
+ * Generates both pinned templates using the current release and catalog stamps.
247
+ *
248
+ * The complete script is a cache input because it contains the revisions,
249
+ * exclusions and every transformation rule. A hit still verifies output bytes.
250
+ */
251
+ const generate = async () => {
252
+ await bundle({
253
+ mode: "nest",
254
+ repository: "nestia-start",
255
+ revision: "8188661cb1c1b0fb30e6184b06422764d64a5f68",
256
+ exceptions: [
257
+ ".git",
258
+ ".github/dependabot.yml",
259
+ ".github/workflows/dependabot-automerge.yml",
260
+ "pnpm-lock.yaml",
261
+ "packages/api/src/functional",
262
+ "packages/api/src/structures",
263
+ "packages/backend/src/MyModule.ts",
264
+ "packages/backend/src/controllers",
265
+ "packages/backend/src/providers",
266
+ "packages/backend/test/features"
267
+ ],
268
+ transform: (key, value) => {
269
+ if (key.endsWith("package.json")) {
270
+ const parsed = JSON.parse(update(value));
271
+ trimTemplateDependencies(parsed);
272
+ return JSON.stringify(parsed, null, 2);
273
+ }
274
+ if (key === "pnpm-workspace.yaml") return updateWorkspaceCatalog(value);
275
+ if (key === "packages/backend/test/helpers/ArgumentParser.ts") return ARGUMENT_PARSER;
276
+ if (key.endsWith("tsconfig.json")) return updateTsConfig(value);
277
+ return value;
278
+ }
279
+ });
280
+ await bundle({
281
+ mode: "sdk",
282
+ repository: "nestia-sdk-template",
283
+ revision: "37a019e2b8dea3d02237137aaec2f242f53dcd2d",
284
+ exceptions: [
285
+ ".git",
286
+ ".github/dependabot.yml",
287
+ ".github/workflows/build.yml",
288
+ ".github/workflows/dependabot-automerge.yml",
289
+ "pnpm-lock.yaml",
290
+ "src/functional",
291
+ "src/structures",
292
+ "test/features"
293
+ ],
294
+ transform: (key, value) => {
295
+ if (key.endsWith("package.json")) {
296
+ const parsed = JSON.parse(update(value, { sdkAggregate: key === "package.json" }));
297
+ trimTemplateDependencies(parsed);
298
+ return JSON.stringify(parsed, null, 2);
299
+ }
300
+ if (key === "test/utils/ArgumentParser.ts") return ARGUMENT_PARSER;
301
+ if (key.endsWith("tsconfig.json")) return updateTsConfig(value);
302
+ return value;
303
+ }
304
+ });
305
+ };
306
+ const main = async () => {
307
+ if (await run({
308
+ inputs: [
309
+ version,
310
+ CATALOGS,
311
+ fs.readFileSync(__filename, "utf8")
312
+ ],
313
+ outputs: ["NEST_TEMPLATE", "SDK_TEMPLATE"].map((name) => `${ROOT}/src/bundles/${name}.ts`),
314
+ stampFile: `${ASSETS}/.bundle-cache.json`,
315
+ generate
316
+ })) console.log("Reuse verified migration template bundles.");
317
+ };
318
+ main().catch((exp) => {
319
+ console.error(exp);
320
+ process.exit(-1);
321
+ });
322
+ //#endregion
323
+
324
+ //# sourceMappingURL=bundle.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundle.mjs","names":[],"sources":[],"mappings":""}
@@ -0,0 +1,55 @@
1
+ import { __commonJSMin } from "./_virtual/_rolldown/runtime.mjs";
2
+ //#region ../../package.json
3
+ var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4
+ module.exports = {
5
+ "private": true,
6
+ "name": "@nestia/station",
7
+ "version": "14.0.3",
8
+ "description": "Nestia station",
9
+ "scripts": {
10
+ "build": "pnpm --filter=./packages/* -r build",
11
+ "evidence": "pnpm --filter=./config --filter=./packages/* --filter=./tests/* -r --no-bail --workspace-concurrency=1 run evidence",
12
+ "evidence:tests": "pnpm --filter=./tests/* --fail-if-no-match -r --no-bail --workspace-concurrency=1 run evidence",
13
+ "format": "prettier --write \"packages/**/*.ts\" \"tests/**/*.ts\"",
14
+ "format:check": "prettier --check \"packages/**/*.ts\" \"tests/**/*.ts\"",
15
+ "test": "pnpm build && pnpm evidence && pnpm test:go && pnpm test:unit && pnpm test:e2e",
16
+ "package:prepare": "pnpm build && node deploy/copy-readme.cjs",
17
+ "package:latest": "pnpm package:prepare && pnpm --filter=./packages/* -r publish --tag latest",
18
+ "package:next": "pnpm package:prepare && pnpm --filter=./packages/* -r publish --tag next",
19
+ "package:rc": "pnpm package:prepare && pnpm --filter=./packages/* -r publish --tag rc",
20
+ "package:tgz": "pnpm package:prepare && node deploy/tarballs",
21
+ "release": "rimraf packages/migrate/assets && bumpp -r",
22
+ "test:unit": "pnpm --filter=./packages/* --filter=./tests/* -r --no-bail --if-present run test:unit",
23
+ "test:go": "ttsx --no-plugins --tsconfig config/tsconfig.json config/testing/CompilerEnvironment.ts",
24
+ "test:e2e": "pnpm --filter=@nestia/test-sdk --fail-if-no-match integration"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/samchon/nestia"
29
+ },
30
+ "author": "Jeongho Nam",
31
+ "license": "MIT",
32
+ "bugs": { "url": "https://github.com/samchon/nestia/issues" },
33
+ "homepage": "https://nestia.io",
34
+ "devDependencies": {
35
+ "@trivago/prettier-plugin-sort-imports": "catalog:typescript",
36
+ "@wrtnlabs/evidence": "catalog:samchon",
37
+ "@types/ts-expose-internals": "npm:ts-expose-internals@5.4.5",
38
+ "bumpp": "^10.4.1",
39
+ "cross-env": "catalog:utils",
40
+ "prettier": "catalog:typescript",
41
+ "prettier-plugin-jsdoc": "catalog:typescript",
42
+ "rimraf": "catalog:utils",
43
+ "sloc": "^0.3.0",
44
+ "ttsc": "catalog:typescript",
45
+ "typescript": "catalog:typescript",
46
+ "yaml": "catalog:utils"
47
+ },
48
+ "packageManager": "pnpm@10.6.4"
49
+ };
50
+ }));
51
+ //#endregion
52
+ export default require_package();
53
+ export { require_package };
54
+
55
+ //# sourceMappingURL=package.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package.mjs","names":[],"sources":["../../../package.json"],"sourcesContent":[""],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestia/migrate",
3
- "version": "14.0.2",
3
+ "version": "14.0.3",
4
4
  "description": "Migration program from swagger to NestJS",
5
5
  "main": "lib/index.js",
6
6
  "bin": {
@@ -67,8 +67,8 @@
67
67
  "access": "public"
68
68
  },
69
69
  "scripts": {
70
- "build": "pnpm run bundle && rimraf lib && ttsc && tsc --emitDeclarationOnly && rolldown -c",
71
- "bundle": "node src/executable/bundle.js",
70
+ "build": "pnpm run bundle && rimraf lib && ttsc && rolldown -c",
71
+ "bundle": "cross-env NODE_OPTIONS=\"--no-experimental-strip-types --no-experimental-detect-module\" ttsx --no-plugins --tsconfig tsconfig.bundle.json src/executable/bundle.ts",
72
72
  "dev": "rimraf lib && ttsc --watch",
73
73
  "test": "node lib/test",
74
74
  "evidence": "evidence"
@@ -49,6 +49,6 @@ export const NEST_TEMPLATE: Record<string, string> = {
49
49
  "packages/backend/test/webpack.ts": "import { DynamicExecutor } from \"@nestia/e2e\";\nimport cp from \"node:child_process\";\nimport { sleep_for } from \"tstl\";\n\nimport { MyConfiguration } from \"../src/MyConfiguration\";\nimport { MyGlobal } from \"../src/MyGlobal\";\nimport { TestAutomation } from \"./helpers/TestAutomation\";\nimport { TestAutomationStdio } from \"./helpers/TestAutomationStdio\";\n\nconst wait = async (): Promise<void> => {\n while (true)\n try {\n await fetch(`http://localhost:${MyConfiguration.API_PORT()}/dsafdsafsd`);\n return;\n } catch (exp) {\n await sleep_for(100);\n }\n};\n\nconst main = async (): Promise<void> => {\n MyGlobal.testing = true;\n\n const report: DynamicExecutor.IReport = await TestAutomation.execute({\n open: async () => {\n const backend: cp.ChildProcess = cp.fork(\n `${MyConfiguration.ROOT}/dist/server.js`,\n {\n cwd: `${MyConfiguration.ROOT}/dist`,\n },\n );\n await wait();\n return backend;\n },\n close: async (backend) => {\n backend.kill();\n },\n options: await TestAutomationStdio.getOptions(),\n onComplete: TestAutomationStdio.onComplete,\n });\n TestAutomationStdio.report(report);\n};\nmain().catch((exp: unknown) => {\n console.log(exp);\n process.exit(-1);\n});\n",
50
50
  "packages/backend/tsconfig.json": "{\n \"extends\": \"../../config/tsconfig.json\",\n \"compilerOptions\": {\n \"outDir\": \"lib\",\n \"rootDir\": \"src\",\n \"experimentalDecorators\": true,\n \"emitDecoratorMetadata\": true\n },\n \"include\": [\"src\"]\n}\n",
51
51
  "packages/backend/webpack.config.js": "const path = require(\"path\");\n\nconst CopyWebpackPlugin = require(\"copy-webpack-plugin\");\nconst WriteFilePlugin = require(\"write-file-webpack-plugin\");\nconst { IgnorePlugin } = require(\"webpack\");\n\nconst lazyImports = [\n \"@modelcontextprotocol/sdk\",\n \"@fastify/static\",\n \"@fastify/view\",\n \"@nestjs/microservices\",\n \"@nestjs/websockets\",\n \"class-transformer\",\n \"class-validator\",\n];\n\n// @reference https://tech-blog.s-yoshiki.com/entry/297\nmodule.exports = {\n // CUSTOMIZE HERE\n entry: {\n server: \"./lib/executable/server.js\",\n },\n output: {\n path: path.join(__dirname, \"dist\"),\n filename: \"[name].js\",\n },\n optimization: {\n minimize: true,\n },\n\n // JUST KEEP THEM\n mode: \"production\",\n target: \"node\",\n plugins: [\n new CopyWebpackPlugin({\n patterns: [\n {\n from: \".env\",\n to: \"[name][ext]\",\n },\n ],\n }),\n new WriteFilePlugin(),\n new IgnorePlugin({\n checkResource: (resource) => {\n if (lazyImports.some((modulo) => resource.startsWith(modulo))) {\n try {\n require.resolve(resource);\n } catch (err) {\n return true;\n }\n }\n return false;\n },\n }),\n ],\n};\n",
52
- "pnpm-workspace.yaml": "packages:\n - \"config\"\n - \"packages/*\"\ncatalogs:\n samchon:\n \"@nestia/benchmark\": ^14.0.2\n \"@nestia/core\": ^14.0.2\n \"@nestia/e2e\": ^14.0.2\n \"@nestia/fetcher\": ^14.0.2\n \"@nestia/sdk\": ^14.0.2\n nestia: ^14.0.2\n tgrid: ^1.2.1\n tstl: ^3.0.0\n typia: 15.0.0\n rolldown:\n rolldown: ^1.1.5\n utils:\n rimraf: ^6.1.3\n uuid: ^13.0.0\n typescript:\n \"@ttsc/lint\": ^0.18.2\n \"@ttsc/paths\": ^0.18.2\n \"@ttsc/unplugin\": ^0.28.1\n ttsc: ^0.28.1\n typescript: ^7.0.2\n",
52
+ "pnpm-workspace.yaml": "packages:\n - \"config\"\n - \"packages/*\"\ncatalogs:\n samchon:\n \"@nestia/benchmark\": ^14.0.3\n \"@nestia/core\": ^14.0.3\n \"@nestia/e2e\": ^14.0.3\n \"@nestia/fetcher\": ^14.0.3\n \"@nestia/sdk\": ^14.0.3\n nestia: ^14.0.3\n tgrid: ^1.2.1\n tstl: ^3.0.0\n typia: 15.0.0\n rolldown:\n rolldown: ^1.1.5\n utils:\n rimraf: ^6.1.3\n uuid: ^13.0.0\n typescript:\n \"@ttsc/lint\": ^0.18.2\n \"@ttsc/paths\": ^0.18.2\n \"@ttsc/unplugin\": ^0.28.1\n ttsc: ^0.28.1\n typescript: ^7.0.2\n",
53
53
  "typos.toml": "[default]\nlocale = 'en-us'\nextend-ignore-re = [\n \"(?Rm)^.*(<!--|#|//)\\\\s*spellchecker:disable-line(-->|\\n)?$\",\n \"(?s)(<!--|#|//)\\\\s*spellchecker:off\\\\s*(-->|\\n).*?(<!--|#|//)\\\\s*spellchecker:on\",\n]\n\n[default.extend-words]\nJeongho = \"Jeongho\"\nNam = \"Nam\"\ntypia = \"typia\"\n\n[files]\nextend-exclude = [\"*.json\"]"
54
54
  }
@@ -5,7 +5,7 @@ export const SDK_TEMPLATE: Record<string, string> = {
5
5
  "LICENSE": "MIT License\n\nCopyright (c) 2024 Jeongho Nam\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n",
6
6
  "README.md": "# Software Development Kit\nThis is a SDK library generated by [`@nestia/migrate`](https://nestia.io/docs/migrate) or [`@nestia/editor`](https://nestia.io/docs/editor).\n\nWith this SDK library, you can easily and safely interact with backend server.\n\nJust import and call some API functions like gif image below:\n\n![nestia-sdk-demo](https://user-images.githubusercontent.com/13158709/215004990-368c589d-7101-404e-b81b-fbc936382f05.gif)\n\n> Left is server code, and right is client code utilizing the SDK\n\n\n\n\n## How to Test\n```bash\npnpm install\npnpm run start # run only \"test/start.ts\" file\npnpm run test # everything under the \"test/features\" directory\npnpm run test:simulate # \"test/features\" with mockup simulation mode\n```\n\nIf you run `pnpm run start` command, only [test/start.ts](test/start.ts) file would be executed.\n\nOtherwise you run `pnpm run test` command instead, run everything in the [test/features](test/features) directory.\n\nFor reference, the [test/features](test/features) directory and E2E test functions (for each API endpoints) would be automatically composed only when you've configured the \"E2E test function generation mode\" of the `@nestia/migrate` (or `@nestia/editor`).\n\n```bash\npnpm dlx @nestia/migrate\n? Migration mode (Use arrow keys):\n NestJS\n > SDK\n? Swagger file location: assets/input/clickhouse.json\n? Output directory path: assets/output/clickhouse-sdk-manual\n? Mokup Simulator: true\n? E2E Test Functions: true\n```\n\n\n\n\n## Deploy\n```bash\npnpm install\npnpm run deploy\n```\n\nJust run `pnpm run deploy` command, then your SDK library would be published.\n\nBy the way, the initial package name of this template repository is `@ORGANIZATION/PROJECT-api`. I think it would better to change the word to your own organization and project name. If you're utilizing `VsCode`, you can do it through `Edit > Replace in Files` (*Ctrl + Shift + H*) feature.\n\n-----------\n\n> ## What [`Nestia`](https://nestia.io) is:\n> ![Nestia Logo](https://nestia.io/logo.png)\n> \n> [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/samchon/nestia/blob/master/LICENSE)\n> [![npm version](https://img.shields.io/npm/v/@nestia/core.svg)](https://www.npmjs.com/package/@nestia/core)\n> [![Downloads](https://img.shields.io/npm/dm/@nestia/core.svg)](https://www.npmjs.com/package/@nestia/core)\n> [![Build Status](https://github.com/samchon/nestia/workflows/build/badge.svg)](https://github.com/samchon/nestia/actions?query=workflow%3Abuild)\n> [![Guide Documents](https://img.shields.io/badge/guide-documents-forestgreen)](https://nestia.io/docs/)\n> \n> Nestia is a set of helper libraries for NestJS, supporting below features:\n> \n> - `@nestia/core`: Super-fast decorators\n> - `@nestia/sdk`:\n> - Swagger generator evolved than ever\n> - SDK library generator for clients\n> - Mockup Simulator for client applications\n> - Automatic E2E test functions generator\n> - `@nestia/migrate`: Migration from Swagger to NestJS\n> - `@nestia/editor`: Online TypeScript Swagger Editor\n> - `nestia`: Just CLI (command line interface) tool\n> \n>> **Note**\n>> \n>> - **Only one line** required, with pure TypeScript type\n>> - Enhance performance **30x** up\n>> - Runtime validator is **20,000x faster** than `class-validator`\n>> - JSON serialization is **200x faster** than `class-transformer`\n>> - Software Development Kit\n>> - SDK is a collection of `fetch` functions with type definitions like [tRPC](https://> trpc.io/)\n>> - Mockup simulator means embedded backend simulator in SDK\n>> - similar with [msw](https://mswjs.io/), but fully automated\n",
7
7
  "hello.js": "function print(command, description) {\n return console.log(`\\x1b[1m${command}\\x1b[2m: ${description}\\x1b[0m`);\n}\n\nconsole.log(\"-----------------------------------------\");\nconsole.log(\"\\x1b[7mGenerated by \\x1b[2m@nestia/editor\\x1b[0m\");\nconsole.log(\"\");\nconsole.log(\" - \\x1b[36mhttps://nestia.io/docs/editor\\x1b[0m\");\nconsole.log(\" - \\x1b[36mhttps://github.com/samchon/nestia\\x1b[0m\");\nconsole.log(\"-----------------------------------------\");\n\nprint(\"pnpm run start\", \"Run only test/start.ts\");\nprint(\"pnpm run test\", \"Run every test/features/**/*.ts files\");\nprint(\"pnpm run test:simulate\", \"Test with mockup simulator\");\n",
8
- "package.json": "{\n \"name\": \"@ORGANIZATION/PROJECT-api\",\n \"version\": \"0.1.0\",\n \"description\": \"SDK library generated by Nestia\",\n \"main\": \"src/index.ts\",\n \"exports\": {\n \".\": \"./src/index.ts\",\n \"./lib/*\": \"./src/*.ts\",\n \"./package.json\": \"./package.json\"\n },\n \"publishConfig\": {\n \"main\": \"lib/index.mjs\",\n \"module\": \"lib/index.mjs\",\n \"types\": \"lib/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./lib/index.d.ts\",\n \"import\": \"./lib/index.mjs\",\n \"default\": \"./lib/index.js\"\n },\n \"./lib/*\": {\n \"types\": \"./lib/*.d.ts\",\n \"import\": \"./lib/*.mjs\",\n \"default\": \"./lib/*.js\"\n },\n \"./package.json\": \"./package.json\"\n }\n },\n \"scripts\": {\n \"build\": \"rimraf lib && ttsc && rolldown -c\",\n \"build:test\": \"rimraf bin && ttsc --project test/tsconfig.json\",\n \"deploy\": \"pnpm run build && pnpm publish\",\n \"dev\": \"pnpm run build:test --watch\",\n \"hello\": \"node hello\",\n \"start\": \"ttsx test/start.ts\",\n \"swagger\": \"ttsx test/swagger.ts\",\n \"test\": \"ttsx test/index.ts\",\n \"test:simulate\": \"ttsx test/index.ts --simulate true\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/samchon/nestia\"\n },\n \"author\": \"Jeongho Nam\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/samchon/nestia/issues\"\n },\n \"homepage\": \"https://nestia.io\",\n \"files\": [\n \"lib\",\n \"swagger.json\",\n \"package.json\",\n \"README.md\"\n ],\n \"dependencies\": {\n \"@nestia/fetcher\": \"^14.0.2\",\n \"tgrid\": \"^1.2.1\",\n \"typia\": \"15.0.0\"\n },\n \"devDependencies\": {\n \"@nestia/e2e\": \"^14.0.2\",\n \"@ttsc/unplugin\": \"^0.28.1\",\n \"@types/express\": \"^4.17.21\",\n \"@types/swagger-ui-express\": \"^4.1.6\",\n \"chalk\": \"4.1.2\",\n \"express\": \"^4.19.2\",\n \"rimraf\": \"^5.0.5\",\n \"rolldown\": \"^1.1.5\",\n \"swagger-ui-express\": \"^5.0.0\",\n \"tinyglobby\": \"^0.2.17\",\n \"ttsc\": \"^0.28.1\",\n \"typescript\": \"^7.0.2\",\n \"@nestia/core\": \"^14.0.2\"\n },\n \"packageManager\": \"pnpm@10.19.0\"\n}",
8
+ "package.json": "{\n \"name\": \"@ORGANIZATION/PROJECT-api\",\n \"version\": \"0.1.0\",\n \"description\": \"SDK library generated by Nestia\",\n \"main\": \"src/index.ts\",\n \"exports\": {\n \".\": \"./src/index.ts\",\n \"./lib/*\": \"./src/*.ts\",\n \"./package.json\": \"./package.json\"\n },\n \"publishConfig\": {\n \"main\": \"lib/index.mjs\",\n \"module\": \"lib/index.mjs\",\n \"types\": \"lib/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./lib/index.d.ts\",\n \"import\": \"./lib/index.mjs\",\n \"default\": \"./lib/index.js\"\n },\n \"./lib/*\": {\n \"types\": \"./lib/*.d.ts\",\n \"import\": \"./lib/*.mjs\",\n \"default\": \"./lib/*.js\"\n },\n \"./package.json\": \"./package.json\"\n }\n },\n \"scripts\": {\n \"build\": \"rimraf lib && ttsc && rolldown -c\",\n \"build:test\": \"rimraf bin && ttsc --project test/tsconfig.json\",\n \"deploy\": \"pnpm run build && pnpm publish\",\n \"dev\": \"pnpm run build:test --watch\",\n \"hello\": \"node hello\",\n \"start\": \"ttsx test/start.ts\",\n \"swagger\": \"ttsx test/swagger.ts\",\n \"test\": \"ttsx test/index.ts\",\n \"test:simulate\": \"ttsx test/index.ts --simulate true\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/samchon/nestia\"\n },\n \"author\": \"Jeongho Nam\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/samchon/nestia/issues\"\n },\n \"homepage\": \"https://nestia.io\",\n \"files\": [\n \"lib\",\n \"swagger.json\",\n \"package.json\",\n \"README.md\"\n ],\n \"dependencies\": {\n \"@nestia/fetcher\": \"^14.0.3\",\n \"tgrid\": \"^1.2.1\",\n \"typia\": \"15.0.0\"\n },\n \"devDependencies\": {\n \"@nestia/e2e\": \"^14.0.3\",\n \"@ttsc/unplugin\": \"^0.28.1\",\n \"@types/express\": \"^4.17.21\",\n \"@types/swagger-ui-express\": \"^4.1.6\",\n \"chalk\": \"4.1.2\",\n \"express\": \"^4.19.2\",\n \"rimraf\": \"^5.0.5\",\n \"rolldown\": \"^1.1.5\",\n \"swagger-ui-express\": \"^5.0.0\",\n \"tinyglobby\": \"^0.2.17\",\n \"ttsc\": \"^0.28.1\",\n \"typescript\": \"^7.0.2\",\n \"@nestia/core\": \"^14.0.3\"\n },\n \"packageManager\": \"pnpm@10.19.0\"\n}",
9
9
  "rolldown.config.mjs": "import ttsc from \"@ttsc/unplugin/rolldown\";\nimport path from \"node:path\";\nimport { globSync } from \"tinyglobby\";\n\nexport default {\n input: globSync(\"./src/**/*.ts\"),\n external: (id) => !id.startsWith(\".\") && !path.isAbsolute(id),\n output: {\n dir: \"./lib\",\n format: \"esm\",\n sourcemap: true,\n entryFileNames: \"[name].mjs\",\n preserveModules: true,\n preserveModulesRoot: \"src\",\n },\n plugins: [ttsc()],\n};\n",
10
10
  "src/HttpError.ts": "export { HttpError } from \"@nestia/fetcher\";\n",
11
11
  "src/IConnection.ts": "export type { IConnection } from \"@nestia/fetcher\";\n",
@@ -41,7 +41,9 @@ export namespace NestiaMigrateCommander {
41
41
  *
42
42
  * It stops with an error when the output directory exists, when its parent
43
43
  * does not exist or is not a directory, when the input cannot be read or
44
- * fetched, or when the document is invalid.
44
+ * fetched, or when the document is invalid. Explicit arguments follow Node's
45
+ * executable/script/flags layout; omitting them reads the current process
46
+ * arguments.
45
47
  *
46
48
  * Creation and writing use `fs.promises` through the injected archiver, so
47
49
  * the volume decides case policy and permissions, and the checks that precede
@@ -52,11 +54,11 @@ export namespace NestiaMigrateCommander {
52
54
  * @evidence contracts/common.md#prohibited-implementation-shortcuts The checks apply to every input, and a formatting failure keeps the original text.
53
55
  * @evidence contracts/common.md#meaningful-documentation The comment states the conditions under which it stops.
54
56
  */
55
- export const main = async (): Promise<void> => {
57
+ export const main = async (argv?: string[]): Promise<void> => {
56
58
  const resolve = (str: string | undefined) =>
57
59
  str ? path.resolve(str).split("\\").join("/") : undefined;
58
60
  const options: NestiaMigrateInquirer.IOutput =
59
- await NestiaMigrateInquirer.parse();
61
+ await NestiaMigrateInquirer.parse(argv);
60
62
 
61
63
  // VALIDATE OUTPUT DIRECTORY
62
64
  const parent: string = resolve(options.output + "/..")!;
@@ -1,4 +1,4 @@
1
- import { program } from "commander";
1
+ import { Command } from "commander";
2
2
  import { createPromptModule } from "inquirer";
3
3
 
4
4
  /**
@@ -34,14 +34,17 @@ export namespace NestiaMigrateInquirer {
34
34
  * Parses the flags and asks for the missing options.
35
35
  *
36
36
  * A boolean flag given without a value is `true`, and one given a value is
37
- * true only for the text `true`.
37
+ * true only for the text `true`. Each invocation owns its parser; explicit
38
+ * arguments use Node's executable/script/flags layout and default to the
39
+ * current process arguments.
38
40
  *
39
- * @evidence contracts/common.md#principled-implementation Commander parses the flags, the action asks a prompt for each undefined option, and boolean flags are normalized by one rule, so the result has every field set.
40
- * @evidence contracts/common.md#clear-and-simple-design One function that wires the parser and the prompts around one action.
41
+ * @evidence contracts/common.md#principled-implementation A fresh Commander parser interprets the supplied Node-style arguments, the action asks a prompt for each undefined option, and boolean flags are normalized by one rule, so the result has every field set without retaining another invocation's options.
42
+ * @evidence contracts/common.md#clear-and-simple-design One invocation owns the parser and prompt action; the optional argument vector defaults to the ordinary process input.
41
43
  * @evidence contracts/common.md#prohibited-implementation-shortcuts It asks only for what is missing.
42
44
  * @evidence contracts/common.md#meaningful-documentation The comment states the boolean flag rule.
43
45
  */
44
- export const parse = async (): Promise<IOutput> => {
46
+ export const parse = async (argv?: string[]): Promise<IOutput> => {
47
+ const program = new Command();
45
48
  // PREPARE ASSETS
46
49
  program.option("--mode [nest/sdk]", "migration mode");
47
50
  program.option(
@@ -65,7 +68,7 @@ export namespace NestiaMigrateInquirer {
65
68
  reject(exp);
66
69
  }
67
70
  });
68
- program.parseAsync().catch(reject);
71
+ program.parseAsync(argv).catch(reject);
69
72
  });
70
73
  const select =
71
74
  (name: string) =>
@@ -0,0 +1,65 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+
4
+ /**
5
+ * Reuses a complete template generation only while its inputs and outputs
6
+ * match.
7
+ *
8
+ * The caller owns the generated paths and cold generation. This module owns the
9
+ * validity manifest; failed generation never publishes a new manifest.
10
+ * Concurrent generation of the same output paths is not supported.
11
+ *
12
+ * @evidence contracts/common.md#principled-implementation Input identity includes the cache implementation and caller-supplied generator inputs. Reuse requires every expected output's current SHA-256 to match the manifest; a missing, changed or partial generation cannot authorize reuse.
13
+ * @evidence contracts/common.md#clear-and-simple-design One operation checks a manifest, delegates cold generation and publishes its successful output digests. The caller retains template-specific fetching and stamping rules.
14
+ * @evidence contracts/common.md#prohibited-implementation-shortcuts Generated contents are never replaced by expected answers. Invalid metadata is treated as a cache miss and failed generation remains a rejection.
15
+ * @evidence contracts/common.md#meaningful-documentation Documents manifest ownership, failed publication and the existing single-writer premise.
16
+ * @evidence contracts/performance.md#efficient-algorithms A hit hashes each output once, with time proportional to input/output bytes and one manifest rather than scanning template trees or fetching Git history.
17
+ * @evidence contracts/performance.md#reuse-equivalent-work The cache implementation, caller inputs and current output digests jointly establish reuse validity; changed inputs, edited outputs and missing files invalidate it.
18
+ * @evidence contracts/performance.md#bound-retention-and-release-resources Each output set owns one replaceable manifest, not per-run history. Synchronous reads and awaited writes close their file handles. The caller must serialize writers to the same paths.
19
+ * @evidence contracts/portability.md#os-neutral-implementation Node fs consumes caller-owned native paths; identity hashes bytes and never assumes timestamp resolution, case folding or path separators.
20
+ */
21
+ export const run = async ({
22
+ inputs,
23
+ outputs,
24
+ stampFile,
25
+ generate,
26
+ }: {
27
+ inputs: readonly unknown[];
28
+ outputs: readonly string[];
29
+ stampFile: string;
30
+ generate: () => Promise<void>;
31
+ }): Promise<boolean> => {
32
+ const digest = (content: string | Buffer): string =>
33
+ crypto.createHash("sha256").update(content).digest("hex");
34
+ const input = digest(
35
+ JSON.stringify([fs.readFileSync(__filename, "utf8"), inputs]),
36
+ );
37
+ let stamp: { input?: string; outputs?: string[] } | undefined;
38
+ if (fs.existsSync(stampFile)) {
39
+ try {
40
+ stamp = JSON.parse(fs.readFileSync(stampFile, "utf8"));
41
+ } catch {
42
+ // Invalid or interrupted metadata cannot authorize reuse.
43
+ }
44
+ }
45
+ if (
46
+ outputs.length !== 0 &&
47
+ stamp?.input === input &&
48
+ outputs.every(
49
+ (file, index) =>
50
+ fs.existsSync(file) &&
51
+ stamp.outputs?.[index] === digest(fs.readFileSync(file)),
52
+ )
53
+ )
54
+ return true;
55
+ await generate();
56
+ await fs.promises.writeFile(
57
+ stampFile,
58
+ JSON.stringify({
59
+ input,
60
+ outputs: outputs.map((file) => digest(fs.readFileSync(file))),
61
+ }),
62
+ "utf8",
63
+ );
64
+ return false;
65
+ };