@bpmnkit/core 1.1.0 → 1.3.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 (50) hide show
  1. package/README.md +31 -0
  2. package/dist/bpmn/bpmn-builder.d.ts +8 -0
  3. package/dist/bpmn/bpmn-builder.js +6 -2
  4. package/dist/bpmn/compact.d.ts +37 -5
  5. package/dist/bpmn/compact.js +218 -30
  6. package/dist/bpmn/connector-line.d.ts +46 -0
  7. package/dist/bpmn/connector-line.js +135 -0
  8. package/dist/bpmn/optimize/patterns.js +4 -3
  9. package/dist/bpmn/process-delta.d.ts +91 -0
  10. package/dist/bpmn/process-delta.js +259 -0
  11. package/dist/bpmn/process-text-writer.d.ts +63 -0
  12. package/dist/bpmn/process-text-writer.js +202 -0
  13. package/dist/bpmn/process-text.d.ts +200 -0
  14. package/dist/bpmn/process-text.js +1568 -0
  15. package/dist/bpmn/rest-connector.d.ts +6 -0
  16. package/dist/bpmn/rest-connector.js +6 -0
  17. package/dist/bpmn/secrets.d.ts +15 -0
  18. package/dist/bpmn/secrets.js +59 -0
  19. package/dist/bpmn/utils.js +4 -0
  20. package/dist/bpmn/zeebe-extensions.d.ts +10 -0
  21. package/dist/bpmn/zeebe-extensions.js +7 -0
  22. package/dist/connectors/aliases.d.ts +21 -0
  23. package/dist/connectors/aliases.js +272 -0
  24. package/dist/connectors/api.d.ts +118 -0
  25. package/dist/connectors/api.js +280 -0
  26. package/dist/connectors/apply-element.d.ts +59 -0
  27. package/dist/connectors/apply-element.js +385 -0
  28. package/dist/connectors/apply.d.ts +136 -0
  29. package/dist/connectors/apply.js +352 -0
  30. package/dist/connectors/cards.d.ts +96 -0
  31. package/dist/connectors/cards.js +306 -0
  32. package/dist/connectors/catalog.d.ts +79 -0
  33. package/dist/connectors/catalog.js +209 -0
  34. package/dist/connectors/index.d.ts +33 -0
  35. package/dist/connectors/index.js +24 -0
  36. package/dist/connectors/lines.d.ts +108 -0
  37. package/dist/connectors/lines.js +568 -0
  38. package/dist/connectors/select.d.ts +85 -0
  39. package/dist/connectors/select.js +419 -0
  40. package/dist/connectors/template-types.d.ts +188 -0
  41. package/dist/connectors/template-types.js +6 -0
  42. package/dist/connectors/templates/bpmnkit.d.ts +12 -0
  43. package/dist/connectors/templates/bpmnkit.js +186 -0
  44. package/dist/connectors/templates/generated.d.ts +3 -0
  45. package/dist/connectors/templates/generated.js +95885 -0
  46. package/dist/connectors/validate.d.ts +66 -0
  47. package/dist/connectors/validate.js +271 -0
  48. package/dist/index.d.ts +11 -1
  49. package/dist/index.js +5 -0
  50. package/package.json +5 -1
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Resolving and applying `with` lines (`parseConnectorLine` in
3
+ * `@bpmnkit/core`), and writing them back.
4
+ *
5
+ * The model writes intent: an alias, an operation, a few inputs. This turns
6
+ * that into a fully applied element template, deterministically, and never
7
+ * throws: an unknown alias, an operation it cannot tell, an input the
8
+ * operation does not have or a credential written as a value is repaired or
9
+ * reported, and a required input still missing becomes a question.
10
+ */
11
+ import type { BpmnDefinitions, BpmnFlowElement, ConnectorLine, ProcessTextProblem, ProcessTextQuestion } from "../index.js";
12
+ import { type ApiService } from "./api.js";
13
+ import { type ConnectorCard } from "./cards.js";
14
+ /**
15
+ * How to write `with` lines — the system prompt of the connect pass, which
16
+ * configures the connectors of a diagram that already has its shape. The
17
+ * connector cards for the diagram's tasks follow it in the prompt. A test
18
+ * parses its example and expects every line to resolve.
19
+ */
20
+ export declare const CONNECT_GUIDE = "Connect the diagram: write one with line for each node that calls an outside system, nothing else.\nwith <id>: <alias> <operation> | key=value | key==FEEL expression\n- <id> is a node of the diagram, written exactly as before the colon of its cards. <alias>, <operation> and the keys come from the connector cards.\n- When the request names a system, use that system's card.\n- Write every input marked *. Write a mode (key=choice) only to change its default, with the inputs that choice adds.\n- A value starting with = is FEEL: text== \"Order \" + orderId. Without =, it is literal text. A variable is FEEL too: to==email, never {{email}} or ${email}; {{\u2026}} is only for secrets.\n- Credentials are never values: token={{secrets.SLACK_TOKEN}}.\n- result=name keeps the response in a variable; result=name: response.body keeps a part of it.\n- A plain task that becomes a connector needs no other change. Leave out nodes no card fits.\n- An api card lists real endpoints of a service for the http connector: write http <METHOD> <path> | api=<service>. The base URL, the authentication and the {params} of the path, read from variables of the same name, are added. Prefer a dedicated connector's card to an api card.\n\nExample:\nwith notify: slack chat.postMessage | token={{secrets.SLACK_TOKEN}} | data.channel=#ops | data.text== \"Order \" + orderId + \" failed\"\nwith fetch: http GET https://api.example.com/orders | result=order: response.body\nwith charge: http POST /v1/customers | api=stripe | body=={email: email} | result=customer: response.body";
21
+ /** What {@link resolveConnectorLine} made of a line. */
22
+ export interface ResolvedConnectorLine {
23
+ /** The template, when the alias named one. */
24
+ templateId?: string;
25
+ /** The operation's card, when the line named one or the template has only one. */
26
+ card?: ConnectorCard;
27
+ /** Values for `applyConnectorTemplate`/`applyTemplateToElement`, the operation's included. */
28
+ values: Record<string, string>;
29
+ /** What could not be used. */
30
+ problems: string[];
31
+ /** What was changed to make the line usable, e.g. a misspelt alias or a literal credential. */
32
+ fixes: string[];
33
+ /** What a person should check or give, with the input that answers it. */
34
+ questions: {
35
+ text: string;
36
+ input: string;
37
+ }[];
38
+ }
39
+ /** Options of {@link resolveConnectorLine} and {@link applyConnectorLines}. */
40
+ export interface ConnectorLineOptions {
41
+ /**
42
+ * Services of the API index (`@bpmnkit/connector-gen/api-index`) an `http`
43
+ * line may call. A line naming one with `api=<id>`, or calling a URL under
44
+ * its base URL, gets the base URL, the authentication and the headers the
45
+ * operation needs; a call the index does not know becomes a question.
46
+ */
47
+ apis?: readonly ApiService[];
48
+ }
49
+ /**
50
+ * Whether a `with` line's alias names a connector, as the resolver reads it: exactly, by a
51
+ * template id, or within a letter or two of one.
52
+ */
53
+ export declare function isConnectorAlias(alias: string): boolean;
54
+ /**
55
+ * Resolves a `with` line against the catalog: the template its alias names,
56
+ * the operation, and the values to apply.
57
+ *
58
+ * - An unknown alias within two letters of one is read as that one.
59
+ * - The operation is the first word after the alias, matched exactly or by
60
+ * its last dotted part (`postMessage` for `chat.postMessage`). It may also
61
+ * be given as the input that selects it.
62
+ * - Words without a key: an HTTP method sets `method`, a URL or `=` FEEL sets
63
+ * `url`, on a connector that has them.
64
+ * - A key the operation lacks, written as the end of one it has
65
+ * (`channel` for `data.channel`), is read as that one.
66
+ * - `result=name` sets the result variable; `result=name: expr` sets the
67
+ * result expression `={name: expr}`.
68
+ * - A credential written as a value is replaced by a `{{secrets.…}}`
69
+ * placeholder: the diagram never carries one.
70
+ * - On `http`, `api=<service>` or a URL under a service's base URL completes
71
+ * the call from `options.apis`: base URL, path parameters, authentication
72
+ * and required headers. A call the index lacks is a question.
73
+ */
74
+ export declare function resolveConnectorLine(given: ConnectorLine, options?: ConnectorLineOptions): ResolvedConnectorLine;
75
+ /** What {@link applyConnectorLines} did. */
76
+ export interface AppliedConnectorLines {
77
+ /** The changed document. The input is never mutated. */
78
+ definitions: BpmnDefinitions;
79
+ problems: ProcessTextProblem[];
80
+ fixes: string[];
81
+ /** Required inputs the lines left out, as questions with a line to finish. */
82
+ questions: ProcessTextQuestion[];
83
+ }
84
+ /**
85
+ * Applies `with` lines to the elements they name: each line is resolved
86
+ * ({@link resolveConnectorLine}) and written with `applyTemplateToElement`,
87
+ * which converts a plain task into the template's element type and stamps the
88
+ * template. A line for an element that already carries the same template
89
+ * changes only the inputs it names. A required input the line did not give
90
+ * becomes a question; the rest of the line is still applied.
91
+ *
92
+ * Pass `parseProcessText(text).connectors` with the expanded diagram, or the
93
+ * lines of a change script with the ids they resolve to.
94
+ */
95
+ export declare function applyConnectorLines(definitions: BpmnDefinitions, lines: ReadonlyArray<ConnectorLine & {
96
+ elementId: string;
97
+ }>, options?: ConnectorLineOptions): AppliedConnectorLines;
98
+ /**
99
+ * The `with` line that re-creates an element's connector, after `with <id>: `,
100
+ * or `undefined` when the element has no template this catalog knows.
101
+ *
102
+ * Written so a model reading a diagram (`writeProcessText`'s `connectorLine`
103
+ * option) keeps its connectors when it rewrites or changes it: the operation,
104
+ * and every input that differs from the template's default. Hidden and
105
+ * generated values are left out — applying the line sets them again.
106
+ */
107
+ export declare function connectorLineFor(element: BpmnFlowElement, definitions?: BpmnDefinitions): string | undefined;
108
+ //# sourceMappingURL=lines.d.ts.map
@@ -0,0 +1,568 @@
1
+ /**
2
+ * Resolving and applying `with` lines (`parseConnectorLine` in
3
+ * `@bpmnkit/core`), and writing them back.
4
+ *
5
+ * The model writes intent: an alias, an operation, a few inputs. This turns
6
+ * that into a fully applied element template, deterministically, and never
7
+ * throws: an unknown alias, an operation it cannot tell, an input the
8
+ * operation does not have or a credential written as a value is repaired or
9
+ * reported, and a required input still missing becomes a question.
10
+ */
11
+ import { apiAuthValues, apiHeaders, apiUrl, findApiOperation } from "./api.js";
12
+ import { applyTemplateToElement, messageRefOf } from "./apply-element.js";
13
+ import { evalCondition, resolveValues } from "./apply.js";
14
+ import { connectorAlias, connectorCards, templateIdForAlias } from "./cards.js";
15
+ import { allTemplates, getTemplate, isSecretField, propertyKey } from "./catalog.js";
16
+ /**
17
+ * How to write `with` lines — the system prompt of the connect pass, which
18
+ * configures the connectors of a diagram that already has its shape. The
19
+ * connector cards for the diagram's tasks follow it in the prompt. A test
20
+ * parses its example and expects every line to resolve.
21
+ */
22
+ export const CONNECT_GUIDE = `Connect the diagram: write one with line for each node that calls an outside system, nothing else.
23
+ with <id>: <alias> <operation> | key=value | key==FEEL expression
24
+ - <id> is a node of the diagram, written exactly as before the colon of its cards. <alias>, <operation> and the keys come from the connector cards.
25
+ - When the request names a system, use that system's card.
26
+ - Write every input marked *. Write a mode (key=choice) only to change its default, with the inputs that choice adds.
27
+ - A value starting with = is FEEL: text== "Order " + orderId. Without =, it is literal text. A variable is FEEL too: to==email, never {{email}} or \${email}; {{…}} is only for secrets.
28
+ - Credentials are never values: token={{secrets.SLACK_TOKEN}}.
29
+ - result=name keeps the response in a variable; result=name: response.body keeps a part of it.
30
+ - A plain task that becomes a connector needs no other change. Leave out nodes no card fits.
31
+ - An api card lists real endpoints of a service for the http connector: write http <METHOD> <path> | api=<service>. The base URL, the authentication and the {params} of the path, read from variables of the same name, are added. Prefer a dedicated connector's card to an api card.
32
+
33
+ Example:
34
+ with notify: slack chat.postMessage | token={{secrets.SLACK_TOKEN}} | data.channel=#ops | data.text== "Order " + orderId + " failed"
35
+ with fetch: http GET https://api.example.com/orders | result=order: response.body
36
+ with charge: http POST /v1/customers | api=stripe | body=={email: email} | result=customer: response.body`;
37
+ const HTTP_TEMPLATE = "io.camunda.connectors.HttpJson.v2";
38
+ const HTTP_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]);
39
+ const SECRET = /^\{\{\s*secrets\.[A-Za-z0-9_]+\s*\}\}$/;
40
+ function distance(a, b) {
41
+ const row = Array.from({ length: b.length + 1 }, (_, j) => j);
42
+ for (let i = 1; i <= a.length; i++) {
43
+ let diagonal = row[0] ?? 0;
44
+ row[0] = i;
45
+ for (let j = 1; j <= b.length; j++) {
46
+ const above = row[j] ?? 0;
47
+ row[j] = Math.min(above + 1, (row[j - 1] ?? 0) + 1, diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
48
+ diagonal = above;
49
+ }
50
+ }
51
+ return row[b.length] ?? 0;
52
+ }
53
+ /** The template an alias names, or the one a near miss most likely meant. */
54
+ function templateFor(alias, fixes) {
55
+ const exact = templateIdForAlias(alias);
56
+ if (exact)
57
+ return exact;
58
+ const byId = allTemplates().find((t) => t.id.toLowerCase() === alias);
59
+ if (byId)
60
+ return byId.id;
61
+ let best;
62
+ for (const template of allTemplates()) {
63
+ const candidate = connectorAlias(template.id).toLowerCase();
64
+ const d = distance(alias, candidate);
65
+ // Two letters off a short alias is another word: "api" is not "a2a"
66
+ const allowed = Math.min(alias.length, candidate.length) <= 4 ? 1 : 2;
67
+ if (d <= allowed && (best === undefined || d < best.d))
68
+ best = { id: template.id, alias: candidate, d };
69
+ }
70
+ if (best)
71
+ fixes.push(`read connector "${alias}" as "${best.alias}"`);
72
+ return best?.id;
73
+ }
74
+ /**
75
+ * Whether a `with` line's alias names a connector, as the resolver reads it: exactly, by a
76
+ * template id, or within a letter or two of one.
77
+ */
78
+ export function isConnectorAlias(alias) {
79
+ return templateFor(alias.toLowerCase(), []) !== undefined;
80
+ }
81
+ /** The properties active once a card's operation is chosen. */
82
+ function activeProperties(template, values) {
83
+ const resolved = resolveValues(template, values);
84
+ return template.properties.filter((p) => p.type !== "Hidden" && (!p.condition || evalCondition(p.condition, resolved)));
85
+ }
86
+ /** The key of the active task header bound to `header`, e.g. GitHub's `resultExpressionCreateIssue`. */
87
+ function headerKey(props, header) {
88
+ const prop = props.find((p) => p.binding.type === "zeebe:taskHeader" && p.binding.key === header);
89
+ return prop && propertyKey(prop);
90
+ }
91
+ function pickCard(cards, args, values) {
92
+ if (cards.length === 1)
93
+ return { card: cards[0], rest: args };
94
+ const word = args[0]?.toLowerCase();
95
+ if (word !== undefined) {
96
+ const named = cards.find((c) => c.operation?.toLowerCase() === word) ??
97
+ cards.find((c) => c.operation?.toLowerCase().endsWith(`.${word}`)) ??
98
+ // `chat.completions.create`, the SDK call, for the operation `chat`
99
+ cards.find((c) => c.operation !== undefined && word.startsWith(`${c.operation.toLowerCase()}.`));
100
+ if (named)
101
+ return { card: named, rest: args.slice(1) };
102
+ // `sendEmailImap`, an operation the connector does not have, for `sendEmailSmtp`: the
103
+ // one operation that shares the longest start with it, when that start is a word or more
104
+ const shared = (op) => {
105
+ let k = 0;
106
+ while (k < op.length && k < word.length && op[k] === word[k])
107
+ k++;
108
+ return k;
109
+ };
110
+ const ranked = cards
111
+ .map((c) => ({ c, n: shared(c.operation?.toLowerCase() ?? "") }))
112
+ .sort((a, b) => b.n - a.n);
113
+ const [best, next] = ranked;
114
+ if (best && best.n >= 5 && best.n > (next?.n ?? 0)) {
115
+ return { card: best.c, rest: args.slice(1), guessed: true };
116
+ }
117
+ }
118
+ // `method=chat.postMessage` written as an input names the operation too
119
+ const byValues = cards.filter((c) => Object.entries(c.values).every(([k, v]) => values[k] !== undefined && values[k] === v));
120
+ if (byValues.length === 1)
121
+ return { card: byValues[0], rest: args };
122
+ return { rest: args };
123
+ }
124
+ /**
125
+ * Resolves a `with` line against the catalog: the template its alias names,
126
+ * the operation, and the values to apply.
127
+ *
128
+ * - An unknown alias within two letters of one is read as that one.
129
+ * - The operation is the first word after the alias, matched exactly or by
130
+ * its last dotted part (`postMessage` for `chat.postMessage`). It may also
131
+ * be given as the input that selects it.
132
+ * - Words without a key: an HTTP method sets `method`, a URL or `=` FEEL sets
133
+ * `url`, on a connector that has them.
134
+ * - A key the operation lacks, written as the end of one it has
135
+ * (`channel` for `data.channel`), is read as that one.
136
+ * - `result=name` sets the result variable; `result=name: expr` sets the
137
+ * result expression `={name: expr}`.
138
+ * - A credential written as a value is replaced by a `{{secrets.…}}`
139
+ * placeholder: the diagram never carries one.
140
+ * - On `http`, `api=<service>` or a URL under a service's base URL completes
141
+ * the call from `options.apis`: base URL, path parameters, authentication
142
+ * and required headers. A call the index lacks is a question.
143
+ */
144
+ export function resolveConnectorLine(given, options = {}) {
145
+ const out = { values: {}, problems: [], fixes: [], questions: [] };
146
+ const line = apiCardLine(given, options.apis ?? [], out.fixes);
147
+ const templateId = templateFor(line.alias, out.fixes);
148
+ const template = templateId === undefined ? undefined : getTemplate(templateId);
149
+ if (!templateId || !template) {
150
+ out.problems.push(`no connector is called "${line.alias}"`);
151
+ return out;
152
+ }
153
+ out.templateId = templateId;
154
+ const cards = connectorCards(templateId);
155
+ const { card, rest, guessed } = pickCard(cards, line.args, line.values);
156
+ if (!card) {
157
+ const names = cards.map((c) => c.operation).filter(Boolean);
158
+ out.problems.push(`${connectorAlias(templateId)} has several operations; name one of ${names.slice(0, 8).join(", ")}${names.length > 8 ? ", …" : ""}`);
159
+ return out;
160
+ }
161
+ out.card = card;
162
+ if (guessed)
163
+ out.fixes.push(`read operation "${line.args[0]}" as "${card.operation}"`);
164
+ // Words without a key first: `http POST` makes `body` an input, as a mode does
165
+ const values = {};
166
+ const templateKeys = new Set(template.properties.map(propertyKey));
167
+ for (const arg of rest) {
168
+ if (HTTP_METHODS.has(arg.toUpperCase()) && templateKeys.has("method")) {
169
+ values.method = arg.toUpperCase();
170
+ }
171
+ else if (/^(https?:\/\/|=|["']|\/)/.test(arg) && templateKeys.has("url")) {
172
+ values.url = arg.replace(/^(["'])(.*)\1$/, "$2");
173
+ }
174
+ else {
175
+ out.problems.push(`"${arg}" is not an input of ${connectorAlias(templateId)}; ignored`);
176
+ }
177
+ }
178
+ // A mode the line sets (authentication.type=bearer) switches on the inputs that come with it
179
+ const { result: _result, api: _api, ...written } = line.values;
180
+ const props = activeProperties(template, { ...card.values, ...values, ...written });
181
+ const keys = new Set(props.map(propertyKey));
182
+ const secrets = new Set(props
183
+ .filter((p) => p.type !== "Configuration" && isSecretField(p, propertyKey(p)))
184
+ .map(propertyKey));
185
+ for (const [written, value] of Object.entries(line.values)) {
186
+ if (written === "api")
187
+ continue;
188
+ if (written === "result") {
189
+ const colon = value.indexOf(":");
190
+ const name = (colon < 0 ? value : value.slice(0, colon)).trim();
191
+ const expression = colon < 0 ? "" : value.slice(colon + 1).trim();
192
+ const key = headerKey(props, expression ? "resultExpression" : "resultVariable");
193
+ if (key === undefined || !/^[A-Za-z_]\w*$/.test(name)) {
194
+ out.problems.push(`result="${value}" cannot be written here; ignored`);
195
+ }
196
+ else {
197
+ values[key] = expression ? `={${name}: ${expression.replace(/^=\s*/, "")}}` : name;
198
+ }
199
+ continue;
200
+ }
201
+ let key = written;
202
+ if (!keys.has(key) && !(key in card.values)) {
203
+ const ends = [...keys].filter((k) => k.endsWith(`.${written}`) || k.endsWith(`_${written}`));
204
+ if (ends.length !== 1 || ends[0] === undefined) {
205
+ out.problems.push(`${connectorAlias(templateId)}${card.operation ? ` ${card.operation}` : ""} has no input "${written}"; ignored`);
206
+ continue;
207
+ }
208
+ key = ends[0];
209
+ out.fixes.push(`read "${written}" as "${key}"`);
210
+ }
211
+ // `url=api.notion.base` beside a positional URL is not one: the positional stands. With
212
+ // api=, the index completes the positional path, so a FEEL url= only gets it wrong
213
+ if (key === "url" &&
214
+ values.url !== undefined &&
215
+ (!/^(https?:\/\/|=|\/|["'])/.test(value) || line.values.api !== undefined)) {
216
+ out.fixes.push(`kept the URL ${values.url}, not url=${value}`);
217
+ continue;
218
+ }
219
+ values[key] =
220
+ key === "headers" ? feelHeaders(value, out.fixes) : feelForVariable(key, value, out.fixes);
221
+ }
222
+ for (const key of secrets) {
223
+ const value = values[key];
224
+ if (value === undefined || value === "" || value.startsWith("=") || SECRET.test(value))
225
+ continue;
226
+ const name = `${connectorAlias(templateId)}_${key}`.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
227
+ values[key] = `{{secrets.${name}}}`;
228
+ out.fixes.push(`"${key}" holds a credential; it is the secret ${name} now, never a value`);
229
+ }
230
+ if (templateId === HTTP_TEMPLATE) {
231
+ const service = apiServiceFor(line.values.api, values.url, options.apis ?? [], out);
232
+ if (service)
233
+ applyApiService(service, values, line.values, out);
234
+ }
235
+ else if (line.values.api !== undefined) {
236
+ out.problems.push("api= is for the http connector; ignored");
237
+ }
238
+ out.values = { ...card.values, ...values };
239
+ return out;
240
+ }
241
+ /**
242
+ * A line written like an API card's head, `api github GET /issues`, read as the call it
243
+ * means: `http GET /issues | api=github`; one that starts with the method, `GET /issues`,
244
+ * as `http GET /issues`.
245
+ */
246
+ function apiCardLine(given, apis, fixes) {
247
+ let line = given;
248
+ // `with fetch: https://api.github.com/… | api=github GET`: a URL where the alias goes is a
249
+ // REST call to it, and a method after the service in api= is the call's method
250
+ if (/^https?:\/\//i.test(line.alias)) {
251
+ fixes.push(`read "${line.alias}" as "http ${line.alias}"`);
252
+ line = { ...line, alias: "http", args: [line.alias, ...line.args] };
253
+ }
254
+ const apiMethod = /^(\S+)\s+(get|post|put|patch|delete)$/i.exec(line.values.api ?? "");
255
+ if (apiMethod?.[1] && apiMethod[2]) {
256
+ const method = apiMethod[2].toUpperCase();
257
+ fixes.push(`read api=${line.values.api} as api=${apiMethod[1]} with ${method}`);
258
+ const hasMethod = line.args.some((arg) => HTTP_METHODS.has(arg.toUpperCase()));
259
+ line = {
260
+ ...line,
261
+ args: hasMethod ? line.args : [method, ...line.args],
262
+ values: { ...line.values, api: apiMethod[1] },
263
+ };
264
+ }
265
+ // `http GET api github — List workflow runs for a repository`: an API card's line copied
266
+ // with the summary where the path goes. The summary names the operation
267
+ const dash = line.args.findIndex((arg) => arg === "—" || arg === "-");
268
+ if (line.alias === "http" && dash >= 0) {
269
+ const summary = line.args
270
+ .slice(dash + 1)
271
+ .join(" ")
272
+ .trim()
273
+ .toLowerCase();
274
+ for (const service of apis) {
275
+ const op = service.operations.find((o) => o.summary?.toLowerCase() === summary);
276
+ if (!op)
277
+ continue;
278
+ fixes.push(`read "${line.args.slice(dash + 1).join(" ")}" as ${op.method} ${op.path} of ${service.name}`);
279
+ return { ...line, args: [op.method, op.path], values: { ...line.values, api: service.id } };
280
+ }
281
+ }
282
+ // `with list: GET /repos/…` is a REST call missing its alias
283
+ if (HTTP_METHODS.has(line.alias.toUpperCase())) {
284
+ fixes.push(`read "${line.alias}" as "http ${line.alias.toUpperCase()}"`);
285
+ return { ...line, alias: "http", args: [line.alias.toUpperCase(), ...line.args] };
286
+ }
287
+ // `stripe POST /v1/refunds` names a service of the index where a connector alias goes
288
+ if (apis.some((s) => s.id === line.alias) &&
289
+ templateIdForAlias(line.alias) === undefined &&
290
+ !allTemplates().some((t) => t.id.toLowerCase() === line.alias)) {
291
+ // `STRIPE_API_POST` is an operation of the card read as its method
292
+ const args = line.args.map((arg) => {
293
+ const method = /(?:^|[_.-])(get|post|put|patch|delete)$/i.exec(arg)?.[1];
294
+ return method ? method.toUpperCase() : arg;
295
+ });
296
+ fixes.push(`read "${line.alias}" as "http … | api=${line.alias}"`);
297
+ return { ...line, alias: "http", args, values: { ...line.values, api: line.alias } };
298
+ }
299
+ const service = line.args[0]?.toLowerCase();
300
+ if (line.alias !== "api" || !apis.some((s) => s.id === service))
301
+ return line;
302
+ fixes.push(`read "api ${line.args[0]}" as "http … | api=${service}"`);
303
+ return {
304
+ ...line,
305
+ alias: "http",
306
+ args: line.args.slice(1),
307
+ values: { ...line.values, api: service ?? "" },
308
+ };
309
+ }
310
+ /** `{{orderId}}`, `{{variables.orderId}}` or `${orderId}`: a variable, which FEEL reads as `=orderId`. */
311
+ const TEMPLATED_VARIABLE = /^=?\s*(?:\{\{\s*(?:variables\.)?([A-Za-z_][\w.]*)\s*\}\}|\$\{\s*([A-Za-z_][\w.]*)\s*\})\s*$/;
312
+ /** `Notion-Version: 2026-03-11`, headers written as text, as the FEEL context the connector reads. */
313
+ function feelHeaders(value, fixes) {
314
+ if (/^\s*[={]/.test(value) || !/^\s*[\w-]+\s*:/.test(value))
315
+ return value;
316
+ const entries = value.split(/[,;]\s*(?=[\w-]+\s*:)/).map((pair) => {
317
+ const colon = pair.indexOf(":");
318
+ return `${JSON.stringify(pair.slice(0, colon).trim())}: ${JSON.stringify(pair.slice(colon + 1).trim())}`;
319
+ });
320
+ fixes.push(`read headers ${value} as a FEEL context`);
321
+ return `={${entries.join(", ")}}`;
322
+ }
323
+ /** A variable written in another template syntax, as the FEEL expression it means. */
324
+ function feelForVariable(key, value, fixes) {
325
+ // `== "Order " + ${orderId} + " failed"`: a template variable inside FEEL is the variable
326
+ if (value.startsWith("=") && /\$\{\s*[A-Za-z_][\w.]*\s*\}/.test(value)) {
327
+ const feel = value.replace(/\$\{\s*([A-Za-z_][\w.]*)\s*\}/g, "$1");
328
+ fixes.push(`read "${key}" ${value} as ${feel}`);
329
+ return feel;
330
+ }
331
+ // `channel==#ops` is the literal #ops: no FEEL starts with # or @
332
+ if (/^=\s*[#@][\w.-]+$/.test(value)) {
333
+ const literal = value.replace(/^=\s*/, "");
334
+ fixes.push(`read "${key}" ${value} as the text ${literal}`);
335
+ return literal;
336
+ }
337
+ const match = TEMPLATED_VARIABLE.exec(value);
338
+ const name = match?.[1] ?? match?.[2];
339
+ if (name === undefined || name.startsWith("secrets."))
340
+ return value;
341
+ fixes.push(`read "${key}" ${value} as the variable =${name}`);
342
+ return `=${name}`;
343
+ }
344
+ /** The service an `http` line calls: the one `api=` names, or the one whose base URL its URL starts with. */
345
+ function apiServiceFor(name, url, apis, out) {
346
+ if (name !== undefined) {
347
+ const wanted = name.trim().toLowerCase();
348
+ const named = apis.find((s) => s.id === wanted);
349
+ if (!named)
350
+ out.problems.push(`no API "${name}" is in the API index; api= ignored`);
351
+ return named;
352
+ }
353
+ if (url === undefined)
354
+ return undefined;
355
+ const under = apis.find((s) => s.baseUrl !== undefined && url.startsWith(`${s.baseUrl}/`));
356
+ if (under)
357
+ return under;
358
+ // A path alone, with one service in play, is a path of that service
359
+ const only = apis.length === 1 ? apis[0] : undefined;
360
+ if (only && url.startsWith("/")) {
361
+ out.fixes.push(`read ${url} as a path of ${only.name}`);
362
+ return only;
363
+ }
364
+ return undefined;
365
+ }
366
+ /**
367
+ * Completes an `http` line from the API index: the base URL before a path, the
368
+ * path's `{params}` read from variables, the service's authentication unless
369
+ * the line sets its own, and the headers the operation needs. A call the index
370
+ * does not have is kept, with a question to check it.
371
+ */
372
+ function applyApiService(service, values, written, out) {
373
+ const url = values.url;
374
+ if (!Object.keys(written).some((k) => k.startsWith("authentication."))) {
375
+ Object.assign(values, apiAuthValues(service));
376
+ }
377
+ // A FEEL URL is the line's own: nothing to look up
378
+ if (url === undefined || url.startsWith("="))
379
+ return;
380
+ const base = service.baseUrl;
381
+ // `/charges/{{chargeId}}/refunds` is the path parameter `{chargeId}` in another syntax
382
+ const given = (base !== undefined && url.startsWith(base) ? url.slice(base.length) : url).replace(/\{\{\s*(?:variables\.)?([A-Za-z_]\w*)\s*\}\}/g, "{$1}");
383
+ // `/repos/web/Actions/runs`: a word of the service's paths, in the case the service writes it
384
+ const spelling = new Map(service.operations
385
+ .flatMap((op) => op.path.split("/"))
386
+ .filter((part) => part !== "" && !part.startsWith("{"))
387
+ .map((part) => [part.toLowerCase(), part]));
388
+ const path = given
389
+ .split("/")
390
+ .map((part) => spelling.get(part.toLowerCase()) ?? part)
391
+ .join("/");
392
+ if (path !== given)
393
+ out.fixes.push(`read ${given} as ${path}, as ${service.name} spells it`);
394
+ if (!path.startsWith("/"))
395
+ return;
396
+ const method = values.method ?? "GET";
397
+ const op = findApiOperation(service, method, path);
398
+ if (base === undefined) {
399
+ out.questions.push({
400
+ text: `${service.name} has no fixed address: give the full URL of ${method} ${path} for your account.`,
401
+ input: "url",
402
+ });
403
+ }
404
+ else {
405
+ values.url = apiUrl(base, path);
406
+ }
407
+ if (!op) {
408
+ out.questions.push({
409
+ text: `${method} ${path} is not an operation of ${service.name} in the API index — check the method and the URL.`,
410
+ input: "url",
411
+ });
412
+ return;
413
+ }
414
+ if (!("headers" in written)) {
415
+ const { headers, missing } = apiHeaders(op);
416
+ if (headers !== undefined)
417
+ values.headers = headers;
418
+ if (missing.length > 0) {
419
+ out.questions.push({
420
+ text: `${service.name} needs the header${missing.length > 1 ? "s" : ""} ${missing.join(", ")} for ${method} ${op.path}.`,
421
+ input: "headers",
422
+ });
423
+ }
424
+ }
425
+ }
426
+ /**
427
+ * Applies `with` lines to the elements they name: each line is resolved
428
+ * ({@link resolveConnectorLine}) and written with `applyTemplateToElement`,
429
+ * which converts a plain task into the template's element type and stamps the
430
+ * template. A line for an element that already carries the same template
431
+ * changes only the inputs it names. A required input the line did not give
432
+ * becomes a question; the rest of the line is still applied.
433
+ *
434
+ * Pass `parseProcessText(text).connectors` with the expanded diagram, or the
435
+ * lines of a change script with the ids they resolve to.
436
+ */
437
+ export function applyConnectorLines(definitions, lines, options = {}) {
438
+ const out = { definitions, problems: [], fixes: [], questions: [] };
439
+ for (const line of lines) {
440
+ const resolved = resolveConnectorLine(line, options);
441
+ for (const message of resolved.problems)
442
+ out.problems.push({ line: line.line, message });
443
+ out.fixes.push(...resolved.fixes.map((fix) => `${line.id}: ${fix}`));
444
+ const template = resolved.templateId ? getTemplate(resolved.templateId) : undefined;
445
+ if (!template || !resolved.card)
446
+ continue;
447
+ // A line for a node that already carries this connector changes only what it names:
448
+ // answering "which channel?" must not drop the token the first line set
449
+ const current = elementOf(out.definitions, line.elementId);
450
+ const kept = current?.unknownAttributes["zeebe:modelerTemplate"] === template.id
451
+ ? readValues(out.definitions, current, template)
452
+ : {};
453
+ const applied = applyTemplateToElement(out.definitions, line.elementId, template, {
454
+ ...kept,
455
+ ...resolved.values,
456
+ });
457
+ out.definitions = applied.definitions;
458
+ const card = resolved.card;
459
+ const head = `with ${line.id}: ${card.alias}${card.operation ? ` ${card.operation}` : ""}`;
460
+ const element = elementOf(out.definitions, line.elementId);
461
+ for (const question of resolved.questions) {
462
+ out.questions.push({
463
+ elementId: line.elementId,
464
+ text: `"${element?.name ?? line.id}": ${question.text}`,
465
+ options: [],
466
+ draft: `${head} | ${question.input}=`,
467
+ });
468
+ }
469
+ for (const problem of applied.problems) {
470
+ if (problem.kind === "missing-required" && problem.key !== undefined) {
471
+ const input = [...card.required, ...card.optional].find((i) => i.key === problem.key);
472
+ out.questions.push({
473
+ elementId: line.elementId,
474
+ text: `"${element?.name ?? line.id}" needs ${input?.label ?? problem.key} for ${card.title}.`,
475
+ options: [],
476
+ draft: `${head} | ${problem.key}=`,
477
+ });
478
+ }
479
+ else {
480
+ out.problems.push({ line: line.line, message: problem.message });
481
+ }
482
+ }
483
+ }
484
+ return out;
485
+ }
486
+ function elementOf(definitions, id) {
487
+ return definitions.processes.flatMap((p) => p.flowElements).find((el) => el.id === id);
488
+ }
489
+ function child(ext, name) {
490
+ return ext?.find((x) => x.name === name);
491
+ }
492
+ /** What an element holds for each binding of a template, by property key. */
493
+ function readValues(definitions, element, template) {
494
+ const ext = element.extensionElements;
495
+ const inputs = new Map();
496
+ for (const c of child(ext, "zeebe:ioMapping")?.children ?? []) {
497
+ if (c.name === "zeebe:input" && c.attributes.target !== undefined) {
498
+ inputs.set(c.attributes.target, c.attributes.source ?? "");
499
+ }
500
+ }
501
+ const headers = new Map((child(ext, "zeebe:taskHeaders")?.children ?? []).map((c) => [
502
+ c.attributes.key ?? "",
503
+ c.attributes.value ?? "",
504
+ ]));
505
+ const properties = new Map((child(ext, "zeebe:properties")?.children ?? []).map((c) => [
506
+ c.attributes.name ?? "",
507
+ c.attributes.value ?? "",
508
+ ]));
509
+ const messageId = messageRefOf(element);
510
+ const message = definitions?.messages.find((m) => m.id === messageId);
511
+ const subscription = child(message?.extensionElements, "zeebe:subscription")?.attributes;
512
+ const values = {};
513
+ for (const prop of template.properties) {
514
+ const key = propertyKey(prop);
515
+ if (!key || key in values)
516
+ continue;
517
+ const b = prop.binding;
518
+ let value;
519
+ if (b.type === "zeebe:input")
520
+ value = inputs.get(b.name);
521
+ else if (b.type === "zeebe:taskHeader")
522
+ value = headers.get(b.key);
523
+ else if (b.type === "zeebe:property")
524
+ value = properties.get(b.name);
525
+ else if (b.type === "bpmn:Message#property" && b.name === "name")
526
+ value = message?.name;
527
+ else if (b.type === "bpmn:Message#zeebe:subscription#property")
528
+ value = subscription?.[b.name];
529
+ if (value !== undefined)
530
+ values[key] = value;
531
+ }
532
+ return values;
533
+ }
534
+ /**
535
+ * The `with` line that re-creates an element's connector, after `with <id>: `,
536
+ * or `undefined` when the element has no template this catalog knows.
537
+ *
538
+ * Written so a model reading a diagram (`writeProcessText`'s `connectorLine`
539
+ * option) keeps its connectors when it rewrites or changes it: the operation,
540
+ * and every input that differs from the template's default. Hidden and
541
+ * generated values are left out — applying the line sets them again.
542
+ */
543
+ export function connectorLineFor(element, definitions) {
544
+ const templateId = element.unknownAttributes["zeebe:modelerTemplate"];
545
+ const template = templateId === undefined ? undefined : getTemplate(templateId);
546
+ if (!templateId || !template)
547
+ return undefined;
548
+ const raw = readValues(definitions, element, template);
549
+ const card = connectorCards(templateId)
550
+ .filter((c) => Object.entries(c.values).every(([k, v]) => raw[k] === v))
551
+ .sort((a, b) => Object.keys(b.values).length - Object.keys(a.values).length)[0];
552
+ const fixed = card?.values ?? {};
553
+ const parts = [`${connectorAlias(templateId)}${card?.operation ? ` ${card.operation}` : ""}`];
554
+ const written = new Set();
555
+ for (const prop of activeProperties(template, raw)) {
556
+ const key = propertyKey(prop);
557
+ const value = raw[key];
558
+ if (!key || written.has(key) || key in fixed || value === undefined || prop.generatedValue) {
559
+ continue;
560
+ }
561
+ written.add(key);
562
+ if (prop.value !== undefined && String(prop.value) === value)
563
+ continue;
564
+ parts.push(`${key}=${value.replace(/\s+/g, " ").trim()}`);
565
+ }
566
+ return parts.join(" | ");
567
+ }
568
+ //# sourceMappingURL=lines.js.map