@automateinc/fleet-types 1.0.102 → 1.0.104

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.
@@ -2,9 +2,8 @@
2
2
 
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { existsSync } from "node:fs";
5
- import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
5
+ import { mkdir, writeFile } from "node:fs/promises";
6
6
  import { createRequire } from "node:module";
7
- import { tmpdir } from "node:os";
8
7
  import path from "node:path";
9
8
  import { loadEnvFile } from "node:process";
10
9
  import { fileURLToPath } from "node:url";
@@ -51,137 +50,128 @@ async function generateTypes() {
51
50
  const apiRoot = path.resolve(callerRoot, fleetApiPath);
52
51
  const outputPath = path.resolve(callerRoot, fleetApiTypesPath);
53
52
  const routerSourcePath = path.join(apiRoot, "src/routers/trpc/index.ts");
54
- const prismaTypesPath = path.join(apiRoot, "prisma/types.d.ts");
53
+ const apiTsconfigPath = path.join(apiRoot, "tsconfig.json");
55
54
  const executableExtension = process.platform === "win32" ? ".cmd" : "";
56
- const apiTscPath = path.join(apiRoot, `node_modules/.bin/tsc${executableExtension}`);
57
- const biomePath = path.join(packageRoot, `node_modules/.bin/biome${executableExtension}`);
58
- const temporaryDirectory = await mkdtemp(path.join(tmpdir(), "fleet-trpc-types-"));
59
- const declarationOutputDirectory = path.join(temporaryDirectory, "declarations");
60
- const declarationTsconfigPath = path.join(temporaryDirectory, "tsconfig.json");
61
- const prismaJsonShimPath = path.join(temporaryDirectory, "prisma-json.d.ts");
62
- const serviceProviderShimPath = path.join(temporaryDirectory, "service-provider.d.ts");
55
+ const callerBiomePath = path.join(callerRoot, `node_modules/.bin/biome${executableExtension}`);
56
+ const packageBiomePath = path.join(packageRoot, `node_modules/.bin/biome${executableExtension}`);
57
+ const biomePath = existsSync(callerBiomePath) ? callerBiomePath : packageBiomePath;
63
58
  const requireFromPackage = createRequire(path.join(packageRoot, "package.json"));
64
59
  const ts = requireFromPackage("typescript");
60
+ const configResult = ts.readConfigFile(apiTsconfigPath, ts.sys.readFile);
65
61
 
66
- try {
67
- const prismaTypesContent = await readFile(prismaTypesPath, "utf8");
68
- const prismaTypesSource = ts.createSourceFile(prismaTypesPath, prismaTypesContent, ts.ScriptTarget.Latest, true);
69
- let coordsType;
70
- const findCoordsType = node => {
71
- if (ts.isModuleDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === "PrismaJson") {
72
- const body = node.body;
73
- if (body && ts.isModuleBlock(body)) {
74
- coordsType = body.statements.find(
75
- statement => ts.isTypeAliasDeclaration(statement) && statement.name.text === "Coords",
76
- );
77
- }
78
- }
79
- ts.forEachChild(node, findCoordsType);
80
- };
81
- findCoordsType(prismaTypesSource);
82
- if (!coordsType) {
83
- throw new Error(`PrismaJson.Coords was not found in ${prismaTypesPath}.`);
84
- }
85
- const coordsTypeDeclaration = ts
86
- .createPrinter({ newLine: ts.NewLineKind.LineFeed })
87
- .printNode(ts.EmitHint.Unspecified, coordsType, prismaTypesSource);
88
-
89
- await writeFile(
90
- prismaJsonShimPath,
91
- `export {};\ndeclare global { namespace PrismaJson { ${coordsTypeDeclaration} } }\n`,
92
- );
93
- await writeFile(
94
- serviceProviderShimPath,
95
- "export declare class ServiceProvider { static getAuthenticationService(): { login(email: string, password: string, tokenExpiry?: string): Promise<string> }; static getEncryptionService(): { decodeId(encodedId: string, prefix: string): number }; }\n",
96
- );
97
- await writeFile(
98
- declarationTsconfigPath,
99
- `${JSON.stringify(
100
- {
101
- compilerOptions: {
102
- declaration: true,
103
- declarationMap: false,
104
- emitDeclarationOnly: true,
105
- incremental: true,
106
- noEmit: false,
107
- outDir: declarationOutputDirectory,
108
- paths: {
109
- "@/*": [path.join(apiRoot, "src/*")],
110
- "@/providers": [serviceProviderShimPath],
111
- "@/providers/service.provider": [serviceProviderShimPath],
112
- },
113
- tsBuildInfoFile: path.join(temporaryDirectory, "tsconfig.tsbuildinfo"),
114
- typeRoots: [path.join(apiRoot, "node_modules/@types")],
115
- },
116
- extends: path.join(apiRoot, "tsconfig.json"),
117
- files: [routerSourcePath, prismaJsonShimPath],
118
- },
119
- null,
120
- 2,
121
- )}\n`,
122
- );
123
-
124
- const typeScriptResult = spawnSync(apiTscPath, ["--project", declarationTsconfigPath, "--pretty"], {
125
- cwd: apiRoot,
62
+ if (configResult.error) {
63
+ throw new Error(formatTypeScriptDiagnostics(ts, [configResult.error], apiRoot));
64
+ }
65
+
66
+ const parsedConfig = ts.parseJsonConfigFileContent(
67
+ configResult.config,
68
+ ts.sys,
69
+ apiRoot,
70
+ {
71
+ declaration: true,
72
+ declarationMap: false,
73
+ emitDeclarationOnly: true,
74
+ incremental: false,
75
+ noEmit: false,
76
+ noEmitOnError: false,
77
+ },
78
+ apiTsconfigPath,
79
+ );
80
+
81
+ if (parsedConfig.errors.length > 0) {
82
+ throw new Error(formatTypeScriptDiagnostics(ts, parsedConfig.errors, apiRoot));
83
+ }
84
+
85
+ const program = ts.createProgram({
86
+ options: parsedConfig.options,
87
+ rootNames: parsedConfig.fileNames,
88
+ });
89
+ const routerSource = program.getSourceFile(routerSourcePath);
90
+
91
+ if (!routerSource) {
92
+ throw new Error(`Unable to load AppRouter source at ${routerSourcePath}.`);
93
+ }
94
+
95
+ const sourceDiagnostics = [
96
+ ...program.getSyntacticDiagnostics(routerSource),
97
+ ...program.getSemanticDiagnostics(routerSource),
98
+ ].filter(diagnostic => diagnostic.category === ts.DiagnosticCategory.Error);
99
+
100
+ if (sourceDiagnostics.length > 0) {
101
+ throw new Error(formatTypeScriptDiagnostics(ts, sourceDiagnostics, apiRoot));
102
+ }
103
+
104
+ let emittedDeclaration;
105
+ const emitResult = program.emit(
106
+ routerSource,
107
+ (fileName, content) => {
108
+ if (fileName.endsWith(".d.ts")) emittedDeclaration = content;
109
+ },
110
+ undefined,
111
+ true,
112
+ );
113
+ const emitDiagnostics = emitResult.diagnostics.filter(
114
+ diagnostic => diagnostic.category === ts.DiagnosticCategory.Error,
115
+ );
116
+
117
+ if (emitDiagnostics.length > 0) {
118
+ throw new Error(formatTypeScriptDiagnostics(ts, emitDiagnostics, apiRoot));
119
+ }
120
+ if (!emittedDeclaration) {
121
+ throw new Error(`TypeScript did not emit a declaration for ${routerSourcePath}.`);
122
+ }
123
+
124
+ const emittedPath = routerSourcePath.replace(/\.ts$/, ".d.ts");
125
+ const sourceFile = ts.createSourceFile(emittedPath, emittedDeclaration, ts.ScriptTarget.Latest, true);
126
+ const statements = sourceFile.statements.filter(
127
+ statement =>
128
+ ts.isImportDeclaration(statement) ||
129
+ ts.isImportEqualsDeclaration(statement) ||
130
+ (ts.isVariableStatement(statement) &&
131
+ statement.declarationList.declarations.some(
132
+ declaration => ts.isIdentifier(declaration.name) && declaration.name.text === "appRouter",
133
+ )) ||
134
+ (ts.isTypeAliasDeclaration(statement) && statement.name.text === "AppRouter"),
135
+ );
136
+
137
+ if (!statements.some(statement => ts.isTypeAliasDeclaration(statement))) {
138
+ throw new Error("AppRouter was not found in the emitted declaration.");
139
+ }
140
+
141
+ const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
142
+ const appRouterDeclaration = statements
143
+ .map(statement => printer.printNode(ts.EmitHint.Unspecified, statement, sourceFile))
144
+ .join("\n")
145
+ .replace(/^(?: {4})+/gm, indentation => "\t".repeat(indentation.length / 4));
146
+
147
+ await mkdir(path.dirname(outputPath), { recursive: true });
148
+ await writeFile(
149
+ outputPath,
150
+ `// Generated by \`npx @automateinc/fleet-types generate\`. Do not edit manually.\n${appRouterDeclaration}\n`,
151
+ );
152
+
153
+ if (existsSync(biomePath)) {
154
+ const biomeResult = spawnSync(biomePath, ["format", "--write", outputPath], {
155
+ cwd: callerRoot,
126
156
  stdio: "inherit",
127
157
  });
128
-
129
- if (typeScriptResult.error) {
130
- throw typeScriptResult.error;
158
+ if (biomeResult.error) {
159
+ throw biomeResult.error;
131
160
  }
132
- if (typeScriptResult.status !== 0) {
133
- throw new Error(`TypeScript declaration generation failed with exit code ${typeScriptResult.status}.`);
134
- }
135
-
136
- const emittedPath = path
137
- .join(declarationOutputDirectory, path.relative(path.join(apiRoot, "src"), routerSourcePath))
138
- .replace(/\.ts$/, ".d.ts");
139
- const emittedDeclaration = await readFile(emittedPath, "utf8");
140
- const sourceFile = ts.createSourceFile(emittedPath, emittedDeclaration, ts.ScriptTarget.Latest, true);
141
- const statements = sourceFile.statements.filter(
142
- statement =>
143
- ts.isImportDeclaration(statement) ||
144
- ts.isImportEqualsDeclaration(statement) ||
145
- (ts.isVariableStatement(statement) &&
146
- statement.declarationList.declarations.some(
147
- declaration => ts.isIdentifier(declaration.name) && declaration.name.text === "appRouter",
148
- )) ||
149
- (ts.isTypeAliasDeclaration(statement) && statement.name.text === "AppRouter"),
150
- );
151
-
152
- if (!statements.some(statement => ts.isTypeAliasDeclaration(statement))) {
153
- throw new Error("AppRouter was not found in the emitted declaration.");
161
+ if (biomeResult.status !== 0) {
162
+ throw new Error(`Biome formatting failed with exit code ${biomeResult.status}.`);
154
163
  }
164
+ }
155
165
 
156
- const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
157
- const appRouterDeclaration = statements
158
- .map(statement => printer.printNode(ts.EmitHint.Unspecified, statement, sourceFile))
159
- .join("\n")
160
- .replace(/^(?: {4})+/gm, indentation => "\t".repeat(indentation.length / 4));
161
-
162
- await mkdir(path.dirname(outputPath), { recursive: true });
163
- await writeFile(
164
- outputPath,
165
- `// Generated by \`npx @automateinc/fleet-types generate\`. Do not edit manually.\n${appRouterDeclaration}\n`,
166
- );
167
-
168
- if (existsSync(biomePath)) {
169
- const biomeResult = spawnSync(biomePath, ["format", "--write", outputPath], {
170
- cwd: callerRoot,
171
- stdio: "inherit",
172
- });
173
- if (biomeResult.error) {
174
- throw biomeResult.error;
175
- }
176
- if (biomeResult.status !== 0) {
177
- throw new Error(`Biome formatting failed with exit code ${biomeResult.status}.`);
178
- }
179
- }
166
+ console.log(`Generated ${path.relative(callerRoot, outputPath)} from ${routerSourcePath}`);
167
+ }
180
168
 
181
- console.log(`Generated ${path.relative(callerRoot, outputPath)} from ${routerSourcePath}`);
182
- } finally {
183
- await rm(temporaryDirectory, { force: true, recursive: true });
184
- }
169
+ function formatTypeScriptDiagnostics(ts, diagnostics, currentDirectory) {
170
+ return ts.formatDiagnosticsWithColorAndContext(diagnostics, {
171
+ getCanonicalFileName: fileName => fileName,
172
+ getCurrentDirectory: () => currentDirectory,
173
+ getNewLine: () => "\n",
174
+ });
185
175
  }
186
176
 
187
177
  function printUsage() {
@@ -0,0 +1,61 @@
1
+ // Generated by `npx @automateinc/fleet-types generate`. Do not edit manually.
2
+ export declare const appRouter: import("@trpc/server").TRPCBuiltRouter<
3
+ {
4
+ ctx: {
5
+ client: "FLEET_WEB" | "FLEET_MOBILE" | "FLEET_MOBILE_USER" | undefined;
6
+ regionId: string | undefined;
7
+ request: import("express").Request<
8
+ import("express-serve-static-core").ParamsDictionary,
9
+ any,
10
+ any,
11
+ import("qs").ParsedQs,
12
+ Record<string, any>
13
+ >;
14
+ token: string | undefined;
15
+ };
16
+ meta: object;
17
+ errorShape: import("@trpc/server").TRPCDefaultErrorShape;
18
+ transformer: false;
19
+ },
20
+ import("@trpc/server").TRPCDecorateCreateRouterOptions<{
21
+ auth: import("@trpc/server").TRPCBuiltRouter<
22
+ {
23
+ ctx: {
24
+ client: "FLEET_WEB" | "FLEET_MOBILE" | "FLEET_MOBILE_USER" | undefined;
25
+ regionId: string | undefined;
26
+ request: import("express").Request<
27
+ import("express-serve-static-core").ParamsDictionary,
28
+ any,
29
+ any,
30
+ import("qs").ParsedQs,
31
+ Record<string, any>
32
+ >;
33
+ token: string | undefined;
34
+ };
35
+ meta: object;
36
+ errorShape: import("@trpc/server").TRPCDefaultErrorShape;
37
+ transformer: false;
38
+ },
39
+ import("@trpc/server").TRPCDecorateCreateRouterOptions<{
40
+ login: import("@trpc/server").TRPCMutationProcedure<{
41
+ input: {
42
+ email: string;
43
+ password: string;
44
+ };
45
+ output: {
46
+ token: string;
47
+ };
48
+ meta: object;
49
+ }>;
50
+ refreshToken: import("@trpc/server").TRPCMutationProcedure<{
51
+ input: void;
52
+ output: {
53
+ token: string;
54
+ };
55
+ meta: object;
56
+ }>;
57
+ }>
58
+ >;
59
+ }>
60
+ >;
61
+ export type AppRouter = typeof appRouter;
package/package.json CHANGED
@@ -57,5 +57,5 @@
57
57
  "test": "echo \"Error: no test specified\" && exit 1"
58
58
  },
59
59
  "types": "dist/types/index.d.ts",
60
- "version": "1.0.102"
60
+ "version": "1.0.104"
61
61
  }