#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
import { apiClient } from "@processor/api/http";
import type { WireRoutingRule } from "@editor/policies/types";
import {
type SupportingFileBindings,
type ToolApiStep,
} from "@editor/hooks/tools/shared/toolAutomation";
import type {
PolicyRunView,
PolicyRunStatus,
RunOutputFile,
} from "@editor/policies/types";
/**
* Pipelines service layer: the backend contract.
*
* A "pipeline" in the portal IS a backend policy (PolicyController, Policy.java):
* an ordered chain of tool steps with input sources, a trigger, and an output
* destination. This surface lists EVERY backend policy (the user-facing Policies
* page builds only a friendly subset of the same records). Like Sources, it
* calls the real Stirling API base `/api/v1/policies`.
*/
/** One tool invocation in a pipeline. `operation` is a Stirling endpoint path. */
export interface PipelineStep {
operation: string;
parameters: Record<string, unknown>;
fileParameters?: SupportingFileBindings;
}
/** When a policy input fires automatically. `type` keys a trigger bean (e.g. "schedule"). */
export interface TriggerConfig {
type: string;
options: Record<string, unknown>;
}
/**
* One input of a pipeline: a persisted source paired with the trigger that decides when that
* source is pulled. A `null` trigger means the input is pulled only on a manual run. Mirrors the
* backend `PipelineInput`.
*/
export interface PipelineInput {
sourceId: string;
trigger: TriggerConfig | null;
}
/** Where a run's outputs are delivered. `type` keys an output sink (e.g. "inline"). */
export interface OutputSpec {
type: string;
options: Record<string, unknown>;
}
/** Source types that can be written to (used as a pipeline's output destination). */
export type PipelineOutputMode =
| "folder"
| "s3"
| "onedrive"
| "sharepoint"
| "googledrive"
| "vectordb";
/**
* The stored policy record: the create/update body (`id` blank on create) and what
* the backend returns from GET/POST. Mirrors Policy.java exactly; `owner`/`teamId`
* are stamped server-side. Each input pairs a source with its own trigger; an input
* with a `null` trigger (or a policy with no triggered inputs) runs only on demand.
*/
export interface Policy {
id?: string;
name: string;
owner?: string | null;
enabled: boolean;
/** Whether this is a policy (blocking) rather than an ordinary pipeline. */
required?: boolean;
/** Row icon key (see pipelineIcon); chosen in the builder. Empty falls back to the category glyph. */
icon?: string;
inputs: PipelineInput[];
steps: PipelineStep[];
/**
* Inline output, used only when no destinations are referenced (editor/one-off runs that return
* results to the caller). Portal pipelines set {@link outputIds} instead.
*/
output: OutputSpec;
/**
* The saved Sources this policy delivers its output to (each a source used as a write target),
* resolved live at run time; a run is delivered to every one. Empty means the inline {@link
* output} is used.
*/
outputIds: string[];
/**
* Per-document delivery: each rule sends the document types it names to its own destination,
* tried in order, first match wins. Empty (the default) means every document goes to {@link
* outputIds}. A rule reading the classification verdict makes the backend prepend a classify
* step, so the verdict exists to route on.
*/
routingRules?: WireRoutingRule[];
/** Whether the editor runs this policy per file, and on which moment. */
editor?: { allowed: boolean; runOn: "upload" | "export" };
teamId?: number | null;
}
/** Overview row status: enabled (fires automatically) or paused. */
export type PipelineStatus = "active" | "paused";
/** A source a pipeline pulls documents from, resolved to its display name. */
export interface PipelineSourceRef {
id: string;
name: string;
}
/** One row in the Pipelines overview. Mirrors the backend `PolicyView`. */
export interface PipelineView {
id: string;
name: string;
enabled: boolean;
/** Whether this is a policy - blocking on failure (see {@link Policy.required}); badged in the list. */
required: boolean;
/** Icon key for the list row (see pipelineIcon). Empty when none set; may be a category id. */
icon: string;
status: PipelineStatus;
/** Trigger summary: "manual" or the trigger type (e.g. "schedule"). */
trigger: string;
sources: PipelineSourceRef[];
/** Operation endpoint paths, in run order. */
steps: string[];
/** Output sink type (e.g. "inline", "folder"). */
output: string;
owner: string;
}
export interface PipelineKpi {
value: number;
description: string;
}
export interface PipelinesOverviewResponse {
kpis: PipelineKpi[];
pipelines: PipelineView[];
}
/** A trigger kind and the source types it works with. Mirrors the backend `TriggerInfo`. */
export interface TriggerInfo {
/** Matches `TriggerConfig.type` (e.g. "schedule", "folder-watch"). */
type: string;
/** Whether the trigger needs at least one compatible source to function. */
requiresSource: boolean;
/** Source types it supports; empty means source-agnostic (no constraint). */
supportedSourceTypes: string[];
}
// One run view for the whole app: the builder test-run poll and the catalogue runs list read the
// same backend PolicyRunView, so the type is defined once in the codec (imported above) and
// re-exported here for callers that reach it through the pipelines API.
export type { PolicyRunView, PolicyRunStatus, RunOutputFile };
/** GET /api/v1/policies/overview: KPI strip + one row per policy for the admin. */
export async function fetchPipelines(): Promise<PipelinesOverviewResponse> {
return apiClient.local.json<PipelinesOverviewResponse>(
"/api/v1/policies/overview",
);
}
/** GET /api/v1/policies/{id}: the raw policy record (steps, sources, trigger), for editing. */
export async function fetchPipeline(id: string): Promise<Policy> {
return apiClient.local.json<Policy>(
`/api/v1/policies/${encodeURIComponent(id)}`,
);
}
/** POST /api/v1/policies: create (blank id) or update (matched id) a policy. */
export async function savePipeline(policy: Policy): Promise<Policy> {
return apiClient.local.json<Policy>("/api/v1/policies", {
method: "POST",
body: policy,
});
}
/** DELETE /api/v1/policies/{id}: remove a policy. */
export async function deletePipeline(id: string): Promise<void> {
await apiClient.local.json<void>(
`/api/v1/policies/${encodeURIComponent(id)}`,
{
method: "DELETE",
},
);
}
/** GET /api/v1/policies/triggers: available triggers + their source compatibility. */
export async function fetchTriggers(): Promise<TriggerInfo[]> {
return apiClient.local.json<TriggerInfo[]>("/api/v1/policies/triggers");
}
/**
* The caller's policy-management capability, mirroring the backend gate: whether they may create,
* edit, or delete pipelines and policies (a manager). Others view but can't change them.
*/
export interface PolicyPermissions {
canManagePolicies: boolean;
}
/** GET /api/v1/policies/permissions: whether the caller may create/edit/delete pipelines & policies. */
export async function fetchPolicyPermissions(): Promise<PolicyPermissions> {
return apiClient.local.json<PolicyPermissions>(
"/api/v1/policies/permissions",
);
}
/**
* What a manual trigger found and started. Mirrors the backend `SweepOutcome`:
* when `runIds` is empty, the counts say why - no files listed, all already
* processed at their current version, parked by a failed run, or still in
* flight from an earlier sweep.
*/
export interface TriggerOutcome {
runIds: string[];
filesListed: number;
alreadyProcessed: number;
parked: number;
inFlight: number;
}
/**
* POST /api/v1/policies/{id}/trigger: run the pipeline now against its configured
* sources, regardless of the enabled flag. Returns the runs started plus what the
* sweep skipped; poll {@link fetchRun} for each run id.
*/
export async function triggerPipeline(id: string): Promise<TriggerOutcome> {
return apiClient.local.json<TriggerOutcome>(
`/api/v1/policies/${encodeURIComponent(id)}/trigger`,
{
method: "POST",
accountLinkBlockContext: { pipelineId: id, trigger: "manual" },
},
);
}
/** What an ad-hoc test run posts: the steps as they stand, with no source and no trigger. */
export interface TestRunDefinition {
name: string;
steps: ToolApiStep[];
output: OutputSpec;
}
/**
* A fresh, in-memory supporting file sent inline with a test run, bound to the run key a test step's
* `fileParameters` references. Only unsaved picks ride along here; a stored file keeps its
* `asset:<id>` binding, which the backend resolves from the saved policy (see `runPipelineTest`).
*/
export interface TestRunAsset {
key: string;
file: File;
}
/**
* POST /api/v1/policies/run: run a definition against one uploaded file now. The builder's test
* path - callers force an inline output so nothing reaches the pipeline's real destination, and
* the pipeline need not be saved first. Fresh supporting files travel as keyed `assets[i]` parts;
* a stored file keeps its `asset:<id>` binding, and `policyId` lets the backend resolve it from that
* saved policy (so its bytes need not be re-sent).
*/
export async function runPipelineTest(
definition: TestRunDefinition,
file: File,
assets: TestRunAsset[] = [],
policyId?: string,
): Promise<{ runId: string }> {
const form = new FormData();
form.append(
"json",
new Blob([JSON.stringify(definition)], { type: "application/json" }),
);
form.append("fileInput", file);
if (policyId) form.append("policyId", policyId);
assets.forEach((asset, i) => {
form.append(`assets[${i}].key`, asset.key);
form.append(`assets[${i}].file`, asset.file);
});
// The POST returns the identifier as `jobId`, but it is the same run id every other endpoint
// (fetchRun, fetchRunOutput) calls `runId`; normalise to that here so callers see one name.
const res = await apiClient.local.multipart<{ jobId: string }>(
"/api/v1/policies/run",
form,
{
pipelineId: policyId,
pipelineName: definition.name,
trigger: "manual",
},
);
return { runId: res.jobId };
}
/** GET /api/v1/general/files/{id}: download one of a run's outputs. */
export async function fetchRunOutput(fileId: string): Promise<Blob> {
return apiClient.local.blob(
`/api/v1/general/files/${encodeURIComponent(fileId)}`,
);
}
/** GET /api/v1/policies/run/{runId}: current status, error, and step cursor of a run. */
export async function fetchRun(runId: string): Promise<PolicyRunView> {
return apiClient.local.json<PolicyRunView>(
`/api/v1/policies/run/${encodeURIComponent(runId)}`,
);
}