Skip to content

Commit

Permalink
style: lint with prettier v3
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Jul 28, 2023
1 parent 77ac9aa commit 3292277
Show file tree
Hide file tree
Showing 15 changed files with 57 additions and 59 deletions.
4 changes: 1 addition & 3 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
{
"trailingComma": "es5"
}
{}
2 changes: 1 addition & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ async function main() {
const json = JSON.stringify(schema, null, 2);
const outfile = resolve(
process.cwd(),
args.write === true ? "schema.json" : args.write
args.write === true ? "schema.json" : args.write,
);
await writeFile(outfile, json);
} else {
Expand Down
20 changes: 10 additions & 10 deletions src/generator/dts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,13 @@ function extractTypeImports(declarations: string) {
declarations = declarations.replace(
new RegExp(
`typeof import\\(['"]${source}['"]\\)(\\.${type}|\\[['"]${type}['"]\\])`,
"g"
"g",
),
alias
alias,
);
}
imports.push(
`import type { ${sourceImports.join(", ")} } from '${source}'`
`import type { ${sourceImports.join(", ")} } from '${source}'`,
);
}
return [...imports, declarations].join("\n");
Expand All @@ -104,7 +104,7 @@ export function generateTypes(schema: Schema, opts: GenerateTypesOptions = {}) {
function _genTypes(
schema: Schema,
spaces: string,
opts: GenerateTypesOptions
opts: GenerateTypesOptions,
): string[] {
const buff: string[] = [];

Expand All @@ -119,13 +119,13 @@ function _genTypes(
buff.push(
`${escapeKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: ${
val.tsType
},\n`
},\n`,
);
} else if (val.type === "object") {
buff.push(
`${escapeKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: {`,
..._genTypes(val, spaces, opts),
"},\n"
"},\n",
);
} else {
let type: string;
Expand All @@ -139,7 +139,7 @@ function _genTypes(
buff.push(
`${escapeKey(key)}${
isRequired(schema, key, opts) ? "" : "?"
}: ${type},\n`
}: ${type},\n`,
);
}
}
Expand All @@ -161,7 +161,7 @@ function _genTypes(

function getTsType(
type: TypeDescriptor | TypeDescriptor[],
opts: GenerateTypesOptions
opts: GenerateTypesOptions,
): string {
if (Array.isArray(type)) {
return (
Expand Down Expand Up @@ -201,13 +201,13 @@ function getTsType(
export function genFunctionType(schema, opts: GenerateTypesOptions) {
return `(${genFunctionArgs(schema.args, opts)}) => ${getTsType(
schema.returns,
opts
opts,
)}`;
}

export function genFunctionArgs(
args: Schema["args"],
opts: GenerateTypesOptions
opts: GenerateTypesOptions,
) {
return (
args
Expand Down
4 changes: 2 additions & 2 deletions src/generator/md.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export function generateMarkdown(schema: Schema) {
export function _generateMarkdown(
schema: Schema,
title: string,
level: string
level: string,
) {
const lines: string[] = [];

Expand All @@ -24,7 +24,7 @@ export function _generateMarkdown(

// Type and default
lines.push(
`- **Type**: \`${schema.markdownType || schema.tsType || schema.type}\``
`- **Type**: \`${schema.markdownType || schema.tsType || schema.type}\``,
);
if ("default" in schema) {
lines.push(`- **Default**: \`${JSON.stringify(schema.default)}\``);
Expand Down
36 changes: 18 additions & 18 deletions src/loader/babel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ type GetCodeFn = (loc: t.SourceLocation) => string;

const babelPluginUntyped: PluginItem = function (
api: ConfigAPI,
options: { experimentalFunctions?: boolean }
options: { experimentalFunctions?: boolean },
) {
api.cache.using(() => version);

Expand All @@ -32,7 +32,7 @@ const babelPluginUntyped: PluginItem = function (
declaration.init.params,
t.isBlockStatement(declaration.init.body)
? (declaration.init.body as t.BlockStatement)
: t.blockStatement([t.returnStatement(declaration.init.body)])
: t.blockStatement([t.returnStatement(declaration.init.body)]),
);
newDeclaration.returnType = declaration.init.returnType;
p.replaceWith(newDeclaration);
Expand All @@ -43,7 +43,7 @@ const babelPluginUntyped: PluginItem = function (
const schema = parseJSDocs(
p.node.leadingComments
.filter((c) => c.type === "CommentBlock")
.map((c) => c.value)
.map((c) => c.value),
);

const valueNode =
Expand All @@ -57,7 +57,7 @@ const babelPluginUntyped: PluginItem = function (
(prop) =>
"key" in prop &&
prop.key.type === "Identifier" &&
prop.key.name === "$schema"
prop.key.name === "$schema",
);
if (schemaProp && "value" in schemaProp) {
if (schemaProp.value.type === "ObjectExpression") {
Expand All @@ -70,7 +70,7 @@ const babelPluginUntyped: PluginItem = function (
} else {
// Object has not $schema
valueNode.properties.unshift(
...astify({ $schema: schema }).properties
...astify({ $schema: schema }).properties,
);
}
} else {
Expand All @@ -87,7 +87,7 @@ const babelPluginUntyped: PluginItem = function (
const schema = parseJSDocs(
(p.parent.leadingComments || [])
.filter((c) => c.type === "CommentBlock")
.map((c) => c.value)
.map((c) => c.value),
);
schema.type = "function";
schema.args = [];
Expand Down Expand Up @@ -143,16 +143,16 @@ const babelPluginUntyped: PluginItem = function (
arg,
mergedTypes(
arg,
inferAnnotationType(lparam.typeAnnotation, getCode)
)
inferAnnotationType(lparam.typeAnnotation, getCode),
),
);
}

// Infer type from default value
if (param.type === "AssignmentPattern") {
Object.assign(
arg,
mergedTypes(arg, inferArgType(param.right, getCode))
mergedTypes(arg, inferArgType(param.right, getCode)),
);
}
schema.args = schema.args || [];
Expand Down Expand Up @@ -198,9 +198,9 @@ const babelPluginUntyped: PluginItem = function (
t.variableDeclaration("const", [
t.variableDeclarator(
t.identifier(p.node.id.name),
astify({ $schema: schema })
astify({ $schema: schema }),
),
])
]),
);
}
},
Expand Down Expand Up @@ -241,12 +241,12 @@ function parseJSDocs(input: string | string[]): Schema {
};

const lines: string[] = (Array.isArray(input) ? input : [input]).flatMap(
(c) => c.split("\n").map((l) => l.replace(/(^\s*\*+ )|([\s*]+$)/g, ""))
(c) => c.split("\n").map((l) => l.replace(/(^\s*\*+ )|([\s*]+$)/g, "")),
);

const firstTag = lines.findIndex((l) => l.startsWith("@"));
const comments = clumpLines(
lines.slice(0, firstTag >= 0 ? firstTag : undefined)
lines.slice(0, firstTag >= 0 ? firstTag : undefined),
);

if (comments.length === 1) {
Expand All @@ -269,7 +269,7 @@ function parseJSDocs(input: string | string[]): Schema {
}
return typedefs;
},
{} as Record<string, string>
{} as Record<string, string>,
);
for (const tag of tags) {
if (tag.startsWith("@type")) {
Expand All @@ -283,7 +283,7 @@ function parseJSDocs(input: string | string[]): Schema {
schema.markdownType = type;
schema.tsType = schema.tsType.replace(
new RegExp(typedefs[typedef], "g"),
typedef
typedef,
);
}
continue;
Expand Down Expand Up @@ -317,7 +317,7 @@ function astify(val) {
return t.objectExpression(
Object.getOwnPropertyNames(val)
.filter((key) => val[key] !== undefined && val[key] !== null)
.map((key) => t.objectProperty(t.identifier(key), astify(val[key])))
.map((key) => t.objectProperty(t.identifier(key), astify(val[key]))),
);
}

Expand Down Expand Up @@ -360,7 +360,7 @@ function inferArgType(e: t.Expression, getCode: GetCodeFn): TypeDescriptor {

function inferAnnotationType(
ann: t.Identifier["typeAnnotation"],
getCode: GetCodeFn
getCode: GetCodeFn,
): TypeDescriptor | null {
if (ann.type !== "TSTypeAnnotation") {
return null;
Expand All @@ -370,7 +370,7 @@ function inferAnnotationType(

function inferTSType(
tsType: t.TSType,
getCode: GetCodeFn
getCode: GetCodeFn,
): TypeDescriptor | null {
if (tsType.type === "TSParenthesizedType") {
return inferTSType(tsType.typeAnnotation, getCode);
Expand Down
4 changes: 2 additions & 2 deletions src/loader/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export interface LoaderOptions {

export async function loadSchema(
entryPath: string,
options: LoaderOptions = {}
options: LoaderOptions = {},
): Promise<Schema> {
const _jitiRequire = jiti(
process.cwd(),
Expand All @@ -27,7 +27,7 @@ export async function loadSchema(
plugins: [[untypedPlugin, { experimentalFunctions: true }]],
},
},
})
}),
);

const resolvedEntryPath = _jitiRequire.resolve(entryPath);
Expand Down
8 changes: 4 additions & 4 deletions src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export interface ResolveSchemaOptions extends NormalizeSchemaOptions {}
export async function resolveSchema(
obj: InputObject,
defaults?: InputObject,
options: ResolveSchemaOptions = {}
options: ResolveSchemaOptions = {},
): Promise<Schema> {
const schema = await _resolveSchema(obj, "", {
root: obj,
Expand All @@ -41,7 +41,7 @@ export async function resolveSchema(
async function _resolveSchema(
input: InputValue,
id: string,
ctx: _ResolveCtx
ctx: _ResolveCtx,
): Promise<Schema> {
// Check cache
if (id in ctx.resolveCache) {
Expand Down Expand Up @@ -89,7 +89,7 @@ async function _resolveSchema(
const child = (schema.properties[key] = await _resolveSchema(
node[key],
joinPath(id, key),
ctx
ctx,
));

// Infer @required
Expand Down Expand Up @@ -143,7 +143,7 @@ export async function applyDefaults(ref: InputObject, input: InputObject) {

function normalizeSchema(
schema: Partial<Schema>,
options: NormalizeSchemaOptions
options: NormalizeSchemaOptions,
): asserts schema is Schema {
if (schema.type === "array" && !("items" in schema)) {
schema.items = {
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export type JSType =
// eslint-disable-next-line no-use-before-define
export type ResolveFn = (
value: any,
get: (key: string) => any
get: (key: string) => any,
) => JSValue | Promise<JSValue>;

export interface TypeDescriptor {
Expand Down
4 changes: 2 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export function mergedTypes(...types: TypeDescriptor[]): TypeDescriptor {
return types[0];
}
const tsTypes = normalizeTypes(
types.flatMap((t) => t.tsType).filter(Boolean)
types.flatMap((t) => t.tsType).filter(Boolean),
);
return {
type: normalizeTypes(types.flatMap((t) => t.type).filter(Boolean)),
Expand Down Expand Up @@ -162,7 +162,7 @@ export function getTypeDescriptor(type: string | JSType): TypeDescriptor {
if (importName && firstType) {
markdownType = markdownType.replace(
match[0],
pascalCase(importName) + pascalCase(firstType)
pascalCase(importName) + pascalCase(firstType),
);
}
}
Expand Down
2 changes: 1 addition & 1 deletion test/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ describe("resolveSchema", () => {
const schema = await resolveSchema(
{ foo: { bar: 123 } },
{ foo: { bar: 123 } },
{ ignoreDefaults: true }
{ ignoreDefaults: true },
);

expect(schema).toMatchObject({
Expand Down
2 changes: 1 addition & 1 deletion test/transform.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@ function expectCodeToMatch(code: string, pattern: RegExp, expected: any) {
expect(result).toBeDefined();
// eslint-disable-next-line no-new-func, unicorn/new-for-builtins
const obj = Function(
'"use strict";return (' + result.replace(/;$/, "") + ")"
'"use strict";return (' + result.replace(/;$/, "") + ")",
)();
expect(obj).toMatchObject(expected);
}
Loading

0 comments on commit 3292277

Please sign in to comment.