Open json-to-typescript in Script Kit

Demo

https://github.com/johnlindquist/kit/assets/7313176/504d163c-60b3-45f9-b805-3c3090bbb876

// Name: JSON to TypeScript
// Description: Convert some JSON to TypeScript models
import "@johnlindquist/kit"
import jsonToTS from "json-to-ts"
import { submitShortcut } from "@johnlindquist/kit/core/utils"
import { refreshable } from "@josxa/kit-utils"
import { crudArg } from "@josxa/kit-utils"
import ModernError from "modern-errors"
let json = args[0]
if (!json) {
json = await editor({
language: "json",
validate(input: string): true | string {
try {
JSON.parse(input)
return true
} catch (err) {
return ModernError.normalize(err).message
}
},
shortcuts: [submitShortcut],
})
}
const rootName = await crudArg("Name of the root type?")
const options: Parameters<typeof jsonToTS>[1] = {
rootName,
useTypeAlias: true,
}
await refreshable(async ({ refresh }) => {
let types = ""
try {
types = `${jsonToTS(JSON.parse(json), options).join("\n\n")}\n`
} catch (error) {
const hint = ModernError.normalize(error).message
setHint(hint)
exit()
}
if (options.useTypeAlias) {
types = types.replaceAll(/^type /g, "export type ")
} else {
types = types.replaceAll(/^interface /g, "export interface ")
}
await editor({
value: types,
language: "ts",
shortcuts: [
{
key: `${cmd}+shift+t`,
name: `Use ${options.useTypeAlias ? "Interfaces" : "Types"}`,
onPress: () => {
options.useTypeAlias = !options.useTypeAlias
refresh()
},
visible: true,
bar: "right",
},
{
name: "Copy to Clipboard",
key: `${cmd}+shift+c`,
onPress: async (input) => {
await clipboard.writeText(input)
setHint("Copied to clipboard")
},
visible: true,
bar: "right",
},
],
})
})