Skip to content
Open
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
17 changes: 17 additions & 0 deletions .chronus/changes/json-schema-filenames.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
changeKind: feature
packages:
- "@typespec/json-schema"
---

Support a `file-name` template for schema filenames, including `.schema.json` and `.schema.yaml`. Implicit schema ids and references follow the configured filenames.

Directory paths are not allowed in the template; use `emitter-output-dir` to configure the output directory.
Templates resolving to empty names or directory markers are rejected, and output filename collisions are reported as errors instead of overwriting schemas.

```yaml
options:
"@typespec/json-schema":
file-type: json
file-name: "{name}.schema.{ext}"
```
12 changes: 12 additions & 0 deletions packages/json-schema/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,18 @@ See [Configuring output directory for more info](https://typespec.io/docs/handbo

Serialize the schema as either yaml or json.

### `file-name`

**Type:** `string`

**Default:** `"{name}.{ext}"`

File name template for each schema. Supports `{name}` for the declaration name
and `{ext}` for the extension selected by `file-type`.
Directory separators and `#` are not allowed; use `emitter-output-dir` for the output directory.
Also determines implicit schema ids and references. Does not change the bundle
file name, which is controlled by `bundleId`.

### `int64-strategy`

**Type:** `"string" | "number"`
Expand Down
31 changes: 30 additions & 1 deletion packages/json-schema/src/json-schema-emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import {
getPattern,
getRelativePathFromDirectory,
getSummary,
interpolatePath,
isStringType,
isType,
isTypeRefType,
Expand Down Expand Up @@ -1019,6 +1020,31 @@ export class JsonSchemaEmitter extends TypeEmitter<Record<string, any>, JSONSche
content: this.#serializeSourceFileContent(content),
});
} else {
const paths = new DuplicateTracker<string, JsonSchemaDeclaration>();
for (const sf of sourceFiles) {
if (sf.meta.shouldEmit) {
paths.track(sf.path, this.#typeForSourceFile.get(sf)!);
}
}

let hasDuplicatePaths = false;
for (const [path, types] of paths.entries()) {
hasDuplicatePaths = true;
const file = getRelativePathFromDirectory(
this.emitter.getOptions().emitterOutputDir,
path,
false,
);
for (const type of types) {
reportDiagnostic(this.emitter.getProgram(), {
code: "duplicate-output-file",
format: { file },
target: type,
});
}
}
if (hasDuplicatePaths) return;

for (const sf of sourceFiles) {
const emittedSf = await this.emitter.emitSourceFile(sf);

Expand Down Expand Up @@ -1180,7 +1206,10 @@ export class JsonSchemaEmitter extends TypeEmitter<Record<string, any>, JSONSche

#newFileScope(type: JsonSchemaDeclaration) {
const sourceFile = this.emitter.createSourceFile(
`${sanitizePathSegment(this.declarationName(type)!)}.${this.#fileExtension()}`,
interpolatePath(this.emitter.getOptions()["file-name"] ?? "{name}.{ext}", {
name: sanitizePathSegment(this.declarationName(type)!),
ext: this.#fileExtension(),
}),
Comment thread
timotheeguerin marked this conversation as resolved.
Resolved
Comment thread
timotheeguerin marked this conversation as resolved.
Resolved
);

sourceFile.meta.shouldEmit = true;
Expand Down
40 changes: 39 additions & 1 deletion packages/json-schema/src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,20 @@ export type PolymorphicModelsStrategy = "ignore" | "oneOf" | "anyOf";
export interface JSONSchemaEmitterOptions {
/**
* Serialize the schema as either yaml or json.
* @defaultValue yaml it not specified infer from the `output-file` extension
* @defaultValue yaml
*/
"file-type"?: FileType;

/**
* File name template for each schema. Supports `{name}` for the declaration name
* and `{ext}` for the extension selected by `file-type`.
* Directory separators and `#` are not allowed; use `emitter-output-dir` for the output directory.
* Also determines implicit schema ids and references. Does not change the bundle
* file name, which is controlled by `bundleId`.
* @defaultValue `{name}.{ext}`
*/
"file-name"?: string;

/**
* How to handle 64-bit integers on the wire. Options are:
*
Expand Down Expand Up @@ -94,6 +104,18 @@ export const EmitterOptionsSchema: JSONSchemaType<JSONSchemaEmitterOptions> = {
nullable: true,
description: "Serialize the schema as either yaml or json.",
},
"file-name": {
type: "string",
nullable: true,
default: "{name}.{ext}",
description: [
"File name template for each schema. Supports `{name}` for the declaration name",
"and `{ext}` for the extension selected by `file-type`.",
"Directory separators and `#` are not allowed; use `emitter-output-dir` for the output directory.",
"Also determines implicit schema ids and references. Does not change the bundle",
"file name, which is controlled by `bundleId`.",
].join("\n"),
},
"int64-strategy": {
type: "string",
enum: ["string", "number"],
Expand Down Expand Up @@ -155,6 +177,22 @@ export const EmitterOptionsSchema: JSONSchemaType<JSONSchemaEmitterOptions> = {
export const $lib = createTypeSpecLibrary({
name: "@typespec/json-schema",
diagnostics: {
"invalid-file-name": {
severity: "error",
messages: {
default:
"The 'file-name' option must not contain directory separators. Use 'emitter-output-dir' to configure the output directory.",
empty:
"The 'file-name' option must resolve to a non-empty file name other than '.' or '..'. Use '{name}' and '{ext}' as placeholders.",
fragment: "The 'file-name' option must not contain '#', which is a URI fragment delimiter.",
},
},
"duplicate-output-file": {
severity: "error",
messages: {
default: paramMessage`Multiple schemas emit to the same file "${"file"}". Configure 'file-name' to produce unique filenames.`,
},
},
"invalid-prefix-items": {
severity: "error",
messages: {
Expand Down
34 changes: 33 additions & 1 deletion packages/json-schema/src/on-emit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { createAssetEmitter } from "@typespec/asset-emitter";
import {
type EmitContext,
type Enum,
interpolatePath,
type Model,
NoTarget,
type Scalar,
type Union,
} from "@typespec/compiler";
import { getJsonSchemaTypes } from "./decorators.js";
import { JsonSchemaEmitter } from "./json-schema-emitter.js";
import type { JSONSchemaEmitterOptions } from "./lib.js";
import { type JSONSchemaEmitterOptions, reportDiagnostic } from "./lib.js";
export { $flags, $lib, EmitterOptionsSchema, type JSONSchemaEmitterOptions } from "./lib.js";

export const namespace = "TypeSpec.JsonSchema";
Expand All @@ -18,6 +20,36 @@ export type JsonSchemaDeclaration = Model | Union | Enum | Scalar;
* Internal: TypeSpec emitter entry point
*/
export async function $onEmit(context: EmitContext<JSONSchemaEmitterOptions>) {
if (context.options["file-name"]?.match(/[/\\]/)) {
Comment thread
timotheeguerin marked this conversation as resolved.
Resolved
reportDiagnostic(context.program, {
code: "invalid-file-name",
target: NoTarget,
});
return;
}

if (context.options["file-name"]?.includes("#")) {
reportDiagnostic(context.program, {
code: "invalid-file-name",
messageId: "fragment",
target: NoTarget,
});
return;
}

const fileName = interpolatePath(context.options["file-name"] ?? "{name}.{ext}", {
name: "{name}",
ext: context.options["file-type"] === "json" ? "json" : "yaml",
});
if (fileName === "" || fileName === "." || fileName === "..") {
Comment thread
timotheeguerin marked this conversation as resolved.
Resolved
reportDiagnostic(context.program, {
code: "invalid-file-name",
messageId: "empty",
target: NoTarget,
});
return;
}

const emitter = createAssetEmitter(context.program, JsonSchemaEmitter as any, context);

if (emitter.getOptions().emitAllModels) {
Expand Down
6 changes: 6 additions & 0 deletions packages/json-schema/test/ids.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ describe("implicit ids", () => {
code: "@typespec/json-schema/duplicate-id",
message: `There are multiple types with the same id "Foo.json".`,
},
{
code: "@typespec/json-schema/duplicate-output-file",
},
{
code: "@typespec/json-schema/duplicate-output-file",
},
]);
});
});
Expand Down
Loading
Loading