@widgetic/workflows 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/README.md +107 -46
  2. package/dist/api/apiContext.d.ts +4 -0
  3. package/dist/api/apiContext.js +17 -0
  4. package/dist/api/types.d.ts +168 -0
  5. package/dist/api/types.js +3 -0
  6. package/dist/api/workflowsApi.d.ts +109 -0
  7. package/dist/api/workflowsApi.js +657 -0
  8. package/dist/components/Workflows.svelte +41 -17
  9. package/dist/components/WorkflowsEmptyState.svelte +16 -5
  10. package/dist/components/WorkflowsEmptyState.svelte.d.ts +5 -16
  11. package/dist/components/WorkflowsHeader.svelte +2 -2
  12. package/dist/components/WorkflowsWorkspace.svelte +87 -0
  13. package/dist/components/WorkflowsWorkspace.svelte.d.ts +14 -0
  14. package/dist/components/canvas/AddBlockMenu.svelte +101 -0
  15. package/dist/components/canvas/AddBlockMenu.svelte.d.ts +5 -0
  16. package/dist/components/canvas/CanvasToolbar.svelte +95 -0
  17. package/dist/components/canvas/CanvasToolbar.svelte.d.ts +9 -0
  18. package/dist/components/canvas/CompositionNodeView.svelte +125 -0
  19. package/dist/components/canvas/CompositionNodeView.svelte.d.ts +5 -0
  20. package/dist/components/canvas/ConditionNodeView.svelte +95 -0
  21. package/dist/components/canvas/ConditionNodeView.svelte.d.ts +5 -0
  22. package/dist/components/canvas/HandlePoint.svelte +32 -0
  23. package/dist/components/canvas/HandlePoint.svelte.d.ts +14 -0
  24. package/dist/components/canvas/TriggerNodeView.svelte +75 -0
  25. package/dist/components/canvas/TriggerNodeView.svelte.d.ts +5 -0
  26. package/dist/components/canvas/WorkflowCanvas.svelte +380 -0
  27. package/dist/components/canvas/WorkflowCanvas.svelte.d.ts +25 -0
  28. package/dist/components/canvas/WorkflowEdgeView.svelte +58 -0
  29. package/dist/components/canvas/WorkflowEdgeView.svelte.d.ts +4 -0
  30. package/dist/components/editor/EditorBanners.svelte +143 -0
  31. package/dist/components/editor/EditorBanners.svelte.d.ts +7 -0
  32. package/dist/components/editor/EditorCanvasArea.svelte +85 -0
  33. package/dist/components/editor/EditorCanvasArea.svelte.d.ts +3 -0
  34. package/dist/components/editor/EditorTabs.svelte +81 -0
  35. package/dist/components/editor/EditorTabs.svelte.d.ts +7 -0
  36. package/dist/components/editor/EditorTopBar.svelte +132 -0
  37. package/dist/components/editor/EditorTopBar.svelte.d.ts +9 -0
  38. package/dist/components/editor/RunsTab.svelte +256 -0
  39. package/dist/components/editor/RunsTab.svelte.d.ts +3 -0
  40. package/dist/components/editor/SettingsTab.svelte +180 -0
  41. package/dist/components/editor/SettingsTab.svelte.d.ts +7 -0
  42. package/dist/components/editor/WorkflowEditor.svelte +185 -0
  43. package/dist/components/editor/WorkflowEditor.svelte.d.ts +15 -0
  44. package/dist/components/index.d.ts +0 -2
  45. package/dist/components/index.js +0 -2
  46. package/dist/components/list/CreateWorkflowDialog.svelte +89 -0
  47. package/dist/components/list/CreateWorkflowDialog.svelte.d.ts +9 -0
  48. package/dist/components/list/WorkflowList.svelte +204 -0
  49. package/dist/components/list/WorkflowList.svelte.d.ts +12 -0
  50. package/dist/components/list/WorkflowRow.svelte +191 -0
  51. package/dist/components/list/WorkflowRow.svelte.d.ts +10 -0
  52. package/dist/components/panel/BlockProblems.svelte +47 -0
  53. package/dist/components/panel/BlockProblems.svelte.d.ts +6 -0
  54. package/dist/components/panel/CompositionForm.svelte +127 -0
  55. package/dist/components/panel/CompositionForm.svelte.d.ts +7 -0
  56. package/dist/components/panel/CompositionPicker.svelte +179 -0
  57. package/dist/components/panel/CompositionPicker.svelte.d.ts +14 -0
  58. package/dist/components/panel/ConditionForm.svelte +105 -0
  59. package/dist/components/panel/ConditionForm.svelte.d.ts +7 -0
  60. package/dist/components/panel/EventValueRow.svelte +85 -0
  61. package/dist/components/panel/EventValueRow.svelte.d.ts +12 -0
  62. package/dist/components/panel/NextStepSelect.svelte +70 -0
  63. package/dist/components/panel/NextStepSelect.svelte.d.ts +12 -0
  64. package/dist/components/panel/ProblemsList.svelte +101 -0
  65. package/dist/components/panel/ProblemsList.svelte.d.ts +3 -0
  66. package/dist/components/panel/RuleCard.svelte +191 -0
  67. package/dist/components/panel/RuleCard.svelte.d.ts +13 -0
  68. package/dist/components/panel/SidePanel.svelte +82 -0
  69. package/dist/components/panel/SidePanel.svelte.d.ts +3 -0
  70. package/dist/components/panel/TestRow.svelte +150 -0
  71. package/dist/components/panel/TestRow.svelte.d.ts +15 -0
  72. package/dist/components/panel/TestRunPanel.svelte +85 -0
  73. package/dist/components/panel/TestRunPanel.svelte.d.ts +3 -0
  74. package/dist/components/panel/TestTriggerCard.svelte +121 -0
  75. package/dist/components/panel/TestTriggerCard.svelte.d.ts +7 -0
  76. package/dist/components/panel/TriggerForm.svelte +385 -0
  77. package/dist/components/panel/TriggerForm.svelte.d.ts +7 -0
  78. package/dist/components/panel/VersionHistory.svelte +123 -0
  79. package/dist/components/panel/VersionHistory.svelte.d.ts +3 -0
  80. package/dist/components/ui/ActionButton.svelte +85 -0
  81. package/dist/components/ui/ActionButton.svelte.d.ts +27 -0
  82. package/dist/components/ui/ConfirmDialog.svelte +52 -0
  83. package/dist/components/ui/ConfirmDialog.svelte.d.ts +16 -0
  84. package/dist/components/ui/Icon.svelte +32 -0
  85. package/dist/components/ui/Icon.svelte.d.ts +9 -0
  86. package/dist/components/ui/Menu.svelte +211 -0
  87. package/dist/components/ui/Menu.svelte.d.ts +21 -0
  88. package/dist/components/ui/Modal.svelte +129 -0
  89. package/dist/components/ui/Modal.svelte.d.ts +13 -0
  90. package/dist/components/ui/Notice.svelte +36 -0
  91. package/dist/components/ui/Notice.svelte.d.ts +11 -0
  92. package/dist/components/ui/SelectField.svelte +74 -0
  93. package/dist/components/ui/SelectField.svelte.d.ts +16 -0
  94. package/dist/components/ui/StatusBadge.svelte +41 -0
  95. package/dist/components/ui/StatusBadge.svelte.d.ts +9 -0
  96. package/dist/components/ui/TextField.svelte +97 -0
  97. package/dist/components/ui/TextField.svelte.d.ts +29 -0
  98. package/dist/components/ui/icons.d.ts +34 -0
  99. package/dist/components/ui/icons.js +54 -0
  100. package/dist/components/ui/types.d.ts +26 -0
  101. package/dist/components/ui/types.js +1 -0
  102. package/dist/editor/apiErrorText.d.ts +10 -0
  103. package/dist/editor/apiErrorText.js +53 -0
  104. package/dist/editor/autosave.d.ts +47 -0
  105. package/dist/editor/autosave.js +119 -0
  106. package/dist/editor/blockLabels.d.ts +91 -0
  107. package/dist/editor/blockLabels.js +196 -0
  108. package/dist/editor/canvasContext.d.ts +52 -0
  109. package/dist/editor/canvasContext.js +37 -0
  110. package/dist/editor/canvasWords.d.ts +24 -0
  111. package/dist/editor/canvasWords.js +40 -0
  112. package/dist/editor/capabilityModel.d.ts +46 -0
  113. package/dist/editor/capabilityModel.js +113 -0
  114. package/dist/editor/editorState.svelte.d.ts +220 -0
  115. package/dist/editor/editorState.svelte.js +713 -0
  116. package/dist/editor/flowAdapter.d.ts +59 -0
  117. package/dist/editor/flowAdapter.js +166 -0
  118. package/dist/editor/formatCount.d.ts +5 -0
  119. package/dist/editor/formatCount.js +15 -0
  120. package/dist/editor/graphDiff.d.ts +27 -0
  121. package/dist/editor/graphDiff.js +64 -0
  122. package/dist/editor/graphModel.d.ts +154 -0
  123. package/dist/editor/graphModel.js +457 -0
  124. package/dist/editor/issueText.d.ts +64 -0
  125. package/dist/editor/issueText.js +101 -0
  126. package/dist/editor/listState.svelte.d.ts +82 -0
  127. package/dist/editor/listState.svelte.js +250 -0
  128. package/dist/editor/statsRange.d.ts +26 -0
  129. package/dist/editor/statsRange.js +41 -0
  130. package/dist/editor/testRun.d.ts +36 -0
  131. package/dist/editor/testRun.js +74 -0
  132. package/dist/editor/zonedTime.d.ts +20 -0
  133. package/dist/editor/zonedTime.js +134 -0
  134. package/dist/i18n/language.d.ts +3 -3
  135. package/dist/i18n/messages.d.ts +396 -4
  136. package/dist/i18n/messages.js +421 -8
  137. package/dist/index.d.ts +2 -1
  138. package/dist/index.js +1 -1
  139. package/dist/types/index.d.ts +31 -3
  140. package/package.json +5 -1
@@ -0,0 +1,657 @@
1
+ /**
2
+ * What the workflows screen asks the Widgetic API. A small client of its own (the generated SDKs do not know these routes
3
+ * yet), written the way the other modules' clients are: one place that adds the token, retries once with a fresh token
4
+ * when the API refuses it, gives each request a time limit, and turns every failure into a {@link WorkflowsApiError}.
5
+ *
6
+ * GET /workspaces/{workspaceId}/workflows the list
7
+ * POST /workspaces/{workspaceId}/workflows a new workflow (Idempotency-Key)
8
+ * GET /workspaces/{workspaceId}/workflows/{id} one workflow with its draft
9
+ * PUT /workspaces/{workspaceId}/workflows/{id} save the draft (the revision it started from)
10
+ * DELETE /workspaces/{workspaceId}/workflows/{id} delete one that was never published
11
+ * POST /workspaces/{workspaceId}/workflows/{id}/duplicate a copy (Idempotency-Key)
12
+ * POST /workspaces/{workspaceId}/workflows/{id}/publish the draft becomes the next version (Idempotency-Key)
13
+ * POST /workspaces/{workspaceId}/workflows/{id}/discard the draft goes back to what is live
14
+ * GET /workspaces/{workspaceId}/workflows/{id}/versions[/{versionId}] the version history, and one version
15
+ * POST /workspaces/{workspaceId}/workflows/{id}/versions/{versionId}/restore copy a version into the draft
16
+ * POST /workspaces/{workspaceId}/workflows/{id}/{pause|resume|archive|unarchive}
17
+ * GET /workspaces/{workspaceId}/workflows/{id}/stats the counts of the Runs tab
18
+ * GET /workspaces/{workspaceId}/workflows/composition-options the compositions to choose from, with what each can do
19
+ *
20
+ * The API never gives a refusal a sentence of ours to show: a screen reads `code` (and `details`) and says it in the person's
21
+ * language. What the client never does: send cookies, put a token anywhere but the `Authorization` header, or keep one.
22
+ *
23
+ * Failures are told apart as far as the screens need: a session that is over (401 after one fresh token), a plan without
24
+ * workflows (403), a workflow that is gone (404), a draft somebody else saved (409 `revision_changed`), a draft the
25
+ * publish check refuses (422, with the issues), and everything else. A request that was cancelled stays the `AbortError`
26
+ * it was.
27
+ */
28
+ import { parseGraph } from '@widgetic/workflows-engine';
29
+ import { workflowsWarn } from '../utils/logger.js';
30
+ import { WORKFLOW_STATUSES } from './types.js';
31
+ /** How long a request may take before it is given up: the reads, and the writes (a publish reads every composition). */
32
+ export const READ_TIMEOUT_MS = 15_000;
33
+ export const WRITE_TIMEOUT_MS = 30_000;
34
+ /** What went wrong with a request, as far as the screens care. */
35
+ export class WorkflowsApiError extends Error {
36
+ /** The HTTP status; null when no answer came (offline, blocked by the page's policy, too slow, a token that could not be had). */
37
+ status;
38
+ /**
39
+ * The API's error code (`BUSINESS_STATE_CONFLICT`, `AUTHZ_PLAN_RESTRICTION`...), or the screen's own: `NETWORK_ERROR`,
40
+ * `TIMEOUT`, `TOKEN_UNAVAILABLE`, `INVALID_RESPONSE`, or `HTTP_<status>` when the answer carried no code.
41
+ */
42
+ code;
43
+ /** What the API said besides (`reason`, `currentRevision`, `issues`...), as it came; null when it said nothing more. */
44
+ details;
45
+ constructor(message, details) {
46
+ super(message, details.cause === undefined ? undefined : { cause: details.cause });
47
+ this.name = 'WorkflowsApiError';
48
+ this.status = details.status;
49
+ this.code = details.code;
50
+ this.details = details.details ?? null;
51
+ }
52
+ /** The person's session is over: the API refused the token, and the fresh one too. */
53
+ get sessionEnded() {
54
+ return this.status === 401;
55
+ }
56
+ /** The account's plan does not include workflows. */
57
+ get planRestricted() {
58
+ return this.status === 403 && this.code === 'AUTHZ_PLAN_RESTRICTION';
59
+ }
60
+ /** The workflow, version or composition is not there (any more). */
61
+ get notFound() {
62
+ return this.status === 404;
63
+ }
64
+ /** Somebody saved the draft since this screen read it: the screen reloads, it never overwrites. */
65
+ get revisionChanged() {
66
+ return this.status === 409 && this.details?.reason === 'revision_changed';
67
+ }
68
+ /** The revision the draft is at now, when the API said (a refused save or publish). */
69
+ get currentRevision() {
70
+ const revision = this.details?.currentRevision;
71
+ return typeof revision === 'number' && Number.isInteger(revision) ? revision : null;
72
+ }
73
+ /** Why a 409 was refused (`revision_changed`, `nothing_to_publish`, `nothing_to_discard`, `workflow_archived`, `wrong_state`). */
74
+ get conflictReason() {
75
+ const reason = this.details?.reason;
76
+ return this.status === 409 && typeof reason === 'string' ? reason : null;
77
+ }
78
+ /** What stopped a publish (422) or a save of a document the engine cannot read (400): the blocks to fix. */
79
+ get issues() {
80
+ const issues = this.details?.issues;
81
+ if (!Array.isArray(issues))
82
+ return [];
83
+ return issues.filter(isIssueLike);
84
+ }
85
+ }
86
+ /** Whether an error is a request that was cancelled on purpose (the screen was taken down). */
87
+ export function isCancelled(error) {
88
+ return (typeof error === 'object' &&
89
+ error !== null &&
90
+ error.name === 'AbortError');
91
+ }
92
+ /** A key the gateway accepts as an `Idempotency-Key` (`^[A-Za-z0-9_-]{8,50}$`). */
93
+ export function makeIdempotencyKey() {
94
+ const random = globalThis.crypto?.randomUUID?.();
95
+ if (random)
96
+ return random;
97
+ // Very old browsers: still unique enough for one person's one click.
98
+ return `k${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`;
99
+ }
100
+ // ---------------------------------------------------------------------------------------------------------------------
101
+ // Reading what the API said
102
+ // ---------------------------------------------------------------------------------------------------------------------
103
+ function isRecord(value) {
104
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
105
+ }
106
+ function isIssueLike(value) {
107
+ return (isRecord(value) &&
108
+ typeof value.code === 'string' &&
109
+ (value.severity === 'error' || value.severity === 'warning'));
110
+ }
111
+ function nonEmptyText(value) {
112
+ return typeof value === 'string' && value.trim() !== '' ? value : null;
113
+ }
114
+ function invalidResponse(what) {
115
+ return new WorkflowsApiError(`The API's answer about ${what} was not what the screen expects`, {
116
+ status: null,
117
+ code: 'INVALID_RESPONSE'
118
+ });
119
+ }
120
+ function readText(source, key, what) {
121
+ const value = source[key];
122
+ if (typeof value !== 'string')
123
+ throw invalidResponse(`${what} (${key})`);
124
+ return value;
125
+ }
126
+ function readNullableText(source, key, what) {
127
+ const value = source[key];
128
+ if (value === null || value === undefined)
129
+ return null;
130
+ if (typeof value !== 'string')
131
+ throw invalidResponse(`${what} (${key})`);
132
+ return value;
133
+ }
134
+ function readWholeNumber(source, key, what) {
135
+ const value = source[key];
136
+ if (typeof value !== 'number' || !Number.isFinite(value))
137
+ throw invalidResponse(`${what} (${key})`);
138
+ return value;
139
+ }
140
+ function readBoolean(source, key, what) {
141
+ const value = source[key];
142
+ if (typeof value !== 'boolean')
143
+ throw invalidResponse(`${what} (${key})`);
144
+ return value;
145
+ }
146
+ function readTextList(source, key, what) {
147
+ const value = source[key];
148
+ if (value === undefined || value === null)
149
+ return [];
150
+ if (!Array.isArray(value))
151
+ throw invalidResponse(`${what} (${key})`);
152
+ return value.filter((entry) => typeof entry === 'string');
153
+ }
154
+ function isWorkflowStatus(value) {
155
+ return typeof value === 'string' && WORKFLOW_STATUSES.includes(value);
156
+ }
157
+ /** One workflow of the list (or the same fields of a workflow in full). */
158
+ export function readWorkflowListItem(data) {
159
+ if (!isRecord(data))
160
+ throw invalidResponse('a workflow');
161
+ const status = data.status;
162
+ if (!isWorkflowStatus(status))
163
+ throw invalidResponse('a workflow (status)');
164
+ return {
165
+ id: readText(data, 'id', 'a workflow'),
166
+ name: readText(data, 'name', 'a workflow'),
167
+ status,
168
+ revision: readWholeNumber(data, 'revision', 'a workflow'),
169
+ unpublishedChanges: readBoolean(data, 'unpublishedChanges', 'a workflow'),
170
+ compositionIds: readTextList(data, 'compositionIds', 'a workflow'),
171
+ blockCount: readWholeNumber(data, 'blockCount', 'a workflow'),
172
+ timezone: readText(data, 'timezone', 'a workflow'),
173
+ runsCount: readWholeNumber(data, 'runsCount', 'a workflow'),
174
+ liveVersionId: readNullableText(data, 'liveVersionId', 'a workflow'),
175
+ createdAt: readText(data, 'createdAt', 'a workflow'),
176
+ updatedAt: readText(data, 'updatedAt', 'a workflow'),
177
+ firstPublishedAt: readNullableText(data, 'firstPublishedAt', 'a workflow'),
178
+ lastPublishedAt: readNullableText(data, 'lastPublishedAt', 'a workflow'),
179
+ pausedAt: readNullableText(data, 'pausedAt', 'a workflow'),
180
+ archivedAt: readNullableText(data, 'archivedAt', 'a workflow')
181
+ };
182
+ }
183
+ /**
184
+ * A graph the API sent, read by the engine. A document the engine cannot read is not something a screen can draw, so it is
185
+ * a failed answer (the engine's own reading also drops what it does not know, so a newer gateway cannot crash an older
186
+ * screen).
187
+ */
188
+ function readGraph(value, what) {
189
+ const read = parseGraph(value);
190
+ if (!read.graph) {
191
+ workflowsWarn(`The graph of ${what} could not be read: ${read.issues.map((issue) => issue.code).join(', ')}`);
192
+ throw invalidResponse(`${what} (graph)`);
193
+ }
194
+ return read.graph;
195
+ }
196
+ export function readWorkflowVersion(data) {
197
+ if (!isRecord(data))
198
+ throw invalidResponse('a version');
199
+ const publishedByValue = data.publishedBy;
200
+ let publishedBy = null;
201
+ if (isRecord(publishedByValue) && typeof publishedByValue.id === 'string') {
202
+ publishedBy = {
203
+ id: publishedByValue.id,
204
+ name: typeof publishedByValue.name === 'string' ? publishedByValue.name : null
205
+ };
206
+ }
207
+ return {
208
+ id: readText(data, 'id', 'a version'),
209
+ versionNumber: readWholeNumber(data, 'versionNumber', 'a version'),
210
+ publishedAt: readText(data, 'publishedAt', 'a version'),
211
+ publishedBy,
212
+ timezone: readText(data, 'timezone', 'a version'),
213
+ isLive: readBoolean(data, 'isLive', 'a version')
214
+ };
215
+ }
216
+ export function readWorkflowVersionDetail(data) {
217
+ if (!isRecord(data))
218
+ throw invalidResponse('a version');
219
+ return {
220
+ ...readWorkflowVersion(data),
221
+ startNodeId: readText(data, 'startNodeId', 'a version'),
222
+ graph: readGraph(data.graph, 'a version')
223
+ };
224
+ }
225
+ export function readWorkflowDetail(data) {
226
+ if (!isRecord(data))
227
+ throw invalidResponse('a workflow');
228
+ return {
229
+ ...readWorkflowListItem(data),
230
+ graph: readGraph(data.graph, 'a workflow'),
231
+ liveVersion: data.liveVersion === null || data.liveVersion === undefined
232
+ ? null
233
+ : readWorkflowVersion(data.liveVersion),
234
+ everPublished: readBoolean(data, 'everPublished', 'a workflow')
235
+ };
236
+ }
237
+ function readWorkflowList(data) {
238
+ if (!isRecord(data) || !Array.isArray(data.items))
239
+ throw invalidResponse('the list of workflows');
240
+ return {
241
+ items: data.items.map(readWorkflowListItem),
242
+ total: readWholeNumber(data, 'total', 'the list of workflows'),
243
+ limit: readWholeNumber(data, 'limit', 'the list of workflows'),
244
+ offset: readWholeNumber(data, 'offset', 'the list of workflows')
245
+ };
246
+ }
247
+ function readPublishResult(data) {
248
+ if (!isRecord(data))
249
+ throw invalidResponse('a publish');
250
+ return {
251
+ workflow: readWorkflowDetail(data.workflow),
252
+ version: readWorkflowVersion(data.version),
253
+ warnings: Array.isArray(data.warnings) ? data.warnings.filter(isIssueLike) : []
254
+ };
255
+ }
256
+ function readCounts(value, what) {
257
+ if (!Array.isArray(value))
258
+ throw invalidResponse(what);
259
+ const counts = [];
260
+ for (const entry of value) {
261
+ if (isRecord(entry) &&
262
+ typeof entry.id === 'string' &&
263
+ typeof entry.total === 'number' &&
264
+ Number.isFinite(entry.total)) {
265
+ counts.push({ id: entry.id, total: entry.total });
266
+ }
267
+ }
268
+ return counts;
269
+ }
270
+ function readStats(data) {
271
+ if (!isRecord(data))
272
+ throw invalidResponse('the counts');
273
+ const started = data.started;
274
+ return {
275
+ workflowId: readText(data, 'workflowId', 'the counts'),
276
+ versionId: readNullableText(data, 'versionId', 'the counts'),
277
+ from: readText(data, 'from', 'the counts'),
278
+ to: readText(data, 'to', 'the counts'),
279
+ started: typeof started === 'number' && Number.isFinite(started) ? started : null,
280
+ nodes: readCounts(data.nodes, 'the counts (nodes)'),
281
+ edges: readCounts(data.edges, 'the counts (edges)'),
282
+ failed: readCounts(data.failed, 'the counts (failed)')
283
+ };
284
+ }
285
+ const FIELD_TYPES = ['text', 'number', 'boolean'];
286
+ function readCapabilityReason(value) {
287
+ return value === 'widget_keeps_no_data' ||
288
+ value === 'widget_reports_no_actions' ||
289
+ value === 'widget_not_published'
290
+ ? value
291
+ : null;
292
+ }
293
+ /** The address of a thumbnail, when it is one an `<img>` should be given: http or https, nothing else. */
294
+ export function usableImageUrl(value) {
295
+ const text = nonEmptyText(value);
296
+ if (text === null)
297
+ return null;
298
+ try {
299
+ const parsed = new URL(text);
300
+ return parsed.protocol === 'https:' || parsed.protocol === 'http:' ? parsed.href : null;
301
+ }
302
+ catch {
303
+ return null;
304
+ }
305
+ }
306
+ function readOptionField(value) {
307
+ if (!isRecord(value))
308
+ return null;
309
+ const { table, column, label, type } = value;
310
+ if (typeof table !== 'string' || typeof column !== 'string')
311
+ return null;
312
+ if (typeof type !== 'string' || !FIELD_TYPES.includes(type))
313
+ return null;
314
+ return {
315
+ table,
316
+ column,
317
+ label: typeof label === 'string' && label !== '' ? label : column,
318
+ type: type
319
+ };
320
+ }
321
+ function readOptionAction(value) {
322
+ if (!isRecord(value) || typeof value.id !== 'string' || typeof value.metric !== 'string')
323
+ return null;
324
+ return {
325
+ id: value.id,
326
+ metric: value.metric,
327
+ label: typeof value.label === 'string' && value.label !== '' ? value.label : value.metric,
328
+ selector: typeof value.selector === 'string' && value.selector !== '' ? value.selector : null
329
+ };
330
+ }
331
+ /**
332
+ * One composition the editor can offer. What a composition cannot do reads as "not enabled" and never as an error: the
333
+ * capability model is the API's, and an answer that left a part out is treated as "this composition cannot do that".
334
+ */
335
+ export function readCompositionOption(data) {
336
+ if (!isRecord(data))
337
+ throw invalidResponse('a composition');
338
+ const inputs = isRecord(data.inputs) ? data.inputs : {};
339
+ const actions = isRecord(data.actions) ? data.actions : {};
340
+ return {
341
+ id: readText(data, 'id', 'a composition'),
342
+ name: typeof data.name === 'string' ? data.name : '',
343
+ thumbnailUrl: usableImageUrl(data.thumbnailUrl),
344
+ published: data.published === true,
345
+ allowedWebsites: readTextList(data, 'allowedWebsites', 'a composition'),
346
+ inputs: {
347
+ enabled: inputs.enabled === true,
348
+ reason: readCapabilityReason(inputs.reason),
349
+ tables: readTextList(inputs, 'tables', 'a composition (inputs)'),
350
+ fields: Array.isArray(inputs.fields)
351
+ ? inputs.fields
352
+ .map(readOptionField)
353
+ .filter((field) => field !== null)
354
+ : []
355
+ },
356
+ actions: {
357
+ enabled: actions.enabled === true,
358
+ reason: readCapabilityReason(actions.reason),
359
+ items: Array.isArray(actions.items)
360
+ ? actions.items
361
+ .map(readOptionAction)
362
+ .filter((item) => item !== null)
363
+ : []
364
+ }
365
+ };
366
+ }
367
+ function readCompositionOptionList(data) {
368
+ if (!isRecord(data) || !Array.isArray(data.items))
369
+ throw invalidResponse('the compositions');
370
+ return {
371
+ items: data.items.map(readCompositionOption),
372
+ total: readWholeNumber(data, 'total', 'the compositions'),
373
+ limit: readWholeNumber(data, 'limit', 'the compositions'),
374
+ offset: readWholeNumber(data, 'offset', 'the compositions')
375
+ };
376
+ }
377
+ /** The error code, sentence and details of an API error answer, when it has them. */
378
+ function describeFailureBody(body) {
379
+ if (!isRecord(body))
380
+ return { code: null, message: null, details: null };
381
+ const error = isRecord(body.error) ? body.error : null;
382
+ return {
383
+ code: nonEmptyText(error?.code),
384
+ message: nonEmptyText(error?.message) ?? nonEmptyText(body.message),
385
+ details: isRecord(error?.details) ? error.details : null
386
+ };
387
+ }
388
+ /** The query string of the list: only what was asked for. */
389
+ export function buildListQueryString(query) {
390
+ const parameters = new URLSearchParams();
391
+ if (query?.search !== undefined && query.search.trim() !== '')
392
+ parameters.set('search', query.search.trim());
393
+ if (query?.status !== undefined)
394
+ parameters.set('status', query.status);
395
+ if (query?.sort !== undefined)
396
+ parameters.set('sort', `${query.sort.field}:${query.sort.direction}`);
397
+ if (query?.limit !== undefined)
398
+ parameters.set('limit', String(query.limit));
399
+ if (query?.offset !== undefined)
400
+ parameters.set('offset', String(query.offset));
401
+ const text = parameters.toString();
402
+ return text === '' ? '' : `?${text}`;
403
+ }
404
+ export function buildCompositionOptionsQueryString(query) {
405
+ const parameters = new URLSearchParams();
406
+ if (query?.search !== undefined && query.search.trim() !== '')
407
+ parameters.set('search', query.search.trim());
408
+ if (query?.ids !== undefined)
409
+ parameters.set('ids', query.ids.join(','));
410
+ if (query?.limit !== undefined)
411
+ parameters.set('limit', String(query.limit));
412
+ if (query?.offset !== undefined)
413
+ parameters.set('offset', String(query.offset));
414
+ const text = parameters.toString();
415
+ return text === '' ? '' : `?${text}`;
416
+ }
417
+ function buildStatsQueryString(query) {
418
+ const parameters = new URLSearchParams();
419
+ if (query?.versionId !== undefined)
420
+ parameters.set('versionId', query.versionId);
421
+ if (query?.from !== undefined)
422
+ parameters.set('from', query.from);
423
+ if (query?.to !== undefined)
424
+ parameters.set('to', query.to);
425
+ const text = parameters.toString();
426
+ return text === '' ? '' : `?${text}`;
427
+ }
428
+ /** One request's time limit, joined with the cancel of whoever asked. */
429
+ function startAttempt(outer, timeoutMs) {
430
+ const controller = new AbortController();
431
+ let timedOut = false;
432
+ const timer = setTimeout(() => {
433
+ timedOut = true;
434
+ controller.abort();
435
+ }, timeoutMs);
436
+ const cancelWithOuter = () => controller.abort();
437
+ if (outer?.aborted)
438
+ controller.abort();
439
+ else
440
+ outer?.addEventListener('abort', cancelWithOuter, { once: true });
441
+ return {
442
+ signal: controller.signal,
443
+ timedOut: () => timedOut,
444
+ finish: () => {
445
+ clearTimeout(timer);
446
+ outer?.removeEventListener('abort', cancelWithOuter);
447
+ }
448
+ };
449
+ }
450
+ /** Makes the client of one screen: one workspace, one way to get a token. */
451
+ export function createWorkflowsApi(options) {
452
+ const apiBase = `${options.apiUrl.replace(/\/+$/, '')}/v1`;
453
+ const workspaceBase = `/workspaces/${encodeURIComponent(options.workspaceId)}/workflows`;
454
+ const readTimeoutMs = options.readTimeoutMs ?? READ_TIMEOUT_MS;
455
+ const writeTimeoutMs = options.writeTimeoutMs ?? WRITE_TIMEOUT_MS;
456
+ const sendRequest = options.fetchImplementation ?? ((...parameters) => globalThis.fetch(...parameters));
457
+ async function tokenFor(reason, refusedToken) {
458
+ try {
459
+ return await options.getAccessToken(reason, refusedToken);
460
+ }
461
+ catch (cause) {
462
+ throw new WorkflowsApiError('The access token could not be had', {
463
+ status: null,
464
+ code: 'TOKEN_UNAVAILABLE',
465
+ cause
466
+ });
467
+ }
468
+ }
469
+ async function readEnvelope(response) {
470
+ const text = await response.text();
471
+ let body = null;
472
+ try {
473
+ body = text.length > 0 ? JSON.parse(text) : null;
474
+ }
475
+ catch {
476
+ if (response.ok) {
477
+ throw new WorkflowsApiError('The answer was not JSON', {
478
+ status: null,
479
+ code: 'INVALID_RESPONSE'
480
+ });
481
+ }
482
+ }
483
+ if (!response.ok) {
484
+ const failure = describeFailureBody(body);
485
+ throw new WorkflowsApiError(failure.message ?? `The API answered ${response.status}`, {
486
+ status: response.status,
487
+ code: failure.code ?? `HTTP_${response.status}`,
488
+ details: failure.details
489
+ });
490
+ }
491
+ if (!isRecord(body) || body.success !== true) {
492
+ throw new WorkflowsApiError('The answer was not a success envelope', {
493
+ status: null,
494
+ code: 'INVALID_RESPONSE'
495
+ });
496
+ }
497
+ return body.data;
498
+ }
499
+ /** Makes one request with the person's token, and once more with a fresh token when the API refuses it (401). */
500
+ async function request(method, path, details) {
501
+ // A caller that has cancelled already gets no token asked for and no request made.
502
+ if (details.signal?.aborted)
503
+ throw new DOMException('The request was cancelled', 'AbortError');
504
+ const attempt = startAttempt(details.signal, details.timeoutMs);
505
+ try {
506
+ const send = (token) => {
507
+ const headers = {
508
+ Accept: 'application/json',
509
+ Authorization: `Bearer ${token}`
510
+ };
511
+ if (details.body !== undefined)
512
+ headers['Content-Type'] = 'application/json';
513
+ if (details.idempotencyKey !== undefined)
514
+ headers['Idempotency-Key'] = details.idempotencyKey;
515
+ return sendRequest(`${apiBase}${path}`, {
516
+ method,
517
+ headers,
518
+ body: details.body === undefined ? undefined : JSON.stringify(details.body),
519
+ // The token is the credential; the gateway never allows cookies on these routes.
520
+ credentials: 'omit',
521
+ mode: 'cors',
522
+ signal: attempt.signal
523
+ });
524
+ };
525
+ const firstToken = await tokenFor('initial');
526
+ let response = await send(firstToken);
527
+ if (response.status === 401) {
528
+ response = await send(await tokenFor('expired', firstToken));
529
+ }
530
+ return await readEnvelope(response);
531
+ }
532
+ catch (error) {
533
+ if (error instanceof WorkflowsApiError)
534
+ throw error;
535
+ if (attempt.timedOut()) {
536
+ throw new WorkflowsApiError('The request took too long', {
537
+ status: null,
538
+ code: 'TIMEOUT',
539
+ cause: error
540
+ });
541
+ }
542
+ if (isCancelled(error))
543
+ throw error;
544
+ throw new WorkflowsApiError('The request could not be made', {
545
+ status: null,
546
+ code: 'NETWORK_ERROR',
547
+ cause: error
548
+ });
549
+ }
550
+ finally {
551
+ attempt.finish();
552
+ }
553
+ }
554
+ const pathOfWorkflow = (workflowId) => `${workspaceBase}/${encodeURIComponent(workflowId)}`;
555
+ return {
556
+ async listWorkflows(query, requestOptions = {}) {
557
+ return readWorkflowList(await request('GET', `${workspaceBase}${buildListQueryString(query)}`, {
558
+ signal: requestOptions.signal,
559
+ timeoutMs: readTimeoutMs
560
+ }));
561
+ },
562
+ async createWorkflow(input, requestOptions = {}) {
563
+ const body = { name: input.name };
564
+ if (input.compositionId)
565
+ body.compositionId = input.compositionId;
566
+ if (input.timezone)
567
+ body.timezone = input.timezone;
568
+ return readWorkflowDetail(await request('POST', workspaceBase, {
569
+ body,
570
+ idempotencyKey: requestOptions.idempotencyKey ?? makeIdempotencyKey(),
571
+ signal: requestOptions.signal,
572
+ timeoutMs: writeTimeoutMs
573
+ }));
574
+ },
575
+ async getWorkflow(workflowId, requestOptions = {}) {
576
+ return readWorkflowDetail(await request('GET', pathOfWorkflow(workflowId), {
577
+ signal: requestOptions.signal,
578
+ timeoutMs: readTimeoutMs
579
+ }));
580
+ },
581
+ async saveDraft(workflowId, input, requestOptions = {}) {
582
+ return readWorkflowListItem(await request('PUT', pathOfWorkflow(workflowId), {
583
+ body: input,
584
+ signal: requestOptions.signal,
585
+ timeoutMs: writeTimeoutMs
586
+ }));
587
+ },
588
+ async deleteWorkflow(workflowId, requestOptions = {}) {
589
+ await request('DELETE', pathOfWorkflow(workflowId), {
590
+ signal: requestOptions.signal,
591
+ timeoutMs: writeTimeoutMs
592
+ });
593
+ },
594
+ async duplicateWorkflow(workflowId, requestOptions = {}) {
595
+ return readWorkflowDetail(await request('POST', `${pathOfWorkflow(workflowId)}/duplicate`, {
596
+ idempotencyKey: requestOptions.idempotencyKey ?? makeIdempotencyKey(),
597
+ signal: requestOptions.signal,
598
+ timeoutMs: writeTimeoutMs
599
+ }));
600
+ },
601
+ async publishWorkflow(workflowId, revision, requestOptions = {}) {
602
+ return readPublishResult(await request('POST', `${pathOfWorkflow(workflowId)}/publish`, {
603
+ body: { revision },
604
+ idempotencyKey: requestOptions.idempotencyKey ?? makeIdempotencyKey(),
605
+ signal: requestOptions.signal,
606
+ timeoutMs: writeTimeoutMs
607
+ }));
608
+ },
609
+ async discardChanges(workflowId, revision, requestOptions = {}) {
610
+ return readWorkflowDetail(await request('POST', `${pathOfWorkflow(workflowId)}/discard`, {
611
+ body: { revision },
612
+ signal: requestOptions.signal,
613
+ timeoutMs: writeTimeoutMs
614
+ }));
615
+ },
616
+ async listVersions(workflowId, requestOptions = {}) {
617
+ const data = await request('GET', `${pathOfWorkflow(workflowId)}/versions`, {
618
+ signal: requestOptions.signal,
619
+ timeoutMs: readTimeoutMs
620
+ });
621
+ if (!isRecord(data) || !Array.isArray(data.items))
622
+ throw invalidResponse('the versions');
623
+ return data.items.map(readWorkflowVersion);
624
+ },
625
+ async getVersion(workflowId, versionId, requestOptions = {}) {
626
+ return readWorkflowVersionDetail(await request('GET', `${pathOfWorkflow(workflowId)}/versions/${encodeURIComponent(versionId)}`, {
627
+ signal: requestOptions.signal,
628
+ timeoutMs: readTimeoutMs
629
+ }));
630
+ },
631
+ async restoreVersion(workflowId, versionId, revision, requestOptions = {}) {
632
+ return readWorkflowDetail(await request('POST', `${pathOfWorkflow(workflowId)}/versions/${encodeURIComponent(versionId)}/restore`, {
633
+ body: { revision },
634
+ signal: requestOptions.signal,
635
+ timeoutMs: writeTimeoutMs
636
+ }));
637
+ },
638
+ async changeState(workflowId, action, requestOptions = {}) {
639
+ return readWorkflowListItem(await request('POST', `${pathOfWorkflow(workflowId)}/${action}`, {
640
+ signal: requestOptions.signal,
641
+ timeoutMs: writeTimeoutMs
642
+ }));
643
+ },
644
+ async getStats(workflowId, query, requestOptions = {}) {
645
+ return readStats(await request('GET', `${pathOfWorkflow(workflowId)}/stats${buildStatsQueryString(query)}`, {
646
+ signal: requestOptions.signal,
647
+ timeoutMs: readTimeoutMs
648
+ }));
649
+ },
650
+ async listCompositionOptions(query, requestOptions = {}) {
651
+ return readCompositionOptionList(await request('GET', `${workspaceBase}/composition-options${buildCompositionOptionsQueryString(query)}`, {
652
+ signal: requestOptions.signal,
653
+ timeoutMs: readTimeoutMs
654
+ }));
655
+ }
656
+ };
657
+ }