Skip to content
Draft

Tspq #9671

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/tspq/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Changelog - @typespec/tspq

## 0.78.0

### Features

- Initial release of the tspq CLI.
21 changes: 21 additions & 0 deletions packages/tspq/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Microsoft Corporation. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
13 changes: 13 additions & 0 deletions packages/tspq/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# @typespec/tspq

TypeSpec tspq is a CLI for querying information from a TypeSpec spec by compiling it.

## Usage

```bash
tspq summary ./main.tsp
```

```bash
tspq summary ./main.tsp --json
```
2 changes: 2 additions & 0 deletions packages/tspq/cmd/tspq.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/usr/bin/env node
import "../dist/src/cli.js";
52 changes: 52 additions & 0 deletions packages/tspq/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
{
"name": "@typespec/tspq",
"version": "0.78.0",
"author": "Microsoft Corporation",
"description": "TypeSpec query CLI",
"homepage": "https://typespec.io",
"readme": "https://github.com/microsoft/typespec/blob/main/README.md",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/microsoft/typespec.git"
},
"bugs": {
"url": "https://github.com/microsoft/typespec/issues"
},
"keywords": [
"typespec"
],
"type": "module",
"bin": {
"tspq": "./cmd/tspq.js"
},
"engines": {
"node": ">=20.0.0"
},
"scripts": {
"clean": "rimraf ./dist ./temp",
"build": "tsc -p tsconfig.build.json",
"watch": "tsc -p tsconfig.build.json --watch",
"test": "vitest run",
"test:watch": "vitest -w",
"test:ci": "vitest run --coverage --reporter=junit --reporter=default",
"lint": "eslint . --max-warnings=0",
"lint:fix": "eslint . --fix"
},
"files": [
"dist/**",
"!dist/test/**"
],
"dependencies": {
"@typespec/compiler": "workspace:^",
"picocolors": "~1.1.1",
"yargs": "~18.0.0"
},
"devDependencies": {
"@types/node": "~25.0.2",
"@types/yargs": "~17.0.33",
"rimraf": "~6.1.2",
"typescript": "~5.9.2",
"vitest": "^4.0.15"
}
}
143 changes: 143 additions & 0 deletions packages/tspq/src/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/* eslint-disable no-console */
import { logDiagnostics, NodeHost, resolvePath } from "@typespec/compiler";
import yargs from "yargs";
import { compileWithLocalCompiler } from "./compile-with-local-compiler.js";
import { TypePrinter } from "./printer.js";
import { summarizeProgram } from "./summary.js";
import { getTypeViewJson, type TypeViewJsonOptions } from "./type-view-json.js";

try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
await import("source-map-support/register.js");
} catch {
// package only present in dev.
}

async function main() {
await yargs(process.argv.slice(2))
.scriptName("tspq")
.help()
.strict()
.parserConfiguration({
"greedy-arrays": false,
"boolean-negation": false,
})
.option("pretty", {
type: "boolean",
description: "Enable color and formatting in output.",
default: true,
})
.command(
"view <reference>",
"View details about a specific type.",
(cmd) => {
return cmd
.positional("reference", {
description: "Type reference to inspect.",
type: "string",
})
.option("json", {
type: "boolean",
description: "Output view as JSON.",
default: false,
})
.option("depth", {
type: "number",
description: "How many levels deep to expand nested types (default: 1).",
default: 1,
})
.option("entrypoint", {
description: "Path to the TypeSpec entrypoint.",
type: "string",
});
},
async (args) => {
const program = await compileWithLocalCompiler(resolvePath(process.cwd(), args.entrypoint));

if (program.diagnostics.length > 0) {
logDiagnostics(program.diagnostics, NodeHost.logSink);
if (program.hasError()) {
process.exit(1);
}
}

if (!args.reference) {
console.error("Type reference is required.");
process.exit(1);
}

const [resolvedType, diagnostics] = program.resolveTypeReference(args.reference);
if (diagnostics.length > 0) {
logDiagnostics(diagnostics, NodeHost.logSink);
if (diagnostics.some((diag) => diag.severity === "error")) {
process.exit(1);
}
}

if (!resolvedType) {
console.error(`Type reference not found: ${args.reference}`);
process.exit(1);
}

if (args.json) {
const options: TypeViewJsonOptions = { depth: args.depth };
console.log(JSON.stringify(getTypeViewJson(program, resolvedType, options), null, 2));
} else {
const printer = new TypePrinter(args.pretty);
console.log(printer.formatTypeView(program, resolvedType));
}
},
)
.command(
"summary",
"Compile a TypeSpec spec and print a summary.",
(cmd) => {
return cmd
.option("entrypoint", {
description: "Path to the TypeSpec entrypoint.",
type: "string",
})
.option("json", {
type: "boolean",
description: "Output summary as JSON.",
default: false,
});
},
async (args) => {
const program = await compileWithLocalCompiler(resolvePath(process.cwd(), args.entrypoint));

if (program.diagnostics.length > 0) {
logDiagnostics(program.diagnostics, NodeHost.logSink);
if (program.hasError()) {
process.exit(1);
}
}

const summary = summarizeProgram(program);
if (args.json) {
console.log(JSON.stringify(summary, null, 2));
} else {
const printer = new TypePrinter(args.pretty);
console.log(printer.formatSummary(summary));
}
},
)
.demandCommand(1, "You must use one of the supported commands.").argv;
}

function internalError(error: unknown): never {
console.error("Internal error!");
console.error("File issue at https://github.com/microsoft/typespec");
console.error();
console.error(error);

process.exit(1);
}

process.on("unhandledRejection", (error: unknown) => {
console.error("Unhandled promise rejection!");
internalError(error);
});

main().catch(internalError);
37 changes: 37 additions & 0 deletions packages/tspq/src/compile-with-local-compiler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { normalizePath, type Program } from "@typespec/compiler";
import { resolveModule, type ResolveModuleHost } from "@typespec/compiler/module-resolver";
import { readFile, realpath, stat } from "fs/promises";
import { dirname } from "path";
import { pathToFileURL } from "url";

export async function compileWithLocalCompiler(entrypoint: string): Promise<Program> {
const entrypointPath = normalizePath(entrypoint);
const compiler = await importTypeSpecCompiler(dirname(entrypointPath));
const resolved = compiler.resolvePath(entrypointPath);
const program = await compiler.compile(compiler.NodeHost, resolved, { noEmit: true });
return program;
}

async function importTypeSpecCompiler(
baseDir: string,
): Promise<typeof import("@typespec/compiler")> {
try {
const host: ResolveModuleHost = {
realpath,
readFile: async (path: string) => await readFile(path, "utf-8"),
stat,
};
const resolved = await resolveModule(host, "@typespec/compiler", {
baseDir,
conditions: ["import"],
});
return await import(
pathToFileURL(resolved.type === "module" ? resolved.mainFile : resolved.path).toString()
);
} catch (err: any) {
if (err.code === "MODULE_NOT_FOUND") {
return await import("@typespec/compiler");
}
throw err;
}
}
Loading
Loading