SPB Git

Repository Public

generate.mjs 10.5 KB 194 lines javascript

1// Generates src/generated.ts from docs/OPENAPI.yaml (the contract generated from the server's route registry).2//   node scripts/generate.mjs           write src/generated.ts3//   node scripts/generate.mjs --check   exit 1 when src/generated.ts is stale relative to the YAML4import crypto from "node:crypto"5import fs from "node:fs"6import path from "node:path"7import { fileURLToPath } from "node:url"8import YAML from "yaml"910const here = path.dirname(fileURLToPath(import.meta.url))11const yamlPath = process.env.SPMAIL_OPENAPI ?? path.resolve(here, "../../../docs/OPENAPI.yaml")12const outPath = path.resolve(here, "../src/generated.ts")13const source = fs.readFileSync(yamlPath, "utf8")14const doc = YAML.parse(source)1516// The contract inlines every schema. These entries give stable, friendly names to the shapes that matter:17// [name, operationId, where ("body" | status code), JSON path inside that schema].18const NAMED = [19  ["EmailAddress", "getMessagesId", "200", ["properties", "from", "items"]],20  ["Recipient", "postMessagesSend", "body", ["properties", "to", "items"]],21  ["AttachmentRef", "postMessagesSend", "body", ["properties", "attachments", "items"]],22  ["FolderRef", "getMessagesId", "200", ["properties", "folders", "items"]],23  ["Attachment", "getMessagesIdAttachments", "200", ["properties", "data", "items"]],24  ["MessageAuth", "getMessagesId", "200", ["properties", "auth"]],25  ["MessageSummary", "getMessages", "200", ["properties", "data", "items"]],26  ["Message", "getMessagesId", "200", []],27  ["MessageUpdateParams", "patchMessagesId", "body", []],28  ["Thread", "getThreadsId", "200", []],29  ["ThreadSummary", "getThreads", "200", ["properties", "data", "items"]],30  ["Changes", "getMessagesChanges", "200", []],31  ["Folder", "postFolders", "201", []],32  ["FolderCreateParams", "postFolders", "body", []],33  ["OutboundStatus", "getMessagesOutboundId", "200", ["properties", "status"]],34  ["OutboundRecipient", "getMessagesOutboundId", "200", ["properties", "recipients", "items"]],35  ["OutboundMessage", "getMessagesOutboundId", "200", []],36  ["SendParams", "postMessagesSend", "body", []],37  ["ReplyParams", "postMessagesIdReply", "body", []],38  ["ForwardParams", "postMessagesIdForward", "body", []],39  ["BatchResult", "postMessagesSendBatch", "200", []],40  ["DraftCreateParams", "postDrafts", "body", []],41  ["DraftUpdateParams", "patchDraftsId", "body", []],42  ["UploadedFile", "postFiles", "201", []],43  ["AddressKind", "getAddressesId", "200", ["properties", "kind"]],44  ["Address", "getAddressesId", "200", []],45  ["AddressCreateParams", "postAddresses", "body", []],46  ["AddressUpdateParams", "patchAddressesId", "body", []],47  ["Automation", "getAddressesIdAutomation", "200", []],48  ["AutomationUpdateParams", "putAddressesIdAutomation", "body", []],49  ["WebhookEventType", "postWebhooks", "body", ["properties", "events", "items"]],50  ["Webhook", "getWebhooksId", "200", []],51  ["WebhookCreateParams", "postWebhooks", "body", []],52  ["WebhookUpdateParams", "patchWebhooksId", "body", []],53  ["WebhookDelivery", "postWebhookDeliveriesIdReplay", "200", []],54  ["WebhookTestResult", "postWebhooksIdTest", "200", []],55  ["Event", "getEvents", "200", ["properties", "data", "items"]],56  ["TemplateVariable", "getTemplatesId", "200", ["properties", "variables", "items"]],57  ["TemplateSummary", "getTemplates", "200", ["properties", "templates", "items"]],58  ["Template", "getTemplatesId", "200", []],59  ["TemplateRenderParams", "postTemplatesIdRender", "body", []],60  ["RenderedTemplate", "postTemplatesIdRender", "200", []],61  ["MeAddress", "getMe", "200", ["properties", "addresses", "items"]],62  ["Me", "getMe", "200", []],63  ["Health", "getHealth", "200", []],64]6566const ops = []67for (const [route, item] of Object.entries(doc.paths)) {68  for (const [method, op] of Object.entries(item)) ops.push({ route, method: method.toUpperCase(), op })69}70const opById = new Map(ops.map((o) => [o.op.operationId, o]))71const deref = (s) => (s && s.$ref ? doc.components.schemas[s.$ref.split("/").pop()] : s)72const bodySchema = (op) => {73  const c = op.requestBody?.content74  if (!c) return undefined75  return c["application/json"]?.schema ?? { "x-binary": true }76}77const responseSchema = (op, code) => {78  const r = op.responses?.[code]79  if (!r) return undefined80  const c = r.content81  if (!c) return undefined82  return c["application/json"]?.schema ?? { "x-binary": true }83}84const at = (schema, pointer) => pointer.reduce((s, k) => (s == null ? s : deref(s)[k]), schema)8586// Canonical form: key order independent, documentation ignored.87const canon = (v) => {88  if (Array.isArray(v)) return `[${v.map(canon).join(",")}]`89  if (v && typeof v === "object") {90    return `{${Object.keys(v).filter((k) => k !== "description" && k !== "title" && k !== "example" && k !== "default").sort().map((k) => `${JSON.stringify(k)}:${canon(v[k])}`).join(",")}}`91  }92  return JSON.stringify(v)93}94const names = new Map() // canonical schema -> name (first declaration wins)95const named = []96for (const [name, opId, where, pointer] of NAMED) {97  const o = opById.get(opId)98  if (!o) throw new Error(`generate: unknown operation ${opId} (needed for ${name})`)99  const root = where === "body" ? bodySchema(o.op) : responseSchema(o.op, where)100  const schema = at(root, pointer)101  if (!schema) throw new Error(`generate: no schema for ${name} (${opId} ${where} /${pointer.join("/")})`)102  const key = canon(schema)103  if (!names.has(key)) names.set(key, name)104  named.push({ name, schema, alias: names.get(key) !== name ? names.get(key) : null })105}106107const ident = (k) => (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(k) ? k : JSON.stringify(k))108const doc1 = (s, pad) => (s?.description ? `${pad}/** ${String(s.description).replace(/\*\//g, "*\\/").replace(/\s+/g, " ")} */\n` : "")109function ts(schema, pad = "", self = null) {110  if (schema === undefined) return "unknown"111  if (schema["x-binary"]) return "Uint8Array"112  if (schema.$ref) return schema.$ref.split("/").pop() === "Error" ? "ErrorBody" : ts(deref(schema), pad)113  const known = names.get(canon(schema))114  if (known && known !== self) return known115  if (schema.const !== undefined) return JSON.stringify(schema.const)116  if (schema.enum) return schema.enum.map((e) => JSON.stringify(e)).join(" | ")117  const alt = schema.anyOf ?? schema.oneOf118  if (alt) return alt.map((x) => wrap(ts(x, pad))).join(" | ")119  if (schema.allOf) return schema.allOf.map((x) => wrap(ts(x, pad))).join(" & ")120  if (Array.isArray(schema.type)) return schema.type.map((t) => ts({ ...schema, type: t }, pad)).join(" | ")121  switch (schema.type) {122    case "string": return schema.format === "binary" ? "Uint8Array" : "string"123    case "number": case "integer": return "number"124    case "boolean": return "boolean"125    case "null": return "null"126    case "array": return `${wrap(ts(schema.items ?? {}, pad))}[]`127    case "object": return object(schema, pad)128    default: return schema.properties ? object(schema, pad) : "unknown"129  }130}131const wrap = (t) => (/[|&]/.test(t) && !/^[{(]/.test(t) ? `(${t})` : /^\{[\s\S]*\}\s*[|&]/.test(t) ? `(${t})` : t)132function object(schema, pad) {133  const req = new Set(schema.required ?? [])134  const inner = `${pad}  `135  const lines = Object.entries(schema.properties ?? {}).map(([k, v]) => `${doc1(v, inner)}${inner}${ident(k)}${req.has(k) ? "" : "?"}: ${ts(v, inner)}`)136  const extra = schema.additionalProperties137  if (extra && extra !== false) lines.push(`${inner}[key: string]: ${extra === true || !Object.keys(extra).length ? "unknown" : ts(extra, inner)}`)138  if (!lines.length) return extra === false ? "Record<string, never>" : "Record<string, unknown>"139  return `{\n${lines.join("\n")}\n${pad}}`140}141142const sha = crypto.createHash("sha256").update(source).digest("hex")143let out = `// GENERATED FILE — do not edit. Source: docs/OPENAPI.yaml (sha256 ${sha}).144// Regenerate with \`pnpm generate\` in packages/sdk-ts; a test fails when this file is stale.145/* eslint-disable */146147/** sha256 of the OpenAPI document these types were generated from. */148export const OPENAPI_SHA256 = ${JSON.stringify(sha)}149/** \`info.version\` of the OpenAPI document. */150export const OPENAPI_VERSION = ${JSON.stringify(doc.info.version)}151152/** Error envelope of every non-2xx answer. */153export interface ErrorBody {154  error: { code: string; message: string; details?: unknown }155}156157`158for (const n of named) {159  if (n.alias) { out += `export type ${n.name} = ${n.alias}\n\n`; continue }160  const body = ts(n.schema, "", n.name)161  out += `${doc1(n.schema, "")}${body.startsWith("{") ? `export interface ${n.name} ${body}` : `export type ${n.name} = ${body}`}\n\n`162}163164out += `/** Every operation of the API: path/query parameters, request body and the body of each 2xx answer. */\nexport interface Operations {\n`165const scopes = {}166for (const { route, method, op } of ops) {167  const id = op.operationId168  scopes[id] = op["x-required-scopes"] ?? []169  const params = (op.parameters ?? []).filter((p) => p.in === "path")170  const query = (op.parameters ?? []).filter((p) => p.in === "query")171  const pad = "    "172  const fields = (list) => (list.length ? `{\n${list.map((p) => `${pad}  ${ident(p.name)}${p.required ? "" : "?"}: ${ts(p.schema ?? {}, `${pad}  `)}`).join("\n")}\n${pad}}` : "Record<string, never>")173  const body = bodySchema(op)174  const ok = Object.keys(op.responses ?? {}).filter((c) => /^2\d\d$/.test(c))175  // A 2xx answer documented without its own content has the same body as the first documented one (e.g. 201/202 of a send).176  const first = ok.map((c) => responseSchema(op, c)).find(Boolean)177  out += `  /** ${method} ${route}${op.summary ? ` — ${String(op.summary).replace(/\*\//g, "")}` : ""} */\n`178  out += `  ${ident(id)}: {\n${pad}method: ${JSON.stringify(method)}\n${pad}path: ${JSON.stringify(route)}\n${pad}params: ${fields(params)}\n${pad}query: ${fields(query)}\n${pad}body: ${body ? ts(body, pad) : "undefined"}\n`179  out += `${pad}responses: {\n${ok.map((c) => `${pad}  ${c}: ${ts(responseSchema(op, c) ?? first, `${pad}  `)}`).join("\n")}\n${pad}}\n  }\n`180}181out += `}\n\n/** Scopes accepted by each operation (\`x-required-scopes\`; any one of them, see docs/API.md §3 for the finer rules). */\nexport const OPERATION_SCOPES = ${JSON.stringify(scopes, null, 2)} as const\n`182183if (process.argv.includes("--check")) {184  const current = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : ""185  if (current !== out) {186    console.error("src/generated.ts is stale relative to docs/OPENAPI.yaml — run `pnpm generate` in packages/sdk-ts")187    process.exit(1)188  }189  console.log(`src/generated.ts is up to date (${ops.length} operations, sha256 ${sha.slice(0, 12)}…)`)190} else {191  fs.writeFileSync(outPath, out)192  console.log(`src/generated.ts written (${ops.length} operations, ${named.length} named types)`)193}194
Files main
Menu

Theme