@bpmnkit/core 1.2.0 → 1.4.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 (51) hide show
  1. package/README.md +26 -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 +39 -5
  5. package/dist/bpmn/compact.js +151 -29
  6. package/dist/bpmn/connector-line.d.ts +46 -0
  7. package/dist/bpmn/connector-line.js +135 -0
  8. package/dist/bpmn/full-operations.js +8 -1
  9. package/dist/bpmn/optimize/patterns.js +1 -3
  10. package/dist/bpmn/process-delta.d.ts +7 -0
  11. package/dist/bpmn/process-delta.js +34 -2
  12. package/dist/bpmn/process-text-writer.d.ts +12 -2
  13. package/dist/bpmn/process-text-writer.js +16 -1
  14. package/dist/bpmn/process-text.d.ts +36 -1
  15. package/dist/bpmn/process-text.js +412 -17
  16. package/dist/bpmn/rest-connector.d.ts +6 -0
  17. package/dist/bpmn/rest-connector.js +6 -0
  18. package/dist/bpmn/secrets.d.ts +15 -0
  19. package/dist/bpmn/secrets.js +59 -0
  20. package/dist/bpmn/utils.js +4 -0
  21. package/dist/bpmn/zeebe-extensions.d.ts +10 -0
  22. package/dist/bpmn/zeebe-extensions.js +7 -0
  23. package/dist/connectors/aliases.d.ts +21 -0
  24. package/dist/connectors/aliases.js +272 -0
  25. package/dist/connectors/api.d.ts +118 -0
  26. package/dist/connectors/api.js +280 -0
  27. package/dist/connectors/apply-element.d.ts +59 -0
  28. package/dist/connectors/apply-element.js +385 -0
  29. package/dist/connectors/apply.d.ts +136 -0
  30. package/dist/connectors/apply.js +352 -0
  31. package/dist/connectors/cards.d.ts +96 -0
  32. package/dist/connectors/cards.js +306 -0
  33. package/dist/connectors/catalog.d.ts +79 -0
  34. package/dist/connectors/catalog.js +209 -0
  35. package/dist/connectors/index.d.ts +33 -0
  36. package/dist/connectors/index.js +24 -0
  37. package/dist/connectors/lines.d.ts +108 -0
  38. package/dist/connectors/lines.js +568 -0
  39. package/dist/connectors/select.d.ts +85 -0
  40. package/dist/connectors/select.js +419 -0
  41. package/dist/connectors/template-types.d.ts +188 -0
  42. package/dist/connectors/template-types.js +6 -0
  43. package/dist/connectors/templates/bpmnkit.d.ts +12 -0
  44. package/dist/connectors/templates/bpmnkit.js +186 -0
  45. package/dist/connectors/templates/generated.d.ts +3 -0
  46. package/dist/connectors/templates/generated.js +95885 -0
  47. package/dist/connectors/validate.d.ts +66 -0
  48. package/dist/connectors/validate.js +271 -0
  49. package/dist/index.d.ts +7 -3
  50. package/dist/index.js +2 -0
  51. package/package.json +5 -1
@@ -0,0 +1,280 @@
1
+ /**
2
+ * API cards: the real endpoints of an HTTP API, for the REST connector.
3
+ *
4
+ * A dedicated connector is the first choice for a system. When there is none —
5
+ * Stripe, Notion, most of the long tail — the REST connector can still call
6
+ * the system, but only with the right base URL, path and authentication. These
7
+ * come from an index of the APIs' OpenAPI specs, built offline into
8
+ * `@bpmnkit/connector-gen/api-index`. That index is too large for core, so
9
+ * core has only its shape and works on the services a caller loaded.
10
+ */
11
+ import { searchTerms } from "./cards.js";
12
+ /** The word that names a service: `twilio-voice` → `twilio`. */
13
+ export function apiBrand(id) {
14
+ return id.split("-")[0] ?? id;
15
+ }
16
+ /** Brands that are also everyday words: they name the service only as "<brand> API". */
17
+ const EVERYDAY = new Set(["box", "square", "replicate", "docker", "copper", "gusto", "nasa"]);
18
+ function lowerWords(text) {
19
+ return text.toLowerCase().split(/[^a-z0-9]+/);
20
+ }
21
+ /**
22
+ * The services a text names, by id: "Charge the card with Stripe" names
23
+ * `stripe`; "Send an SMS via Twilio" names every Twilio service.
24
+ */
25
+ export function apiServicesIn(text, services) {
26
+ const words = lowerWords(text);
27
+ const present = new Set(words);
28
+ return services
29
+ .filter((s) => {
30
+ const brand = apiBrand(s.id);
31
+ if (!present.has(brand))
32
+ return false;
33
+ if (!EVERYDAY.has(brand))
34
+ return true;
35
+ return words.some((w, i) => w === brand && words[i + 1] === "api");
36
+ })
37
+ .map((s) => s.id);
38
+ }
39
+ /** The method a verb asks for. */
40
+ const VERB_METHOD = {
41
+ create: "POST",
42
+ add: "POST",
43
+ new: "POST",
44
+ post: "POST",
45
+ send: "POST",
46
+ submit: "POST",
47
+ list: "GET",
48
+ get: "GET",
49
+ fetch: "GET",
50
+ read: "GET",
51
+ find: "GET",
52
+ search: "GET",
53
+ retrieve: "GET",
54
+ load: "GET",
55
+ look: "GET",
56
+ update: "PATCH",
57
+ change: "PATCH",
58
+ edit: "PATCH",
59
+ set: "PATCH",
60
+ delete: "DELETE",
61
+ remove: "DELETE",
62
+ };
63
+ /** `issues` and `issue` are one word for matching. */
64
+ function stem(word) {
65
+ if (word.length > 4 && word.endsWith("ies"))
66
+ return `${word.slice(0, -3)}y`;
67
+ if (word.length > 3 && word.endsWith("s") && !word.endsWith("ss"))
68
+ return word.slice(0, -1);
69
+ return word;
70
+ }
71
+ function stems(text) {
72
+ return new Set(searchTerms(text).map(stem));
73
+ }
74
+ function pathWords(path) {
75
+ return stems(path.replace(/\{[^}]*\}/g, " ").replace(/[_/-]+/g, " "));
76
+ }
77
+ /**
78
+ * The operations of a service that best fit a task name, best first: words of
79
+ * the summary count most, then of the path, then of the operation id, and a
80
+ * verb that asks for the operation's method ("Create" → POST) adds to it, as
81
+ * does a path that ends in a word of the text, and each word of the path the
82
+ * text does not have takes one off. Without a verb, POST is preferred. An operation
83
+ * needs a word other than a verb in common. Shorter paths win ties.
84
+ */
85
+ export function rankApiOperations(service, text) {
86
+ // "GitHub" is also searched as git and hub: none of them tells one operation from another
87
+ const brand = new Set([
88
+ ...lowerWords(`${service.id} ${service.name}`).map(stem),
89
+ ...stems(`${service.id} ${service.name}`),
90
+ ]);
91
+ const terms = [...stems(text)].filter((t) => !brand.has(t));
92
+ const methods = new Set(terms.map((t) => VERB_METHOD[t]).filter((m) => m !== undefined));
93
+ const content = terms.filter((t) => VERB_METHOD[t] === undefined);
94
+ if (content.length === 0)
95
+ return [];
96
+ const words = service.operations.map((op) => ({
97
+ op,
98
+ summary: stems(op.summary ?? ""),
99
+ path: pathWords(op.path),
100
+ id: stems(op.id ?? ""),
101
+ }));
102
+ // A word in a tenth of the service's operations or more names an area, not an operation:
103
+ // "GitHub Actions" is in hundreds of GitHub's summaries, "runs" in a few
104
+ const common = new Set(content.filter((term) => words.filter((w) => w.summary.has(term) || w.path.has(term)).length * 10 >=
105
+ Math.max(20, words.length)));
106
+ const ranked = [];
107
+ for (const { op, summary, path, id } of words) {
108
+ let hits = 0;
109
+ let score = 0;
110
+ for (const term of content) {
111
+ const s = summary.has(term) ? 3 : path.has(term) ? 2 : id.has(term) ? 1 : 0;
112
+ if (s > 0)
113
+ hits++;
114
+ score += common.has(term) ? s / 3 : s;
115
+ }
116
+ if (hits === 0)
117
+ continue;
118
+ for (const term of terms)
119
+ if (VERB_METHOD[term] !== undefined && summary.has(term))
120
+ score += 1;
121
+ if (methods.has(op.method))
122
+ score += 2;
123
+ // A task without a verb that reads acts: "Refund payment" posts a refund
124
+ else if (methods.size === 0 && op.method === "POST")
125
+ score += 1;
126
+ // The resource itself: "Refund payment" is /v1/refunds more than /…/refund_payment
127
+ const last = op.path
128
+ .split("/")
129
+ .filter((p) => p !== "" && !p.startsWith("{"))
130
+ .at(-1);
131
+ if (last !== undefined && content.includes(stem(last.toLowerCase())))
132
+ score += 2;
133
+ // A path the task does not describe is a more specific operation than it asks for:
134
+ // "Refund payment" is POST /v1/refunds, not /v1/terminal/readers/{reader}/refund_payment
135
+ const known = new Set(terms);
136
+ for (const word of path)
137
+ if (!known.has(word) && !/^v?\d+$/.test(word))
138
+ score -= 1;
139
+ ranked.push({ op, score, hits });
140
+ }
141
+ return ranked.sort((a, b) => b.score - a.score ||
142
+ a.op.path.split("/").length - b.op.path.split("/").length ||
143
+ a.op.path.length - b.op.path.length);
144
+ }
145
+ /** The operations of {@link rankApiOperations}, best first. */
146
+ export function findApiOperations(service, text, options = {}) {
147
+ return rankApiOperations(service, text)
148
+ .slice(0, options.limit ?? 3)
149
+ .map((r) => r.op);
150
+ }
151
+ /** The secret names a service's credentials go by: `STRIPE_TOKEN`. */
152
+ export function apiSecretNames(service) {
153
+ const prefix = service.id.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
154
+ switch (service.auth.type) {
155
+ case "bearer":
156
+ return { "authentication.token": `${prefix}_TOKEN` };
157
+ case "apiKey":
158
+ return { "authentication.value": `${prefix}_API_KEY` };
159
+ case "basic":
160
+ return {
161
+ "authentication.username": `${prefix}_USERNAME`,
162
+ "authentication.password": `${prefix}_PASSWORD`,
163
+ };
164
+ case "oauth-client-credentials-flow":
165
+ return { "authentication.clientSecret": `${prefix}_CLIENT_SECRET` };
166
+ default:
167
+ return {};
168
+ }
169
+ }
170
+ /** The REST connector's authentication inputs for a service, credentials as secrets. */
171
+ export function apiAuthValues(service) {
172
+ const values = { "authentication.type": service.auth.type };
173
+ if (service.auth.type === "apiKey") {
174
+ values["authentication.apiKeyLocation"] = service.auth.in === "query" ? "query" : "headers";
175
+ values["authentication.name"] = service.auth.name;
176
+ }
177
+ for (const [key, name] of Object.entries(apiSecretNames(service))) {
178
+ values[key] = `{{secrets.${name}}}`;
179
+ }
180
+ return values;
181
+ }
182
+ function authText(service) {
183
+ const secrets = Object.values(apiSecretNames(service));
184
+ const auth = service.auth.type === "apiKey"
185
+ ? `auth=apiKey(${service.auth.in} ${service.auth.name})`
186
+ : `auth=${service.auth.type}`;
187
+ return secrets.length > 0 ? `${auth} secret=${secrets.join(",")}` : auth;
188
+ }
189
+ /** One operation as a card line: `POST /v1/customers — Create a customer | form body: name email`. */
190
+ export function formatApiOperation(op) {
191
+ const parts = [
192
+ `${op.method} ${op.path}${op.summary ? ` — ${op.summary}` : op.id ? ` — ${op.id}` : ""}`,
193
+ ];
194
+ if (op.query?.length)
195
+ parts.push(`query: ${op.query.join(" ")}`);
196
+ if (op.body?.length)
197
+ parts.push(`${op.form ? "form body" : "body"}: ${op.body.join(" ")}`);
198
+ if (op.headers?.length)
199
+ parts.push(`headers: ${op.headers.join(", ")}`);
200
+ return parts.join(" | ");
201
+ }
202
+ /**
203
+ * A service and its picked operations as a prompt block:
204
+ *
205
+ * ```
206
+ * api stripe — Stripe API https://api.stripe.com auth=bearer secret=STRIPE_TOKEN
207
+ * POST /v1/customers — Create a customer | form body: name email description
208
+ * ```
209
+ *
210
+ * A service without a fixed host says so: its URL is the reader's to give.
211
+ */
212
+ export function formatApiCard(card) {
213
+ const { service } = card;
214
+ const base = service.baseUrl ?? "(base URL: the account's own)";
215
+ return [
216
+ `api ${service.id} — ${service.name} ${base} ${authText(service)}`,
217
+ ...card.operations.map(formatApiOperation),
218
+ ].join("\n");
219
+ }
220
+ function pathPattern(path) {
221
+ const escaped = path
222
+ .split(/\{[^}]*\}/)
223
+ .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
224
+ .join("[^/]+");
225
+ return new RegExp(`^${escaped}/?$`);
226
+ }
227
+ /**
228
+ * The operation of a service a call names, by method and path. The path may be
229
+ * the spec's (`/repos/{owner}/{repo}/issues`) or filled in (`/repos/acme/web/issues`).
230
+ */
231
+ export function findApiOperation(service, method, path) {
232
+ const bare = path.split("?")[0] ?? path;
233
+ const upper = method.toUpperCase();
234
+ const same = service.operations.filter((op) => op.method === upper);
235
+ return same.find((op) => op.path === bare) ?? same.find((op) => pathPattern(op.path).test(bare));
236
+ }
237
+ const FEEL_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
238
+ /**
239
+ * A URL for the REST connector: the base URL and the path, each `{param}` of
240
+ * the path read from the process variable of the same name —
241
+ * `="https://api.github.com/repos/" + string(owner) + "/" + string(repo) + "/issues"`.
242
+ * A path without parameters stays a literal URL.
243
+ */
244
+ export function apiUrl(baseUrl, path) {
245
+ const parts = path.split(/(\{[^}]*\})/).filter((p) => p !== "");
246
+ if (!parts.some((p) => p.startsWith("{")))
247
+ return `${baseUrl}${path}`;
248
+ const terms = [];
249
+ let literal = baseUrl;
250
+ for (const part of parts) {
251
+ const name = /^\{([^}]*)\}$/.exec(part)?.[1];
252
+ if (name !== undefined && FEEL_NAME.test(name)) {
253
+ terms.push(JSON.stringify(literal), `string(${name})`);
254
+ literal = "";
255
+ }
256
+ else {
257
+ literal += part;
258
+ }
259
+ }
260
+ if (literal !== "")
261
+ terms.push(JSON.stringify(literal));
262
+ return `=${terms.filter((t) => t !== '""').join(" + ")}`;
263
+ }
264
+ /** The headers an operation needs besides authentication, as a FEEL context; `undefined` when none. */
265
+ export function apiHeaders(op) {
266
+ const entries = [];
267
+ const missing = [];
268
+ if (op.form)
269
+ entries.push(`"Content-Type": "application/x-www-form-urlencoded"`);
270
+ for (const header of op.headers ?? []) {
271
+ const colon = header.indexOf(":");
272
+ if (colon < 0)
273
+ missing.push(header);
274
+ else {
275
+ entries.push(`${JSON.stringify(header.slice(0, colon).trim())}: ${JSON.stringify(header.slice(colon + 1).trim())}`);
276
+ }
277
+ }
278
+ return entries.length > 0 ? { headers: `={${entries.join(", ")}}`, missing } : { missing };
279
+ }
280
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Applying an element template to an element of a parsed model.
3
+ *
4
+ * `applyElementTemplate` answers with builder options, which is enough for an
5
+ * outbound task built from scratch. An inbound connector is not: its message
6
+ * name and correlation key live on a root `bpmn:message` the event references,
7
+ * and an RPA task's scripts on `zeebe:linkedResources` — places no builder
8
+ * option reaches. This writes all of it onto an element that already exists.
9
+ */
10
+ import type { BpmnDefinitions, BpmnFlowElement } from "../index.js";
11
+ import { type ApplyProblem } from "./apply.js";
12
+ import type { ElementTemplate } from "./template-types.js";
13
+ /** The one `elementType.eventDefinition` this toolkit writes. */
14
+ export declare const APPLIED_EVENT_DEFINITION = "bpmn:MessageEventDefinition";
15
+ /** The result of {@link applyTemplateToElement}. */
16
+ export interface ApplyToElementResult {
17
+ /**
18
+ * The model with the template applied — a copy; the input is never mutated.
19
+ * When the element is missing or the template does not apply to it, this is
20
+ * the input, unchanged, and `problems` says why.
21
+ */
22
+ definitions: BpmnDefinitions;
23
+ /** Same meaning as `ApplyResult.problems`, plus anything that stopped a write. */
24
+ problems: ApplyProblem[];
25
+ }
26
+ /** The id of the root message an element references, if any. */
27
+ export declare function messageRefOf(element: BpmnFlowElement): string | undefined;
28
+ /**
29
+ * Applies an element template to one element of a parsed model — every binding
30
+ * kind, including the inbound ones builder options cannot carry.
31
+ *
32
+ * - **Element type.** `elementType` converts the element (keeping its id and
33
+ * wiring), and `elementType.eventDefinition` makes an event a message event.
34
+ * A template whose `appliesTo` does not cover the element is refused.
35
+ * - **Messages.** `bpmn:Message#property` names the root `bpmn:message` the
36
+ * event definition or receive task references — reusing one already carrying
37
+ * that name, renaming the element's own when nothing else uses it, creating
38
+ * one otherwise. `bpmn:Message#zeebe:subscription#property` writes that
39
+ * message's `zeebe:subscription`, which is where Camunda reads the
40
+ * correlation key; one left on the element itself is removed.
41
+ * - **Generated values.** A property with `generatedValue` and no value — the
42
+ * inbound message name — keeps the name of the message the element already
43
+ * references, and is otherwise derived from the template and element ids,
44
+ * never from a clock or random source.
45
+ * - **Extensions.** `zeebe:taskDefinition`, `ioMapping`, `taskHeaders`,
46
+ * `properties`, `adHoc` and `linkedResources` are replaced wholesale when the
47
+ * template declares a binding of that kind, in place, and left alone when it
48
+ * does not. `zeebe:modelerTemplate`, `…Version` and `…Icon` are stamped.
49
+ *
50
+ * Deterministic and idempotent: the same model, template and values give the
51
+ * same XML, and applying twice gives the same model as applying once.
52
+ *
53
+ * @param definitions - The model; not mutated.
54
+ * @param elementId - A flow element anywhere in its processes, sub-processes included.
55
+ * @param template - Any element template, bundled or a workspace's own.
56
+ * @param values - Keyed as in {@link applyElementTemplate}; `name` sets the element's name.
57
+ */
58
+ export declare function applyTemplateToElement(definitions: BpmnDefinitions, elementId: string, template: ElementTemplate, values?: Record<string, string>): ApplyToElementResult;
59
+ //# sourceMappingURL=apply-element.d.ts.map