-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.ts
More file actions
1149 lines (1106 loc) · 48.4 KB
/
Copy pathapi.ts
File metadata and controls
1149 lines (1106 loc) · 48.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
/**
* Flowable REST API client — single request() funnel.
*
* Per ADR-001: TypeScript strict (noUncheckedIndexedAccess, exactOptionalPropertyTypes).
* Per Pattern P-001: every Flowable REST call MUST go through request() in this file.
* Components and screens never call fetch() directly — bypassing this funnel makes
* the ApiInspector go blind (Pattern P-001 enforcement).
* Per Pattern P-003: errors propagate verbatim — request() throws FlowableError with
* the engine response body as .message and the HTTP status as .status. Callers
* render err.message directly in <ErrorBox/> with no friendly rewrites.
* Per Pattern P-004: DMN endpoints live under /flowable-rest/dmn-api (not /service)
* — every DMN wrapper passes { base: dmnBase() }.
*
* The single exception to P-001 is uploadDeployment() (multipart FormData) which
* builds the request manually but still pushes to API_LOG and dispatches api:log.
* See ADR-001 / P-001 / P-003 / P-004 in _bmad-output/planning-artifacts/architecture.md.
*/
// ── Type vocabulary + DTOs ────────────────────────────────────────────────
//
// Extracted to src/api-types.ts at Story 21.x to satisfy the 50 KB NFR-21
// navigability limit. Every symbol is re-exported below so existing
// `import { FlowableTask } from "../api"` call sites resolve unchanged.
export type {
AddAttachmentPayload,
ApiLogEntry,
ExecuteDecisionBody,
FlowableAppDefinition,
FlowableAttachment,
FlowableBatch,
FlowableBatchPart,
FlowableConfig,
FlowableDecision,
FlowableDecisionExecutionInputVariable,
FlowableDecisionResult,
FlowableDecisionResultVariable,
FlowableDeployment,
FlowableDmnExecutionAudit,
FlowableDmnRuleConditionResult,
FlowableDmnRuleExecution,
FlowableEngineInfo,
FlowableEventSubscription,
FlowableFormProperty,
FlowableGroup,
FlowableHistoricActivity,
FlowableHistoricDecisionExecution,
FlowableHistoricProcessInstance,
FlowableHistoricTask,
FlowableHistoricVariable,
FlowableHistoricVariableValue,
FlowableJob,
FlowablePage,
FlowableProcessDefinition,
FlowableProcessInstance,
FlowableResource,
FlowableTask,
FlowableTaskForm,
FlowableTenant,
FlowableUser,
FlowableVariable,
FlowableVariableInput,
HTTPMethod,
QueryParams,
RequestOpts,
} from "./api-types";
export { FlowableError } from "./api-types";
import {
getAppDefinition,
getAppDeploymentResource,
listAppDefinitions,
listAppDeploymentResources,
listAppDeployments,
} from "./api-app";
import {
getHistoricProcessInstance,
listHistoricActivities,
listHistoricInstances,
listHistoricTasks,
listHistoricVariables,
} from "./api-history";
import {
addUserToGroup,
createGroup,
createUser,
deleteGroup,
deleteUser,
getGroup,
getUser,
getUserGroups,
listGroupMembers,
listGroups,
listUsers,
removeUserFromGroup,
updateGroup,
updateUser,
} from "./api-identity";
import type {
AddAttachmentPayload,
ApiLogEntry,
ExecuteDecisionBody,
FlowableAttachment,
FlowableBatch,
FlowableBatchPart,
FlowableConfig,
FlowableDecision,
FlowableDecisionResult,
FlowableDeployment,
FlowableDmnExecutionAudit,
FlowableEngineInfo,
FlowableEventSubscription,
FlowableHistoricDecisionExecution,
FlowableJob,
FlowablePage,
FlowableProcessDefinition,
FlowableProcessInstance,
FlowableResource,
FlowableTask,
FlowableTaskForm,
FlowableTenant,
FlowableVariable,
FlowableVariableInput,
HTTPMethod,
QueryParams,
RequestOpts,
} from "./api-types";
import { FlowableError } from "./api-types";
import { type AuthStrategy, BasicAuthStrategy } from "./lib/auth-strategy";
import { randomId } from "./lib/random-id";
// ── Config (purely in-memory — flowatch.connections.v1 is the sole persistence key) ──
const defaultCfg: FlowableConfig = {
baseUrl: "http://localhost:8080/flowable-rest/service",
username: "rest-admin",
password: "test",
tenantId: "",
};
let cfg: FlowableConfig = { ...defaultCfg };
// Flowable splits its REST API across sub-apps. The BPMN/runtime/identity endpoints
// live under `/flowable-rest/service`, but DMN is mounted at `/flowable-rest/dmn-api`
// (and CMMN at `/cmmn-api`, the App API at `/app-api`).
//
// Story 34.1: per-sub-app URI prefixes are configurable per connection (FR-59).
// connectionRoot() strips the configured servicePath suffix from baseUrl to
// recover the deployment root; each sub-app base = root + its configured
// segment, falling back to the standard flowable-rest:7.2.0 default when the
// operator leaves the field blank. Backward-compat: with all fields blank,
// servicePath defaults to "/service" and dmnBase resolves identically to the
// pre-34.1 `baseUrl.replace(/\/service\/?$/, "/dmn-api")`.
const trimTrailingSlash = (s: string): string => s.replace(/\/+$/, "");
const servicePath = (): string => cfg.servicePath || "/service";
// Exported for the api-base derivation unit tests (Story 34.1 AC-5) — no live
// non-standard-mount engine exists for make stack (COMPAT-BOUNDARY, Story 29.1).
export const connectionRoot = (): string => {
const base = trimTrailingSlash(cfg.baseUrl);
const sp = servicePath();
// When baseUrl does NOT end with the configured servicePath (operator typed a
// bare root, or a non-standard service mount), return baseUrl as-is — the
// sub-app segment still appends, degrading gracefully rather than throwing.
return base.endsWith(sp) ? base.slice(0, base.length - sp.length) : base;
};
export const dmnBase = (): string => connectionRoot() + (cfg.dmnPath || "/dmn-api");
// Story 34.1: forward-reserved — no Flowatch CMMN consumer yet (FR-50). Added
// for four-helper symmetry so a future CMMN list/detail screen inherits the
// helper rather than re-deriving the prefix. Exported (unlike a purely-internal
// helper) precisely because it has no production call site yet; the api-base
// unit test is its only exerciser until FR-50 lands.
export const cmmnBase = (): string => connectionRoot() + (cfg.cmmnPath || "/cmmn-api");
// Story 25.1: Flowable App API sub-app — mirrors the `dmnBase()` shape per
// compat.md row 28. Read-only at this story; app-runtime (app-instances) is not
// exposed in flowable-rest:7.2.0 (PRD FR-55 scope-reduced).
export const appBase = (): string => connectionRoot() + (cfg.appPath || "/app-api");
export const API_LOG: ApiLogEntry[] = [];
const MAX_LOG = 60;
let logFrozen = false;
const logCall = (entry: ApiLogEntry): void => {
if (logFrozen) return;
API_LOG.unshift(entry);
if (API_LOG.length > MAX_LOG) API_LOG.length = MAX_LOG;
window.dispatchEvent(new CustomEvent<ApiLogEntry>("api:log", { detail: entry }));
};
// Clone-and-redact: keeps the headers object handed to fetch() untouched.
function redactAuthHeader(headers: Record<string, string>): Record<string, string> {
const out = { ...headers };
if (out.Authorization) {
const space = out.Authorization.indexOf(" ");
out.Authorization = space > 0 ? `${out.Authorization.slice(0, space)} ***` : "***";
}
return out;
}
// Truncate at capture time so large bodies don't lock the Inspector on render.
export const BODY_BYTE_BUDGET = 16 * 1024;
export interface TruncatedBody {
__truncated: true;
__originalBytes: number;
__preview: string;
}
export const captureBody = (body: unknown): unknown => {
try {
const json = JSON.stringify(body);
if (json === undefined) return body;
if (json.length <= BODY_BYTE_BUDGET) return body;
const envelope: TruncatedBody = {
__truncated: true,
__originalBytes: json.length,
__preview: json.slice(0, BODY_BYTE_BUDGET),
};
return envelope;
} catch {
return body;
}
};
// Dev-only seed hook: lets Playwright visual tests inject deterministic API_LOG
// entries without going through the real request() funnel. Guarded by Vite's
// DEV flag so production bundles never expose it. (Story 2.4 / Path B.)
if (import.meta.env.DEV && typeof window !== "undefined") {
const w = window as unknown as {
__flowatchSeedApiLog?: (entries: ApiLogEntry[]) => void;
__flowatchClearApiLog?: () => void;
__flowatchPauseApiLog?: () => void;
__flowatchResumeApiLog?: () => void;
};
w.__flowatchSeedApiLog = (entries) => {
for (const entry of entries) {
API_LOG.unshift(entry);
if (API_LOG.length > MAX_LOG) API_LOG.length = MAX_LOG;
window.dispatchEvent(new CustomEvent<ApiLogEntry>("api:log", { detail: entry }));
}
};
w.__flowatchClearApiLog = () => {
API_LOG.length = 0;
// Use a distinct event so listeners can react to the clear without
// mistaking a synthetic blank entry for a real API call. ApiInspector
// subscribes to both events and re-reads API_LOG on either signal.
window.dispatchEvent(new Event("api:log-cleared"));
};
w.__flowatchPauseApiLog = () => {
logFrozen = true;
};
w.__flowatchResumeApiLog = () => {
logFrozen = false;
};
}
const qs = (params?: QueryParams): string => {
if (!params) return "";
const usp = new URLSearchParams();
Object.entries(params).forEach(([k, v]) => {
if (v === undefined || v === null || v === "") return;
usp.append(k, String(v));
});
const s = usp.toString();
return s ? `?${s}` : "";
};
// ── Pluggable auth strategy (Story 28.1 — ADR-009) ────────────────────────
// Active strategy produces the Authorization header for request() +
// multipartFetch(). Default BasicAuthStrategy reads cfg via a getter closure;
// Story 28.2's dispatcher swaps it per the active authStrategyConfig.kind.
let authStrategy: AuthStrategy = new BasicAuthStrategy(() => ({
username: cfg.username,
password: cfg.password,
}));
export function setAuthStrategy(s: AuthStrategy): void {
authStrategy = s;
}
export function getAuthStrategy(): AuthStrategy {
return authStrategy;
}
// Shared multipart POST envelope used by `uploadDeployment` (Story 9.2) and
// `addTaskAttachment` file path (Story 21.2). Bypasses `request()` because the
// body is FormData (non-JSON) but logs via API_LOG identically. `buildFd` is a
// callback so FormData / Blob constructor throws land in the API_LOG entry
// with status=0 (Story 9.2 AC-7 + Story 8.1 deferred-work closure). Returns
// the raw Response — caller parses via `.json()`.
const multipartFetch = async (
root: string,
path: string,
buildFd: () => FormData,
): Promise<Response> => {
const url = root.replace(/\/$/, "") + path;
const t0 = performance.now();
const entry: ApiLogEntry = {
id: randomId(),
method: "POST",
path,
url,
status: 0,
ms: 0,
at: new Date().toISOString(),
};
try {
const fd = buildFd();
// Story 28.1: delegate the Authorization header to the active strategy
// (this path is the non-obvious SECOND seam point — miss it and Bearer/
// OIDC uploads silently leak Basic). `null` → no header sent.
const headers: Record<string, string> = {};
const authHeader = await authStrategy.authorizationHeader();
if (authHeader !== null) headers.Authorization = authHeader;
entry.headers = redactAuthHeader(headers);
const res = await fetch(url, { method: "POST", headers, body: fd });
entry.status = res.status;
entry.ms = Math.round(performance.now() - t0);
if (!res.ok) {
const text = await res.text().catch(() => "");
entry.error = text || `HTTP ${res.status}`;
logCall(entry);
throw new FlowableError(entry.error, res.status);
}
logCall(entry);
return res;
} catch (err) {
if (entry.status === 0) {
entry.error = err instanceof Error ? err.message : String(err);
entry.ms = Math.round(performance.now() - t0);
logCall(entry);
}
throw err;
}
};
// ── request() funnel ─────────────────────────────────────────────────────
//
// Generic over T (the JSON response shape). Wrappers that opt into raw text
// pin T = string at the call site (see getProcessDefinitionResource,
// getDmnDecisionResource, jobStacktrace). Per AC-3, the runtime guarantees
// the declared T matches when opts.raw is true.
export async function request<T = unknown>(
method: HTTPMethod,
path: string,
opts: RequestOpts = {},
): Promise<T> {
const { params, body, base, raw, asResponse } = opts;
const root = (base || cfg.baseUrl).replace(/\/$/, "");
const url = root + path + qs(params);
const t0 = performance.now();
const entry: ApiLogEntry = {
id: randomId(),
method,
path: path + qs(params),
url,
status: 0,
ms: 0,
at: new Date().toISOString(),
};
try {
// Story 28.1: the active AuthStrategy produces the Authorization header
// (async — chosen for OIDC's on-demand token refresh, Story 28.4). `null`
// → no Authorization header sent (reserved no-auth / empty-token case).
const headers: Record<string, string> = {
Accept: raw ? "*/*" : "application/json",
};
const authHeader = await authStrategy.authorizationHeader();
if (authHeader !== null) headers.Authorization = authHeader;
if (body) {
headers["Content-Type"] = "application/json";
}
const init: RequestInit = { method, headers };
entry.headers = redactAuthHeader(headers);
if (body) {
init.body = JSON.stringify(body);
entry.body = captureBody(body);
}
const res = await fetch(url, init);
entry.status = res.status;
entry.ms = Math.round(performance.now() - t0);
if (!res.ok) {
const text = await res.text().catch(() => "");
entry.error = text || `HTTP ${res.status}`;
logCall(entry);
// Story 28.1: 401-recovery seam. The active strategy's onUnauthorized
// hook is ADDITIVE — it fires a recovery side-channel (Bearer 28.3 →
// open Settings; OIDC 28.4 → silent renew / re-auth) but the error
// STILL propagates so the calling screen surfaces its ErrorBox. Basic
// leaves the hook undefined → optional-chaining no-ops.
if (res.status === 401) await authStrategy.onUnauthorized?.();
throw new FlowableError(entry.error, res.status);
}
// Story 9.6: when asResponse is set, log the entry and hand the caller the
// raw Response so they pick the body method (.blob() for binary, .text()
// for XML, etc.). NFR-8 is preserved — entry.body stays undefined; the
// response bytes never enter API_LOG.
if (asResponse) {
logCall(entry);
return res as unknown as T;
}
const data: T = raw
? ((await res.text()) as unknown as T)
: res.headers.get("content-type")?.includes("application/json")
? ((await res.json()) as T)
: ((await res.text()) as unknown as T);
logCall(entry);
return data;
} catch (err) {
if (entry.status === 0) {
entry.error = err instanceof Error ? err.message : String(err);
entry.ms = Math.round(performance.now() - t0);
logCall(entry);
}
throw err;
}
}
// ── Repository (BPMN) ─────────────────────────────────────────────────────
const listDeployments = (params?: QueryParams) =>
request<FlowablePage<FlowableDeployment>>("GET", "/repository/deployments", { params });
const getDeployment = (id: string) =>
request<FlowableDeployment>("GET", `/repository/deployments/${id}`);
const createDeployment = (form: unknown) =>
request<FlowableDeployment>("POST", "/repository/deployments", { body: form });
const deleteDeployment = (id: string, cascade?: boolean) =>
request<void>(
"DELETE",
`/repository/deployments/${id}`,
cascade ? { params: { cascade: true } } : {},
);
const listDeploymentResources = (id: string) =>
request<FlowableResource[]>("GET", `/repository/deployments/${id}/resources`);
// Story 9.6: binary download path. Returns the raw Response so callers pick
// the body method (.blob() for octet-stream, .text() for XML). Mirrors
// getProcessDefinitionResource but at the deployment-resource level.
const getDeploymentResource = (deploymentId: string, resourceName: string) =>
request<Response>(
"GET",
`/repository/deployments/${deploymentId}/resourcedata/${encodeURIComponent(resourceName)}`,
{ asResponse: true },
);
const listProcessDefinitions = (params?: QueryParams) =>
request<FlowablePage<FlowableProcessDefinition>>("GET", "/repository/process-definitions", {
params,
});
const getProcessDefinition = (id: string) =>
request<FlowableProcessDefinition>("GET", `/repository/process-definitions/${id}`);
/**
* Story 20.1 + RC-16 workaround: read a process definition via the LIST
* endpoint so the response reflects the DB-persisted `category` (and any
* other field the single-GET serves from its BPMN-model cache).
*
* Flowable 7.2.0 GET /repository/process-definitions/{id} returns
* `category` from the BPMN model cache (populated at deploy from the BPMN
* file's <targetNamespace>); the DB-persisted `act_re_procdef.category_`
* column — updated by `updateProcessDefinition` — is ignored. The LIST
* endpoint reads `category_` directly, so the post-edit value surfaces
* here. Engine `id`/`processDefinitionId` filters are silently ignored on
* the LIST endpoint; we filter by `key` (extracted from the engine's
* `key:version:UUID` id format) and JS-filter by id. The wrapper falls
* through to the single-GET if the list doesn't surface the id (defensive;
* should never happen for a deployed definition).
*
* Used by the /definitions/$id route loader so the detail page reflects
* the operator's edit. Other consumers of `getProcessDefinition` (single
* call) are unchanged; the wire-level contract there is documented per RC-16.
*/
const getProcessDefinitionFresh = async (id: string): Promise<FlowableProcessDefinition> => {
const [key] = id.split(":");
const page = await request<FlowablePage<FlowableProcessDefinition>>(
"GET",
"/repository/process-definitions",
{ params: { key, size: 200 } },
);
const found = page.data.find((d) => d.id === id);
if (found) return found;
return request<FlowableProcessDefinition>("GET", `/repository/process-definitions/${id}`);
};
const suspendProcessDefinition = (id: string, suspend: boolean) =>
request<FlowableProcessDefinition>("PUT", `/repository/process-definitions/${id}`, {
body: { action: suspend ? "suspend" : "activate" },
});
/**
* Story 20.1: edit fields on a process definition (currently: `category`).
*
* Funnels `PUT /repository/process-definitions/{id}` through `request()` with
* a partial-fields body (e.g. `{category: "finance"}`). The engine accepts
* `{category: ""}` to clear the value (revert to default per docs/compat.md
* line 149). Verified live on flowable-rest 7.2.0 per docs/compat.md FR-43.
*
* Endpoint-duality with `suspendProcessDefinition` (Story 9.4): both wrappers
* PUT to the SAME wire URL but the engine discriminates by body shape:
* - `{action: "suspend" | "activate"}` → suspend / activate path
* - `{category: "…"}` → field-update path
* Per CLAUDE.md "Operator-feel UI labels can diverge from wire-level action
* verbs" (Story 12.2 codification), the two operator-feel actions get distinct
* wrappers even though they share a URL. The `fields` parameter shape allows
* future Epic 21 / 22 field extensions (name, description, …) to land as a
* type-level addition rather than a wrapper-signature churn.
*
* Engine response: `200 OK` with the full FlowableProcessDefinition body
* echoed back (confirmed in T-10 live probe per spec AC-13).
*/
const updateProcessDefinition = (id: string, fields: Partial<{ category: string }>) => {
// Empty body collides with the suspend/activate body discriminator on the same URL.
if (Object.keys(fields).length === 0)
throw new Error("updateProcessDefinition requires at least one field");
return request<FlowableProcessDefinition>("PUT", `/repository/process-definitions/${id}`, {
body: fields,
});
};
const getProcessDefinitionResource = (id: string): Promise<string> =>
request<string>("GET", `/repository/process-definitions/${id}/resourcedata`, { raw: true });
// ── Runtime ───────────────────────────────────────────────────────────────
const listProcessInstances = (params?: QueryParams) =>
request<FlowablePage<FlowableProcessInstance>>("GET", "/runtime/process-instances", { params });
const getProcessInstance = (id: string) =>
request<FlowableProcessInstance>("GET", `/runtime/process-instances/${id}`);
const startProcessInstance = (body: Record<string, unknown>) =>
request<FlowableProcessInstance>("POST", "/runtime/process-instances", { body });
const deleteProcessInstance = (id: string, reason?: string) =>
request<void>(
"DELETE",
`/runtime/process-instances/${id}`,
reason ? { params: { deleteReason: reason } } : {},
);
const getProcessInstanceVariables = (id: string) =>
request<FlowableVariable[]>("GET", `/runtime/process-instances/${id}/variables`);
/**
* Story 19.1: edit/add runtime variables on a running process instance.
*
* PUT body is ALWAYS an array — even single-variable edits pass
* `[{name, value, type, scope}]`. The engine returns 201 Created with a
* JSON-array body echoing each variable (see docs/runtime-caveats.md RC-15
* — every entry carries `scope: "local"` regardless of input; the GET-side
* read shows the actual persisted scope). The wrapper ignores the response
* body via `request<void>`; callers read state via the GET endpoint.
* 4xx errors come back as JSON `{"message":"Bad request","exception":"..."}`
* and are surfaced verbatim through ErrorBox per Pattern P-003. Verified
* live on flowable-rest 7.2.0 per docs/compat.md FR-19.
*
* The wrapper drops `scope: "global"` from the body — the engine treats an
* absent scope as global; only an explicit `scope: "local"` targets the
* current execution. Sending it both ways works (idempotent on global) but
* the minimum-wire convention matches Flowable's documented contract.
*/
const updateInstanceVariables = (instanceId: string, vars: FlowableVariableInput[]) => {
const body = vars.map((v) => {
const out: FlowableVariableInput = { name: v.name, value: v.value };
if (v.type !== undefined) out.type = v.type;
if (v.scope === "local") out.scope = "local";
return out;
});
return request<void>("PUT", `/runtime/process-instances/${instanceId}/variables`, { body });
};
/**
* Story 19.2: delete a single runtime variable by name from a running
* process instance.
*
* Funnels `DELETE /runtime/process-instances/{id}/variables/{name}` through
* `request()`. The variable name is `encodeURIComponent`-wrapped — variable
* names may contain periods, slashes, spaces, or unicode characters (e.g.
* `my.nested.key`, `with spaces`); without encoding, `foo/bar` would route
* to a different endpoint. Verified live on flowable-rest 7.2.0 per
* docs/compat.md FR-19 (the raw probe at line 150 deleted a variable named
* `probe` and reverted cleanly).
*
* Engine response on success: `204 No Content`. 4xx (e.g. variable doesn't
* exist) propagates verbatim through `<ErrorBox>` per Pattern P-003.
*/
const deleteInstanceVariable = (instanceId: string, name: string) =>
request<void>(
"DELETE",
`/runtime/process-instances/${instanceId}/variables/${encodeURIComponent(name)}`,
);
const listTasks = (params?: QueryParams) =>
request<FlowablePage<FlowableTask>>("GET", "/runtime/tasks", { params });
const getTask = (id: string) => request<FlowableTask>("GET", `/runtime/tasks/${id}`);
const taskAction = (taskId: string, action: string, body?: Record<string, unknown>) =>
request<FlowableTask>("POST", `/runtime/tasks/${taskId}`, { body: { action, ...(body ?? {}) } });
/**
* Story 21.1: edit fields on a runtime task (priority / dueDate / owner /
* assignee).
*
* Funnels `PUT /runtime/tasks/{id}` through `request()` with a partial-fields
* body (e.g. `{priority: 75, dueDate: null}`). Nullable string + datetime
* fields use `null` to clear — verified live on flowable-rest 7.2.0 per
* docs/compat.md FR-44 + the T-9 probe. Empty-string is silently coerced to
* `null` by the engine; the wrapper sends `null` for clarity.
*
* Two-method endpoint duality with `taskAction` (Story 11.x): both wrappers
* hit the SAME wire URL `/runtime/tasks/{id}`, but discriminated by HTTP
* method:
* - POST {action: "claim" | "complete" | "delegate" | "resolve" | "unclaim"}
* → action-verb path (`taskAction`)
* - PUT {<field>: <value>}
* → field-patch path (`updateTask`)
* Per CLAUDE.md "Operator-feel UI labels can diverge from wire-level action
* verbs" (Story 12.2 codification), the two operator-feel actions get
* distinct wrappers. The `fields` parameter shape allows future scope
* extensions (name, description, category, parentTaskId, tenantId per
* compat.md line 61) to land as a type-level addition without churn.
*
* Priority is numeric (Flowable default = 50); the engine accepts 0-100 but
* the wrapper does NOT pre-validate — operator typos surface as engine 4xx.
* `dueDate` is ISO-8601 UTC; the caller is responsible for the local→UTC
* round-trip (see `<EditTaskModal>` + Story 12.2 `<input type="datetime-local">`
* convention).
*
* Engine response: `200 OK` with the echoed FlowableTask body.
*/
const updateTask = (
id: string,
fields: Partial<{
priority: number;
dueDate: string | null;
owner: string | null;
assignee: string | null;
}>,
) => {
if (Object.keys(fields).length === 0) throw new Error("updateTask requires at least one field");
return request<FlowableTask>("PUT", `/runtime/tasks/${id}`, { body: fields });
};
const getTaskVariables = (taskId: string) =>
request<FlowableVariable[]>("GET", `/runtime/tasks/${taskId}/variables`);
/**
* Story 21.2: list a runtime task's attachments.
*
* Funnels `GET /runtime/tasks/{taskId}/attachments` through `request()`.
* Response shape: a BARE ARRAY of FlowableAttachment (NOT a paged envelope).
* Verified live on flowable-rest 7.2.0 per docs/compat.md FR-45.
*/
const listTaskAttachments = (taskId: string) =>
request<FlowableAttachment[]>("GET", `/runtime/tasks/${taskId}/attachments`);
/**
* Story 21.2: add an attachment to a runtime task.
*
* Discriminated-union payload. The wrapper branches:
* - `kind: "url"` → JSON POST through `request()` with body
* `{name, description?, type?, externalUrl}`.
* - `kind: "file"` → multipart POST that bypasses `request()` (FormData
* body) but logs via the same envelope as `uploadDeployment`. Pattern
* P-001 is preserved — the manual fetch() is intra-file.
*
* Multipart field names per Flowable's documented contract:
* `name` / `description` (optional) / `type` (optional MIME) / `content`
* (binary). The engine derives `id` / `time` / `userId` server-side.
*
* Engine response: `201 Created` (URL path) / `200 OK` (file path —
* varies per engine version; the wrapper accepts both via res.ok) with
* the echoed FlowableAttachment body. Verified live on flowable-rest 7.2.0
* per docs/compat.md FR-45.
*/
/**
* Story 21.3: fetch the binary content of a task attachment (file-mode only).
*
* Returns the raw `Response` so the caller picks the body method
* (`.blob()` for binary, `.text()` for text). Mirrors `getDeploymentResource`
* (Story 9.6) at the task-attachment level. URL-mode attachments are
* opened via their `externalUrl` directly — they do NOT use this wrapper.
*
* Engine response: `200 OK` with binary body. Verified live on
* flowable-rest 7.2.0 per docs/compat.md FR-45.
*/
const getTaskAttachmentContent = (taskId: string, attachmentId: string) =>
request<Response>("GET", `/runtime/tasks/${taskId}/attachments/${attachmentId}/content`, {
asResponse: true,
});
/**
* Story 21.3: remove a task attachment by id.
*
* Funnels `DELETE /runtime/tasks/{taskId}/attachments/{attachmentId}` through
* `request()`. Symmetric pair with `addTaskAttachment` (Story 21.2).
*
* Engine response: `204 No Content`. Verified live on flowable-rest 7.2.0
* per docs/compat.md FR-45.
*/
const deleteTaskAttachment = (taskId: string, attachmentId: string) =>
request<void>("DELETE", `/runtime/tasks/${taskId}/attachments/${attachmentId}`);
const addTaskAttachment = async (
taskId: string,
payload: AddAttachmentPayload,
): Promise<FlowableAttachment> => {
if (payload.kind === "url") {
return request<FlowableAttachment>("POST", `/runtime/tasks/${taskId}/attachments`, {
body: {
name: payload.name,
description: payload.description,
type: payload.type,
externalUrl: payload.externalUrl,
},
});
}
const res = await multipartFetch(cfg.baseUrl, `/runtime/tasks/${taskId}/attachments`, () => {
const fd = new FormData();
fd.append("name", payload.name);
if (payload.description) fd.append("description", payload.description);
if (payload.type) fd.append("type", payload.type);
fd.append("content", payload.file, payload.name);
return fd;
});
return (await res.json()) as FlowableAttachment;
};
// Story 24.2: event subscriptions are runtime engine state (what messages /
// signals / timers the engine is waiting on per running instance).
// `/runtime/event-subscriptions` accepts processInstanceId, eventType,
// eventName, tenantId, size, start, sort, order. Read-only — no per-id
// mutation surface verified in compat.md.
const listEventSubscriptions = (params?: QueryParams) =>
request<FlowablePage<FlowableEventSubscription>>("GET", "/runtime/event-subscriptions", {
params,
});
// ── Form ──────────────────────────────────────────────────────────────────
const getTaskForm = (taskId: string) =>
request<FlowableTaskForm>("GET", "/form/form-data", { params: { taskId } });
// Story 11.3: body shape is `{ taskId, properties }` per the Flowable contract;
// `properties` is an array of `{ id, value }` envelopes (value is always a
// string at the wire — booleans become "true" / "false"; numbers serialise
// via their JS string form).
const submitTaskForm = (
taskId: string,
body: { properties: Array<{ id: string; value: string }> },
) => request<FlowableTaskForm>("POST", "/form/form-data", { body: { taskId, ...body } });
// ── Management ───────────────────────────────────────────────────────────
const listJobs = (params?: QueryParams) =>
request<FlowablePage<FlowableJob>>("GET", "/management/jobs", { params });
const getJob = (id: string) => request<FlowableJob>("GET", `/management/jobs/${id}`);
const listTimerJobs = (params?: QueryParams) =>
request<FlowablePage<FlowableJob>>("GET", "/management/timer-jobs", { params });
const listDeadLetterJobs = (params?: QueryParams) =>
request<FlowablePage<FlowableJob>>("GET", "/management/deadletter-jobs", { params });
const executeJob = (id: string) =>
request<void>("POST", `/management/jobs/${id}`, { body: { action: "execute" } });
// Timer-job IDs live in a different namespace than executable-job IDs in
// Flowable 7.x — a POST to /management/jobs/{timerId} returns 404, and the
// timer-jobs endpoint only accepts `move` or `reschedule` (NOT `execute`).
// The supported "fire timer now" recipe is `move` (queues to executable;
// the async executor picks it up on its next poll). The handler-side label
// "Execute now" reflects the operator-feel; the wire-level verb is `move`.
const executeTimerJob = (id: string) =>
request<void>("POST", `/management/timer-jobs/${id}`, { body: { action: "move" } });
// Reschedule a timer job to a new dueDate (Flowable 7.x action verb). The
// payload key is `dueDate` per the engine contract; format is ISO-8601.
const rescheduleTimerJob = (id: string, dueDate: string) =>
request<FlowableJob>("POST", `/management/timer-jobs/${id}`, {
body: { action: "reschedule", dueDate },
});
const moveDeadLetterJob = (id: string) =>
request<FlowableJob>("POST", `/management/deadletter-jobs/${id}`, { body: { action: "move" } });
const jobStacktrace = (id: string): Promise<string> =>
request<string>("GET", `/management/jobs/${id}/exception-stacktrace`, { raw: true });
// Timer / dead-letter jobs live in separate namespaces — their stacktrace
// endpoints are NOT under /management/jobs/{id}. Mirrors the executeJob /
// executeTimerJob / moveDeadLetterJob namespace separation.
const timerJobStacktrace = (id: string): Promise<string> =>
request<string>("GET", `/management/timer-jobs/${id}/exception-stacktrace`, { raw: true });
const deadLetterJobStacktrace = (id: string): Promise<string> =>
request<string>("GET", `/management/deadletter-jobs/${id}/exception-stacktrace`, { raw: true });
// Story 24.1 (FR-53): batch operations + per-part stacktrace. Read-only.
// `batchPartStacktrace` uses `raw: true` — engine returns the stacktrace as
// text/plain (mirrors `jobStacktrace` shape). 404 → FlowableError with
// status === 404 → mapped to null at the panel via `fetchBatchPartStacktrace
// OrNull` (status-aware error-probe per Epic 11 retro §4.4). Path ids are
// `encodeURIComponent`-wrapped — defensive against engine-supplied ids that
// might contain reserved characters (mirrors `deleteInstanceVariable` shape).
const listBatches = (params?: QueryParams) =>
request<FlowablePage<FlowableBatch>>("GET", "/management/batches", { params });
const getBatch = (id: string) =>
request<FlowableBatch>("GET", `/management/batches/${encodeURIComponent(id)}`);
const listBatchParts = (batchId: string, params?: QueryParams) =>
request<FlowablePage<FlowableBatchPart>>(
"GET",
`/management/batches/${encodeURIComponent(batchId)}/batch-parts`,
{ params },
);
const batchPartStacktrace = (id: string): Promise<string> =>
request<string>("GET", `/management/batch-parts/${encodeURIComponent(id)}/exception-stacktrace`, {
raw: true,
});
// ── History ──────────────────────────────────────────────────────────────
// Historic-process-instance wrappers extracted to src/api-history.ts per NFR-21
// navigability (50 KB per-source-file limit). Pattern P-001 preserved.
// ── App (mounted under /flowable-rest/app-api, not /service) ─────────────
// App-sub-app read wrappers extracted to src/api-app.ts per NFR-21
// navigability (50 KB per-source-file limit). Pattern P-001 preserved.
// The write path (deployBar) stays here — it uses multipartFetch/uploadDeployment.
// ── Identity ─────────────────────────────────────────────────────────────
// Identity-surface wrappers extracted to src/api-identity.ts per NFR-21
// navigability (50 KB per-source-file limit). All wrappers funnel through
// the same `request<T>` exported above; Pattern P-001 preserved.
// Tenants are not exposed as a dedicated endpoint in flowable-rest 7.2.
// Derive distinct tenantIds from deployments (truthy values only).
//
// 60-second TTL cache on the derivation. The Topbar pill, route loaders,
// and badge probes all call api.listTenants(); without the cache, every
// chrome render hammers /repository/deployments. The TTL is short enough
// that newly-deployed tenantIds appear within a minute; long enough that
// the chrome doesn't re-derive on every cycleTenant() click.
//
// The /repository/deployments?size=200 page caps the derivation at 200
// deployments per page. Engines with >200 deployments (multiple tenants
// × many definitions) may produce truncated tenant lists. Future
// enhancement (post-MVP): page through /repository/deployments with
// multiple ?start= requests to enumerate all tenants.
let _tenantsCache: { value: { data: FlowableTenant[] }; at: number } | null = null;
const TENANTS_CACHE_TTL_MS = 60_000;
const TENANTS_PAGE_SIZE = 200;
const listTenants = async (): Promise<{ data: FlowableTenant[] }> => {
const now = Date.now();
if (_tenantsCache && now - _tenantsCache.at < TENANTS_CACHE_TTL_MS) {
return _tenantsCache.value;
}
const res = await listDeployments({ size: TENANTS_PAGE_SIZE });
if (res?.data && res.data.length === TENANTS_PAGE_SIZE) {
// eslint-disable-next-line no-console
console.warn(
`[flowatch] api.listTenants: /repository/deployments returned ${TENANTS_PAGE_SIZE} rows (page cap reached); tenant list may be truncated for very large engines.`,
);
}
const ids = new Set<string>();
(res?.data || []).forEach((d) => {
if (d.tenantId) ids.add(d.tenantId);
});
const value = { data: [...ids].map((id) => ({ id, name: id })) };
_tenantsCache = { value, at: now };
return value;
};
// Test-only export — call this in tests to reset the module-scoped cache
// between cases. Also used in production once: by api.setConfig() when the
// engine endpoint changes (per Story 14.4 AC-9).
export const __clearTenantsCache = (): void => {
_tenantsCache = null;
};
// ── DMN (mounted under /flowable-rest/dmn-api, not /service) ─────────────
const listDecisions = (params?: QueryParams) =>
request<FlowablePage<FlowableDecision>>("GET", "/dmn-repository/decisions", {
params,
base: dmnBase(),
});
const listDmnDeployments = (params?: QueryParams) =>
request<FlowablePage<FlowableDeployment>>("GET", "/dmn-repository/deployments", {
params,
base: dmnBase(),
});
// Story 15.3: tightened signature. The body shape matches Flowable 7.x's
// POST /dmn-rule/execute — `decisionKey` + an array of typed input variables.
// Pass `parentDeploymentId` to lock execution to a specific deployment;
// without it, the engine picks the latest version of the decision key.
const executeDecision = (body: ExecuteDecisionBody) =>
request<FlowableDecisionResult>("POST", "/dmn-rule/execute", { body, base: dmnBase() });
// Direct DMN XML fetch by decision-table id. Mirrors the BPMN side's
// /repository/process-definitions/{id}/resourcedata shape — one endpoint,
// no deployment-resources discovery hop. The `decisionTableId` matches a
// `FlowableDecision.id`. The DMN sub-app does NOT expose a
// `/deployments/{id}/resources` listing endpoint (returns 500 "No
// endpoint" on flowable-rest 7.2 OSS), which is why we fetch by decision
// id rather than by deployment+filename.
const getDmnDecisionResource = (decisionId: string): Promise<string> =>
request<string>("GET", `/dmn-repository/decision-tables/${decisionId}/resourcedata`, {
raw: true,
base: dmnBase(),
});
// Story 15.4: list historic DMN decision executions.
//
// Supported params (per Flowable 7.x DMN-history REST surface):
// size, start, sort, order — pagination + sort
// decisionKey, decisionKeyLike — filter by decision key
// processInstanceId — filter by parent process instance
// executionId — filter by Flowable execution context
// activityId — filter by triggering activity
// startedBefore, startedAfter — ISO 8601 timestamp bounds
// tenantId — tenant scoping
const listDmnHistoryExecutions = (params?: QueryParams) =>
request<FlowablePage<FlowableHistoricDecisionExecution>>(
"GET",
"/dmn-history/historic-decision-executions",
{ params, base: dmnBase() },
);
// Fetch the rich audit data for a single historic decision execution —
// surfaces hit policy, typed input/result maps, and the per-rule
// condition+conclusion trace. Used by the executions row-expand panel.
const getDmnHistoryAuditdata = (executionId: string) =>
request<FlowableDmnExecutionAudit>(
"GET",
`/dmn-history/historic-decision-executions/${executionId}/auditdata`,
{ base: dmnBase() },
);
// Single-deployment GET — mirror of the BPMN side's `api.getDeployment`,
// powers the kind-aware `/deployments/$id` route loader.
const getDmnDeployment = (id: string) =>
request<FlowableDeployment>("GET", `/dmn-repository/deployments/${id}`, { base: dmnBase() });
// Binary download for an individual DMN deployment resource — mirror of
// BPMN's `getDeploymentResource`. Returns the raw Response so the caller
// picks .blob() / .text(); used by the kind-aware DeploymentDetail.
const getDmnDeploymentResource = (deploymentId: string, resourceName: string) =>
request<Response>(
"GET",
`/dmn-repository/deployments/${deploymentId}/resourcedata/${encodeURIComponent(resourceName)}`,
{ asResponse: true, base: dmnBase() },
);
// Story 15.2: DELETE a DMN deployment. Pass `{cascade: true}` to delete
// decisions still referenced by historic executions (mirrors BPMN's
// removeDeployment cascade flag at /repository/deployments/{id}). Without
// cascade, the engine returns 409 Conflict if any historic execution
// references a decision from this deployment.
const removeDmnDeployment = (id: string, params?: { cascade?: boolean }) =>
request<void>(
"DELETE",
`/dmn-repository/deployments/${id}`,
params?.cascade ? { params: { cascade: true }, base: dmnBase() } : { base: dmnBase() },
);
// ── Deployment helpers (multipart upload) ────────────────────────────────
// Flowable expects multipart/form-data, not the JSON-with-base64 shape we used
// in mock mode. We build a FormData and send via raw fetch (bypassing request()
// because the body is non-JSON), but still log the call.
interface UploadOpts {
base?: string;
deploymentName?: string;
/**
* Path under `base` to POST the multipart deployment to. Defaults to
* `/repository/deployments` (BPMN sub-app). The DMN sub-app uses
* `/dmn-repository/deployments` — `deployDmn` passes that explicitly.
* Without this override, DMN deploys hit `/dmn-api/repository/deployments`
* which returns "No endpoint POST …" from flowable-rest 7.2.
*/
path?: string;
}
// Story 25.1: `content` widened from `string` to `string | Blob` so .bar /
// .zip archives can be uploaded as binary Blob/File directly. Blob branch
// pass-throughs without re-wrapping (wrapping a Blob in `new Blob([blob])`
// works but is a wasteful copy). Existing `deployBpmn` / `deployDmn` callers
// pass strings and are unaffected.
const uploadDeployment = async (
filename: string,
content: string | Blob,
type: string,
opts: UploadOpts = {},
): Promise<FlowableDeployment> => {
const root = opts.base || cfg.baseUrl;
const path = opts.path || "/repository/deployments";
// FormData build happens inside multipartFetch's try (Story 9.2 AC-7) so a
// Blob constructor throw lands in API_LOG with status=0.
const res = await multipartFetch(root, path, () => {
const fd = new FormData();
const blob = content instanceof Blob ? content : new Blob([content], { type });
fd.append("file", blob, filename);
if (cfg.tenantId) fd.append("tenantId", cfg.tenantId);
if (opts.deploymentName) fd.append("deploymentName", opts.deploymentName);
return fd;
});
return (await res.json()) as FlowableDeployment;
};
const deployBpmn = (name: string, xml: string) =>
uploadDeployment(name, xml, "application/xml", { deploymentName: name });
// Story 25.1: signature widened — `content` accepts string XML or a Blob/File
// (used by the .bar extractor that POSTs each bundled .dmn entry as a Blob).
const deployDmn = (name: string, xml: string | Blob) =>
uploadDeployment(name, xml, "application/xml", {
deploymentName: name,
base: dmnBase(),
path: "/dmn-repository/deployments",
});
// Story 25.1: deploy a Flowable App archive (.bar / .zip) through the App
// sub-app. The AppDeployer cascades into BpmnDeployer + DmnDeployer for
// bundled .bpmn / .dmn entries — a single POST registers the app-def AND
// every bundled artefact. The child BPMN / DMN deployments are linked to
// the app deployment via `parentDeploymentId` (the BPMN child appears in
// /repository/deployments with parentDeploymentId pointing at this
// app-deployment id, NOT at itself like a standalone BPMN deploy). RC-17.
const deployBar = (filename: string, file: Blob | File) =>
uploadDeployment(filename, file, "application/zip", {
deploymentName: filename,
base: appBase(),
path: "/app-repository/deployments",
});
const ping = () => request<FlowableEngineInfo>("GET", "/management/engine");
// Test a specific saved connection without mutating the global cfg.
// Temporarily swaps authStrategy so the call routes through the full request()
// funnel (API_LOG entry + NFR-8 redaction). Safe in single-tab browser context.