Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

21.7 KB
Raw Blame
/**
 * Generates the committed frontend files derived from the Java OpenAPI spec:
 * toolApiTypes.ts (each tool's request shape) and toolIO.ts (what it accepts and
 * produces, from `@ToolIO` via the `x-stirling-io` extension).
 *
 * One pass over one spec, so the two cannot drift apart.
 */

import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { parseArgs } from "node:util";
import { compile, type JSONSchema } from "json-schema-to-typescript";

// Endpoints a pipeline can reference. filter/integration are not user-facing tools but a stored
// pipeline can contain one; the AI namespace is admitted one endpoint at a time, not wholesale.
const ALLOWED_PATH_PREFIXES = [
  "/api/v1/general/",
  "/api/v1/misc/",
  "/api/v1/security/",
  "/api/v1/convert/",
  "/api/v1/filter/",
  "/api/v1/integration/",
  "/api/v1/ai/tools/classify-and-label",
  "/api/v1/docparse/ingest",
  // Admitted on its own rather than the whole form namespace: this is the only /form/ endpoint
  // that takes a document and returns one, so it is the only one a pipeline can chain.
  "/api/v1/form/form-detection/detect",
];

// File plumbing, not user parameters: `fileInput` and `file` are the uploaded primary document
// (endpoints use one name or the other - `file` is never a second, supporting upload) and `fileId`
// a server-side handle. Stripped from every generated request model. Named supporting-file fields
// (stampImage, attachments, ...) are real parameters and kept.
const BASE_FILE_FIELDS = new Set(["fileInput", "file", "fileId"]);

// The shared "upload a file or provide a file ID" wrapper schema and its two
// branches. An endpoint whose body is exactly this has no parameters, so it must
// resolve to an empty model. It needs separate handling because the wrapper is a
// `oneOf`, which survives the flat-field stripping above and would otherwise leak
// the file fields into the output.
const FILE_WRAPPER_COMPONENTS = new Set([
  "PDFFile",
  "PDFFileUpload",
  "PDFFileRef",
]);

const COMPONENT_REF_PREFIX = "#/components/schemas/";

const IO_EXTENSION = "x-stirling-io";
const IO_VOCABULARY_EXTENSION = "x-stirling-io-vocabulary";

function fileHeader(...extra: string[]): string {
  return [
    "// AUTO-GENERATED FILE. DO NOT EDIT.",
    "// Generated by scripts/generate-tool-api-types.mts from the Java OpenAPI spec",
    "// (SwaggerDoc.json). Regenerate with: task frontend:tool-models",
    ...extra,
  ].join("\n");
}

const FILE_HEADER = fileHeader(
  "// Tools that take only a file input have no parameters; their model is Record<string, never>.",
);

type Json = Record<string, unknown>;

interface DiscoveredTool {
  path: string;
  className: string;
}

function isObject(value: unknown): value is Json {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

/** A single file upload: `type: string, format: binary` (a Java MultipartFile param). */
function isBinaryField(schema: unknown): schema is Json {
  return (
    isObject(schema) && schema.type === "string" && schema.format === "binary"
  );
}

/** A multi file upload: an array of binary items (some specs also flag the array itself binary). */
function isBinaryArrayField(schema: unknown): schema is Json {
  if (!isObject(schema) || schema.type !== "array") return false;
  return schema.format === "binary" || isBinaryField(schema.items);
}

/**
 * Recursively sort object keys so the output is byte-stable regardless of the
 * key ordering springdoc happens to emit.
 */
function deepSortKeys(value: unknown): unknown {
  if (Array.isArray(value)) return value.map(deepSortKeys);
  if (isObject(value)) {
    const sorted: Json = {};
    for (const key of Object.keys(value).sort()) {
      sorted[key] = deepSortKeys(value[key]);
    }
    return sorted;
  }
  return value;
}

function pascalCase(segment: string): string {
  return segment
    .split(/[-_/]/)
    .filter(Boolean)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join("");
}

/** Fallback class name for an inline request body (no $ref to name it after). */
function pathToClassName(path: string): string {
  const relevant = path.replace(/^\/api\/v1\//, "");
  return `${pascalCase(relevant)}Request`;
}

function dedupe(name: string, used: Set<string>): string {
  let candidate = name;
  let n = 2;
  while (used.has(candidate)) candidate = `${name}${n++}`;
  used.add(candidate);
  return candidate;
}

/** The request body schema for a POST endpoint (multipart wins, then JSON), or null. */
function requestBodySchema(pathItem: Json): Json | null {
  const post = pathItem.post;
  if (!isObject(post)) return null;
  const requestBody = post.requestBody;
  if (!isObject(requestBody)) return null;
  const content = requestBody.content;
  if (!isObject(content)) return null;
  for (const mediaType of ["multipart/form-data", "application/json"]) {
    const entry = content[mediaType];
    if (isObject(entry) && isObject(entry.schema)) return entry.schema;
  }
  return null;
}

/**
 * A POST endpoint's query parameters as a property map plus the required ones.
 * Some tools take inputs on the query string alongside the multipart body (e.g.
 * merge-pdfs' `fileOrder`), so a complete model has to fold them in. Ref-valued
 * param schemas are inlined later by rewriteRefs.
 */
function queryParameters(pathItem: Json): { props: Json; required: string[] } {
  const props: Json = {};
  const required: string[] = [];
  const post = pathItem.post;
  if (!isObject(post) || !Array.isArray(post.parameters))
    return { props, required };
  for (const param of post.parameters) {
    if (
      !isObject(param) ||
      param.in !== "query" ||
      typeof param.name !== "string"
    )
      continue;
    if (!isObject(param.schema)) continue;
    const schema = structuredClone(param.schema);
    if (!("description" in schema) && typeof param.description === "string") {
      schema.description = param.description;
    }
    props[param.name] = schema;
    if (param.required === true) required.push(param.name);
  }
  return { props, required };
}

/**
 * Rewrite every `#/components/schemas/X` ref to `#/definitions/X` in place (the
 * form json-schema-to-typescript expects) and collect the referenced component
 * names so the caller can inline them.
 */
function rewriteRefs(node: unknown, found: Set<string>): void {
  if (Array.isArray(node)) {
    for (const item of node) rewriteRefs(item, found);
    return;
  }
  if (!isObject(node)) return;
  const ref = node.$ref;
  if (typeof ref === "string" && ref.startsWith(COMPONENT_REF_PREFIX)) {
    const name = ref.slice(COMPONENT_REF_PREFIX.length);
    node.$ref = `#/definitions/${name}`;
    found.add(name);
  }
  for (const value of Object.values(node)) rewriteRefs(value, found);
}

/** Keep only fields the client must send: drop those with a default or already stripped. */
function computeRequired(schema: Json, properties: Json): string[] {
  const required = Array.isArray(schema.required)
    ? (schema.required as string[])
    : [];
  return required.filter((name) => {
    const prop = properties[name];
    return name in properties && !(isObject(prop) && "default" in prop);
  });
}

/**
 * The `x-stirling-io` declaration for every endpoint that carries one, path-sorted.
 *
 * Restricted to `endpoints`, the paths that become {@link ToolEndpoint}: the table is typed by
 * that union, so a declaration outside it would not type-check. `dropped` is reported rather
 * than discarded silently, since a tool losing its declaration this way is invisible otherwise.
 */
function collectToolIO(
  paths: Json,
  endpoints: Set<string>,
): { table: Record<string, unknown>; dropped: string[] } {
  const table: Record<string, unknown> = {};
  const dropped: string[] = [];
  for (const path of Object.keys(paths).sort()) {
    const pathItem = paths[path];
    if (!isObject(pathItem)) continue;
    for (const operation of Object.values(pathItem)) {
      if (isObject(operation) && operation[IO_EXTENSION]) {
        if (endpoints.has(path)) table[path] = operation[IO_EXTENSION];
        else dropped.push(path);
      }
    }
  }
  return { table, dropped };
}

function renderToolIO(spec: Json, table: Record<string, unknown>): string {
  if (Object.keys(table).length === 0) {
    throw new Error(
      `No ${IO_EXTENSION} declarations in the spec. The backend publishes these from @ToolIO; regenerate with 'task backend:swagger'.`,
    );
  }
  // Published separately: deriving the unions from the declarations present would shrink them
  // whenever an endpoint is disabled in a build.
  const vocabulary = spec[IO_VOCABULARY_EXTENSION];
  if (!isObject(vocabulary)) {
    throw new Error(
      `No ${IO_VOCABULARY_EXTENSION} in the spec; regenerate it from a current backend.`,
    );
  }
  const union = (values: string[]) =>
    values.map((v) => JSON.stringify(v)).join(" | ");
  const formats = vocabulary.formats as string[];

  const body = `${fileHeader()}

/**
 * What each tool endpoint accepts and produces, so a chain can be checked while it is being
 * edited rather than by running it. Declared in Java with \`@ToolIO\`; see
 * \`utils/toolIOCompat\` for the compatibility rules that read this table.
 */

import { type ToolEndpoint } from "@editor/types/toolApiTypes";

/** The kind of file a tool consumes or produces. \`ANY\` accepts or produces anything; \`NONE\` means no file at all. */
export type ToolFormat = ${union(formats)};

/** Every format, for iteration. */
export const TOOL_FORMATS = ${JSON.stringify(formats)} as const satisfies readonly ToolFormat[];

/** Filename extensions from the backend ToolFormat declarations. */
export const TOOL_FORMAT_EXTENSIONS = ${JSON.stringify(vocabulary.extensions)} as const satisfies Record<ToolFormat, readonly string[]>;

/** The filename extensions of one format, as literals. */
export type ToolFormatExtension<F extends ToolFormat> = (typeof TOOL_FORMAT_EXTENSIONS)[F][number];

/** How many files go in and come out. A multi-output tool returns its results zipped, and the caller unpacks them. */
export type ToolArity = ${union(vocabulary.arities as string[])};

/** One condition on a request parameter, guarding a {@link ToolIOCase}. */
export interface ToolIOWhen {
  param: string;
  matches: string[];
  /** The value the endpoint uses when this parameter is absent; omitted when it has none. */
  default?: string;
}

/** An output that applies when every condition in \`when\` holds. */
export interface ToolIOCase {
  when: ToolIOWhen[];
  produces: ToolFormat;
  arity: ToolArity;
}

/** What one endpoint accepts and produces. */
export interface ToolIOSpec {
  accepts: ToolFormat[];
  /** Overrides the broad format categories for filename-based input checks. */
  inputExtensions?: string[];
  produces: ToolFormat;
  arity: ToolArity;
  cases?: ToolIOCase[];
}

/**
 * What each endpoint accepts and produces, keyed by {@link ToolEndpoint} so the paths live in
 * exactly one place. Partial: endpoints that manage a session, a device or a stored resource
 * rather than transform a document declare nothing.
 */
export type ToolIOTable = Partial<Record<ToolEndpoint, ToolIOSpec>>;

export const TOOL_IO: ToolIOTable = ${JSON.stringify(table)};

/** The declaration for an endpoint, or undefined when it declares none. */
export function toolIOFor(
  operation: string,
  table: ToolIOTable = TOOL_IO,
): ToolIOSpec | undefined {
  // The table's own keys are the valid set, so a hasOwn guard is the narrowing.
  return Object.hasOwn(table, operation)
    ? table[operation as ToolEndpoint]
    : undefined;
}
`;

  return body;
}

function writeOutput(outputPath: string, contents: string): void {
  mkdirSync(dirname(outputPath), { recursive: true });
  writeFileSync(outputPath, contents, "utf-8");
}

async function main(): Promise<void> {
  const { values } = parseArgs({
    options: {
      spec: { type: "string" },
      output: { type: "string" },
      "io-output": { type: "string" },
    },
  });
  if (!values.spec || !values.output || !values["io-output"]) {
    throw new Error(
      "Usage: generate-tool-api-types.mts --spec <SwaggerDoc.json> --output <file.ts> --io-output <file.ts>",
    );
  }
  const specPath = resolve(values.spec);
  const outputPath = resolve(values.output);
  const ioOutputPath = resolve(values["io-output"]);

  const spec = JSON.parse(readFileSync(specPath, "utf-8")) as Json;

  const paths = isObject(spec.paths) ? spec.paths : {};
  const components =
    isObject(spec.components) && isObject(spec.components.schemas)
      ? spec.components.schemas
      : {};

  const tools: DiscoveredTool[] = [];
  const definitions: Record<string, Json> = {};
  const usedClassNames = new Set<string>();
  const pendingComponents = new Set<string>();
  const skipped: string[] = [];
  // Named file fields (as File uploads) per model, so a caller can tell a file param from a scalar
  // string param - which `format: binary` -> `string` would otherwise erase.
  const fileFieldsByClass: Record<string, string[]> = {};

  for (const path of Object.keys(paths).sort()) {
    if (
      path.includes("{") ||
      !ALLOWED_PATH_PREFIXES.some((p) => path.startsWith(p))
    )
      continue;
    const pathItem = paths[path];
    if (!isObject(pathItem)) continue;
    const bodySchema = requestBodySchema(pathItem);
    if (!bodySchema) {
      if (isObject(pathItem.post)) skipped.push(path);
      continue;
    }

    // Resolve the request model into a fresh, mutable clone so we never mutate the shared spec.
    const ref = bodySchema.$ref;
    const refComponent =
      typeof ref === "string" && ref.startsWith(COMPONENT_REF_PREFIX)
        ? ref.slice(COMPONENT_REF_PREFIX.length)
        : null;
    let className: string;
    let modelSchema: Json;
    if (refComponent && FILE_WRAPPER_COMPONENTS.has(refComponent)) {
      // File-only endpoint: model it as an empty object so it becomes
      // Record<string, never> rather than the wrapper's file union. Named after
      // the path since the wrapper schema is shared. Query params still fold in
      // below.
      className = pathToClassName(path);
      modelSchema = { type: "object", properties: {} };
    } else if (refComponent) {
      const component = components[refComponent];
      if (!isObject(component)) continue;
      className = refComponent;
      modelSchema = structuredClone(component);
    } else {
      className = pathToClassName(path);
      modelSchema = structuredClone(bodySchema);
    }

    // A component shared by several endpoints (e.g. GeneralFile) is only defined once.
    if (!(className in definitions)) {
      const uniqueName = dedupe(className, usedClassNames);
      className = uniqueName;
      const bodyProps: Json = isObject(modelSchema.properties)
        ? structuredClone(modelSchema.properties)
        : {};
      const query = queryParameters(pathItem);
      // Body wins over query on a name collision.
      const properties: Json = { ...query.props, ...bodyProps };
      // `file` is stripped as a primary-document alias (see BASE_FILE_FIELDS). That only holds while
      // no endpoint uses `file` as a *supporting* upload beside a primary `fileInput`; if one ever
      // does, blanket-stripping would silently drop it. Fail generation so the assumption is fixed
      // here rather than shipping a lost file.
      if ("file" in properties && "fileInput" in properties) {
        throw new Error(
          `${path} has both 'fileInput' and 'file' uploads. 'file' is stripped as a primary-document` +
            " alias, which would drop it as a supporting file. Rename the supporting param or revise" +
            " BASE_FILE_FIELDS handling in this generator.",
        );
      }
      for (const field of BASE_FILE_FIELDS) delete properties[field];
      // Type each named file upload as File/File[] (not the `string` a binary format yields) via
      // json-schema-to-typescript's `tsType` override, and record it. Base file fields are already
      // stripped, so what remains is the real supporting-file params.
      const fileFields: string[] = [];
      for (const [name, prop] of Object.entries(properties)) {
        if (isBinaryField(prop)) {
          prop.tsType = "File";
          fileFields.push(name);
        } else if (isBinaryArrayField(prop)) {
          prop.tsType = "File[]";
          fileFields.push(name);
        }
      }
      fileFieldsByClass[className] = fileFields;
      modelSchema.properties = properties;
      const required = new Set(computeRequired(modelSchema, properties));
      for (const name of query.required) {
        const prop = properties[name];
        if (name in properties && !(isObject(prop) && "default" in prop)) {
          required.add(name);
        }
      }
      if (required.size > 0) modelSchema.required = [...required];
      else delete modelSchema.required;
      modelSchema.title = className;
      rewriteRefs(modelSchema, pendingComponents);
      definitions[className] = modelSchema;
    }

    tools.push({ path, className });
  }

  const { table: ioDeclarations, dropped } = collectToolIO(
    paths,
    new Set(tools.map((tool) => tool.path)),
  );
  if (dropped.length > 0) {
    console.warn(
      `Dropped ${dropped.length} @ToolIO declaration(s) on paths that are not tool endpoints. Add the namespace to ALLOWED_PATH_PREFIXES if a pipeline can contain these steps:\n  ${dropped.join("\n  ")}`,
    );
  }
  writeOutput(ioOutputPath, renderToolIO(spec, ioDeclarations));
  console.log(
    `Generated ${Object.keys(ioDeclarations).length} tool I/O declarations.`,
  );

  // Transitively inline every referenced component into `definitions`, rewriting its refs too.
  const queue = [...pendingComponents];
  while (queue.length > 0) {
    const name = queue.pop() as string;
    if (name in definitions) continue;
    const component = components[name];
    if (!isObject(component)) continue;
    const cloned = structuredClone(component);
    cloned.title = name;
    const nested = new Set<string>();
    rewriteRefs(cloned, nested);
    definitions[name] = cloned;
    for (const next of nested) if (!(next in definitions)) queue.push(next);
  }

  await compileAndWrite(
    tools,
    definitions,
    fileFieldsByClass,
    outputPath,
    skipped,
  );
}

async function compileAndWrite(
  tools: DiscoveredTool[],
  definitions: Record<string, Json>,
  fileFieldsByClass: Record<string, string[]>,
  outputPath: string,
  skipped: string[],
): Promise<void> {
  // json-schema-to-typescript only emits a named, exported interface per schema
  // if something references it, so wrap every model in one root object. The root
  // interface itself is stripped from the output afterwards.
  const rootName = "__ToolApiRootAutogen";
  const uniqueClassNames = [...new Set(tools.map((t) => t.className))];
  const rootSchema: JSONSchema = {
    title: rootName,
    type: "object",
    additionalProperties: false,
    properties: Object.fromEntries(
      uniqueClassNames.map((name) => [name, { $ref: `#/definitions/${name}` }]),
    ),
    definitions: definitions,
  };

  // Canonicalize key order so a reordering in SwaggerDoc.json can never change
  // the generated file (which would flake the committed-types CI check).
  const canonicalRoot = deepSortKeys(rootSchema) as JSONSchema;

  const compiled = await compile(canonicalRoot, rootName, {
    bannerComment: "",
    additionalProperties: false,
    declareExternallyReferenced: true,
    unreachableDefinitions: false,
    strictIndexSignatures: true,
    format: false,
  });

  // Drop the root wrapper interface, then rewrite empty models (file-only tools)
  // to `Record<string, never>` - the precise, lint-clean type for an object with
  // no properties (json-schema-to-typescript always emits `{}` interfaces here).
  const models = compiled
    .replace(new RegExp(`export interface ${rootName} \\{[^}]*\\}`), "")
    .replace(
      /export interface (\w+) \{\s*\}/g,
      "export type $1 = Record<string, never>;",
    )
    .trim();

  const endpointUnion = tools
    .map((t) => `  | ${JSON.stringify(t.path)}`)
    .join("\n");
  const paramsEntries = tools
    .map((t) => `  ${JSON.stringify(t.path)}: ${t.className};`)
    .join("\n");
  const endpointList = tools
    .map((t) => `  ${JSON.stringify(t.path)},`)
    .join("\n");
  // Endpoints that take supporting files, mapped to those file params' names. Only endpoints with at
  // least one are listed, so membership answers "does this tool take extra files".
  const fileFieldEntries = tools
    .filter((t) => (fileFieldsByClass[t.className] ?? []).length > 0)
    .map(
      (t) =>
        `  ${JSON.stringify(t.path)}: ${JSON.stringify(fileFieldsByClass[t.className])},`,
    )
    .join("\n");

  const footer = [
    "/** Endpoint path for a generated tool operation (the operation identity across languages). */",
    `export type ToolEndpoint =\n${endpointUnion};`,
    "",
    "/** Backend request-parameter model for each tool endpoint. */",
    `export interface ToolApiParams {\n${paramsEntries}\n}`,
    "",
    "/** Every generated tool endpoint, for iteration. */",
    `export const TOOL_ENDPOINTS = [\n${endpointList}\n] as const satisfies readonly ToolEndpoint[];`,
    "",
    "/** The supporting-file parameters each endpoint accepts beyond its primary fileInput, by name. */",
    `export const TOOL_FILE_FIELDS = {\n${fileFieldEntries}\n} as const satisfies Partial<\n  Record<ToolEndpoint, readonly string[]>\n>;`,
    "",
    "/** Union of every generated tool request model. */",
    `export type ToolApiRequest = ToolApiParams[ToolEndpoint];`,
  ].join("\n");

  const body = `${FILE_HEADER}\n\n${models}\n\n${footer}\n`;
  writeOutput(outputPath, body);
  console.log(`Generated ${tools.length} tool endpoints.`);
  if (skipped.length > 0) {
    console.log(
      `Skipped ${skipped.length} POST endpoint(s) with no request body: ${skipped.join(", ")}`,
    );
  }
}

main().catch((error: unknown) => {
  console.error(error instanceof Error ? error.message : error);
  process.exit(1);
});