@hasagi/schema 0.7.0 → 0.7.1

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.
@@ -1,14 +0,0 @@
1
- import { ComponentsObject, ExternalDocumentationObject, InfoObject, OpenAPIObject, PathsObject, SecurityRequirementObject, ServerObject, TagObject } from "./open-api-types.js";
2
- export default class OpenAPISchema implements OpenAPIObject {
3
- openapi: string;
4
- info: InfoObject;
5
- servers?: ServerObject[] | undefined;
6
- paths: PathsObject;
7
- components?: ComponentsObject | undefined;
8
- security?: SecurityRequirementObject[] | undefined;
9
- tags?: TagObject[] | undefined;
10
- externalDocs?: ExternalDocumentationObject | undefined;
11
- constructor(schema: OpenAPIObject);
12
- getTypeScriptInterfaces(namespace?: string): string[];
13
- getEndpointInterfaces(namespace?: string): string;
14
- }
package/openapi-schema.js DELETED
@@ -1,134 +0,0 @@
1
- import { formatFieldName } from "./util.js";
2
- const TYPE_OVERRIDES = {
3
- "PluginResourceEvent": { definition: `interface PluginResourceEvent<DataType = unknown> {
4
- uri: string
5
- eventType: {{namespace}}PluginResourceEventType
6
- data: DataType
7
- }` }
8
- };
9
- export default class OpenAPISchema {
10
- openapi;
11
- info;
12
- servers;
13
- paths;
14
- components;
15
- security;
16
- tags;
17
- externalDocs;
18
- constructor(schema) {
19
- Object.assign(this, schema);
20
- }
21
- getTypeScriptInterfaces(namespace) {
22
- if (this.components?.schemas === undefined)
23
- return [];
24
- return Object.entries(this.components.schemas).map(([name, schema]) => {
25
- if (TYPE_OVERRIDES[name] && TYPE_OVERRIDES[name].definition)
26
- return `export ${TYPE_OVERRIDES[TYPE_OVERRIDES[name].rename ?? name].definition}`.replaceAll("{{namespace}}", namespace !== undefined ? `${namespace}.` : "");
27
- if ("$ref" in schema) {
28
- return `export type ${name} = ${schema.$ref.split("/").at(-1)}`;
29
- }
30
- else if (schema.enum !== undefined) {
31
- return `export type ${name} = ${schema.enum.map(e => `"${e}"`).join(" | ")}`;
32
- }
33
- else if (schema.type === "object") {
34
- const _interface = [`export interface ${name.replaceAll("-", "_")} {`];
35
- if (schema.additionalProperties)
36
- _interface.push(`\t[key: string | number]: ${schema.additionalProperties === true ? "any" : getTypeBySchemaObject(schema.additionalProperties, namespace)}`);
37
- if (schema.properties)
38
- Object.entries(schema.properties).forEach(([name, property]) => {
39
- const required = schema.required?.includes(name) ?? false;
40
- _interface.push(`\t${formatFieldName(name)}${required ? "" : "?"}: ${getTypeBySchemaObject(property, namespace)}`);
41
- });
42
- _interface.push("}");
43
- return _interface.join("\n");
44
- }
45
- return getTypeBySchemaObject(schema, namespace);
46
- });
47
- }
48
- getEndpointInterfaces(namespace) {
49
- const endpoints = {};
50
- Object.entries(this.paths).forEach(([path, info]) => {
51
- endpoints[path] = {
52
- get: getMethodInfo(info.get, namespace),
53
- post: getMethodInfo(info.post, namespace),
54
- put: getMethodInfo(info.put, namespace),
55
- patch: getMethodInfo(info.patch, namespace),
56
- head: getMethodInfo(info.head, namespace),
57
- delete: getMethodInfo(info.delete, namespace),
58
- };
59
- });
60
- let endpointsStr = "export interface LCUEndpoints {\n";
61
- Object.entries(endpoints).map(([path, r]) => {
62
- endpointsStr += `\t"${path}": {\n`;
63
- Object.entries(r).map(([method, types]) => endpointsStr += types !== undefined ? `\t\t${method}: { Parameters: ${types.Parameter}, Body: ${types.Body}, Response: ${types.Response} }\n` : "");
64
- endpointsStr += "\t},\n";
65
- }).join("\t");
66
- endpointsStr += "}";
67
- return endpointsStr + "\n\n" +
68
- `// @ts-expect-error
69
- export type LCUEndpoint<Method extends HttpMethod, Path extends EndpointsWithMethod<Method>> = LCUEndpointBodyType<Method, Path> extends never ? (...args: [...LCUEndpoints[Path][Method]["Parameters"]]) => Promise<LCUEndpointResponseType<Method, Path>> : (...args: [...LCUEndpoints[Path][Method]["Parameters"], body: LCUEndpointBodyType<Method, Path>]) => Promise<LCUEndpointResponseType<Method, Path>>
70
- // @ts-expect-error
71
- export type LCUEndpointResponseType<Method extends HttpMethod, Path extends EndpointsWithMethod<Method>> = LCUEndpoints[Path][Method]["Response"]
72
- // @ts-expect-error
73
- export type LCUEndpointBodyType<Method extends HttpMethod, Path extends EndpointsWithMethod<Method>> = LCUEndpoints[Path][Method]["Body"]
74
-
75
- export type EndpointsWithMethod<Method extends HttpMethod> = { [K in keyof LCUEndpoints]: LCUEndpoints[K] extends { [key in Method]: { } } ? K : never }[keyof LCUEndpoints]
76
-
77
- export type HttpMethod = "delete" | "get" | "head" | "patch" | "post" | "put";`;
78
- }
79
- }
80
- function getMethodInfo(info, namespace) {
81
- if (!info)
82
- return undefined;
83
- const pathParams = info.parameters?.filter(p => p.in === "path") ?? [];
84
- const pathParamsObject = `${pathParams.map(p => `${p.name.replaceAll("-", "_").replaceAll("+", "")}: ${getTypeBySchemaObject(p.schema, namespace)}`).join(", ")}`;
85
- const queryParams = info.parameters?.filter(p => p.in === "query") ?? [];
86
- const queryParamsObject = `{ ${queryParams.map(p => `"${p.name}"${p.required ? "" : "?"}: ${getTypeBySchemaObject(p.schema, namespace)}`).join(", ")} }`;
87
- return {
88
- Parameter: `[${pathParamsObject}${queryParams.length > 0 ? `${pathParams.length > 0 ? ", " : ""}params${queryParams.some(p => p.required) ? "" : "?"}: ${queryParamsObject}` : ""}]`,
89
- Body: info.requestBody !== undefined && "content" in info.requestBody ? getTypeBySchemaObject(info.requestBody.content["application/json"]["schema"], namespace) : "never",
90
- Response: info.responses["2XX"] !== undefined && "content" in info.responses["2XX"] ? getTypeBySchemaObject(info.responses["2XX"]["content"]["application/json"]["schema"], namespace) : "void"
91
- };
92
- }
93
- function getTypeBySchemaObject(schema, namespace) {
94
- if (schema === undefined)
95
- return "void";
96
- if ("$ref" in schema)
97
- return `${namespace !== undefined ? `${namespace}.` : ""}${schema.$ref.split("/").at(-1)}`;
98
- switch (schema.type) {
99
- case "string":
100
- return "string";
101
- case "number":
102
- case "integer":
103
- return "number";
104
- case "boolean":
105
- return "boolean";
106
- case "array":
107
- return getArrayTypeBySchemaObject(schema, namespace).split("\n").join("\n\t");
108
- case "object":
109
- return getObjectTypeBySchemaObject(schema, namespace).split("\n").join("\n\t");
110
- default:
111
- return `${namespace}.${TYPE_OVERRIDES[schema.type].rename ? TYPE_OVERRIDES[schema.type].rename : schema.type}` ?? "unknown";
112
- }
113
- }
114
- function getArrayTypeBySchemaObject(schema, namespace) {
115
- if (schema.type !== "array")
116
- throw new Error();
117
- if (schema.items)
118
- return `${getTypeBySchemaObject(schema.items, namespace)}[]`;
119
- return "any[]";
120
- }
121
- function getObjectTypeBySchemaObject(schema, namespace) {
122
- const _interface = [`{`];
123
- if (schema.additionalProperties && !schema.properties)
124
- return schema.additionalProperties === true ? "unknown" : `Record<string, ${getTypeBySchemaObject(schema.additionalProperties, namespace)}>`;
125
- if (schema.additionalProperties)
126
- _interface.push(`\t[key: string | number]: ${schema.additionalProperties === true ? "any" : getTypeBySchemaObject(schema.additionalProperties, namespace)}`);
127
- if (schema.properties)
128
- Object.entries(schema.properties).forEach(([name, property]) => {
129
- const required = schema.required?.includes(name) ?? false;
130
- _interface.push(`\t${formatFieldName(name)}${required ? "" : "?"}: ${getTypeBySchemaObject(property, namespace).split("\n").join("\n\t")}`);
131
- });
132
- _interface.push("}");
133
- return _interface.join("\n");
134
- }