Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 42x 42x 42x 1x 42x 42x 42x 42x 42x 6x 6x 6x 6x 6x 42x 42x 42x 20x 20x 18x 18x 8x 8x 18x 18x 2x 20x 20x 22x 22x 22x 42x 42x 2x 2x 42x 2x 2x 18x 42x 42x 52x 30x 30x 4x 4x 4x 4x 30x 6x 6x 30x 30x 52x 22x 22x 22x 22x 22x 22x 52x 36x 4x 4x 4x 4x 4x 4x 32x 32x 36x 36x 18x 18x 36x 22x 22x 8x 8x 22x 22x 22x 10x 10x 10x 36x 6x 6x 6x 6x 36x 2x 2x 2x 2x 2x 2x 2x 2x 36x 8x 8x 36x 52x 8x 8x 22x 52x 42x 60x 60x 26x 26x 34x 60x 34x 34x | /**
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
import type { JSONSchema, SchemaResolver } from './types.js';
const JSON_SCHEMA_SCALAR_TYPES = [
'any',
'boolean',
'integer',
'null',
'number',
'string',
];
const WILDCARD_PROPERTY_NAME = '(*)';
/** Options for the Picoschema parser. */
export interface PicoschemaOptions {
/** The schema resolver to use. */
schemaResolver?: SchemaResolver;
}
/**
* Parses Picoschema definitions into JSON Schema.
*
* Handles basic types, optional fields, descriptions, arrays, objects,
* enums, wildcards, and named schema resolution.
*
* @param schema The schema definition to parse.
* @param options The options for the parser.
* @return The resulting JSON Schema, or null if the input is null.
*/
export async function picoschema(schema: unknown, options?: PicoschemaOptions) {
return new PicoschemaParser(options).parse(schema);
}
/**
* Parses Picoschema definitions into JSON Schema.
*
* Handles basic types, optional fields, descriptions, arrays, objects,
* enums, wildcards, and named schema resolution.
*/
export class PicoschemaParser {
schemaResolver?: SchemaResolver;
/**
* Constructs a new PicoschemaParser.
*
* @param options The options for the parser.
*/
constructor(options?: PicoschemaOptions) {
this.schemaResolver = options?.schemaResolver;
}
/**
* Resolves a named schema using the configured resolver.
*
* @param schemaName The name of the schema to resolve.
* @return The resolved JSON Schema.
*/
private async mustResolveSchema(schemaName: string): Promise<JSONSchema> {
if (!this.schemaResolver) {
throw new Error(`Picoschema: unsupported scalar type '${schemaName}'.`);
}
const val = await this.schemaResolver(schemaName);
if (!val) {
throw new Error(
`Picoschema: could not find schema with name '${schemaName}'`
);
}
return val;
}
/**
* Parses a schema, detecting if it's Picoschema or JSON Schema.
*
* @param schema The schema definition to parse.
* @return The resulting JSON Schema, or null if the input is null.
*/
async parse(schema: unknown): Promise<JSONSchema | null> {
if (!schema) {
return null;
}
// Allow for top-level named schemas
if (typeof schema === 'string') {
const [type, description] = extractDescription(schema);
if (JSON_SCHEMA_SCALAR_TYPES.includes(type)) {
let out: JSONSchema = { type };
if (description) {
out = { ...out, description };
}
return out;
}
const resolvedSchema = await this.mustResolveSchema(type);
return description ? { ...resolvedSchema, description } : resolvedSchema;
}
// If there's a JSON schema-ish type at the top level, treat as JSON schema.
if (
[...JSON_SCHEMA_SCALAR_TYPES, 'object', 'array'].includes(
(schema as any)?.type
)
) {
return schema;
}
if (typeof (schema as any)?.properties === 'object') {
return { ...schema, type: 'object' };
}
return this.parsePico(schema);
}
/**
* Parses a Picoschema object or string fragment.
*
* @param obj The object or string fragment to parse.
* @param path The current path within the schema structure.
* @return The parsed JSON Schema.
*/
private async parsePico(obj: any, path: string[] = []): Promise<JSONSchema> {
if (typeof obj === 'string') {
const [type, description] = extractDescription(obj);
if (!JSON_SCHEMA_SCALAR_TYPES.includes(type)) {
let resolvedSchema = await this.mustResolveSchema(type);
if (description) resolvedSchema = { ...resolvedSchema, description };
return resolvedSchema;
}
if (type === 'any') {
return description ? { description } : {};
}
return description ? { type, description } : { type };
}
if (typeof obj !== 'object') {
throw new Error(
`Picoschema: only consists of objects and strings. Got: ${JSON.stringify(obj)}`
);
}
const schema: JSONSchema = {
type: 'object',
properties: {},
required: [],
additionalProperties: false,
};
for (const key in obj) {
// wildcard property
if (key === WILDCARD_PROPERTY_NAME) {
schema.additionalProperties = await this.parsePico(obj[key], [
...path,
key,
]);
continue;
}
const [name, typeInfo] = key.split('(');
const isOptional = name.endsWith('?');
const propertyName = isOptional ? name.slice(0, -1) : name;
if (!isOptional) {
schema.required.push(propertyName);
}
if (!typeInfo) {
const prop = { ...(await this.parsePico(obj[key], [...path, key])) };
// make all optional fields also nullable
if (isOptional && typeof prop.type === 'string') {
prop.type = [prop.type, 'null'];
}
schema.properties[propertyName] = prop;
continue;
}
const [type, description] = extractDescription(
typeInfo.substring(0, typeInfo.length - 1)
);
if (type === 'array') {
schema.properties[propertyName] = {
type: isOptional ? ['array', 'null'] : 'array',
items: await this.parsePico(obj[key], [...path, key]),
};
} else if (type === 'object') {
const prop = await this.parsePico(obj[key], [...path, key]);
if (isOptional) prop.type = [prop.type, 'null'];
schema.properties[propertyName] = prop;
} else if (type === 'enum') {
const prop = { enum: obj[key] };
if (isOptional && !prop.enum.includes(null)) prop.enum.push(null);
schema.properties[propertyName] = prop;
} else {
throw new Error(
`Picoschema: parenthetical types must be 'object' or 'array', got: ${type}`
);
}
if (description) {
schema.properties[propertyName].description = description;
}
}
if (!schema.required.length) {
schema.required = undefined;
}
return schema;
}
}
/**
* Extracts the type name and description from a string.
*
* @param input - The input string to extract from.
* @return A tuple containing the type name and description.
*/
function extractDescription(input: string): [string, string | null] {
if (!input.includes(',')) {
return [input, null];
}
const match = input.match(/(.*?), *(.*)$/);
if (!match) {
return [input, null];
}
return [match[1], match[2]];
}
|