typia 13.3.0 → 14.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/lib/internal/_randomPattern.js +20 -3
  2. package/lib/internal/_randomPattern.js.map +1 -1
  3. package/lib/internal/_randomPattern.mjs +5 -1
  4. package/lib/internal/_randomPattern.mjs.map +1 -1
  5. package/lib/internal/_randomStringLength.js +9 -2
  6. package/lib/internal/_randomStringLength.js.map +1 -1
  7. package/lib/internal/_randomStringLength.mjs +3 -1
  8. package/lib/internal/_randomStringLength.mjs.map +1 -1
  9. package/lib/transform.mjs +1 -1
  10. package/native/cmd/ttsc-typia/dynamic_key_tags_transform_test.go +206 -0
  11. package/native/cmd/ttsc-typia/notation_kebab_case_transform_test.go +2 -2
  12. package/native/cmd/ttsc-typia/project_catalog_transform_coverage_test.go +84 -85
  13. package/native/cmd/ttsc-typia/template_literal_type_tags_transform_test.go +3 -1
  14. package/native/cmd/ttsc-typia/transform.go +2 -2
  15. package/native/cmd/ttsc-typia/transform_helpers_test.go +12 -0
  16. package/native/core/factories/MetadataCommentTagFactory.go +96 -27
  17. package/native/core/factories/metadata_comment_tag_factory_coverage_test.go +2 -2
  18. package/native/core/factories/metadata_comment_tag_factory_rejects_out_of_range_integer_test.go +124 -0
  19. package/native/core/programmers/AssertProgrammer.go +20 -6
  20. package/native/core/programmers/RandomProgrammer.go +78 -6
  21. package/native/core/programmers/ValidateProgrammer.go +21 -6
  22. package/native/core/programmers/helpers/RandomJoiner.go +8 -1
  23. package/native/core/programmers/iterate/check_dynamic_properties.go +177 -3
  24. package/native/core/programmers/iterate/check_object.go +12 -1
  25. package/package.json +3 -12
  26. package/src/internal/_randomPattern.ts +18 -3
  27. package/src/internal/_randomStringLength.ts +9 -2
  28. package/lib/executable/FileSystemIdentity.d.ts +0 -44
  29. package/lib/executable/FileSystemIdentity.js +0 -213
  30. package/lib/executable/FileSystemIdentity.js.map +0 -1
  31. package/lib/executable/FileSystemIdentity.mjs +0 -133
  32. package/lib/executable/FileSystemIdentity.mjs.map +0 -1
  33. package/lib/executable/TypiaGenerateWizard.d.ts +0 -9
  34. package/lib/executable/TypiaGenerateWizard.js +0 -852
  35. package/lib/executable/TypiaGenerateWizard.js.map +0 -1
  36. package/lib/executable/TypiaGenerateWizard.mjs +0 -618
  37. package/lib/executable/TypiaGenerateWizard.mjs.map +0 -1
  38. package/lib/executable/generate/ttsc.d.ts +0 -1
  39. package/lib/executable/generate/ttsc.js +0 -53
  40. package/lib/executable/generate/ttsc.js.map +0 -1
  41. package/lib/executable/generate/ttsc.mjs +0 -37
  42. package/lib/executable/generate/ttsc.mjs.map +0 -1
  43. package/lib/executable/typia.d.ts +0 -2
  44. package/lib/executable/typia.js +0 -84
  45. package/lib/executable/typia.js.map +0 -1
  46. package/lib/executable/typia.mjs +0 -60
  47. package/lib/executable/typia.mjs.map +0 -1
  48. package/src/executable/FileSystemIdentity.ts +0 -222
  49. package/src/executable/TypiaGenerateWizard.ts +0 -1133
  50. package/src/executable/generate/ttsc.ts +0 -70
  51. package/src/executable/typia.ts +0 -80
@@ -1,1133 +0,0 @@
1
- import { createCommand } from "commander";
2
- import fs from "fs";
3
- import inquirer from "inquirer";
4
- import { createRequire } from "module";
5
- import os from "os";
6
- import path from "path";
7
- import { glob, isDynamicPattern } from "tinyglobby";
8
- import type {
9
- ITtscCompilerDiagnostic,
10
- ITtscCompilerTransformation,
11
- } from "ttsc";
12
-
13
- import { FileSystemIdentity } from "./FileSystemIdentity";
14
-
15
- export namespace TypiaGenerateWizard {
16
- export async function generate(): Promise<void> {
17
- console.log("----------------------------------------");
18
- console.log(" Typia Generate Wizard");
19
- console.log("----------------------------------------");
20
-
21
- const options: IArguments = await parseArguments();
22
- await build(options);
23
- }
24
-
25
- async function parseArguments(): Promise<IArguments> {
26
- const command = createCommand("typia generate");
27
- command.usage("[options] [files...]");
28
- command.argument("[files...]", "input TypeScript source files or globs");
29
- command.option("--input <path>", "input directory");
30
- command.option("--output <directory>", "output directory");
31
- command.option(
32
- "--project <project>",
33
- "tsconfig.json/jsconfig.json file or directory",
34
- );
35
-
36
- const questioned = { value: false };
37
- const prompt = inquirer.createPromptModule;
38
-
39
- const input = (name: string) => async (message: string) => {
40
- questioned.value = true;
41
- const result = await prompt()({
42
- type: "input",
43
- name,
44
- message,
45
- default: "",
46
- });
47
- return result[name] as string;
48
- };
49
- const configure = async (): Promise<string> => {
50
- const file: string | null = findProjectConfigFile(process.cwd());
51
- if (file === null) {
52
- throw new URIError(
53
- `Unable to find "tsconfig.json" or "jsconfig.json" file.`,
54
- );
55
- }
56
- return file;
57
- };
58
-
59
- return new Promise<IArguments>((resolve, reject) => {
60
- command.action(async (files: string[], options: Partial<IArguments>) => {
61
- try {
62
- if (files.length !== 0 && options.input !== undefined) {
63
- throw new URIError(
64
- "Error on TypiaGenerateWizard.generate(): file arguments cannot be combined with --input.",
65
- );
66
- }
67
- if (files.length === 0) {
68
- options.input ??= await input("input")("input directory");
69
- }
70
- if (files.length !== 0 && options.output === undefined) {
71
- throw new URIError(
72
- "Error on TypiaGenerateWizard.generate(): output directory is required when file arguments are used.",
73
- );
74
- }
75
- const output: string =
76
- options.output ?? (await input("output")("output directory"));
77
- const project: string = options.project ?? (await configure());
78
- if (questioned.value) console.log("");
79
- resolve({
80
- input: options.input,
81
- output,
82
- project,
83
- files,
84
- });
85
- } catch (exp) {
86
- reject(exp);
87
- }
88
- });
89
- command.parseAsync(process.argv.slice(3), { from: "user" }).catch(reject);
90
- });
91
- }
92
-
93
- export interface IArguments {
94
- input?: string;
95
- output: string;
96
- project: string;
97
- files: string[];
98
- }
99
-
100
- async function build(location: IArguments): Promise<void> {
101
- location.output = path.resolve(location.output);
102
- location.project = resolveProjectConfigFile(location.project);
103
-
104
- const policy = new FileSystemIdentity.Policy();
105
- const outputProbe: string = await nearestExistingAncestor(location.output);
106
- await ensureExistingDirectoryPath({
107
- label: "output parent path",
108
- directory: outputProbe,
109
- });
110
- policy.observe(
111
- await FileSystemIdentity.probeDirectory(outputProbe),
112
- outputProbe,
113
- );
114
- policy.observe(
115
- await FileSystemIdentity.inspectDirectory(path.dirname(location.project)),
116
- path.dirname(location.project),
117
- );
118
-
119
- const entries: IInputFile[] =
120
- location.files.length === 0
121
- ? await prepareDirectoryInput(location, policy)
122
- : await prepareFileInputs(location, policy);
123
- const identity: FileSystemIdentity.IIdentity = policy.get();
124
- await inspectTargetDirectories({
125
- identity,
126
- output: location.output,
127
- targets: entries.map((entry) => entry.target),
128
- });
129
-
130
- const binary = resolveTsgoBinary();
131
- const cwd = path.dirname(location.project);
132
- const temporaryProject: ITemporaryProject = await createTemporaryProject({
133
- entries,
134
- project: location.project,
135
- });
136
- let transformed: Record<string, string>;
137
- try {
138
- transformed = transformProject({
139
- binary,
140
- cwd,
141
- projectRoot: cwd,
142
- tsconfig: temporaryProject.config,
143
- });
144
- } finally {
145
- await fs.promises.rm(temporaryProject.directory, {
146
- force: true,
147
- recursive: true,
148
- });
149
- }
150
- const outputByKey: Map<string, string> = indexTransformedOutputs(
151
- transformed,
152
- identity,
153
- );
154
- const outputs: IOutputFile[] = entries.map((entry) => {
155
- const output = getTransformedOutput({
156
- cwd,
157
- entry,
158
- identity,
159
- outputByKey,
160
- });
161
- if (output === undefined) {
162
- throw new URIError(
163
- `Error on TypiaGenerateWizard.generate(): no transformed output for ${entry.file}. Check that --project includes the file.`,
164
- );
165
- }
166
- return { entry, output };
167
- });
168
-
169
- await ensureOutputDirectory(location.output);
170
- await ensureTargetDirectories({
171
- identity,
172
- output: location.output,
173
- targets: outputs.map(({ entry }) => entry.target),
174
- });
175
- await ensurePhysicalTargets({
176
- identity,
177
- output: location.output,
178
- entries: outputs.map(({ entry }) => entry),
179
- });
180
- await ensureTargetFiles(
181
- outputs.map(({ entry }) => entry),
182
- identity,
183
- );
184
- for (const { entry, output } of outputs) {
185
- await fs.promises.writeFile(entry.target, formatOutput(output), "utf8");
186
- }
187
- }
188
-
189
- interface IInputFile {
190
- file: string;
191
- target: string;
192
- }
193
-
194
- interface IOutputFile {
195
- entry: IInputFile;
196
- output: string;
197
- }
198
-
199
- interface ITraversalEntry {
200
- file: string;
201
- name: string;
202
- stat: fs.Stats;
203
- }
204
-
205
- interface ITemporaryProject {
206
- config: string;
207
- directory: string;
208
- }
209
-
210
- async function createTemporaryProject(props: {
211
- entries: IInputFile[];
212
- project: string;
213
- }): Promise<ITemporaryProject> {
214
- const directory: string = await fs.promises.mkdtemp(
215
- path.join(os.tmpdir(), "typia-generate-project-"),
216
- );
217
- const config: string = path.join(directory, "tsconfig.json");
218
- try {
219
- await fs.promises.writeFile(
220
- config,
221
- JSON.stringify({
222
- extends: props.project,
223
- exclude: [],
224
- files: props.entries.map((entry) => compilerInputPath(entry.file)),
225
- include: [],
226
- }),
227
- "utf8",
228
- );
229
- return { config, directory };
230
- } catch (error) {
231
- await fs.promises.rm(directory, { force: true, recursive: true });
232
- throw new URIError(
233
- `Error on TypiaGenerateWizard.generate(): unable to prepare the bounded input project: ${formatUnknownError(error)}`,
234
- );
235
- }
236
- }
237
-
238
- async function ensureOutputDirectory(output: string): Promise<void> {
239
- if (fs.existsSync(output) === false) {
240
- await ensureCreatableDirectory(output);
241
- await fs.promises.mkdir(output, { recursive: true });
242
- } else {
243
- await ensureExistingDirectory({
244
- label: "output path",
245
- directory: output,
246
- });
247
- }
248
- }
249
-
250
- async function ensureTargetDirectories(props: {
251
- identity: FileSystemIdentity.IIdentity;
252
- output: string;
253
- targets: string[];
254
- }): Promise<void> {
255
- await inspectTargetDirectories(props);
256
- const directories: Map<string, string> = targetDirectories(props);
257
- for (const directory of directories.values()) {
258
- try {
259
- await fs.promises.mkdir(directory, { recursive: true });
260
- } catch (exp) {
261
- throw new URIError(
262
- `Error on TypiaGenerateWizard.generate(): unable to create output parent directory ${directory}: ${formatUnknownError(exp)}`,
263
- );
264
- }
265
- await ensureExistingDirectory({
266
- label: "output parent path",
267
- directory,
268
- });
269
- }
270
- }
271
-
272
- async function inspectTargetDirectories(props: {
273
- identity: FileSystemIdentity.IIdentity;
274
- output: string;
275
- targets: string[];
276
- }): Promise<void> {
277
- const directories: Map<string, string> = targetDirectories(props);
278
- for (const directory of directories.values()) {
279
- await ensureOutputAncestorDirectories({
280
- identity: props.identity,
281
- output: props.output,
282
- directory,
283
- });
284
- if (fs.existsSync(directory)) {
285
- await ensureExistingDirectory({
286
- label: "output parent path",
287
- directory,
288
- });
289
- }
290
- }
291
- }
292
-
293
- function targetDirectories(props: {
294
- identity: FileSystemIdentity.IIdentity;
295
- targets: string[];
296
- }): Map<string, string> {
297
- const directories: Map<string, string> = new Map();
298
- for (const target of props.targets) {
299
- const directory: string = path.dirname(target);
300
- directories.set(props.identity.filesystemKey(directory), directory);
301
- }
302
- return directories;
303
- }
304
-
305
- async function ensureCreatableDirectory(directory: string): Promise<void> {
306
- const parent: string = await nearestExistingAncestor(directory);
307
- await ensureExistingDirectoryPath({
308
- label: "output parent path",
309
- directory: parent,
310
- });
311
- }
312
-
313
- async function nearestExistingAncestor(directory: string): Promise<string> {
314
- let current: string = path.resolve(directory);
315
- while (fs.existsSync(current) === false) {
316
- const parent: string = path.dirname(current);
317
- if (parent === current) {
318
- throw new URIError(
319
- `Error on TypiaGenerateWizard.generate(): unable to find existing output parent path: ${directory}`,
320
- );
321
- }
322
- current = parent;
323
- }
324
- return current;
325
- }
326
-
327
- async function ensureOutputAncestorDirectories(props: {
328
- identity: FileSystemIdentity.IIdentity;
329
- output: string;
330
- directory: string;
331
- }): Promise<void> {
332
- const output: string = path.resolve(props.output);
333
- const directory: string = path.resolve(props.directory);
334
- if (props.identity.contains(directory, output) === false) {
335
- throw new URIError(
336
- `Error on TypiaGenerateWizard.generate(): output parent path escapes output directory: ${props.directory}`,
337
- );
338
- }
339
-
340
- const relative: string = path.relative(output, directory);
341
- if (relative === "") {
342
- return;
343
- }
344
-
345
- let current: string = output;
346
- for (const segment of relative.split(path.sep)) {
347
- current = path.join(current, segment);
348
- let stat: fs.Stats;
349
- try {
350
- stat = await fs.promises.lstat(current);
351
- } catch (exp) {
352
- if (isMissingFileError(exp)) {
353
- return;
354
- }
355
- throw new URIError(
356
- `Error on TypiaGenerateWizard.generate(): unable to inspect output parent path ${current}: ${formatUnknownError(exp)}`,
357
- );
358
- }
359
- if (stat.isSymbolicLink()) {
360
- throw new URIError(
361
- `Error on TypiaGenerateWizard.generate(): output parent path contains a symbolic link: ${current}`,
362
- );
363
- }
364
- if (stat.isDirectory() === false) {
365
- throw new URIError(
366
- `Error on TypiaGenerateWizard.generate(): output parent path is not a directory: ${current}`,
367
- );
368
- }
369
- }
370
- }
371
-
372
- async function ensureExistingDirectory(props: {
373
- label: string;
374
- directory: string;
375
- }): Promise<void> {
376
- await ensureExistingDirectoryPath(props);
377
- }
378
-
379
- async function ensureExistingDirectoryPath(props: {
380
- label: string;
381
- directory: string;
382
- }): Promise<void> {
383
- const directory: string = path.resolve(props.directory);
384
- const parsed: path.ParsedPath = path.parse(directory);
385
- const relative: string = path.relative(parsed.root, directory);
386
- let current: string = parsed.root;
387
- for (const segment of relative === "" ? [] : relative.split(path.sep)) {
388
- current = path.join(current, segment);
389
- await ensureExistingDirectorySegment({
390
- label:
391
- path.normalize(current) === path.normalize(directory)
392
- ? props.label
393
- : `${props.label} ancestor`,
394
- directory: current,
395
- });
396
- }
397
- }
398
-
399
- async function ensureExistingDirectorySegment(props: {
400
- label: string;
401
- directory: string;
402
- }): Promise<void> {
403
- const stat: fs.Stats = await fs.promises.lstat(props.directory);
404
- if (stat.isSymbolicLink()) {
405
- throw new URIError(
406
- `Error on TypiaGenerateWizard.generate(): ${props.label} is a symbolic link: ${props.directory}`,
407
- );
408
- }
409
- if (stat.isDirectory() === false) {
410
- throw new URIError(
411
- `Error on TypiaGenerateWizard.generate(): ${props.label} is not a directory: ${props.directory}`,
412
- );
413
- }
414
- }
415
-
416
- async function ensurePhysicalTargets(props: {
417
- identity: FileSystemIdentity.IIdentity;
418
- output: string;
419
- entries: IInputFile[];
420
- }): Promise<void> {
421
- const output: string = await fs.promises.realpath(props.output);
422
- const inputs: Set<string> = new Set();
423
- for (const entry of props.entries) {
424
- inputs.add(
425
- props.identity.filesystemKey(await fs.promises.realpath(entry.file)),
426
- );
427
- }
428
-
429
- for (const entry of props.entries) {
430
- const parent: string = path.dirname(entry.target);
431
- const directory: string = await fs.promises.realpath(parent);
432
- if (props.identity.contains(directory, output) === false) {
433
- throw new URIError(
434
- `Error on TypiaGenerateWizard.generate(): output parent path escapes output directory through a symbolic link: ${parent}`,
435
- );
436
- }
437
-
438
- const target: string = path.join(directory, path.basename(entry.target));
439
- if (inputs.has(props.identity.filesystemKey(target))) {
440
- throw new URIError(
441
- `Error on TypiaGenerateWizard.generate(): output file would overwrite input file through a symbolic link: ${entry.target}`,
442
- );
443
- }
444
- }
445
- }
446
-
447
- async function ensureTargetFiles(
448
- entries: IInputFile[],
449
- identity: FileSystemIdentity.IIdentity,
450
- ): Promise<void> {
451
- const inputs: Set<string> = new Set();
452
- const files: Map<string, IInputFile> = new Map();
453
- for (const entry of entries) {
454
- inputs.add(
455
- fileIdentityKey(
456
- await fs.promises.stat(entry.file, { bigint: true }),
457
- await fs.promises.realpath(entry.file),
458
- ),
459
- );
460
- files.set(identity.filesystemKey(entry.target), entry);
461
- }
462
-
463
- for (const entry of files.values()) {
464
- let stat: fs.BigIntStats;
465
- try {
466
- stat = await fs.promises.lstat(entry.target, { bigint: true });
467
- } catch (exp) {
468
- if (isMissingFileError(exp)) {
469
- continue;
470
- }
471
- throw new URIError(
472
- `Error on TypiaGenerateWizard.generate(): unable to inspect output file ${entry.target}: ${formatUnknownError(exp)}`,
473
- );
474
- }
475
- if (stat.isFile() === false) {
476
- throw new URIError(
477
- `Error on TypiaGenerateWizard.generate(): output file path is not a regular file: ${entry.target}`,
478
- );
479
- }
480
- if (
481
- inputs.has(
482
- fileIdentityKey(stat, await fs.promises.realpath(entry.target)),
483
- )
484
- ) {
485
- throw new URIError(
486
- `Error on TypiaGenerateWizard.generate(): output file would overwrite input file through a physical file alias: ${entry.target}`,
487
- );
488
- }
489
- if (stat.nlink > BigInt(1)) {
490
- throw new URIError(
491
- `Error on TypiaGenerateWizard.generate(): output file has multiple hard links: ${entry.target}`,
492
- );
493
- }
494
- }
495
- }
496
-
497
- async function prepareDirectoryInput(
498
- location: IArguments,
499
- policy: FileSystemIdentity.Policy,
500
- ): Promise<IInputFile[]> {
501
- if (location.input === undefined) {
502
- throw new URIError(
503
- "Error on TypiaGenerateWizard.generate(): input path is required.",
504
- );
505
- }
506
- const input = path.resolve(location.input);
507
- if (fs.existsSync(input) === false) {
508
- throw new URIError(
509
- `Error on TypiaGenerateWizard.generate(): input path does not exist: ${input}`,
510
- );
511
- }
512
- if ((await isDirectory(input)) === false) {
513
- throw new URIError(
514
- "Error on TypiaGenerateWizard.generate(): input path is not a directory.",
515
- );
516
- }
517
-
518
- const inputReal: string = await fs.promises.realpath(input);
519
- const outputReal: string | undefined = await optionalRealPath(
520
- location.output,
521
- );
522
- const files: string[] = [];
523
- await gather({
524
- container: files,
525
- from: input,
526
- inputReal,
527
- outputReal,
528
- policy,
529
- visitedDirectories: new Set(),
530
- visitedFiles: new Set(),
531
- });
532
- return files.map((file) => ({
533
- file,
534
- target: path.join(location.output, path.relative(input, file)),
535
- }));
536
- }
537
-
538
- async function prepareFileInputs(
539
- location: IArguments,
540
- policy: FileSystemIdentity.Policy,
541
- ): Promise<IInputFile[]> {
542
- const targets: Set<string> = new Set();
543
- const output: IInputFile[] = [];
544
- for (const input of await expandFileInputs(
545
- location.files,
546
- location.output,
547
- policy,
548
- )) {
549
- const file: string = path.resolve(input);
550
- policy.observe(
551
- await FileSystemIdentity.inspectDirectory(path.dirname(file)),
552
- path.dirname(file),
553
- );
554
- const identity: FileSystemIdentity.IIdentity = policy.get();
555
- if (fs.existsSync(file) === false) {
556
- throw new URIError(
557
- `Error on TypiaGenerateWizard.generate(): input file does not exist: ${input}`,
558
- );
559
- } else if ((await isFile(file)) === false) {
560
- throw new URIError(
561
- `Error on TypiaGenerateWizard.generate(): input path is not a file: ${input}`,
562
- );
563
- } else if (identity.isDeclarationFile(file)) {
564
- continue;
565
- } else if (identity.isSupportedExtension(file) === false) {
566
- throw new URIError(
567
- `Error on TypiaGenerateWizard.generate(): input file is not a supported TypeScript source: ${input}`,
568
- );
569
- }
570
-
571
- const target: string = path.join(location.output, path.basename(file));
572
- if (identity.isSamePath(file, target)) {
573
- throw new URIError(
574
- `Error on TypiaGenerateWizard.generate(): output file would overwrite input file: ${input}`,
575
- );
576
- }
577
- const key: string = identity.filesystemKey(target);
578
- if (targets.has(key)) {
579
- throw new URIError(
580
- `Error on TypiaGenerateWizard.generate(): duplicate output filename for ${target}`,
581
- );
582
- }
583
- targets.add(key);
584
- output.push({ file, target });
585
- }
586
- if (output.length === 0) {
587
- throw new URIError(
588
- "Error on TypiaGenerateWizard.generate(): input files do not include any supported TypeScript source files outside the output directory.",
589
- );
590
- }
591
- return output;
592
- }
593
-
594
- async function expandFileInputs(
595
- inputs: string[],
596
- directory: string,
597
- policy: FileSystemIdentity.Policy,
598
- ): Promise<string[]> {
599
- const output: string[] = [];
600
- for (const input of inputs) {
601
- const pattern: string = toGlobPattern(input);
602
- if (isDynamicPattern(pattern, { caseSensitiveMatch: true })) {
603
- const searchDirectory: string = await globSearchDirectory(input);
604
- const caseSensitive: boolean | undefined =
605
- await FileSystemIdentity.inspectDirectory(searchDirectory);
606
- if (caseSensitive === undefined) {
607
- throw new URIError(
608
- `Error on TypiaGenerateWizard.generate(): unable to determine filesystem case behavior for input pattern base ${searchDirectory}.`,
609
- );
610
- }
611
- policy.observe(caseSensitive, searchDirectory);
612
- const identity: FileSystemIdentity.IIdentity = policy.get();
613
- const matches: string[] = await glob(pattern, {
614
- absolute: true,
615
- caseSensitiveMatch: identity.caseSensitive,
616
- cwd: process.cwd(),
617
- onlyFiles: true,
618
- });
619
- if (matches.length === 0) {
620
- throw new URIError(
621
- `Error on TypiaGenerateWizard.generate(): input pattern does not match any files: ${input}`,
622
- );
623
- }
624
- output.push(
625
- ...excludeOutputFiles(matches, directory, identity).filter((file) =>
626
- identity.isSupportedExtension(file),
627
- ),
628
- );
629
- } else {
630
- const file: string = path.resolve(input);
631
- policy.observe(
632
- await FileSystemIdentity.inspectDirectory(path.dirname(file)),
633
- path.dirname(file),
634
- );
635
- if (policy.get().contains(file, directory) === false) {
636
- output.push(file);
637
- }
638
- }
639
- }
640
- return output;
641
- }
642
-
643
- function excludeOutputFiles(
644
- files: string[],
645
- directory: string,
646
- identity: FileSystemIdentity.IIdentity,
647
- ): string[] {
648
- return files.filter((file) => identity.contains(file, directory) === false);
649
- }
650
-
651
- async function globSearchDirectory(input: string): Promise<string> {
652
- let current: string = path.resolve(input);
653
- while (
654
- isDynamicPattern(toGlobPattern(current), { caseSensitiveMatch: true })
655
- ) {
656
- const parent: string = path.dirname(current);
657
- if (parent === current) break;
658
- current = parent;
659
- }
660
- if (fs.existsSync(current) && (await isDirectory(current))) return current;
661
- return nearestExistingAncestor(path.dirname(current));
662
- }
663
-
664
- function toGlobPattern(input: string): string {
665
- return input.replace(/\\/g, "/");
666
- }
667
-
668
- function transformProject(props: {
669
- binary: string;
670
- cwd: string;
671
- projectRoot: string;
672
- tsconfig: string;
673
- }): Record<string, string> {
674
- const TtscCompiler = loadTtscCompiler();
675
- const result: ITtscCompilerTransformation = new TtscCompiler({
676
- binary: props.binary,
677
- cwd: props.cwd,
678
- projectRoot: props.projectRoot,
679
- tsconfig: props.tsconfig,
680
- }).transform();
681
- if (result.type === "success") {
682
- return result.typescript;
683
- }
684
- if (result.type === "failure") {
685
- throw new URIError(
686
- `Error on TypiaGenerateWizard.generate(): ${formatDiagnostics(result.diagnostics)}`,
687
- );
688
- }
689
- throw new URIError(
690
- `Error on TypiaGenerateWizard.generate(): ${formatUnknownError(result.error)}`,
691
- );
692
- }
693
-
694
- function resolveProjectConfigFile(project: string): string {
695
- const resolved: string = path.resolve(project);
696
- if (fs.existsSync(resolved) === false) {
697
- throw new URIError(
698
- `Error on TypiaGenerateWizard.generate(): project path does not exist: ${resolved}`,
699
- );
700
- }
701
-
702
- const stat: fs.Stats = fs.statSync(resolved);
703
- if (stat.isDirectory()) {
704
- for (const filename of ["tsconfig.json", "jsconfig.json"]) {
705
- const candidate: string = path.join(resolved, filename);
706
- if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
707
- return resolveRealPath(candidate);
708
- }
709
- }
710
- throw new URIError(
711
- `Error on TypiaGenerateWizard.generate(): project directory has no tsconfig.json or jsconfig.json: ${resolved}`,
712
- );
713
- }
714
- if (stat.isFile() === false) {
715
- throw new URIError(
716
- `Error on TypiaGenerateWizard.generate(): project path is not a file: ${resolved}`,
717
- );
718
- }
719
- return resolveRealPath(resolved);
720
- }
721
-
722
- function findProjectConfigFile(directory: string): string | null {
723
- let current: string = path.resolve(directory);
724
- while (true) {
725
- for (const filename of ["tsconfig.json", "jsconfig.json"]) {
726
- const candidate: string = path.join(current, filename);
727
- if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
728
- return resolveRealPath(candidate);
729
- }
730
- }
731
- const parent: string = path.dirname(current);
732
- if (parent === current) {
733
- return null;
734
- }
735
- current = parent;
736
- }
737
- }
738
-
739
- function loadTtscCompiler(): typeof import("ttsc").TtscCompiler {
740
- const packageRoot: string = resolveTypiaPackageRoot();
741
- const resolved: string | null = resolveFromRoots(
742
- "ttsc",
743
- resolveRuntimeRoots(packageRoot),
744
- );
745
- if (resolved === null) {
746
- throw new URIError(
747
- `Error on TypiaGenerateWizard.generate(): unable to resolve ttsc from the current project, typia package, or workspace root. Run "npm i -D ttsc typescript" before.`,
748
- );
749
- }
750
- const imported = createRequire(resolved)(resolved) as typeof import("ttsc");
751
- return imported.TtscCompiler;
752
- }
753
-
754
- function resolveTsgoBinary(): string {
755
- const explicit: string | undefined = process.env.TTSC_TSGO_BINARY;
756
- if (explicit !== undefined && explicit.length !== 0) {
757
- if (path.isAbsolute(explicit) && fs.existsSync(explicit)) {
758
- return explicit;
759
- }
760
- throw new URIError(
761
- `Error on TypiaGenerateWizard.generate(): TTSC_TSGO_BINARY must be an existing absolute path: ${explicit}`,
762
- );
763
- }
764
-
765
- const packageRoot: string = resolveTypiaPackageRoot();
766
- const manifest: string | null = resolveFromRoots(
767
- "typescript/package.json",
768
- resolveRuntimeRoots(packageRoot),
769
- );
770
- if (manifest === null) {
771
- throw new URIError(
772
- "Error on TypiaGenerateWizard.generate(): unable to resolve typescript from the current project, typia package, or workspace root.",
773
- );
774
- }
775
-
776
- const platform: string = `@typescript/typescript-${process.platform}-${process.arch}`;
777
- const platformManifest: string = createRequire(manifest).resolve(
778
- `${platform}/package.json`,
779
- );
780
- const binary: string = path.join(
781
- path.dirname(platformManifest),
782
- "lib",
783
- process.platform === "win32" ? "tsc.exe" : "tsc",
784
- );
785
- if (fs.existsSync(binary) === false) {
786
- throw new URIError(
787
- `Error on TypiaGenerateWizard.generate(): TypeScript-Go executable not found: ${binary}`,
788
- );
789
- }
790
- return binary;
791
- }
792
-
793
- function resolveTypiaPackageRoot(): string {
794
- // The CLI entrypoint (`lib/executable/typia.js`) lives in the same
795
- // directory as this module, so its `process.argv[1]` path anchors the
796
- // walk-up identically in both the CJS and ESM builds — `__dirname` does
797
- // not exist in the transcoded `.mjs`.
798
- const current: string = path.dirname(path.resolve(process.argv[1] ?? ""));
799
- for (const directory of [
800
- path.resolve(current, "..", ".."),
801
- path.resolve(current, ".."),
802
- ]) {
803
- const file: string = path.join(directory, "package.json");
804
- if (fs.existsSync(file) === false) {
805
- continue;
806
- }
807
- try {
808
- const pack = JSON.parse(fs.readFileSync(file, "utf8")) as Partial<
809
- Record<"name", unknown>
810
- >;
811
- if (pack.name === "typia") {
812
- return directory;
813
- }
814
- } catch {
815
- continue;
816
- }
817
- }
818
-
819
- const resolved: string | null = resolveFromRoots("typia/package.json", [
820
- process.cwd(),
821
- current,
822
- ]);
823
- if (resolved === null) {
824
- throw new URIError(
825
- "Error on TypiaGenerateWizard.generate(): unable to resolve typia package root.",
826
- );
827
- }
828
- return path.dirname(resolved);
829
- }
830
-
831
- function resolveRuntimeRoots(packageRoot: string): string[] {
832
- return [process.cwd(), packageRoot, path.resolve(packageRoot, "..", "..")];
833
- }
834
-
835
- function resolveFromRoots(request: string, roots: string[]): string | null {
836
- for (const root of roots) {
837
- try {
838
- return createRequire(path.join(root, "package.json")).resolve(request);
839
- } catch {
840
- continue;
841
- }
842
- }
843
- return null;
844
- }
845
-
846
- async function isDirectory(current: string): Promise<boolean> {
847
- const stat: fs.Stats = await fs.promises.stat(current);
848
- return stat.isDirectory();
849
- }
850
-
851
- async function isFile(current: string): Promise<boolean> {
852
- const stat: fs.Stats = await fs.promises.stat(current);
853
- return stat.isFile();
854
- }
855
-
856
- async function gather(props: {
857
- container: string[];
858
- from: string;
859
- inputReal: string;
860
- outputReal: string | undefined;
861
- policy: FileSystemIdentity.Policy;
862
- visitedDirectories: Set<string>;
863
- visitedFiles: Set<string>;
864
- }): Promise<void> {
865
- const currentReal: string = await resolveTraversalPath(props.from);
866
- if (
867
- props.outputReal !== undefined &&
868
- isPhysicalSameOrChildPath(currentReal, props.outputReal)
869
- )
870
- return;
871
- ensurePhysicalInputContainment({
872
- file: props.from,
873
- input: props.inputReal,
874
- real: currentReal,
875
- });
876
-
877
- const currentStat: fs.BigIntStats = await fs.promises.stat(props.from, {
878
- bigint: true,
879
- });
880
- const directoryIdentity: string = fileIdentityKey(currentStat, currentReal);
881
- if (props.visitedDirectories.has(directoryIdentity)) {
882
- const lexicalStat: fs.Stats = await fs.promises.lstat(props.from);
883
- if (lexicalStat.isSymbolicLink()) {
884
- throw new URIError(
885
- `Error on TypiaGenerateWizard.generate(): input directory link revisits a physical directory: ${props.from}.`,
886
- );
887
- }
888
- return;
889
- }
890
- props.visitedDirectories.add(directoryIdentity);
891
-
892
- props.policy.observe(
893
- await FileSystemIdentity.inspectDirectory(props.from),
894
- props.from,
895
- );
896
- const identity: FileSystemIdentity.IIdentity = props.policy.get();
897
- const entries: ITraversalEntry[] = await Promise.all(
898
- (await fs.promises.readdir(props.from)).map(async (name) => {
899
- const file: string = path.join(props.from, name);
900
- try {
901
- return { file, name, stat: await fs.promises.lstat(file) };
902
- } catch (error) {
903
- throw new URIError(
904
- `Error on TypiaGenerateWizard.generate(): unable to inspect input path ${file}: ${formatUnknownError(error)}`,
905
- );
906
- }
907
- }),
908
- );
909
- entries.sort((x, y) => {
910
- const linkOrder: number =
911
- Number(x.stat.isSymbolicLink()) - Number(y.stat.isSymbolicLink());
912
- return linkOrder !== 0
913
- ? linkOrder
914
- : Buffer.compare(Buffer.from(x.name), Buffer.from(y.name));
915
- });
916
-
917
- for (const entry of entries) {
918
- let stat: fs.BigIntStats;
919
- let real: string;
920
- try {
921
- stat = await fs.promises.stat(entry.file, { bigint: true });
922
- real = await fs.promises.realpath(entry.file);
923
- } catch (error) {
924
- throw new URIError(
925
- `Error on TypiaGenerateWizard.generate(): input link target is missing or unreadable: ${entry.file}: ${formatUnknownError(error)}`,
926
- );
927
- }
928
-
929
- if (
930
- props.outputReal !== undefined &&
931
- isPhysicalSameOrChildPath(real, props.outputReal)
932
- )
933
- continue;
934
- ensurePhysicalInputContainment({
935
- file: entry.file,
936
- input: props.inputReal,
937
- real,
938
- });
939
-
940
- if (stat.isDirectory()) {
941
- await gather({ ...props, from: entry.file });
942
- continue;
943
- }
944
- if (
945
- stat.isFile() === false ||
946
- identity.isSupportedExtension(entry.name) === false
947
- )
948
- continue;
949
-
950
- const fileIdentity: string = fileIdentityKey(stat, real);
951
- if (props.visitedFiles.has(fileIdentity)) continue;
952
- props.visitedFiles.add(fileIdentity);
953
- props.container.push(entry.file);
954
- }
955
- }
956
-
957
- function formatOutput(output: string): string {
958
- return output.startsWith("// @ts-nocheck")
959
- ? output
960
- : `// @ts-nocheck\n${output}`;
961
- }
962
-
963
- function indexTransformedOutputs(
964
- outputs: Record<string, string>,
965
- identity: FileSystemIdentity.IIdentity,
966
- ): Map<string, string> {
967
- const map: Map<string, string> = new Map();
968
- for (const [file, output] of Object.entries(outputs)) {
969
- const key: string = identity.projectFileKey(file);
970
- if (map.has(key)) {
971
- throw new URIError(
972
- `Error on TypiaGenerateWizard.generate(): transformed outputs have ambiguous filesystem identities: ${file}.`,
973
- );
974
- }
975
- map.set(key, output);
976
- }
977
- return map;
978
- }
979
-
980
- function getTransformedOutput(props: {
981
- cwd: string;
982
- entry: IInputFile;
983
- identity: FileSystemIdentity.IIdentity;
984
- outputByKey: Map<string, string>;
985
- }): string | undefined {
986
- const output = props.outputByKey.get(
987
- props.identity.projectFileKey(projectKey(props.cwd, props.entry.file)),
988
- );
989
- if (output !== undefined) {
990
- return output;
991
- }
992
-
993
- const compilerFile: string = compilerInputPath(props.entry.file);
994
- if (
995
- props.identity.isSamePath(compilerFile, props.entry.file) === false &&
996
- props.identity.contains(compilerFile, props.cwd)
997
- ) {
998
- const compiled: string | undefined = props.outputByKey.get(
999
- props.identity.projectFileKey(projectKey(props.cwd, compilerFile)),
1000
- );
1001
- if (compiled !== undefined) return compiled;
1002
- }
1003
-
1004
- const real: string = resolveRealPath(props.entry.file);
1005
- if (
1006
- props.identity.isSamePath(real, props.entry.file) ||
1007
- props.identity.contains(real, props.cwd) === false
1008
- ) {
1009
- return undefined;
1010
- }
1011
- return props.outputByKey.get(
1012
- props.identity.projectFileKey(projectKey(props.cwd, real)),
1013
- );
1014
- }
1015
-
1016
- function projectKey(root: string, file: string): string {
1017
- return path.relative(root, file).replace(/\\/g, "/");
1018
- }
1019
-
1020
- function resolveRealPath(file: string): string {
1021
- try {
1022
- return fs.realpathSync(file);
1023
- } catch {
1024
- return file;
1025
- }
1026
- }
1027
-
1028
- function compilerInputPath(file: string): string {
1029
- try {
1030
- if (fs.lstatSync(file).isSymbolicLink()) {
1031
- return path.join(
1032
- resolveRealPath(path.dirname(file)),
1033
- path.basename(file),
1034
- );
1035
- }
1036
- } catch {
1037
- return file;
1038
- }
1039
- return resolveRealPath(file);
1040
- }
1041
-
1042
- async function optionalRealPath(file: string): Promise<string | undefined> {
1043
- try {
1044
- return await fs.promises.realpath(file);
1045
- } catch (error) {
1046
- if (isMissingFileError(error)) return undefined;
1047
- throw new URIError(
1048
- `Error on TypiaGenerateWizard.generate(): unable to resolve path ${file}: ${formatUnknownError(error)}`,
1049
- );
1050
- }
1051
- }
1052
-
1053
- async function resolveTraversalPath(file: string): Promise<string> {
1054
- try {
1055
- return await fs.promises.realpath(file);
1056
- } catch (error) {
1057
- throw new URIError(
1058
- `Error on TypiaGenerateWizard.generate(): unable to resolve input path ${file}: ${formatUnknownError(error)}`,
1059
- );
1060
- }
1061
- }
1062
-
1063
- function ensurePhysicalInputContainment(props: {
1064
- file: string;
1065
- input: string;
1066
- real: string;
1067
- }): void {
1068
- if (isPhysicalSameOrChildPath(props.real, props.input)) return;
1069
- throw new URIError(
1070
- `Error on TypiaGenerateWizard.generate(): input path resolves outside the input directory: ${props.file}.`,
1071
- );
1072
- }
1073
-
1074
- function isPhysicalSameOrChildPath(file: string, directory: string): boolean {
1075
- const relative: string = path.relative(directory, file);
1076
- return (
1077
- relative === "" ||
1078
- (relative !== ".." &&
1079
- relative.startsWith(`..${path.sep}`) === false &&
1080
- path.isAbsolute(relative) === false)
1081
- );
1082
- }
1083
-
1084
- function isMissingFileError(exp: unknown): boolean {
1085
- return (
1086
- typeof exp === "object" &&
1087
- exp !== null &&
1088
- "code" in exp &&
1089
- exp.code === "ENOENT"
1090
- );
1091
- }
1092
-
1093
- /**
1094
- * Delegates to {@link FileSystemIdentity.identityKey}, which owns the rule and
1095
- * carries the reasoning for reading the identity as a `bigint`.
1096
- */
1097
- function fileIdentityKey(stat: fs.BigIntStats, realpath: string): string {
1098
- return FileSystemIdentity.identityKey(stat, realpath);
1099
- }
1100
-
1101
- function formatDiagnostics(diagnostics: ITtscCompilerDiagnostic[]): string {
1102
- return diagnostics.length === 0
1103
- ? "transformation failed"
1104
- : diagnostics
1105
- .map((diag) =>
1106
- [
1107
- diag.file ?? "ttsc",
1108
- diag.line === undefined
1109
- ? undefined
1110
- : `${diag.line}:${diag.character ?? 1}`,
1111
- diag.messageText,
1112
- ]
1113
- .filter((part) => part !== undefined && part !== "")
1114
- .join(": "),
1115
- )
1116
- .join("\n");
1117
- }
1118
-
1119
- function formatUnknownError(error: unknown): string {
1120
- if (error instanceof Error) {
1121
- return error.message;
1122
- }
1123
- if (
1124
- typeof error === "object" &&
1125
- error !== null &&
1126
- "message" in error &&
1127
- typeof error.message === "string"
1128
- ) {
1129
- return error.message;
1130
- }
1131
- return String(error);
1132
- }
1133
- }