@widgetic/workflows 0.2.1 → 0.2.3

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.
package/README.md CHANGED
@@ -17,6 +17,15 @@ Workflows are for **Teams and partner accounts** only. On Widgetic the page is
17
17
  went through, and when it was last published. Search by name, show or hide the archived ones, order by name, date
18
18
  created, last published or visitors, and make a workflow (`New workflow`), duplicate it or delete it. The page is told
19
19
  when one is opened (`onOpenWorkflow`) so the address can follow.
20
+ - **Start from a preset.** `New workflow` starts blank (a name, and optionally the composition visitors see first) or, when
21
+ the workspace is offered presets, from one of them. A preset is a published workflow that Widgetic (or, for a partner's
22
+ customer, the partner) offers as a place to start; its card shows the widgets it chains, how many blocks it has and a
23
+ line from the offerer. Choosing one gives the person their own copy of every widget it chains and a draft workflow wired
24
+ like the preset's live version, named as they like (after the preset when they leave it empty); nothing they change
25
+ reaches the preset. The dialog asks for the presets when it opens, so a workspace that is offered none sees the dialog as
26
+ it always was, and when they cannot be read it says so and the blank start keeps working. A start copies every widget,
27
+ so it is given longer than another request, and it is sent with an `Idempotency-Key`: asking again after a timeout does
28
+ not copy twice.
20
29
  - **The editor.** A canvas of blocks joined by lines. A **Composition** block shows a composition; a **Trigger** block
21
30
  waits for something a visitor does (a value they add to a widget, an action in the widget, an event on the page, or a
22
31
  time); a **Condition** block sends the visitor on by the first rule that matches. Blocks go forward only, a workflow
@@ -33,8 +42,10 @@ Workflows are for **Teams and partner accounts** only. On Widgetic the page is
33
42
  - **Runs.** The _Runs_ tab shows how many visitors went through each block and each line over a range of days (counts
34
43
  only: what a visitor typed is never stored).
35
44
  - **Settings.** The time zone that scheduled triggers are told in, the embed code, and the state of the workflow: pause
36
- or resume it, archive or restore it, duplicate it, or delete it (only a draft that was never published: a published
37
- workflow can only be archived, because pages may still use it). The name is edited in the bar above the canvas.
45
+ or resume it, archive or restore it, duplicate it, or delete it. A workflow can be deleted in any state, after one
46
+ confirmation that says what goes with it (its draft, and once it was published its versions and its counts; the
47
+ compositions it uses stay). Archiving is the way to take a workflow out of the list and keep it. The name is edited in
48
+ the bar above the canvas.
38
49
  - Speaks the page's language (`locale`, `messages`) and turns around for right to left (`dir`).
39
50
  - Takes its colours, font and corners from CSS custom properties, so a host or a ui-sdk theme restyles it.
40
51
  - Reports what goes wrong to the page (`onError`) and shows the visitor a "Try again" in place of a part that failed.
@@ -100,27 +111,28 @@ the screen needs, the screen scrolls inside it; it never spills over what the pa
100
111
 
101
112
  ### Props
102
113
 
103
- | Prop | Type | Default | What it does |
104
- | --------------------- | ------------------------------------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
105
- | `apiUrl` | `string` | **required** | The Widgetic API origin, without `/v1` (`https://api.widgetic.com`). |
106
- | `getAccessToken` | `AccessTokenFunction` | **required** | Gives the screen a token for the API. Called with `'initial'` and, after a refusal, `'expired'`. The screen never stores a token. |
107
- | `workspaceId` | `string` | **required** | `personal`, or the id of the organization whose workflows are shown. A change of it starts the screen again. |
108
- | `workflowId` | `string \| null` | the list | The workflow that is open. The page owns it (it is part of the page's address); left out, the screen keeps track by itself. |
109
- | `onOpenWorkflow` | `(workflowId: string \| null) => void` | none | The person opened a workflow, or went back to the list (`null`). |
110
- | `onShowEmbedCode` | `(workflowId: string) => void` | none | Shows the embed code of a workflow. The dialog is the page's (it knows how the tag is built for its Embed SDK); without it there is no button. |
111
- | `presence` | `boolean` | `false` | Tells who else is editing the workflow that is open, and keeps this screen from writing over them (below). Read when a workflow is opened. |
112
- | `locale` | `string \| null` | English | A BCP 47 tag (`de`, `pt-BR`): plural rules, how numbers and dates are written. Translates nothing. |
113
- | `messages` | `Readonly<Record<string, unknown>> \| null` | none | Your own words, by key. A key you leave out stays English. |
114
- | `dir` | `'ltr' \| 'rtl'` | the screen around it | Which way the screen is read. You decide it; it is not worked out from `locale`. |
115
- | `class` | `string` | `''` | Extra classes on the root element. |
116
- | `onError` | `(error: WorkflowsError) => void` | none | Called once for each failure. |
117
- | `fetchImplementation` | `typeof fetch` | the page's `fetch` | For tests and previews: the `fetch` the screen asks the API with. |
114
+ | Prop | Type | Default | What it does |
115
+ | --------------------- | ------------------------------------------- | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
116
+ | `apiUrl` | `string` | **required** | The Widgetic API origin, without `/v1` (`https://api.widgetic.com`). |
117
+ | `getAccessToken` | `AccessTokenFunction` | **required** | Gives the screen a token for the API. Called with `'initial'` and, after a refusal, `'expired'`. The screen never stores a token. |
118
+ | `workspaceId` | `string` | **required** | `personal`, or the id of the organization whose workflows are shown. A change of it starts the screen again. |
119
+ | `workflowId` | `string \| null` | the list | The workflow that is open. The page owns it (it is part of the page's address); left out, the screen keeps track by itself. |
120
+ | `onOpenWorkflow` | `(workflowId: string \| null) => void` | none | The person opened a workflow, or went back to the list (`null`). |
121
+ | `onShowEmbedCode` | `(workflowId: string) => void` | none | Shows the embed code of a workflow. The dialog is the page's (it knows how the tag is built for its Embed SDK); without it there is no button. |
122
+ | `presence` | `boolean` | `false` | Tells who else is editing: on the rows of the list, and in the workflow that is open, where it keeps this screen from writing over them (below). Read when the list or a workflow is opened. |
123
+ | `locale` | `string \| null` | English | A BCP 47 tag (`de`, `pt-BR`): plural rules, how numbers and dates are written. Translates nothing. |
124
+ | `messages` | `Readonly<Record<string, unknown>> \| null` | none | Your own words, by key. A key you leave out stays English. |
125
+ | `dir` | `'ltr' \| 'rtl'` | the screen around it | Which way the screen is read. You decide it; it is not worked out from `locale`. |
126
+ | `class` | `string` | `''` | Extra classes on the root element. |
127
+ | `onError` | `(error: WorkflowsError) => void` | none | Called once for each failure. |
128
+ | `fetchImplementation` | `typeof fetch` | the page's `fetch` | For tests and previews: the `fetch` the screen asks the API with. |
118
129
 
119
130
  `WorkflowsError` is `{ message: string; code: 'RENDER_FAILED' | 'REQUEST_FAILED' | 'SESSION_ENDED'; fatal: boolean }`.
120
131
  The `message` is English, for the page's developer. It is not a sentence to show a visitor: the screen shows its own.
121
132
 
122
133
  **What the screen asks of the API.** `GET/POST /v1/workspaces/{workspaceId}/workflows` and the routes under it (a
123
- workflow, its draft, publish, discard, versions, stats, composition options), always as the person: the token is
134
+ workflow, its draft, publish, discard, versions, stats, composition options, and the presets to start from: `GET …/workflows/presets`
135
+ and `POST …/workflows/from-preset`), always as the person: the token is
124
136
  the person's, and a call the person may not make is refused by the API. The screen holds no service key (a test fails the
125
137
  build if any code of the package that runs in a browser reads one). A change is sent with an `Idempotency-Key`, and a draft
126
138
  with the revision the editor was given, so a draft changed somewhere else is told, not overwritten: the person is offered
@@ -135,6 +147,15 @@ never a lock: what keeps a draft from being overwritten is the revision check ab
135
147
  names a person only to a teammate of the same organization, so a personal workspace has nothing to show and `presence`
136
148
  changes nothing there. The page decides whether to ask for it (the Widgetic site does for an organization's workspace).
137
149
 
150
+ The list says it too. With `presence` on, a row says "Anna is editing" under the name of a workflow a teammate has open
151
+ (or "Someone is editing" when the API gave no name). The list asks `POST /v1/edit-leases/peek` once for a whole page of rows
152
+ (50 at most in one call), when it opens, soon after the rows change, every 20 seconds while the tab is on the screen (the
153
+ API may ask for another pace, kept between 10 and 60 seconds), and when the tab comes back; never while it is hidden.
154
+ Looking takes and renews nothing, so a person who looks at the list does not become an editor of anything. The account's
155
+ own other window is not a teammate and gets no badge. A look that fails (offline, a server error, "cannot tell") leaves the
156
+ badges as they were and the next looks come further apart; an API that says there is no presence here, or a token that may
157
+ not ask, ends the looking and the list goes on without badges. A badge never shuts anything: the row opens as always.
158
+
138
159
  ## Look and feel
139
160
 
140
161
  Nothing in the screen is a literal colour, font or corner. It reads the Widgetic palette, and a theme is a handful of
@@ -183,7 +204,7 @@ Every word a person reads is a message in a catalog of English sentences, `WORKF
183
204
  `workflows.<where>.<what>`. A page gives its own words with `messages`; what it leaves out stays English, so a language
184
205
  can be added a screen at a time.
185
206
 
186
- The catalog has 390 messages. They are grouped by the part of the screen that says them:
207
+ The catalog's messages are grouped by the part of the screen that says them:
187
208
 
188
209
  | Group | What it says |
189
210
  | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
@@ -59,7 +59,7 @@ export interface WorkflowDetail extends WorkflowListItem {
59
59
  graph: WorkflowGraph;
60
60
  /** The version visitors get, without its graph; null before the first publish. */
61
61
  liveVersion: WorkflowVersion | null;
62
- /** Whether this workflow was ever published (it can then be archived but not deleted). */
62
+ /** Whether this workflow was ever published (it then has versions and counts, which a delete takes with it). */
63
63
  everPublished: boolean;
64
64
  }
65
65
  export interface WorkflowList {
@@ -137,6 +137,27 @@ export interface CompositionOptionList {
137
137
  limit: number;
138
138
  offset: number;
139
139
  }
140
+ /** A widget a preset shows: what a card of the preset draws for it. */
141
+ export interface WorkflowPresetWidget {
142
+ name: string;
143
+ /** An http(s) address for an `<img>`, or `null` when the widget has no picture. */
144
+ thumbnailUrl: string | null;
145
+ }
146
+ /**
147
+ * A place to start a new workflow: a published workflow that Widgetic (or, for one of a partner's customers, the partner)
148
+ * offers. Starting from it gives the person their own copy of its widgets, a composition on each copy, and a draft workflow
149
+ * wired like it. It carries nothing about who made it and no id of its own: `key` is how a start names it.
150
+ */
151
+ export interface WorkflowPreset {
152
+ key: string;
153
+ title: string;
154
+ /** What the offerer wrote about it; `null` when they wrote nothing. */
155
+ description: string | null;
156
+ /** How many blocks it has (compositions, triggers and conditions). */
157
+ blockCount: number;
158
+ /** The widgets it shows, once each, in the order they first appear. */
159
+ widgets: WorkflowPresetWidget[];
160
+ }
140
161
  /** What the list asks for. Everything is optional: nothing asked is the first page, newest first, drafts, live and paused. */
141
162
  export interface WorkflowListQuery {
142
163
  search?: string;
@@ -197,5 +218,24 @@ export interface EditLeaseAnswer {
197
218
  /** Who the claim was taken from, when taking over displaced somebody. */
198
219
  tookOverFrom?: EditLeaseHolder;
199
220
  }
221
+ /**
222
+ * Who is editing several workflows at once, as the list reads it (`POST /edit-leases/peek`, see `readEditLeasePeekAnswer`):
223
+ * the teammates only, by the id of the workflow they are editing. It takes and renews nothing, so looking never makes the
224
+ * person who looks an editor.
225
+ */
226
+ export interface EditLeasePeekAnswer {
227
+ /**
228
+ * The teammates who are editing, by the id of the workflow in lower case (the API compares ids that way). A workflow that is
229
+ * not in the map is not being edited by a teammate: nobody is, or the API may not say (it names a person only for a team's
230
+ * workflow the caller may read), or the one editing is the caller's own account in another window, which is not a teammate.
231
+ */
232
+ editors: ReadonlyMap<string, EditLeaseHolder>;
233
+ /** How often the API wants a list that shows presence to look again, in seconds, when it said. */
234
+ heartbeatSeconds: number | null;
235
+ /** `false` when the API could not tell for at least one workflow (`unavailable`): nothing is known for sure, keep what was shown. */
236
+ complete: boolean;
237
+ /** `true` when the API said there is no presence here for every workflow asked about (a personal workspace, or the feature is off). */
238
+ notApplicable: boolean;
239
+ }
200
240
  /** The token function the host gives the screen (see `AccessTokenFunction` of the ui-sdk modules). */
201
241
  export type AccessTokenFunction = (reason: 'initial' | 'expired', refusedToken?: string) => Promise<string> | string;
@@ -1,8 +1,14 @@
1
1
  import type { IssueCode, ValidationIssue, WorkflowGraph } from '@widgetic/workflows-engine';
2
- import { type AccessTokenFunction, type CompositionOption, type CompositionOptionList, type CompositionOptionsQuery, type EditLeaseAnswer, type WorkflowDetail, type WorkflowList, type WorkflowListItem, type WorkflowListQuery, type WorkflowPublishResult, type WorkflowStateAction, type WorkflowStats, type WorkflowStatsQuery, type WorkflowVersion, type WorkflowVersionDetail } from './types.js';
2
+ import { type AccessTokenFunction, type CompositionOption, type CompositionOptionList, type CompositionOptionsQuery, type EditLeaseAnswer, type EditLeasePeekAnswer, type WorkflowDetail, type WorkflowList, type WorkflowListItem, type WorkflowListQuery, type WorkflowPreset, type WorkflowPublishResult, type WorkflowStateAction, type WorkflowStats, type WorkflowStatsQuery, type WorkflowVersion, type WorkflowVersionDetail } from './types.js';
3
3
  /** How long a request may take before it is given up: the reads, and the writes (a publish reads every composition). */
4
4
  export declare const READ_TIMEOUT_MS = 15000;
5
5
  export declare const WRITE_TIMEOUT_MS = 30000;
6
+ /**
7
+ * A start from a preset copies every widget the preset chains, one after the other, so it is given longer than another write:
8
+ * a request that is given up while the gateway is still copying is asked again with the same `Idempotency-Key`, which replays
9
+ * the answer instead of copying twice, but a person would rather wait the seconds it takes.
10
+ */
11
+ export declare const START_FROM_PRESET_TIMEOUT_MS = 90000;
6
12
  /** What went wrong with a request, as far as the screens care. */
7
13
  export declare class WorkflowsApiError extends Error {
8
14
  /** The HTTP status; null when no answer came (offline, blocked by the page's policy, too slow, a token that could not be had). */
@@ -48,6 +54,7 @@ export interface WorkflowsApiOptions {
48
54
  /** For tests. */
49
55
  readTimeoutMs?: number;
50
56
  writeTimeoutMs?: number;
57
+ startFromPresetTimeoutMs?: number;
51
58
  }
52
59
  export interface RequestOptions {
53
60
  signal?: AbortSignal;
@@ -93,6 +100,16 @@ export interface WorkflowsApi {
93
100
  changeState(workflowId: string, action: WorkflowStateAction, options?: RequestOptions): Promise<WorkflowListItem>;
94
101
  getStats(workflowId: string, query?: WorkflowStatsQuery, options?: RequestOptions): Promise<WorkflowStats>;
95
102
  listCompositionOptions(query?: CompositionOptionsQuery, options?: RequestOptions): Promise<CompositionOptionList>;
103
+ /** The presets this workspace can start a workflow from, in the order their offerer set (an empty list when none is offered). */
104
+ listPresets(options?: RequestOptions): Promise<WorkflowPreset[]>;
105
+ /**
106
+ * Makes a workflow of the person's own from a preset: a copy of every widget it chains, a composition on each, and a draft
107
+ * wired like the preset. `name` is left out (or empty) to name it after the preset. It answers the new workflow, a draft.
108
+ */
109
+ startFromPreset(input: {
110
+ key: string;
111
+ name?: string | null;
112
+ }, options?: RetryableRequestOptions): Promise<WorkflowDetail>;
96
113
  /**
97
114
  * "This tab is editing this workflow", and the renewal of that claim. Presence, never a lock: it says who else is
98
115
  * editing and never refuses a save. An answer that cannot be read is `unavailable`.
@@ -102,6 +119,12 @@ export interface WorkflowsApi {
102
119
  takeOverEditLease(workflowId: string, sessionId: string, options?: RequestOptions): Promise<EditLeaseAnswer>;
103
120
  /** Who is editing, without claiming anything. */
104
121
  peekEditLease(workflowId: string, options?: RequestOptions): Promise<EditLeaseAnswer>;
122
+ /**
123
+ * Who is editing these workflows, for the badges of the list: one call for each `EDIT_LEASE_PEEK_BATCH_SIZE` workflows (a
124
+ * longer list is asked in several). It takes and renews nothing, so looking never makes the person who looks an editor.
125
+ * Advice, like all of presence: it refuses nothing. A failure is thrown like any other, and the list keeps what it showed.
126
+ */
127
+ peekEditLeases(workflowIds: readonly string[], options?: RequestOptions): Promise<EditLeasePeekAnswer>;
105
128
  /** Gives this tab's claim up. */
106
129
  releaseEditLease(workflowId: string, sessionId: string, options?: ReleaseEditLeaseOptions): Promise<void>;
107
130
  }
@@ -119,11 +142,28 @@ export declare function usableImageUrl(value: unknown): string | null;
119
142
  * capability model is the API's, and an answer that left a part out is treated as "this composition cannot do that".
120
143
  */
121
144
  export declare function readCompositionOption(data: unknown): CompositionOption;
145
+ /**
146
+ * One preset a workflow can be started from. The key and the title are what a card and a start cannot do without; the
147
+ * description may be missing (a preset its offerer wrote nothing about), and a count that is not a number is refused.
148
+ */
149
+ export declare function readWorkflowPreset(data: unknown): WorkflowPreset;
122
150
  /**
123
151
  * What the API answered about an edit claim, checked. An answer the screen cannot read is `unavailable`: presence is a
124
152
  * convenience, so the editor goes on as if it were not there rather than failing.
125
153
  */
126
154
  export declare function readEditLeaseAnswer(data: unknown): EditLeaseAnswer;
155
+ /** The most workflows the API looks at in one call (`POST /edit-leases/peek` answers 400 above it): a longer list is asked in several. */
156
+ export declare const EDIT_LEASE_PEEK_BATCH_SIZE = 50;
157
+ /**
158
+ * What the API answered about a page of workflows, checked: the teammates who are editing, and whether the API could tell.
159
+ *
160
+ * A workflow counts as being edited only when the API says `held_by_other`, names a holder, and the holder is not the signed-in
161
+ * person's own account (`isYou`: that is another window of theirs, not a teammate, and "Anna is editing" would be untrue of
162
+ * oneself). Everything else is nobody, with one exception that is not "nobody": an answer of `unavailable`, or one that cannot
163
+ * be read, means the API could not tell, so `complete` is `false` and the list keeps what it showed. A missing badge is the
164
+ * safe answer, a wrong one is not.
165
+ */
166
+ export declare function readEditLeasePeekAnswer(data: unknown): EditLeasePeekAnswer;
127
167
  /** The query string of the list: only what was asked for. */
128
168
  export declare function buildListQueryString(query: WorkflowListQuery | undefined): string;
129
169
  export declare function buildCompositionOptionsQueryString(query: CompositionOptionsQuery | undefined): string;
@@ -5,9 +5,11 @@
5
5
  *
6
6
  * GET /workspaces/{workspaceId}/workflows the list
7
7
  * POST /workspaces/{workspaceId}/workflows a new workflow (Idempotency-Key)
8
+ * GET /workspaces/{workspaceId}/workflows/presets the presets a workflow can be started from
9
+ * POST /workspaces/{workspaceId}/workflows/from-preset a draft workflow of one's own from a preset (Idempotency-Key)
8
10
  * GET /workspaces/{workspaceId}/workflows/{id} one workflow with its draft
9
11
  * 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
12
+ * DELETE /workspaces/{workspaceId}/workflows/{id} delete one, in any state, with its versions and counts
11
13
  * POST /workspaces/{workspaceId}/workflows/{id}/duplicate a copy (Idempotency-Key)
12
14
  * POST /workspaces/{workspaceId}/workflows/{id}/publish the draft becomes the next version (Idempotency-Key)
13
15
  * POST /workspaces/{workspaceId}/workflows/{id}/discard the draft goes back to what is live
@@ -20,6 +22,7 @@
20
22
  * POST /edit-leases/workflow/{id}/take-over take the claim from whoever holds it
21
23
  * GET /edit-leases/workflow/{id} who is editing, without claiming
22
24
  * DELETE /edit-leases/workflow/{id}?sessionId= give the claim up
25
+ * POST /edit-leases/peek who is editing several workflows at once (the badges of the list)
23
26
  *
24
27
  * 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
25
28
  * language. What the client never does: send cookies, put a token anywhere but the `Authorization` header, or keep one.
@@ -35,6 +38,12 @@ import { WORKFLOW_STATUSES } from './types.js';
35
38
  /** How long a request may take before it is given up: the reads, and the writes (a publish reads every composition). */
36
39
  export const READ_TIMEOUT_MS = 15_000;
37
40
  export const WRITE_TIMEOUT_MS = 30_000;
41
+ /**
42
+ * A start from a preset copies every widget the preset chains, one after the other, so it is given longer than another write:
43
+ * a request that is given up while the gateway is still copying is asked again with the same `Idempotency-Key`, which replays
44
+ * the answer instead of copying twice, but a person would rather wait the seconds it takes.
45
+ */
46
+ export const START_FROM_PRESET_TIMEOUT_MS = 90_000;
38
47
  /** What went wrong with a request, as far as the screens care. */
39
48
  export class WorkflowsApiError extends Error {
40
49
  /** The HTTP status; null when no answer came (offline, blocked by the page's policy, too slow, a token that could not be had). */
@@ -378,6 +387,50 @@ function readCompositionOptionList(data) {
378
387
  offset: readWholeNumber(data, 'offset', 'the compositions')
379
388
  };
380
389
  }
390
+ /** A widget a preset shows. A name that is not text is not a widget a card can say anything about, so the answer is refused. */
391
+ function readPresetWidget(data) {
392
+ if (!isRecord(data))
393
+ throw invalidResponse('a widget of a preset');
394
+ return {
395
+ name: readText(data, 'name', 'a widget of a preset'),
396
+ thumbnailUrl: usableImageUrl(data.thumbnailUrl)
397
+ };
398
+ }
399
+ /**
400
+ * One preset a workflow can be started from. The key and the title are what a card and a start cannot do without; the
401
+ * description may be missing (a preset its offerer wrote nothing about), and a count that is not a number is refused.
402
+ */
403
+ export function readWorkflowPreset(data) {
404
+ if (!isRecord(data))
405
+ throw invalidResponse('a preset');
406
+ const presetKey = readRequiredText(data, 'key', 'a preset');
407
+ const heading = readRequiredText(data, 'title', 'a preset');
408
+ if (data.widgets !== undefined && !Array.isArray(data.widgets))
409
+ throw invalidResponse('a preset (widgets)');
410
+ return {
411
+ key: presetKey,
412
+ title: heading,
413
+ description: readPresetDescription(data),
414
+ blockCount: readWholeNumber(data, 'blockCount', 'a preset'),
415
+ widgets: (data.widgets ?? []).map(readPresetWidget)
416
+ };
417
+ }
418
+ /** A text the answer cannot do without: it has to be text, and more than spaces. */
419
+ function readRequiredText(source, key, what) {
420
+ const value = readText(source, key, what);
421
+ if (value.trim() === '')
422
+ throw invalidResponse(`${what} (${key})`);
423
+ return value;
424
+ }
425
+ /** What the offerer wrote about a preset: none when they wrote nothing, or only spaces. */
426
+ function readPresetDescription(data) {
427
+ return nonEmptyText(readNullableText(data, 'description', 'a preset'));
428
+ }
429
+ function readWorkflowPresetList(data) {
430
+ if (!isRecord(data) || !Array.isArray(data.items))
431
+ throw invalidResponse('the presets');
432
+ return data.items.map(readWorkflowPreset);
433
+ }
381
434
  /** What the API accepts as the id of an editor tab (an edit claim's `sessionId`). */
382
435
  const EDIT_LEASE_SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{8,64}$/;
383
436
  /** True for a number of seconds worth believing: a positive, finite number. */
@@ -431,6 +484,50 @@ export function readEditLeaseAnswer(data) {
431
484
  answer.tookOverFrom = tookOverFrom;
432
485
  return answer;
433
486
  }
487
+ /** The most workflows the API looks at in one call (`POST /edit-leases/peek` answers 400 above it): a longer list is asked in several. */
488
+ export const EDIT_LEASE_PEEK_BATCH_SIZE = 50;
489
+ /**
490
+ * What the API answered about a page of workflows, checked: the teammates who are editing, and whether the API could tell.
491
+ *
492
+ * A workflow counts as being edited only when the API says `held_by_other`, names a holder, and the holder is not the signed-in
493
+ * person's own account (`isYou`: that is another window of theirs, not a teammate, and "Anna is editing" would be untrue of
494
+ * oneself). Everything else is nobody, with one exception that is not "nobody": an answer of `unavailable`, or one that cannot
495
+ * be read, means the API could not tell, so `complete` is `false` and the list keeps what it showed. A missing badge is the
496
+ * safe answer, a wrong one is not.
497
+ */
498
+ export function readEditLeasePeekAnswer(data) {
499
+ const editors = new Map();
500
+ if (!isRecord(data) || !Array.isArray(data.items)) {
501
+ return { editors, heartbeatSeconds: null, complete: false, notApplicable: false };
502
+ }
503
+ let complete = true;
504
+ let everyItemNotApplicable = data.items.length > 0;
505
+ for (const item of data.items) {
506
+ const outcome = isRecord(item)
507
+ ? EDIT_LEASE_OUTCOMES.find((name) => name === item.outcome)
508
+ : undefined;
509
+ if (outcome !== 'not_applicable')
510
+ everyItemNotApplicable = false;
511
+ if (outcome === undefined || outcome === 'unavailable') {
512
+ complete = false;
513
+ continue;
514
+ }
515
+ if (outcome !== 'held_by_other' || !isRecord(item))
516
+ continue;
517
+ if (item.type !== 'workflow' || typeof item.id !== 'string')
518
+ continue;
519
+ const holder = readEditLeaseHolder(item.holder);
520
+ if (!holder || holder.isYou)
521
+ continue;
522
+ editors.set(item.id.toLowerCase(), holder);
523
+ }
524
+ return {
525
+ editors,
526
+ heartbeatSeconds: isSeconds(data.heartbeatSeconds) ? data.heartbeatSeconds : null,
527
+ complete,
528
+ notApplicable: everyItemNotApplicable
529
+ };
530
+ }
434
531
  /** The error code, sentence and details of an API error answer, when it has them. */
435
532
  function describeFailureBody(body) {
436
533
  if (!isRecord(body))
@@ -510,6 +607,7 @@ export function createWorkflowsApi(options) {
510
607
  const workspaceBase = `/workspaces/${encodeURIComponent(options.workspaceId)}/workflows`;
511
608
  const readTimeoutMs = options.readTimeoutMs ?? READ_TIMEOUT_MS;
512
609
  const writeTimeoutMs = options.writeTimeoutMs ?? WRITE_TIMEOUT_MS;
610
+ const startFromPresetTimeoutMs = options.startFromPresetTimeoutMs ?? START_FROM_PRESET_TIMEOUT_MS;
513
611
  const sendRequest = options.fetchImplementation ?? ((...parameters) => globalThis.fetch(...parameters));
514
612
  async function tokenFor(reason, refusedToken) {
515
613
  try {
@@ -726,6 +824,25 @@ export function createWorkflowsApi(options) {
726
824
  timeoutMs: readTimeoutMs
727
825
  }));
728
826
  },
827
+ async listPresets(requestOptions = {}) {
828
+ return readWorkflowPresetList(await request('GET', `${workspaceBase}/presets`, {
829
+ signal: requestOptions.signal,
830
+ timeoutMs: readTimeoutMs
831
+ }));
832
+ },
833
+ async startFromPreset(input, requestOptions = {}) {
834
+ const body = { key: input.key };
835
+ // A name that is only spaces is no name: the preset's title is used, as when none is given.
836
+ const name = input.name?.trim();
837
+ if (name)
838
+ body.name = name;
839
+ return readWorkflowDetail(await request('POST', `${workspaceBase}/from-preset`, {
840
+ body,
841
+ idempotencyKey: requestOptions.idempotencyKey ?? makeIdempotencyKey(),
842
+ signal: requestOptions.signal,
843
+ timeoutMs: startFromPresetTimeoutMs
844
+ }));
845
+ },
729
846
  // The edit claim calls wait no longer than a read does: a claim is renewed every few seconds, and a renewal that
730
847
  // takes longer than that has told what it will tell.
731
848
  async acquireEditLease(workflowId, sessionId, requestOptions = {}) {
@@ -751,6 +868,39 @@ export function createWorkflowsApi(options) {
751
868
  noStore: true
752
869
  }));
753
870
  },
871
+ async peekEditLeases(workflowIds, requestOptions = {}) {
872
+ // Each workflow once, by the id as the API compares it; an id that is no id is a bug of the caller, never sent.
873
+ const unique = [
874
+ ...new Set(workflowIds.map((workflowId) => {
875
+ if (typeof workflowId !== 'string' || workflowId.trim() === '') {
876
+ throw new TypeError('A workflow id is needed');
877
+ }
878
+ return workflowId.toLowerCase();
879
+ }))
880
+ ];
881
+ const editors = new Map();
882
+ let heartbeatSeconds = null;
883
+ let complete = true;
884
+ let notApplicable = unique.length > 0;
885
+ for (let start = 0; start < unique.length; start += EDIT_LEASE_PEEK_BATCH_SIZE) {
886
+ const batch = unique.slice(start, start + EDIT_LEASE_PEEK_BATCH_SIZE);
887
+ const answer = readEditLeasePeekAnswer(await request('POST', '/edit-leases/peek', {
888
+ body: { items: batch.map((id) => ({ type: 'workflow', id })) },
889
+ signal: requestOptions.signal,
890
+ timeoutMs: readTimeoutMs,
891
+ noStore: true
892
+ }));
893
+ for (const [id, holder] of answer.editors)
894
+ editors.set(id, holder);
895
+ if (answer.heartbeatSeconds !== null)
896
+ heartbeatSeconds = answer.heartbeatSeconds;
897
+ if (!answer.complete)
898
+ complete = false;
899
+ if (!answer.notApplicable)
900
+ notApplicable = false;
901
+ }
902
+ return { editors, heartbeatSeconds, complete, notApplicable };
903
+ },
754
904
  async releaseEditLease(workflowId, sessionId, releaseOptions = {}) {
755
905
  await request('DELETE', leasePath(workflowId, `?sessionId=${encodeURIComponent(checkedSessionId(sessionId))}`), {
756
906
  signal: releaseOptions.signal,
@@ -85,6 +85,11 @@
85
85
  </div>
86
86
  {:else}
87
87
  <div class="flex flex-1 flex-col p-6">
88
- <WorkflowList onopen={(id) => open(id)} onerror={onError} onshowembedcode={onShowEmbedCode} />
88
+ <WorkflowList
89
+ onopen={(id) => open(id)}
90
+ onerror={onError}
91
+ onshowembedcode={onShowEmbedCode}
92
+ {presence}
93
+ />
89
94
  </div>
90
95
  {/if}
@@ -3,10 +3,12 @@
3
3
  can be done with the workflow as a whole: pause it, archive it, copy it, delete it.
4
4
 
5
5
  Pausing is for a while: an embed of a paused workflow shows only its first composition, as a plain embed would. Archiving is
6
- for good, but not lost (it can be brought back). A workflow that was ever published cannot be deleted, because pages out there
7
- may still carry its id; it can be archived instead, and the page says so.
6
+ for good, but not lost (it can be brought back). Deleting is for good and is lost: a workflow can be deleted in any state,
7
+ after one confirmation that says what goes with it (its draft, its versions and its counts; the compositions stay), and a
8
+ page whose embed still names it shows the embed's first composition.
8
9
  -->
9
10
  <script lang="ts">
11
+ import { deleteMessageOf } from '../../editor/deleteWords.js';
10
12
  import { useEditorState } from '../../editor/editorState.svelte.js';
11
13
  import { listTimeZones } from '../../editor/zonedTime.js';
12
14
  import { useWorkflowsLanguage } from '../../i18n/language.js';
@@ -37,7 +39,15 @@
37
39
  });
38
40
 
39
41
  const isLiveOrPaused = $derived(editor.status === 'live' || editor.status === 'paused');
40
- const canDelete = $derived(!(editor.workflow?.everPublished ?? false));
42
+ /** What the confirmation of a delete says goes with this workflow, by how far it got. */
43
+ const deleteMessage = $derived(
44
+ deleteMessageOf({
45
+ name: editor.name,
46
+ status: editor.status,
47
+ firstPublishedAt: editor.workflow?.firstPublishedAt ?? null,
48
+ runsCount: editor.workflow?.runsCount ?? 0
49
+ })
50
+ );
41
51
 
42
52
  async function confirmArchive(): Promise<void> {
43
53
  await editor.changeState('archive');
@@ -145,15 +155,13 @@
145
155
  variant="danger"
146
156
  size="small"
147
157
  class="self-start"
148
- disabled={!editor.canChangeWorkflow || !canDelete}
158
+ disabled={!editor.canChangeWorkflow}
149
159
  onclick={() => (asking = 'delete')}
150
160
  >
151
161
  <Icon name="trash" />
152
162
  {$t('workflows.settings.delete')}
153
163
  </ActionButton>
154
- <p class="text-xs text-ink-muted">
155
- {canDelete ? $t('workflows.settings.deleteHelp') : $t('workflows.settings.deleteBlocked')}
156
- </p>
164
+ <p class="text-xs text-ink-muted">{$t('workflows.settings.deleteHelp')}</p>
157
165
  </div>
158
166
  </section>
159
167
  </div>
@@ -170,7 +178,7 @@
170
178
  {:else if asking === 'delete'}
171
179
  <ConfirmDialog
172
180
  title={$t('workflows.settings.deleteTitle')}
173
- message={$t('workflows.settings.deleteMessage', { name: editor.name })}
181
+ message={$t(deleteMessage.key, deleteMessage.values)}
174
182
  confirmLabel={$t('workflows.settings.delete')}
175
183
  tone="danger"
176
184
  busy={editor.busy === 'deleting'}