suppa-mcp-2 1.43.5 → 1.44.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.
- package/README.md +45 -0
- package/dist/server.js +6 -4
- package/dist/tools/automation.js +29 -1
- package/package.json +1 -1
- package/skills/building-suppa-automations/SKILL.md +185 -0
- package/skills/building-suppa-automations/references/node-reference.md +76 -0
- package/skills/building-suppa-automations/references/publishing.md +41 -0
- package/skills/building-suppa-automations/references/tenant-time.md +43 -0
- package/skills/building-suppa-automations/scripts/auto-layout.mjs +201 -0
- package/skills/building-suppa-automations/scripts/edges.mjs +55 -0
- package/skills/building-suppa-automations/scripts/geometry.mjs +30 -0
- package/skills/building-suppa-automations/scripts/graph-hash.mjs +22 -0
- package/skills/building-suppa-automations/scripts/graph.mjs +21 -0
- package/skills/building-suppa-automations/scripts/layout-check.mjs +9 -0
- package/skills/building-suppa-automations/scripts/layout.mjs +45 -0
- package/skills/building-suppa-automations/scripts/lint-graph.mjs +207 -0
- package/skills/building-suppa-automations/scripts/render-graph.mjs +77 -0
package/README.md
CHANGED
|
@@ -528,6 +528,9 @@ extension table is created outside that check and is not subject to it.
|
|
|
528
528
|
| `suppa_publish_automation` | Publish the draft snapshot (confirm-gated) |
|
|
529
529
|
| `suppa_unpublish_automation` | Deactivate an automation (confirm-gated) |
|
|
530
530
|
|
|
531
|
+
Designing, laying out or optimizing an automation before writing it: the bundled
|
|
532
|
+
`skills/building-suppa-automations` skill (see below).
|
|
533
|
+
|
|
531
534
|
### Forms
|
|
532
535
|
|
|
533
536
|
| Tool | Description |
|
|
@@ -701,6 +704,47 @@ covered; see `references/tabular-parts.md` and `references/registration.md`.
|
|
|
701
704
|
|
|
702
705
|
---
|
|
703
706
|
|
|
707
|
+
## Bundled agent skill: building-suppa-automations
|
|
708
|
+
|
|
709
|
+
`skills/building-suppa-automations/` builds a Suppa 2.0 automation (AutomationWorkflow)
|
|
710
|
+
as a **source you regenerate**, not by hand in the builder, so the canvas reads as the
|
|
711
|
+
process when someone opens it:
|
|
712
|
+
|
|
713
|
+
- **One automation per process.** Several flows can share it, each with its own trigger.
|
|
714
|
+
Loop protection is keyed by workflow id, so splitting one process across
|
|
715
|
+
automations is what produces duplicate runs.
|
|
716
|
+
- **English, numbered node names** (`A5.1 Wait for head approval`). Expressions address
|
|
717
|
+
nodes by name.
|
|
718
|
+
- **Straight-edge layout**, computed from the builder's measured handle offsets.
|
|
719
|
+
- **Lean graphs:**
|
|
720
|
+
- filter in the trigger;
|
|
721
|
+
- one read per entity per flow;
|
|
722
|
+
- request and form flows take what the submission already carries (`formData`,
|
|
723
|
+
`number`, `createdBy`) instead of selecting it again;
|
|
724
|
+
- business rules are visible on the canvas, technical logic goes into one `code` node.
|
|
725
|
+
- **Publishing that survives the builder.** It writes through the API with the builder
|
|
726
|
+
tab closed, verifies the draft by hash, then publishes and tests a live run.
|
|
727
|
+
|
|
728
|
+
The scripts need only Node ≥ 18. They read `{ nodes, connections, settings? }` in the
|
|
729
|
+
stored shape — what `suppa_update_automation` takes — or a `suppa_get_automation` answer
|
|
730
|
+
as is, and write the stored shape. `suppa_health_check` → `skill_files.automations_skill`
|
|
731
|
+
names the installed folder:
|
|
732
|
+
|
|
733
|
+
```bash
|
|
734
|
+
S=node_modules/suppa-mcp-2/skills/building-suppa-automations/scripts
|
|
735
|
+
node $S/lint-graph.mjs graph.json # ERROR / WARN / NOTE; exit 1 on an ERROR
|
|
736
|
+
node $S/auto-layout.mjs graph.json > placed.json # places every node, repairs crossings
|
|
737
|
+
node $S/layout-check.mjs placed.json # must list no problem (exit 0)
|
|
738
|
+
node $S/render-graph.mjs placed.json preview.svg --png preview.png # look before publishing
|
|
739
|
+
```
|
|
740
|
+
|
|
741
|
+
`references/node-reference.md` holds the parameter shapes verified on running
|
|
742
|
+
automations: triggers, conditions, switch outputs, approvals, links, the request
|
|
743
|
+
trigger's output. `references/publishing.md` holds the write → hash → publish → live-test
|
|
744
|
+
order.
|
|
745
|
+
|
|
746
|
+
---
|
|
747
|
+
|
|
704
748
|
## Development
|
|
705
749
|
|
|
706
750
|
```bash
|
|
@@ -791,6 +835,7 @@ suppa-mcp-node/
|
|
|
791
835
|
│ ├── migrate.ts nameMap.ts v1Fields.ts
|
|
792
836
|
│ └── workspace.ts
|
|
793
837
|
├── skills/suppa-entity-code/ # bundled agent skill: write v2 schema code + validator
|
|
838
|
+
├── skills/building-suppa-automations/ # bundled agent skill: design, lay out, lint and publish automations
|
|
794
839
|
├── test/ # vitest suite (ports the Python test suite)
|
|
795
840
|
├── scripts/ # live read-only / write verify scripts
|
|
796
841
|
├── package.json
|
package/dist/server.js
CHANGED
|
@@ -2076,8 +2076,9 @@ export function buildToolTable() {
|
|
|
2076
2076
|
}, async (a) => text(await automation.listAutomations(a.search, a.is_active, a.limit, a.offset)));
|
|
2077
2077
|
reg("suppa_get_automation", {
|
|
2078
2078
|
description: "Get one automation workflow as a normalized graph: nodes + edges, settings,\n" +
|
|
2079
|
-
" and the published snapshot. nodes [{id,type,name,config,position}], edges\n" +
|
|
2080
|
-
' [{from,fromHandle,to,toIndex}], under "published". Distinct from Task workflows
|
|
2079
|
+
" and the published snapshot. nodes [{id,type,name,config,position,…other keys}], edges\n" +
|
|
2080
|
+
' [{from,fromHandle,to,toIndex}], under "published". Distinct from Task workflows.\n' +
|
|
2081
|
+
" Design / reshape: skill building-suppa-automations (suppa_health_check names its folder).",
|
|
2081
2082
|
inputSchema: { automation_id: AutomationId },
|
|
2082
2083
|
annotations: _READ,
|
|
2083
2084
|
}, async (a) => text(await automation.getAutomation(a.automation_id)));
|
|
@@ -2139,8 +2140,7 @@ export function buildToolTable() {
|
|
|
2139
2140
|
name: z.string().describe("Automation name."),
|
|
2140
2141
|
nodes_json: z
|
|
2141
2142
|
.string()
|
|
2142
|
-
.describe('JSON array of nodes: [{"id","type","parameters":{...}}].
|
|
2143
|
-
"trigger (triggerEntity/triggerManual/triggerWebhook)."),
|
|
2143
|
+
.describe('JSON array of nodes: [{"id","type","name","parameters":{...},"position"}].'),
|
|
2144
2144
|
connections_json: z
|
|
2145
2145
|
.string()
|
|
2146
2146
|
.describe('JSON object of connections: {"srcNodeId": {"handle": [{"node": "targetId", "index": 0}]}}.'),
|
|
@@ -3107,6 +3107,8 @@ async function healthCheck(deep = true) {
|
|
|
3107
3107
|
form_v2_cell_rules: await formV2.cellRulesStatus(),
|
|
3108
3108
|
entity_code_validator: await entityCode.validatorStatus(),
|
|
3109
3109
|
sql_skill: sqlKb.sqlSkillFile("SKILL.md") && sqlKb.sqlSkillFile("references") ? "present" : "MISSING",
|
|
3110
|
+
// A path, not "present": the skill is files an agent reads and scripts it runs by path.
|
|
3111
|
+
automations_skill: automation.automationsSkillDir() ?? "MISSING",
|
|
3110
3112
|
},
|
|
3111
3113
|
};
|
|
3112
3114
|
if (!token) {
|
package/dist/tools/automation.js
CHANGED
|
@@ -9,8 +9,25 @@
|
|
|
9
9
|
* present, and is otherwise DERIVED from the `nodes` JSON of live workflows.
|
|
10
10
|
*/
|
|
11
11
|
import { makeRequest, searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, } from "../httpClient.js";
|
|
12
|
+
import { existsSync } from "node:fs";
|
|
13
|
+
import { dirname, join } from "node:path";
|
|
14
|
+
import { fileURLToPath } from "node:url";
|
|
12
15
|
import { ownProjection } from "../projection.js";
|
|
13
16
|
import { makeFilter, jsonResponse, parseJsonParam, ACCESS_METADATA_KEYS, confirmRequired } from "../utils.js";
|
|
17
|
+
/**
|
|
18
|
+
* The bundled building-suppa-automations skill folder, from dist/tools/ or src/tools/ alike — what
|
|
19
|
+
* suppa_health_check names, so an agent on an npx or plugin install (no node_modules of its own)
|
|
20
|
+
* can find the SKILL.md and run the scripts by path.
|
|
21
|
+
*/
|
|
22
|
+
export function automationsSkillDir() {
|
|
23
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
24
|
+
for (const root of [join(here, "..", ".."), join(here, "..", "..", "..")]) {
|
|
25
|
+
const p = join(root, "skills", "building-suppa-automations");
|
|
26
|
+
if (existsSync(join(p, "SKILL.md")) && existsSync(join(p, "scripts", "lint-graph.mjs")))
|
|
27
|
+
return p;
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
14
31
|
export const WORKFLOW_ENTITY = "AutomationWorkflow";
|
|
15
32
|
export const EXECUTE_ENTITY = "AutomationWorkflowExecute";
|
|
16
33
|
export const EXECUTE_DATA_ENTITY = "AutomationWorkflowExecuteData";
|
|
@@ -174,7 +191,14 @@ function _normalizeNodes(nodes) {
|
|
|
174
191
|
}
|
|
175
192
|
return [];
|
|
176
193
|
}
|
|
177
|
-
|
|
194
|
+
// Keys _normalizeNode reads into id/type/name/config/position; every OTHER node key is kept verbatim.
|
|
195
|
+
const _NODE_KEYS_READ = new Set(["id", "type", "nodeType", "kind", "name", "position", "parameters", "config", "data"]);
|
|
196
|
+
/**
|
|
197
|
+
* Raw node -> {id, type, name?, config, position?, ...other node keys}. config = parameters verbatim.
|
|
198
|
+
* The other keys (a merge's inputCount, onError) live beside parameters on the stored node; dropping
|
|
199
|
+
* them made a read -> edit -> suppa_update_automation round trip lose them with no error (live on
|
|
200
|
+
* modern-expo.test, 2026-10-26: automation 160's merge node carries inputCount 2).
|
|
201
|
+
*/
|
|
178
202
|
function _normalizeNode(raw) {
|
|
179
203
|
const node = { id: raw.id ?? null, type: _nodeType(raw), config: _nodeConfig(raw) };
|
|
180
204
|
if (raw.name !== null && raw.name !== undefined) {
|
|
@@ -183,6 +207,10 @@ function _normalizeNode(raw) {
|
|
|
183
207
|
if (raw.position !== null && raw.position !== undefined) {
|
|
184
208
|
node.position = raw.position;
|
|
185
209
|
}
|
|
210
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
211
|
+
if (!_NODE_KEYS_READ.has(k) && v !== undefined)
|
|
212
|
+
node[k] = v;
|
|
213
|
+
}
|
|
186
214
|
return node;
|
|
187
215
|
}
|
|
188
216
|
/** Flatten {src: {handle: [{node, index}]}} -> [{from, fromHandle, to, toIndex}]. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "suppa-mcp-2",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.44.0",
|
|
4
4
|
"description": "MCP server for the Suppa platform (modern.suppa.me) — Tasks, Docs/Pages, Entities & Schema, Forms, Automations, and file attachments, with multi-tenant Google auth. Node port of PyPI suppa-mcp.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: building-suppa-automations
|
|
3
|
+
description: Use when creating, restructuring, renaming, laying out or optimizing a Suppa 2.0 automation (AutomationWorkflow nodes / connections / settings, workflow-builder canvas) — a new business process to automate, a messy or unreadable canvas, crooked edges, unclear node names, idle or duplicate runs, several automations serving one process, or porting a 1.0 BP template.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Building Suppa Automations
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Build an automation as a **source you regenerate** (a script that writes nodes, connections and settings), not by hand in the builder. Three goals: **English, numbered names** that read as the flow; a **layout where edges are straight**; and **no wasted runs or duplicate side effects**.
|
|
11
|
+
|
|
12
|
+
Parameter shapes (triggers, conditions, switch outputs, approvals, links) are in `references/node-reference.md`. Never guess them: `events: ["update"]`, `watchFields: ["stageId"]`, `{ "and": [...] }` and switch outputs `"0"/"1"` are all wrong.
|
|
13
|
+
|
|
14
|
+
## Workflow
|
|
15
|
+
|
|
16
|
+
`scripts/` sits next to this file: `suppa_health_check` → `skill_files.automations_skill` names the installed folder (an npm install: `node_modules/suppa-mcp-2/skills/building-suppa-automations/`). The scripts need only Node ≥ 18. `graph.json` is either shape:
|
|
17
|
+
- the stored one, `{ nodes, connections, settings? }`: nodes carry `parameters`, connections are `{ source: { handle: [{ node, index }] } }`. That is what `suppa_update_automation` takes in `nodes_json` / `connections_json`, and what `auto-layout` / `layout` write;
|
|
18
|
+
- a `suppa_get_automation` answer as is (`nodes[].config` + `edges`): the scripts read its draft side, `--previous` its `published` side.
|
|
19
|
+
|
|
20
|
+
1. Design the flows with the checklist below. Write the build script (ids, names, parameters, settings), never the builder UI.
|
|
21
|
+
2. `node scripts/lint-graph.mjs graph.json`
|
|
22
|
+
- Fix every ERROR: a `$('…')` that names no node or a node that has not run yet, `$()` inside `code`, wiped approvers, unreachable nodes, wrong output handles.
|
|
23
|
+
- Fix every WARN.
|
|
24
|
+
- Answer each NOTE: either it is intended or you fix it.
|
|
25
|
+
3. `node scripts/auto-layout.mjs graph.json > placed.json`. It places every node with no hand-written spec and repairs what the edge model flags. Hand-tune with `scripts/layout.mjs` only when you must.
|
|
26
|
+
4. `node scripts/layout-check.mjs placed.json` has to list no problem (exit 0).
|
|
27
|
+
5. `node scripts/render-graph.mjs placed.json preview.svg --png preview.png`. Look at the picture before publishing.
|
|
28
|
+
6. Publish and test (`references/publishing.md`).
|
|
29
|
+
|
|
30
|
+
## One process = one automation
|
|
31
|
+
|
|
32
|
+
- **One automation per business process.** It may hold **several flows, each with its own trigger**, for example A for a form submission and B for a task stage change. The engine matches every trigger node separately and starts the run at the one that fired. Do not split a process into automations because "a workflow has one entry point" — it does not.
|
|
33
|
+
- **Loop protection is keyed by workflow id.** A write from flow A never starts flow B of the same automation. A write from another automation does start it. So:
|
|
34
|
+
- inside one automation, the flow that writes does its own follow-up (mark the request rejected, notify);
|
|
35
|
+
- across automations, the same write runs twice. That is the classic duplicate notification.
|
|
36
|
+
- **Settings live in the automation.** Put everything tenant-specific in `settings.<key>`: people, project and stage ids, BP switches, testMode. Each flow reads it with `getById AutomationWorkflow id: "={{ $workflow.id }}"` → `activeSettings`. Do not keep a separate settings record or select.
|
|
37
|
+
|
|
38
|
+
## Requests and form submissions: the trigger already holds the data
|
|
39
|
+
|
|
40
|
+
A request (Requests module) **is** a `FormSubmissions` row. Its automation starts from `formSubmission { formId }`. The trigger emits the whole row, with `number` and `requestType` already stamped by the before-insert hook:
|
|
41
|
+
|
|
42
|
+
| Field | Value |
|
|
43
|
+
|---|---|
|
|
44
|
+
| `id`, `number` (`REQ-000035`), `state`, `createdAt` | the request itself |
|
|
45
|
+
| `requestType`, `form` | `{ id, title }`, `{ id, name }` |
|
|
46
|
+
| `createdBy` | `{ id, fullName }` — the submitter |
|
|
47
|
+
| `formData.<key>` | what the user entered: text, numbers, date strings, option values (`"Lutsk"`), arrays for multi-selects and files, **relations as `{ id }` only** (`customer: { id: 72 }`) |
|
|
48
|
+
|
|
49
|
+
**Before adding any read in a request or form flow, look for the value in the trigger first.** Read it as `$('A1. Start…').first().json.formData.<key>`, `….number`, `….createdBy.fullName`.
|
|
50
|
+
- **No read needed:**
|
|
51
|
+
- writing a picked relation (`customer: "={{ { id: F.customer.id } }}"`);
|
|
52
|
+
- an approver or notification recipient (user `id`);
|
|
53
|
+
- a filter by id;
|
|
54
|
+
- a text value in a title or description;
|
|
55
|
+
- an `if` / `switch` on an option the user picked;
|
|
56
|
+
- the submitter's name, the request number.
|
|
57
|
+
- **A read is needed only for what `formData` lacks:**
|
|
58
|
+
- other fields of a picked record: its name, department, head, or the user behind an employee;
|
|
59
|
+
- related records the form does not show.
|
|
60
|
+
The request's own `FormSubmissions` row is never re-read: the trigger is that row.
|
|
61
|
+
- `formData` keys are the form's element keys and are form-specific; typos stay (`descriptoin`). Take them from a real run's trigger output (`suppa_get_automation_run`, step 0) or from the form schema, never by guessing from labels.
|
|
62
|
+
- In a stage-change flow (B) the trigger is the task, not the request. Reach the request through the link the request flow wrote (`EntityLinks`, `request-fulfilment`), and read it once there. Or, cheaper, have flow A copy what B needs onto the task when it creates it.
|
|
63
|
+
|
|
64
|
+
## Names
|
|
65
|
+
|
|
66
|
+
| Element | Rule | Example |
|
|
67
|
+
|---|---|---|
|
|
68
|
+
| node `id` | readable kebab-case; connections use ids | `create-task`, `approve-head` |
|
|
69
|
+
| node `name` | English. Flow letter + step number + an action that says what happens. Business label before the BP code | `A4. Create task`, `A5.1 Wait for head approval`, `A6.1 Equipment (BP 006): deadline = +2 working days`, `B3.6 Rejected: notify submitter` |
|
|
70
|
+
| step numbers | One major number per phase (start, lookups, decide, create, approve, after approval). Its nodes in a row take `.1`, `.2`, … | `A5. Head approval needed?` → `A5.1 Wait for head approval` → `A5.2 …` → `A5.3 Move task to Rejected` |
|
|
71
|
+
| branch nodes | Every node of one branch keeps that branch's number and label | `A6.1 Equipment (BP 006): load holidays` → `A6.1 Equipment (BP 006): hand over to supervisor` |
|
|
72
|
+
| descriptions, messages | the users' language | — |
|
|
73
|
+
| notification templates | `subjectTemplate` and `bodyTemplate` carry the users' language (`uk`) next to `en`: the recipient reads the one their profile is set to | `{ "uk": "Заявку прийнято", "en": "Request accepted" }` |
|
|
74
|
+
|
|
75
|
+
- Expressions address nodes by **name** (`$('A4. Create task')`). Renaming a node means rewriting every `$('old')` and every `«old»` in code comments, inside the same automation.
|
|
76
|
+
- No ASCII apostrophe (`'`) in names, because it breaks `$('…')`. Use `ʼ`.
|
|
77
|
+
- The node registry has no notes field. Put the step-by-step guide («як читати схему») at the top of the automation `description`, keyed by the same step numbers.
|
|
78
|
+
|
|
79
|
+
## Layout
|
|
80
|
+
|
|
81
|
+
Edges are step lines from an **output handle** to an **input handle**. An edge is straight only when both handles have the same y. Same-sized boxes in one row are **not** enough: `if` and `approval` outputs sit 5 px and 29 px below their input, and `switch` outputs are 24 px apart. The measured offsets are in `scripts/geometry.mjs`.
|
|
82
|
+
|
|
83
|
+
`auto-layout.mjs` applies these rules. Know them, so you can judge the picture:
|
|
84
|
+
|
|
85
|
+
1. Columns run left to right, pitch 340. Column = longest path from the trigger.
|
|
86
|
+
2. Place every node by its feeding output, not by row: input y = source handle y + dy. Hand-tuning: `scripts/layout.mjs` with a spec `{ id: [column, sourceId, handle, dy] }`.
|
|
87
|
+
3. **Detours go above the line they leave.** If a lookup can be skipped, its `false` edge to the rejoin node stays straight on the main line, and the lookup goes 150 higher. The same applies to an approval with a straight bypass and to a parallel fetch before a merge.
|
|
88
|
+
4. When an approval's `rejected` line runs far right, raise the next node on the `approved` line (dy −24, or −48 for a following approval). Otherwise the rejected line runs along its border.
|
|
89
|
+
5. Collect the far targets of many branches, such as a shared «reject» node, **below and right of all branch rows**, so their vertical segments fall in empty column gaps.
|
|
90
|
+
6. Branches that end without rejoining stack below, each clear of what is already in their columns. Each flow gets its own band, about 300 px below the previous one.
|
|
91
|
+
7. `layout-check.mjs` must report nothing: no backward edges, no overlaps, no line through or along a node. Report the straight-edge count.
|
|
92
|
+
|
|
93
|
+
## Lean graph checklist
|
|
94
|
+
|
|
95
|
+
Someone who opens the automation should read the flow from the canvas alone. Every node has to earn its place.
|
|
96
|
+
|
|
97
|
+
- **Every node does one of four things:** reads, decides, writes or waits. A node that only reshapes data is allowed in two places: as a `set` right before a `code` node (the sandbox has no `$()`), or as a `set` where branches rejoin. Elsewhere, read `$('…')` directly. `lint-graph` flags the rest.
|
|
98
|
+
- **Business decisions are visible; technical logic is hidden.** A choice the business cares about (which BP step, approved or rejected) is an `if` / `switch` on the canvas. Its outputs are named by the case: `equipment`, `1c-rights`, `rejected`, not `toNew` or `0`, because they label the lines. Lookups, mappings and deadline arithmetic go into one `code` node.
|
|
99
|
+
- **One write per record per phase.** Merge consecutive updates of the same record into one `updateById`, and put related fields (stage, assignee, watchers) into the same write.
|
|
100
|
+
- **Defaults before the save, not after it.** To fill fields of the record being created (a default approver, a status), trigger on `before-insert` and answer with `responseEntity { action: "apply", values: [{ name, value }] }`. The record is saved with the values, which costs no write.
|
|
101
|
+
- An `after-insert` → `updateById` costs one more write.
|
|
102
|
+
- It also starts every `after-update` trigger on that entity a second time.
|
|
103
|
+
- **Read only what the flow uses.** A lookup that only decorates a description is a candidate to drop. Give every `select` a `limit` and `fields`.
|
|
104
|
+
- **One read per entity per flow.** Several reads of the same entity are one query that was split.
|
|
105
|
+
- **The same record, different fields** → one `getById` with all the fields. Related records go in nested `fields` (`employees: { department: { head: { user: { id } } } }`) rather than a second read.
|
|
106
|
+
- **Several records of one entity by known ids** → one `select` with `id in [...]` and `limit` = the count. A picker filter takes several records with `comparator: "in"`. Pick each row afterwards: `$('2. Read the approvers').all().find(i => i.json.id === ID)?.json`, or inside the `code` node.
|
|
107
|
+
- **One node per role** (CEO, CFO, CHRO…, one stage per node) costs a query per role. Keep the role → id map in `settings` and read them together in one `select … id in`. Read them only if you need more than the id, such as a name for a message. For an id alone, settings are enough and need no read.
|
|
108
|
+
- **What legitimately stays separate:**
|
|
109
|
+
- a read that needs the result of a read before it (a task, then its parent);
|
|
110
|
+
- reads on exclusive branches, of which one run takes only one.
|
|
111
|
+
|
|
112
|
+
- **Do not leave dangling ends by accident.** A free `false` / `rejected` / switch output must be intended. Say so in the description, or connect it.
|
|
113
|
+
- **Size budget.** More than ~25 nodes or ~20 columns in one flow means it no longer reads at a glance. Move logic into a `code` node or drop decoration before splitting.
|
|
114
|
+
- **Settings over literals.** Ids, people, stages and switches live in settings. The trigger filter is generated from them in the build.
|
|
115
|
+
|
|
116
|
+
## Safe runs
|
|
117
|
+
|
|
118
|
+
- **Republishing does not restart the runs that are waiting.** A run parked at an `approval` resumes against the graph that is published when the approver answers. If that approval's node id is gone, or the nodes after it read names that no longer exist, the run cannot continue as designed.
|
|
119
|
+
- Keep the ids of approval / wait nodes stable across rebuilds.
|
|
120
|
+
- Before publishing a reshaped graph, list the waiting runs (`suppa_list_automation_runs status: "waiting"`) and say which ones the change strands.
|
|
121
|
+
- `lint-graph graph.json --previous published.json` names approval ids the new graph drops.
|
|
122
|
+
- **Missing configuration is an error, not a quiet stop.** When settings lack a person, a stage or a project, the `code` node throws, for example `throw new Error('Not configured: chro, stage hrd')`. Then the run shows as failed, with the reason.
|
|
123
|
+
- `return []` is for «this record is not ours», such as a filter or a test-mode guard.
|
|
124
|
+
- A `return []` on a missing setting shows as a successful run that did nothing.
|
|
125
|
+
- **A node can run twice; a write must not double.** Runs are retried (`retryCount`), and a stage can be moved back and forth.
|
|
126
|
+
- Before a create that must happen once (a task, a link, a comment), check that it does not exist yet. Look it up by the link or by a field that marks it, such as `automationResults.taskId` on the request.
|
|
127
|
+
- Alternatively, make the write an update of a known record.
|
|
128
|
+
- Updates that set a value (stage, assignee) are safe to repeat.
|
|
129
|
+
- Inserts and `merge` additions (watchers, auditors) are not.
|
|
130
|
+
|
|
131
|
+
## Data in expressions
|
|
132
|
+
|
|
133
|
+
- **Compare enums and records by their stored `value` or `id`, never by `title`.** A title is a localized label. It can be `null` in the run (`type: { title: null, value: "Офісна" }`), and it changes when someone renames it.
|
|
134
|
+
- The same applies to stages and projects: compare their `id`, or a `code` where the entity has one.
|
|
135
|
+
- **Dates and deadlines in the tenant's time zone, not a fixed offset.**
|
|
136
|
+
- A datetime without an offset is read as UTC.
|
|
137
|
+
- A hard-coded `+02:00` / `+03:00` is wrong for half the year (Kyiv switches on the last Sundays of March and October).
|
|
138
|
+
- Compute the instant in the `code` node with `references/tenant-time.md`. A form date `YYYY-MM-DD` is the picked day. «Due at 16:00 that day» becomes `atKyiv(day, '16:00')`.
|
|
139
|
+
- **Write a relation as `{ id }`.**
|
|
140
|
+
- A bare number or a bare `={{ x.id }}` in a relation field returns success and stores `null`.
|
|
141
|
+
- Many-to-one: `"assignee": "={{ { id: … } }}"`.
|
|
142
|
+
- Many-to-many: `[{ id }, …]`, plus `merge: ["field"]` to add rather than replace.
|
|
143
|
+
|
|
144
|
+
## Optimize with measurements
|
|
145
|
+
|
|
146
|
+
- `suppa_get_automation_run` gives per-node timings. Writes cost 150–500 ms each (create task, link, update); reads cost about 30 ms each, plus a node on the canvas. Reads of **the same entity** merge into one query (see «One read per entity per flow»). Reads of different entities stay separate nodes, because merging them through `code` hides what the flow reads.
|
|
147
|
+
- **Idle runs** are the real waste. Filter in the trigger: `watchFields` plus `conditions` (for example `stage.id in [...]`), so moves that mean nothing start no run. Generate the id lists from settings in the build.
|
|
148
|
+
- **A select that returns nothing ends the branch.** Guard optional lookups with an `if`, or fan out to the select and to a `merge` (append) so the flow continues.
|
|
149
|
+
- A `code` node sees only `$json` / `$input`. Feed it from a `set` node that gathers `$('…')` values.
|
|
150
|
+
- testMode: route every role to the test user, and send approvals to a **second** account. An approval whose approver started the run is auto-approved.
|
|
151
|
+
- Check that it really waits: a response comment «Automatically approved…» in the run's approval step means nobody was asked, and the `rejected` path was never run.
|
|
152
|
+
- On modern-expo.test (2026-10-23 – 26) a second account on a plus-address of the tester's own mailbox was still auto-approved in 20 of 20 runs the tester started. The cause is not established; until one approval has waited for a click, the rejection path is untested.
|
|
153
|
+
|
|
154
|
+
## Publish and verify
|
|
155
|
+
|
|
156
|
+
Follow `references/publishing.md`:
|
|
157
|
+
- check the active tenant (the MCP can drift to prod);
|
|
158
|
+
- keep the workflow-builder tab **closed** while writing through the API, because it autosaves a stale graph over yours;
|
|
159
|
+
- compare the draft with the build by hash;
|
|
160
|
+
- publish;
|
|
161
|
+
- test every flow with a real run (form submission, stage change) and read the per-node steps;
|
|
162
|
+
- unpublish and soft-delete automations a merge made redundant.
|
|
163
|
+
|
|
164
|
+
## Common mistakes
|
|
165
|
+
|
|
166
|
+
| Mistake | Fix |
|
|
167
|
+
|---|---|
|
|
168
|
+
| Two automations for one process | One automation, two trigger flows |
|
|
169
|
+
| Guard selects against duplicates from your own other automation | Merge the automations, or let only one side write |
|
|
170
|
+
| `if` true/false or approved/rejected drawn into one row "because same size" | Place by handle offset, detour above |
|
|
171
|
+
| Publishing a draft saved in the builder UI | The UI drops expression `approvers` to `[]`. Rebuild from source |
|
|
172
|
+
| Editing settings partially | Updates merge top-level keys. Resend the whole `settings.<key>`, then republish |
|
|
173
|
+
| Option key `constructor` in settings | The platform strips it. Look options up with `hasOwnProperty` |
|
|
174
|
+
| A node reads `$('X')` where X runs on another branch or later | `undefined` at runtime, with no error. `lint-graph` catches it |
|
|
175
|
+
| Republishing a reshaped graph while runs wait at an approval | Keep approval ids stable; check `status: "waiting"` runs first. `lint-graph --previous` names dropped ids |
|
|
176
|
+
| `return []` when a setting is missing | `throw new Error('Not configured: …')` — a failed run with the reason, not a silent success |
|
|
177
|
+
| A create that a retry or a stage moved back and forth repeats | Look up the link / marker field first, or update a known record |
|
|
178
|
+
| `type.title === 'Офісна'`, a stage compared by name | Compare `value` / `id` / `code`; titles are localized and may be `null` |
|
|
179
|
+
| `deadline: date + 'T16:00:00+02:00'` | `atKyiv(day, '16:00')` from `references/tenant-time.md` |
|
|
180
|
+
| `assignee: "={{ $json.userId }}"` (a bare id) | `"={{ { id: $json.userId } }}"` — a bare id stores `null` |
|
|
181
|
+
| `after-insert` → `updateById` of the same record to fill defaults | `before-insert` + `responseEntity` |
|
|
182
|
+
| A notification with only `en` | Add the users' language (`uk`) to `subjectTemplate` and `bodyTemplate` |
|
|
183
|
+
| Switch outputs `toNew`, `analyst`, `0` | Name them by the business case. They label the canvas lines |
|
|
184
|
+
| A read node per person / per stage of the same entity | One `select … id in [...]`, rows picked by id. `lint-graph` flags it |
|
|
185
|
+
| A select in a request flow for the submitter, the request row or a picked id | Take it from the trigger: `formData.<key>`, `createdBy`, `number`. `lint-graph` flags it |
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# Node reference (verified on published, running automations)
|
|
2
|
+
|
|
3
|
+
Every shape below comes from a published, running automation; the ids in the examples are sample values.
|
|
4
|
+
For a type not listed, call `suppa_get_automation_node_schema`.
|
|
5
|
+
|
|
6
|
+
## Graph
|
|
7
|
+
|
|
8
|
+
```json
|
|
9
|
+
{ "id": "create-task", "type": "suppa", "name": "A4. Create task", "parameters": { … }, "position": { "x": 7900, "y": 292 } }
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Connections: `{ "<from id>": { "<output handle>": [{ "node": "<to id>", "index": 0 }] } }`.
|
|
13
|
+
|
|
14
|
+
| Node type | Output handles |
|
|
15
|
+
|---|---|
|
|
16
|
+
| ordinary nodes, triggers | `main` |
|
|
17
|
+
| `if` | `true` / `false` |
|
|
18
|
+
| `approval` | `approved` / `rejected` |
|
|
19
|
+
| `switch` | the rule's `output` **name** (not an index) |
|
|
20
|
+
|
|
21
|
+
`index` is the target input. Only `merge` uses `1`.
|
|
22
|
+
|
|
23
|
+
## Triggers
|
|
24
|
+
|
|
25
|
+
| Trigger | Parameters | Notes |
|
|
26
|
+
|---|---|---|
|
|
27
|
+
| Form submission / request | `formSubmission` `{ "formId": 1260 }` | Routes on `formId` alone, fires after insert. The output is the FormSubmissions row: `id`, `number`, `state`, `requestType {id,title}`, `form`, `createdBy {id,fullName}`, `formData` (relations as `{id}` only). Read values from it — see SKILL.md «Requests and form submissions». |
|
|
28
|
+
| Entity change | `triggerEntity` `{ "entityName": "Tasks", "events": ["after-update"], "watchFields": ["stage"], "conditions": { "operator": "and", "filters": [ {"operator": "or", "filters": [{"field": "project", "comparator": "=", "value": {"id": 3683}}]}, {"field": "stage.id", "comparator": "in", "value": [947, 968]} ] } }` | `events` take `after-insert` / `after-update` / `after-remove` (and `before-*`). Conditions nest `{operator, filters}`. Relation fields take `{id}` values or dotted paths (`stage.id`). Comparators include `=`, `!=`, `in`, `not in`, `contains`, `is null`, `is not null` (the null checks take no `value`). |
|
|
29
|
+
|
|
30
|
+
Several triggers in one automation are allowed. The run starts at the trigger that fired.
|
|
31
|
+
|
|
32
|
+
## Core nodes
|
|
33
|
+
|
|
34
|
+
| Node | Parameters |
|
|
35
|
+
|---|---|
|
|
36
|
+
| `suppa` getById | `{ "action": "getById", "entityName": "AutomationWorkflow", "id": "={{ $workflow.id }}", "fields": {"id": true, "activeSettings": true} }` — the automation's own settings. |
|
|
37
|
+
| `suppa` select | `{ "action": "select", "entityName": "OrgEmployees", "limit": 50, "fields": {"id": true, "user": {"id": true}}, "conditions": {"operator": "and", "filters": [{"field": "id", "comparator": "in", "value": "={{ … }}"}]} }` — **0 rows ends the branch.** |
|
|
38
|
+
| `suppa` insert / updateById | `{ "action": "updateById", "entityName": "Tasks", "id": "={{ … }}", "fields": {"stage": "={{ x != null ? { id: x } : null }}"}, "merge": ["watchers"] }` — relations are `{id}`. List fields are replaced unless named in `merge`. |
|
|
39
|
+
| `set` | `{ "keepOnlySet": true, "assignments": [{"name": "request", "value": "={{ $('A1. Start: …').first().json }}"}] }` |
|
|
40
|
+
| `code` | `{ "code": "…return [{ … }];" }` — sees only `$json` / `$input`, with no `$()` / `$workflow` / `$now`. Feed it through a `set`. One run covers all input items. |
|
|
41
|
+
| `if` | `{ "expression": "={{ … === true }}" }` |
|
|
42
|
+
| `switch` | `{ "mode": "first", "fallbackEnabled": false, "rules": [{"output": "approvalIt", "condition": "={{ $json.action === 'approvalIt' }}"}] }` |
|
|
43
|
+
| `responseEntity` | Only after a `before-insert` / `before-update` trigger: `{ "action": "apply", "values": [{"name": "status", "value": "={{ … }}"}] }` — the values are applied to the record before it is saved (defaults, normalisation) at the cost of no write. Every listed field takes the value returned, so when a field needs no change, return what came in (`… ?? $('A1. Start…').first().json.<field>`). |
|
|
44
|
+
| `merge` | `{ "mode": "append" }`, node field `"inputCount": 2`. Waits for both inputs and still runs when one select produced nothing (fan out: source → select → input 0, source → merge input 1). |
|
|
45
|
+
| `approval` | `{ "flow": "sequential", "entityName": "Tasks", "instanceId": "={{ … }}", "approvers": "={{ … }}", "description": "Text ={{ expr }}: ={{ expr }}" }` — `approvers` = `[{ "user": { "id": 75 } }]`. |
|
|
46
|
+
| `notification` | `{ "type": "insert", "channels": [{"channel": "inApp"}], "entityName": "Tasks", "recordId": "={{ … }}", "userIds": "={{ [ … ] }}", "subjectTemplate": {"uk": "…", "en": "…"}, "bodyTemplate": {"uk": "… ={{ expr }} …"}, "navigateTo": {"entityId": 45, "instanceId": "={{ … }}"} }` |
|
|
47
|
+
|
|
48
|
+
## Linking a request to its task
|
|
49
|
+
|
|
50
|
+
Do not invent a field on the task. Use `EntityLinks`.
|
|
51
|
+
|
|
52
|
+
To create the link:
|
|
53
|
+
```json
|
|
54
|
+
{ "action": "insert", "entityName": "EntityLinks", "fields": {
|
|
55
|
+
"type": "={{ { id: <link type id from settings> } }}",
|
|
56
|
+
"instanceA": { "type": "many-to-one", "relationTarget": "FormSubmissions", "value": { "id": "={{ … }}" } },
|
|
57
|
+
"instanceB": { "type": "many-to-one", "relationTarget": "Tasks", "value": { "id": "={{ … }}" } } } }
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
To find the request from the task: select `EntityLinks` with the filters
|
|
61
|
+
- `type.id = <type>`,
|
|
62
|
+
- `instanceB.$entityId = 45` (the Tasks entity id),
|
|
63
|
+
- `instanceB.$instanceId = <task id>`,
|
|
64
|
+
|
|
65
|
+
then read `instanceA.value.id ?? instanceA.id`.
|
|
66
|
+
|
|
67
|
+
## Expressions and settings
|
|
68
|
+
|
|
69
|
+
- `={{ js }}` evaluates. Text and several `={{ }}` mix inside one string.
|
|
70
|
+
- Reference a node as `$('Node name').first().json`. `$json` is the incoming item.
|
|
71
|
+
- A trigger or `suppa` item lazily loads `$json.<field>` that was not selected (the item carries `meta.entity`).
|
|
72
|
+
- Settings are stored as jsonb:
|
|
73
|
+
- object keys get re-sorted, so keep an explicit order array;
|
|
74
|
+
- a key named `constructor` is stripped;
|
|
75
|
+
- an update merges top-level keys only, so resend the whole `settings.<key>`;
|
|
76
|
+
- flows read `activeSettings`, so republish after any change.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Publishing and verifying an automation
|
|
2
|
+
|
|
3
|
+
## Draft and published
|
|
4
|
+
|
|
5
|
+
`AutomationWorkflow` has two sides:
|
|
6
|
+
- the **draft** — `nodes` / `connections` / `settings`;
|
|
7
|
+
- the **published** version — `activeNodes` / `activeConnections` / `activeSettings`.
|
|
8
|
+
|
|
9
|
+
Production runs only the published side. `hasUnpublishedChanges` tells you the draft differs.
|
|
10
|
+
|
|
11
|
+
## Order of work
|
|
12
|
+
|
|
13
|
+
1. **Tenant.** Run `suppa_use_tenant("<full https URL>")`, then confirm with `suppa_list_tenants`. Aliases collide, and the MCP may start on (or drift back to) prod. Check again before every write.
|
|
14
|
+
2. **Close the builder.** Any `workflow-builder/<id>` tab must be navigated away before you write through the API. An open builder autosaves its stale graph over yours. It also turns expression `approvers` into `[]`, adds duplicate `condition` keys and re-lays-out the nodes. After writing, compare `nodes` with `activeNodes`. If the draft was overwritten, copy `activeNodes` / `activeConnections` back into it and republish.
|
|
15
|
+
3. **Write.**
|
|
16
|
+
- Small graphs: `suppa_update_automation` (`nodes_json`, `connections_json`, `settings_json`; settings merge top-level).
|
|
17
|
+
- Big graphs (> ~40 KB): build the graph **inside the tenant page** from the stored `activeNodes` plus small inline maps (names, positions, new nodes). Then `POST /api/core/data/AutomationWorkflow/update/<id>` with `{ fields: { … } }` using the page's own session.
|
|
18
|
+
- A page **cannot** fetch `http://127.0.0.1` (Chrome Local Network Access): the call hangs and nothing arrives.
|
|
19
|
+
4. **Verify by hash, not by reading.** `suppa_get_automation` returns 150 KB+. Run `node scripts/graph-hash.mjs graph.json` locally, and compute the same thing in the page:
|
|
20
|
+
|
|
21
|
+
```js
|
|
22
|
+
const canon = (v) => Array.isArray(v) ? '[' + v.map(canon).join(',') + ']' : v && typeof v === 'object' ? '{' + Object.keys(v).sort().map(k => JSON.stringify(k) + ':' + canon(v[k])).join(',') + '}' : JSON.stringify(v);
|
|
23
|
+
const sha = async (s) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)))].map(b => b.toString(16).padStart(2, '0')).join('');
|
|
24
|
+
const key = (nodes) => nodes.map(n => ({ id: n.id, name: n.name, parameters: n.parameters, position: n.position })).sort((a, b) => a.id < b.id ? -1 : 1);
|
|
25
|
+
// compare (await sha(canon(key(row.nodes)))) with the local hash; return booleans, not hashes —
|
|
26
|
+
// the browser tool redacts long hex strings from results
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Settings hashes must drop `constructor` keys, because the platform strips them.
|
|
30
|
+
5. **Publish** with `suppa_publish_automation`. This copies the draft to the published side and runs pre-flight checks.
|
|
31
|
+
- The builder may keep showing «Unpublished changes» for a graph written through the API. It compares its own normalized copy, not the server state.
|
|
32
|
+
- Trust `hasUnpublishedChanges` and `nodes == activeNodes` instead.
|
|
33
|
+
- Never press «Publish changes» in the UI to clear the badge: it publishes the builder's version, with expression approvers wiped.
|
|
34
|
+
6. **Test every flow live.**
|
|
35
|
+
- Submit the form, or move a test task to the stage.
|
|
36
|
+
- Read the run with `suppa_get_automation_run`. The output is large and lands in a file, so summarize it with `node -e` (`steps[].nodeId / status / error / output`).
|
|
37
|
+
- Also confirm that a move which should start nothing starts no run (`suppa_list_automation_runs`).
|
|
38
|
+
- Approvals auto-approve when the approver started the run, so route test approvals to a second account. A real rejection needs a click from that account.
|
|
39
|
+
- Read the approval step of the run: `responses[0].comment` «Automatically approved…» means it did not wait. On modern-expo.test (2026-10-23 – 26) that happened in 20 of 20 runs the tester started, even with a second account (a plus-address of the tester's mailbox), cause not established — so the rejection path counts as tested only after an approval has waited and been rejected by a click.
|
|
40
|
+
7. **Retire what a merge replaced.** Run `suppa_unpublish_automation`, then `suppa_delete_automation`. The delete is soft; `suppa_restore_record('AutomationWorkflow', id)` undoes it.
|
|
41
|
+
8. **Update the description.** Start it with the step guide by flow letter and number, then list the real people per BP or role (test ids stay in settings).
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Tenant time in a `code` node
|
|
2
|
+
|
|
3
|
+
A datetime written without an offset is read as **UTC**, and Kyiv is +02:00 in winter and +03:00 in summer. The switch happens on the last Sunday of March and of October, at 01:00 UTC. So never append a fixed offset. Paste these helpers at the top of the `code` node that computes dates. They use `Intl` time zones when the sandbox has them and fall back to the EU rule Ukraine follows.
|
|
4
|
+
|
|
5
|
+
```js
|
|
6
|
+
const kyivOffsetMin = (d) => {
|
|
7
|
+
try {
|
|
8
|
+
const name = new Intl.DateTimeFormat('en-US', { timeZone: 'Europe/Kyiv', timeZoneName: 'longOffset' }).formatToParts(d).find((p) => p.type === 'timeZoneName').value;
|
|
9
|
+
const m = /GMT([+-])(\d{2}):(\d{2})/.exec(name);
|
|
10
|
+
if (m) return (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3]));
|
|
11
|
+
} catch (e) { /* no Intl time zones in the sandbox */ }
|
|
12
|
+
const y = d.getUTCFullYear();
|
|
13
|
+
const lastSunday = (month) => { const t = new Date(Date.UTC(y, month + 1, 0, 1)); t.setUTCDate(t.getUTCDate() - t.getUTCDay()); return t; };
|
|
14
|
+
return d >= lastSunday(2) && d < lastSunday(9) ? 180 : 120;
|
|
15
|
+
};
|
|
16
|
+
const pad2 = (n) => String(n).padStart(2, '0');
|
|
17
|
+
// The calendar day an instant falls on in Kyiv, as a UTC-midnight Date.
|
|
18
|
+
const kyivDay = (d) => { const k = new Date(d.getTime() + kyivOffsetMin(d) * 60000); return new Date(Date.UTC(k.getUTCFullYear(), k.getUTCMonth(), k.getUTCDate())); };
|
|
19
|
+
// A form date: 'YYYY-MM-DD' is already the picked day; an ISO instant is the Kyiv day it falls on
|
|
20
|
+
// (a picker may send local midnight, which is the previous day in UTC).
|
|
21
|
+
const toKyivDay = (v) => {
|
|
22
|
+
if (v == null || v === '') return null;
|
|
23
|
+
const s = String(v);
|
|
24
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return new Date(s + 'T00:00:00Z');
|
|
25
|
+
const d = new Date(s);
|
|
26
|
+
return Number.isNaN(d.getTime()) ? null : kyivDay(d);
|
|
27
|
+
};
|
|
28
|
+
// ISO-8601 with the right offset for HH:MM Kyiv on that day.
|
|
29
|
+
const atKyiv = (day, hhmm) => {
|
|
30
|
+
const [h, m] = String(hhmm || '16:00').split(':').map(Number);
|
|
31
|
+
const off = kyivOffsetMin(new Date(Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate(), h, m) - 120 * 60000));
|
|
32
|
+
const a = Math.abs(off);
|
|
33
|
+
return `${day.toISOString().slice(0, 10)}T${pad2(h)}:${pad2(m)}:00${off < 0 ? '-' : '+'}${pad2(Math.floor(a / 60))}:${pad2(a % 60)}`;
|
|
34
|
+
};
|
|
35
|
+
// N working days after a Kyiv day; weekends and the days in `off` ('YYYY-MM-DD') are skipped.
|
|
36
|
+
const addBusinessDays = (day, n, off = new Set()) => { const d = new Date(day); while (n > 0) { d.setUTCDate(d.getUTCDate() + 1); if (d.getUTCDay() % 6 !== 0 && !off.has(d.toISOString().slice(0, 10))) n--; } return d; };
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Usage:
|
|
40
|
+
- «due at 16:00 on the picked day»: `atKyiv(toKyivDay(fd.desired_date), '16:00')`;
|
|
41
|
+
- «+2 working days from now»: `atKyiv(addBusinessDays(kyivDay(new Date($json.now)), 2, holidays), '16:00')`. The `code` node has no `$now`, so feed `now: "={{ $now }}"` through the `set` before it, and read holidays from their entity.
|
|
42
|
+
|
|
43
|
+
For a tenant in another zone, replace `'Europe/Kyiv'` and the fallback rule. The trigger payload's `options.timezone` names the tenant's zone.
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// Lays out a whole automation with no hand-written spec, then repairs what the edge model flags.
|
|
2
|
+
// usage: node auto-layout.mjs <graph.json> > placed.json (stderr: straight-edge count and leftovers)
|
|
3
|
+
// graph.json: the stored shape or a suppa_get_automation answer; placed.json is always the stored shape.
|
|
4
|
+
//
|
|
5
|
+
// Rules, in the order they apply:
|
|
6
|
+
// - column = longest path from the flow's trigger, so every edge runs left to right;
|
|
7
|
+
// - each node hangs on one feeding edge (its anchor): the one from the earliest column, i.e. the edge that
|
|
8
|
+
// skips a detour; a node fed from 3+ different branches is a collector and goes below the flow;
|
|
9
|
+
// - at a fork, the edge to a node that another branch rejoins stays straight and that other branch goes
|
|
10
|
+
// above (a skippable lookup, an approval with a bypass); otherwise the first output stays straight and the
|
|
11
|
+
// rest stack below, each clear of what is already in its columns;
|
|
12
|
+
// - after an approval / if whose lower line runs far right, the node on the upper line steps up so the
|
|
13
|
+
// lower line does not run along its border;
|
|
14
|
+
// - flows stack in bands, each trigger 300 below the previous flow's lowest node;
|
|
15
|
+
// - then: whatever the edge model still flags is nudged away (node moved off a line, a target pushed one
|
|
16
|
+
// column right when a vertical segment crosses a node, overlaps pushed apart), up to 80 rounds.
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import { fileURLToPath } from 'node:url';
|
|
19
|
+
import { height, inOffset, outOffset } from './geometry.mjs';
|
|
20
|
+
import { analyse, rect } from './edges.mjs';
|
|
21
|
+
import { readGraph } from './graph.mjs';
|
|
22
|
+
|
|
23
|
+
const TRIGGERS = new Set(['formSubmission', 'triggerEntity', 'triggerWebhook', 'triggerSchedule', 'triggerManual']);
|
|
24
|
+
const handleRank = (n, h) => {
|
|
25
|
+
if (n.type === 'if') return h === 'true' ? 0 : 1;
|
|
26
|
+
if (n.type === 'approval') return h === 'approved' ? 0 : 1;
|
|
27
|
+
if (n.type === 'switch') return (n.parameters?.rules || []).findIndex((r) => r.output === h);
|
|
28
|
+
return h === 'error' ? 9 : 0;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export const autoLayout = (graph, { pitch = 340, x0 = 80, lift = 150, gap = 50, band = 300, clear = 24, rounds = 80 } = {}) => {
|
|
32
|
+
const { nodes, connections } = graph;
|
|
33
|
+
const by = Object.fromEntries(nodes.map((n) => [n.id, n]));
|
|
34
|
+
const order = Object.fromEntries(nodes.map((n, i) => [n.id, i]));
|
|
35
|
+
const succ = Object.fromEntries(nodes.map((n) => [n.id, []]));
|
|
36
|
+
const pred = Object.fromEntries(nodes.map((n) => [n.id, []]));
|
|
37
|
+
let seq = 0;
|
|
38
|
+
for (const [from, hs] of Object.entries(connections)) for (const [h, ts] of Object.entries(hs)) for (const t of ts) {
|
|
39
|
+
if (!by[from] || !by[t.node]) continue;
|
|
40
|
+
const e = { from, to: t.node, handle: h, seq: seq++ };
|
|
41
|
+
succ[from].push(e);
|
|
42
|
+
pred[t.node].push(e);
|
|
43
|
+
}
|
|
44
|
+
for (const id of Object.keys(succ)) succ[id].sort((a, b) => handleRank(by[id], a.handle) - handleRank(by[id], b.handle) || a.seq - b.seq);
|
|
45
|
+
|
|
46
|
+
// flows: a node belongs to the first trigger that reaches it
|
|
47
|
+
const triggers = nodes.filter((n) => TRIGGERS.has(n.type));
|
|
48
|
+
const flow = {};
|
|
49
|
+
for (const t of triggers) {
|
|
50
|
+
const stack = [t.id];
|
|
51
|
+
while (stack.length) { const id = stack.pop(); if (flow[id]) continue; flow[id] = t.id; for (const e of succ[id]) stack.push(e.to); }
|
|
52
|
+
}
|
|
53
|
+
const reach = {};
|
|
54
|
+
const reaches = (a, b) => {
|
|
55
|
+
if (!reach[a]) { const s = new Set(); const st = [a]; while (st.length) for (const e of succ[st.pop()]) if (!s.has(e.to)) { s.add(e.to); st.push(e.to); } reach[a] = s; }
|
|
56
|
+
return reach[a].has(b);
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// topological order (Kahn), columns = longest path, with right-shifts from the repair loop
|
|
60
|
+
const indeg = Object.fromEntries(nodes.map((n) => [n.id, pred[n.id].length]));
|
|
61
|
+
const topo = [];
|
|
62
|
+
const queue = nodes.filter((n) => !indeg[n.id]).map((n) => n.id);
|
|
63
|
+
while (queue.length) { const id = queue.shift(); topo.push(id); for (const e of succ[id]) if (!--indeg[e.to]) queue.push(e.to); }
|
|
64
|
+
if (topo.length !== nodes.length) throw new Error('the graph has a cycle');
|
|
65
|
+
const colMin = {};
|
|
66
|
+
const cols = () => {
|
|
67
|
+
const col = {};
|
|
68
|
+
for (const id of topo) col[id] = Math.max(colMin[id] ?? 0, ...pred[id].map((e) => col[e.from] + 1), 0);
|
|
69
|
+
return col;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
// anchors
|
|
73
|
+
const collector = (id) => new Set(pred[id].map((e) => e.from)).size >= 3;
|
|
74
|
+
const anchorOf = {};
|
|
75
|
+
const pickAnchors = (col) => {
|
|
76
|
+
for (const id of topo) {
|
|
77
|
+
if (!pred[id].length || collector(id)) { anchorOf[id] = null; continue; }
|
|
78
|
+
anchorOf[id] = [...pred[id]].sort((a, b) => col[a.from] - col[b.from] || handleRank(by[a.from], a.handle) - handleRank(by[b.from], b.handle) || a.seq - b.seq)[0];
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
const childrenOf = (s) => succ[s].filter((e) => anchorOf[e.to] === e).map((e) => e);
|
|
82
|
+
|
|
83
|
+
// placement
|
|
84
|
+
const extra = {};
|
|
85
|
+
const pos = {};
|
|
86
|
+
const kindOf = {};
|
|
87
|
+
const place = () => {
|
|
88
|
+
const col = cols();
|
|
89
|
+
pickAnchors(col);
|
|
90
|
+
const anchoredSpan = {};
|
|
91
|
+
const span = (id) => {
|
|
92
|
+
if (anchoredSpan[id]) return anchoredSpan[id];
|
|
93
|
+
let lo = col[id], hi = col[id];
|
|
94
|
+
for (const e of childrenOf(id)) { const [a, b] = span(e.to); lo = Math.min(lo, a); hi = Math.max(hi, b); }
|
|
95
|
+
return (anchoredSpan[id] = [lo, hi]);
|
|
96
|
+
};
|
|
97
|
+
const placed = [];
|
|
98
|
+
const setTop = (id, top) => { pos[id] = { x: x0 + col[id] * pitch, y: Math.round(top) }; placed.push(id); };
|
|
99
|
+
const nodeRect = (id) => rect({ ...by[id], position: pos[id] });
|
|
100
|
+
const bottomIn = (lo, hi, belowY, flowId) => {
|
|
101
|
+
let b = -Infinity;
|
|
102
|
+
for (const id of placed) if (flow[id] === flowId && col[id] >= lo && col[id] <= hi) { const r = nodeRect(id); if (r.y2 > belowY) b = Math.max(b, r.y2); }
|
|
103
|
+
return b;
|
|
104
|
+
};
|
|
105
|
+
const raiseFor = (s, child, handleY, childHandle) => {
|
|
106
|
+
const lower = succ[s].filter((e) => handleRank(by[s], e.handle) > handleRank(by[s], childHandle) && (col[e.to] > col[s] + 1 || anchorOf[e.to] === null));
|
|
107
|
+
if (!lower.length) return 0;
|
|
108
|
+
const lowerY = pos[s].y + Math.min(...lower.map((e) => outOffset(by[s], e.handle)));
|
|
109
|
+
const straightBottom = handleY - inOffset(by[child]) + height(by[child]);
|
|
110
|
+
return Math.min(0, lowerY - clear - straightBottom);
|
|
111
|
+
};
|
|
112
|
+
const dfs = (s, flowId) => {
|
|
113
|
+
const kids = childrenOf(s);
|
|
114
|
+
const rejoin = new Set(kids.filter((e) => kids.some((o) => o !== e && reaches(o.to, e.to))).map((e) => e.to));
|
|
115
|
+
const plan = [];
|
|
116
|
+
let straightTaken = false;
|
|
117
|
+
for (const e of kids) if (rejoin.has(e.to) && !straightTaken) { plan.push([e, 'straight']); straightTaken = true; }
|
|
118
|
+
for (const e of kids) if (!plan.some(([p]) => p === e) && [...rejoin].some((r) => reaches(e.to, r))) plan.push([e, 'above']);
|
|
119
|
+
for (const e of kids) if (!plan.some(([p]) => p === e)) { plan.push([e, straightTaken ? 'below' : 'straight']); straightTaken = true; }
|
|
120
|
+
const order2 = { straight: 0, above: 1, below: 2 };
|
|
121
|
+
plan.sort((a, b) => order2[a[1]] - order2[b[1]]);
|
|
122
|
+
for (const [e, kind] of plan) {
|
|
123
|
+
const child = e.to;
|
|
124
|
+
const handleY = pos[s].y + outOffset(by[s], e.handle);
|
|
125
|
+
let inputY;
|
|
126
|
+
if (kind === 'straight') inputY = handleY + raiseFor(s, child, handleY, e.handle);
|
|
127
|
+
else if (kind === 'above') inputY = handleY - lift;
|
|
128
|
+
else {
|
|
129
|
+
const [lo, hi] = span(child);
|
|
130
|
+
const b = bottomIn(lo, hi, handleY - 30, flowId);
|
|
131
|
+
inputY = b === -Infinity ? handleY + lift : b + gap + inOffset(by[child]);
|
|
132
|
+
}
|
|
133
|
+
kindOf[child] = kind;
|
|
134
|
+
setTop(child, inputY + (extra[child] ?? 0) - inOffset(by[child]));
|
|
135
|
+
dfs(child, flowId);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
let bandTop = 200;
|
|
139
|
+
for (const t of triggers) {
|
|
140
|
+
kindOf[t.id] = 'trigger';
|
|
141
|
+
setTop(t.id, bandTop + (extra[t.id] ?? 0) - outOffset(t, 'main'));
|
|
142
|
+
dfs(t.id, t.id);
|
|
143
|
+
const collectors = topo.filter((id) => flow[id] === t.id && anchorOf[id] === null && id !== t.id);
|
|
144
|
+
for (const c of collectors) {
|
|
145
|
+
const flowBottom = Math.max(...placed.filter((id) => flow[id] === t.id).map((id) => nodeRect(id).y2));
|
|
146
|
+
kindOf[c] = 'collector';
|
|
147
|
+
setTop(c, flowBottom + gap * 2 + (extra[c] ?? 0));
|
|
148
|
+
dfs(c, t.id);
|
|
149
|
+
}
|
|
150
|
+
const flowTop = Math.min(...placed.filter((id) => flow[id] === t.id).map((id) => nodeRect(id).y1));
|
|
151
|
+
if (flowTop < bandTop - 2000) throw new Error('layout ran away upwards');
|
|
152
|
+
bandTop = Math.max(...placed.filter((id) => flow[id] === t.id).map((id) => nodeRect(id).y2)) + band;
|
|
153
|
+
}
|
|
154
|
+
for (const n of nodes) n.position = pos[n.id];
|
|
155
|
+
return col;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
// A row is a node placed above / below / as a collector, plus everything hanging straight off it.
|
|
159
|
+
const rowRoot = (id) => { while (kindOf[id] === 'straight') id = anchorOf[id].from; return id; };
|
|
160
|
+
// Push the lower of two rows down, or lift an above-detour row higher.
|
|
161
|
+
const separate = (upperId, lowerId, amount) => {
|
|
162
|
+
const u = rowRoot(upperId), l = rowRoot(lowerId);
|
|
163
|
+
if (u === l) { extra[lowerId] = (extra[lowerId] ?? 0) + amount; return; }
|
|
164
|
+
if (kindOf[u] === 'above') extra[u] = (extra[u] ?? 0) - amount;
|
|
165
|
+
else if (kindOf[l] === 'below' || kindOf[l] === 'collector' || kindOf[l] === 'above') extra[l] = (extra[l] ?? 0) + amount;
|
|
166
|
+
else extra[lowerId] = (extra[lowerId] ?? 0) + amount;
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
let col = place();
|
|
170
|
+
let report = analyse(graph);
|
|
171
|
+
for (let round = 0; round < rounds && report.problems.length; round++) {
|
|
172
|
+
const p = report.problems[0];
|
|
173
|
+
if (p.kind === 'crossing' && p.seg.dir === 'h') {
|
|
174
|
+
const r = rect(by[p.node]);
|
|
175
|
+
const y = p.seg.y1;
|
|
176
|
+
const nodeAbove = (r.y1 + r.y2) / 2 < y;
|
|
177
|
+
if (rowRoot(p.node) === rowRoot(p.from)) {
|
|
178
|
+
// same row: step the node off the line (an approval's lower line under its own row)
|
|
179
|
+
extra[p.node] = (extra[p.node] ?? 0) + (nodeAbove ? -(r.y2 + clear - y) : y + clear - r.y1);
|
|
180
|
+
} else if (nodeAbove) separate(p.node, p.from, r.y2 + clear - y);
|
|
181
|
+
else separate(p.from, p.node, y + clear - r.y1);
|
|
182
|
+
} else if (p.kind === 'crossing') colMin[p.to] = col[p.to] + 1;
|
|
183
|
+
else if (p.kind === 'overlap') {
|
|
184
|
+
const ra = rect(by[p.a]), rb = rect(by[p.b]);
|
|
185
|
+
const [upper, lower] = ra.y1 + ra.y2 <= rb.y1 + rb.y2 ? [p.a, p.b] : [p.b, p.a];
|
|
186
|
+
const ru = rect(by[upper]), rl = rect(by[lower]);
|
|
187
|
+
separate(upper, lower, ru.y2 + gap - rl.y1);
|
|
188
|
+
} else if (p.kind === 'backward') colMin[p.to] = col[p.from] + 1;
|
|
189
|
+
col = place();
|
|
190
|
+
report = analyse(graph);
|
|
191
|
+
}
|
|
192
|
+
return report;
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
196
|
+
const graph = readGraph(process.argv[2]);
|
|
197
|
+
const report = autoLayout(graph);
|
|
198
|
+
console.error(`straight edges ${report.straight}/${report.total}${report.problems.length ? '' : ', no problems'}`);
|
|
199
|
+
for (const p of report.problems) console.error(' ' + p.text);
|
|
200
|
+
process.stdout.write(JSON.stringify(graph, null, 1));
|
|
201
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Edge model shared by layout-check and auto-layout: the builder draws an edge as a step line —
|
|
2
|
+
// horizontal from the source handle to the midpoint x, vertical, horizontal into the target handle.
|
|
3
|
+
import { MAX_WIDTH, OUT_X, height, inOffset, outOffset } from './geometry.mjs';
|
|
4
|
+
|
|
5
|
+
export const MARGIN = 10; // a line closer than this to a node border reads as touching it
|
|
6
|
+
|
|
7
|
+
export const rect = (n) => ({ x1: n.position.x, y1: n.position.y, x2: n.position.x + MAX_WIDTH, y2: n.position.y + height(n) });
|
|
8
|
+
|
|
9
|
+
export const edges = (graph) => {
|
|
10
|
+
const by = Object.fromEntries(graph.nodes.map((n) => [n.id, n]));
|
|
11
|
+
const list = [];
|
|
12
|
+
for (const [from, handles] of Object.entries(graph.connections)) {
|
|
13
|
+
for (const [handle, targets] of Object.entries(handles)) {
|
|
14
|
+
for (const t of targets) {
|
|
15
|
+
const s = by[from], d = by[t.node];
|
|
16
|
+
if (!s || !d) continue;
|
|
17
|
+
const sx = s.position.x + OUT_X, sy = s.position.y + outOffset(s, handle);
|
|
18
|
+
const tx = d.position.x, ty = d.position.y + inOffset(d);
|
|
19
|
+
const mx = (sx + tx) / 2;
|
|
20
|
+
list.push({
|
|
21
|
+
from, to: t.node, handle, sx, sy, tx, ty,
|
|
22
|
+
segments: [
|
|
23
|
+
{ dir: 'h', x1: sx, x2: mx, y1: sy, y2: sy },
|
|
24
|
+
{ dir: 'v', x1: mx, x2: mx, y1: Math.min(sy, ty), y2: Math.max(sy, ty) },
|
|
25
|
+
{ dir: 'h', x1: mx, x2: tx, y1: ty, y2: ty },
|
|
26
|
+
],
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return list;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const hits = (s, r) => s.x1 < r.x2 + MARGIN && s.x2 > r.x1 - MARGIN && s.y1 < r.y2 + MARGIN && s.y2 > r.y1 - MARGIN;
|
|
35
|
+
|
|
36
|
+
// Everything that makes a canvas hard to read, as structured problems.
|
|
37
|
+
export const analyse = (graph) => {
|
|
38
|
+
const problems = [];
|
|
39
|
+
const list = edges(graph);
|
|
40
|
+
for (const e of list) {
|
|
41
|
+
if (e.tx <= e.sx) problems.push({ kind: 'backward', from: e.from, to: e.to, text: `backward edge ${e.from} → ${e.to} (target must be right of the source)` });
|
|
42
|
+
for (const n of graph.nodes) {
|
|
43
|
+
if (n.id === e.from || n.id === e.to) continue;
|
|
44
|
+
const seg = e.segments.find((g) => g.y1 !== g.y2 || g.x1 !== g.x2 ? hits(g, rect(n)) : false);
|
|
45
|
+
if (seg) problems.push({ kind: 'crossing', from: e.from, to: e.to, handle: e.handle, node: n.id, seg, text: `${e.from} → ${e.to} [${e.handle}] runs through or along ${n.id}` });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const ns = graph.nodes;
|
|
49
|
+
for (let i = 0; i < ns.length; i++) for (let j = i + 1; j < ns.length; j++) {
|
|
50
|
+
const r = rect(ns[i]), q = rect(ns[j]);
|
|
51
|
+
if (r.x1 < q.x2 + 20 && r.x2 > q.x1 - 20 && r.y1 < q.y2 + 20 && r.y2 > q.y1 - 20) problems.push({ kind: 'overlap', a: ns[i].id, b: ns[j].id, text: `nodes overlap: ${ns[i].id} / ${ns[j].id}` });
|
|
52
|
+
}
|
|
53
|
+
const straight = list.filter((e) => e.sy === e.ty).length;
|
|
54
|
+
return { problems, straight, total: list.length };
|
|
55
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Node geometry of the Suppa workflow builder (Vue Flow), measured in the canvas (zoom-independent).
|
|
2
|
+
// position = top-left corner. Widths vary 160..280 with the name; 280 is the worst case.
|
|
3
|
+
export const MAX_WIDTH = 280;
|
|
4
|
+
export const OUT_X = 264; // x of an output handle on a 280-wide node (smaller nodes: width - 16)
|
|
5
|
+
|
|
6
|
+
const isTrigger = (n) => n.type === 'formSubmission' || n.type === 'triggerEntity' || n.type === 'triggerWebhook' || n.type === 'triggerSchedule' || n.type === 'triggerManual';
|
|
7
|
+
const rules = (n) => (n.parameters && n.parameters.rules) || [];
|
|
8
|
+
|
|
9
|
+
export const height = (n) => {
|
|
10
|
+
if (n.type === 'if' || n.type === 'approval') return 98;
|
|
11
|
+
if (n.type === 'switch') return 74 + 24 * (rules(n).length - 1);
|
|
12
|
+
if (isTrigger(n)) return 53;
|
|
13
|
+
return 48;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// y of the input handle, from the node top (merge: every input sits at the same point).
|
|
17
|
+
export const inOffset = (n) => (n.type === 'if' || n.type === 'approval' ? 49 : n.type === 'switch' ? height(n) / 2 : 24);
|
|
18
|
+
|
|
19
|
+
// y of an output handle, from the node top.
|
|
20
|
+
export const outOffset = (n, handle) => {
|
|
21
|
+
if (isTrigger(n)) return 26;
|
|
22
|
+
if (n.type === 'if') return handle === 'false' ? 78 : 54;
|
|
23
|
+
if (n.type === 'approval') return handle === 'rejected' ? 78 : 54;
|
|
24
|
+
if (n.type === 'switch') {
|
|
25
|
+
const i = rules(n).findIndex((r) => r.output === handle);
|
|
26
|
+
if (i < 0) throw new Error(`switch ${n.id} has no output ${handle}`);
|
|
27
|
+
return 54 + 24 * i;
|
|
28
|
+
}
|
|
29
|
+
return 24;
|
|
30
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Fingerprints a graph so the stored draft can be compared with the local build without reading it back
|
|
2
|
+
// through a tool (outputs are huge). The same canon()/sha() run inside the tenant page — see references/publishing.md.
|
|
3
|
+
// usage: node graph-hash.mjs <graph.json> → prints nodes / connections / settings hashes
|
|
4
|
+
// graph.json: the stored shape or a suppa_get_automation answer (its draft side) — both hash the same.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import crypto from 'node:crypto';
|
|
8
|
+
import { readGraph } from './graph.mjs';
|
|
9
|
+
|
|
10
|
+
// The platform strips object keys named `constructor` from stored JSON; drop them so hashes compare.
|
|
11
|
+
const strip = (v) => (Array.isArray(v) ? v.map(strip) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).filter(([k]) => k !== 'constructor').map(([k, x]) => [k, strip(x)])) : v);
|
|
12
|
+
// jsonb re-sorts keys, so the fingerprint sorts them too.
|
|
13
|
+
export const canon = (v) => (Array.isArray(v) ? `[${v.map(canon).join(',')}]` : v && typeof v === 'object' ? `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canon(v[k])}`).join(',')}}` : JSON.stringify(v));
|
|
14
|
+
const sha = (s) => crypto.createHash('sha256').update(s, 'utf8').digest('hex');
|
|
15
|
+
export const nodesKey = (nodes) => nodes.map((n) => ({ id: n.id, name: n.name, parameters: n.parameters, position: n.position })).sort((a, b) => (a.id < b.id ? -1 : 1));
|
|
16
|
+
|
|
17
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
18
|
+
const g = readGraph(process.argv[2]);
|
|
19
|
+
console.log('nodes ', sha(canon(strip(nodesKey(g.nodes)))));
|
|
20
|
+
console.log('connections', sha(canon(g.connections)));
|
|
21
|
+
if (g.settings) console.log('settings ', sha(canon(strip(g.settings))));
|
|
22
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Reads a graph file in either shape the tools hand out and returns the stored shape the scripts work on:
|
|
2
|
+
// - stored (what suppa_update_automation takes): nodes[].parameters + connections { from: { handle: [{ node, index }] } };
|
|
3
|
+
// - normalized (what suppa_get_automation returns): nodes[].config + edges [{ from, fromHandle, to, toIndex }], the
|
|
4
|
+
// published snapshot under `published`.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
|
|
7
|
+
export const toStored = (g) => {
|
|
8
|
+
if (!g || !Array.isArray(g.nodes)) throw new Error('not a graph: expected { nodes, connections } or the suppa_get_automation answer { nodes, edges }');
|
|
9
|
+
const normalized = Array.isArray(g.edges) || g.nodes.some((n) => n && 'config' in n && !('parameters' in n));
|
|
10
|
+
if (!normalized) return g.connections ? g : { ...g, connections: {} };
|
|
11
|
+
const nodes = g.nodes.map(({ config, ...n }) => ('parameters' in n ? n : { ...n, parameters: config ?? {} }));
|
|
12
|
+
const connections = {};
|
|
13
|
+
for (const e of g.edges ?? []) ((connections[e.from] ??= {})[e.fromHandle] ??= []).push({ node: e.to, index: e.toIndex ?? 0 });
|
|
14
|
+
return { nodes, connections, ...(g.settings ? { settings: g.settings } : {}) };
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// side 'published': the snapshot that runs now, when the file is a suppa_get_automation answer (a stored file is itself).
|
|
18
|
+
export const readGraph = (file, { side = 'draft' } = {}) => {
|
|
19
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
20
|
+
return toStored(side === 'published' && raw && raw.published ? raw.published : raw);
|
|
21
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Reports what makes a canvas hard to read: lines through or along nodes, overlapping nodes, backward edges.
|
|
2
|
+
// usage: node layout-check.mjs <graph.json> → exit 1 when anything is reported (stored shape or a suppa_get_automation answer)
|
|
3
|
+
import { analyse } from './edges.mjs';
|
|
4
|
+
import { readGraph } from './graph.mjs';
|
|
5
|
+
|
|
6
|
+
const { problems, straight, total } = analyse(readGraph(process.argv[2]));
|
|
7
|
+
console.log(`straight edges ${straight}/${total}`);
|
|
8
|
+
for (const p of problems) console.log(' ' + p.text);
|
|
9
|
+
process.exit(problems.length ? 1 : 0);
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Places nodes so each input sits level with the output that feeds it: the builder then draws that edge straight.
|
|
2
|
+
// usage: node layout.mjs <graph.json> <spec.json> [--pitch 340] [--x0 80] > placed.json
|
|
3
|
+
// graph.json: { nodes, connections, settings? } or a suppa_get_automation answer; placed.json is the stored shape.
|
|
4
|
+
// spec.json: { "<id>": [column, "<source id>" | null, "<source handle>" | null, dy] }
|
|
5
|
+
// input y = source handle y + dy (dy = 0 → straight); a trigger takes [column, null, null, <y of its output>].
|
|
6
|
+
// Several flows in one automation: give each flow its own trigger row (e.g. flow B's trigger 400+ below flow A's lowest node).
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { inOffset, outOffset } from './geometry.mjs';
|
|
10
|
+
import { readGraph } from './graph.mjs';
|
|
11
|
+
|
|
12
|
+
export const place = (nodes, spec, { pitch = 340, x0 = 80 } = {}) => {
|
|
13
|
+
const by = Object.fromEntries(nodes.map((n) => [n.id, n]));
|
|
14
|
+
const missing = nodes.filter((n) => !spec[n.id]).map((n) => n.id);
|
|
15
|
+
if (missing.length) throw new Error(`no place for: ${missing.join(', ')}`);
|
|
16
|
+
const done = new Set();
|
|
17
|
+
const visiting = new Set();
|
|
18
|
+
const put = (id) => {
|
|
19
|
+
if (done.has(id)) return;
|
|
20
|
+
if (visiting.has(id)) throw new Error(`placement cycle at ${id}`);
|
|
21
|
+
visiting.add(id);
|
|
22
|
+
const [col, from, handle, dy] = spec[id];
|
|
23
|
+
const n = by[id];
|
|
24
|
+
let top;
|
|
25
|
+
if (from == null) top = dy - outOffset(n, 'main');
|
|
26
|
+
else {
|
|
27
|
+
if (!by[from]) throw new Error(`${id}: unknown source ${from}`);
|
|
28
|
+
put(from);
|
|
29
|
+
top = by[from].position.y + outOffset(by[from], handle) + dy - inOffset(n);
|
|
30
|
+
}
|
|
31
|
+
n.position = { x: x0 + col * pitch, y: Math.round(top) };
|
|
32
|
+
done.add(id);
|
|
33
|
+
};
|
|
34
|
+
for (const n of nodes) put(n.id);
|
|
35
|
+
return nodes;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
39
|
+
const [graphFile, specFile, ...rest] = process.argv.slice(2);
|
|
40
|
+
if (!graphFile || !specFile) { console.error('usage: node layout.mjs <graph.json> <spec.json> [--pitch N] [--x0 N]'); process.exit(2); }
|
|
41
|
+
const opt = (k, d) => { const i = rest.indexOf(`--${k}`); return i >= 0 ? Number(rest[i + 1]) : d; };
|
|
42
|
+
const graph = readGraph(graphFile);
|
|
43
|
+
place(graph.nodes, JSON.parse(fs.readFileSync(specFile, 'utf8')), { pitch: opt('pitch', 340), x0: opt('x0', 80) });
|
|
44
|
+
process.stdout.write(JSON.stringify(graph, null, 1));
|
|
45
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// Finds what makes an automation wrong at runtime, hard to read, or heavier than it needs to be.
|
|
2
|
+
// usage: node lint-graph.mjs <graph.json> [--previous published.json]
|
|
3
|
+
// graph.json: the stored { nodes, connections, settings? } or a suppa_get_automation answer as is (its draft side).
|
|
4
|
+
// --previous: the graph that is published now (a suppa_get_automation answer: its `published` side) — names approval
|
|
5
|
+
// nodes the new graph drops, which strands waiting runs.
|
|
6
|
+
// Prints ERROR / WARN / NOTE lines; exits 1 when there is an ERROR.
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { readGraph } from './graph.mjs';
|
|
10
|
+
|
|
11
|
+
const TRIGGERS = new Set(['formSubmission', 'triggerEntity', 'triggerWebhook', 'triggerSchedule', 'triggerManual']);
|
|
12
|
+
const STEP_NAME = /^(?:([A-Z])(?=\d))?(\d+)((?:\.\d+)*)(\.?)\s+\S/;
|
|
13
|
+
const REF = /\$\('([^']*)'\)/g;
|
|
14
|
+
const QUOTED_STEP = /«((?:[A-Z])?\d+(?:\.\d+)*\.?\s[^»]+)»/g;
|
|
15
|
+
|
|
16
|
+
export const lint = (graph, { previous } = {}) => {
|
|
17
|
+
const { nodes, connections = {} } = graph;
|
|
18
|
+
const out = [];
|
|
19
|
+
const seen = new Set();
|
|
20
|
+
const add = (level, msg) => { if (!seen.has(msg)) { seen.add(msg); out.push({ level, msg }); } };
|
|
21
|
+
const by = Object.fromEntries(nodes.map((n) => [n.id, n]));
|
|
22
|
+
const byName = Object.fromEntries(nodes.map((n) => [n.name, n]));
|
|
23
|
+
|
|
24
|
+
// --- edges and handles
|
|
25
|
+
const succ = Object.fromEntries(nodes.map((n) => [n.id, []]));
|
|
26
|
+
const pred = Object.fromEntries(nodes.map((n) => [n.id, []]));
|
|
27
|
+
const validHandles = (n) => {
|
|
28
|
+
const err = n.onError === 'continueErrorOutput' ? ['error'] : [];
|
|
29
|
+
if (n.type === 'if') return ['true', 'false', ...err];
|
|
30
|
+
if (n.type === 'approval') return ['approved', 'rejected', ...err];
|
|
31
|
+
if (n.type === 'switch') return [...(n.parameters?.rules || []).map((r) => r.output), ...(n.parameters?.fallbackEnabled ? ['fallback'] : []), ...err];
|
|
32
|
+
return ['main', ...err];
|
|
33
|
+
};
|
|
34
|
+
for (const [from, handles] of Object.entries(connections)) {
|
|
35
|
+
if (!by[from]) { add('ERROR', `connections from unknown node ${from}`); continue; }
|
|
36
|
+
for (const [h, targets] of Object.entries(handles)) {
|
|
37
|
+
if (!validHandles(by[from]).includes(h)) add('ERROR', `${from}: output "${h}" does not exist on a ${by[from].type} (has ${validHandles(by[from]).join(', ')})`);
|
|
38
|
+
for (const t of targets) {
|
|
39
|
+
if (!by[t.node]) { add('ERROR', `${from} → unknown node ${t.node}`); continue; }
|
|
40
|
+
succ[from].push({ to: t.node, handle: h, index: t.index ?? 0 });
|
|
41
|
+
pred[t.node].push({ from, handle: h });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// --- reachability and flows
|
|
47
|
+
const triggers = nodes.filter((n) => TRIGGERS.has(n.type));
|
|
48
|
+
if (!triggers.length) add('ERROR', 'no trigger node');
|
|
49
|
+
const flowOf = {};
|
|
50
|
+
for (const t of triggers) {
|
|
51
|
+
const stack = [t.id];
|
|
52
|
+
while (stack.length) {
|
|
53
|
+
const id = stack.pop();
|
|
54
|
+
(flowOf[id] ??= new Set()).add(t.id);
|
|
55
|
+
for (const s of succ[id]) if (!flowOf[s.to]?.has(t.id)) stack.push(s.to);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
for (const n of nodes) if (!flowOf[n.id]) add('ERROR', `${n.id} is not reachable from any trigger`);
|
|
59
|
+
for (const n of nodes) if (TRIGGERS.has(n.type) && pred[n.id].length) add('ERROR', `trigger ${n.id} has incoming edges`);
|
|
60
|
+
|
|
61
|
+
const ancestors = (id) => {
|
|
62
|
+
const seen = new Set();
|
|
63
|
+
const stack = [id];
|
|
64
|
+
while (stack.length) for (const p of pred[stack.pop()]) if (!seen.has(p.from)) { seen.add(p.from); stack.push(p.from); }
|
|
65
|
+
return seen;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
// --- ids and names
|
|
69
|
+
const multiFlow = triggers.length > 1;
|
|
70
|
+
const seenNames = new Map();
|
|
71
|
+
for (const n of nodes) {
|
|
72
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(n.id)) add('WARN', `id "${n.id}": use readable kebab-case (create-task), connections are read by id`);
|
|
73
|
+
if (seenNames.has(n.name)) add('ERROR', `name "${n.name}" is used by ${seenNames.get(n.name)} and ${n.id}: $('…') would be ambiguous`);
|
|
74
|
+
seenNames.set(n.name, n.id);
|
|
75
|
+
if (n.name.includes("'")) add('ERROR', `${n.id}: ASCII apostrophe in the name breaks $('…') — use ʼ`);
|
|
76
|
+
if (/[Ѐ-ӿ]/.test(n.name)) add('WARN', `${n.id}: node names are English ("${n.name}")`);
|
|
77
|
+
const m = STEP_NAME.exec(n.name);
|
|
78
|
+
if (!m) add('WARN', `${n.id}: name "${n.name}" has no step number (A4. Create task / A5.1 Wait for head approval)`);
|
|
79
|
+
else if (multiFlow && !m[1]) add('WARN', `${n.id}: several flows — prefix the step with the flow letter (A…, B…)`);
|
|
80
|
+
else if (multiFlow && m[1] && flowOf[n.id]?.size === 1) {
|
|
81
|
+
const trig = by[[...flowOf[n.id]][0]];
|
|
82
|
+
const letter = STEP_NAME.exec(trig.name)?.[1];
|
|
83
|
+
if (letter && letter !== m[1]) add('WARN', `${n.id}: belongs to flow ${letter} (trigger ${trig.id}) but is named ${m[1]}…`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// --- expressions: a node may only read nodes that ran before it
|
|
88
|
+
for (const n of nodes) {
|
|
89
|
+
const text = JSON.stringify(n.parameters ?? {});
|
|
90
|
+
const anc = ancestors(n.id);
|
|
91
|
+
for (const [, ref] of text.matchAll(REF)) {
|
|
92
|
+
const target = byName[ref];
|
|
93
|
+
if (!target) add('ERROR', `${n.id}: $('${ref}') names no node`);
|
|
94
|
+
else if (!anc.has(target.id)) add('ERROR', `${n.id}: $('${ref}') is not upstream of this node — it is undefined at runtime`);
|
|
95
|
+
}
|
|
96
|
+
for (const [, ref] of text.matchAll(QUOTED_STEP)) if (!byName[ref]) add('WARN', `${n.id}: comment or text mentions «${ref}», which is no node name (stale after a rename?)`);
|
|
97
|
+
if (n.type === 'code' && /\$\('/.test(n.parameters?.code ?? '')) add('ERROR', `${n.id}: a code node has no $() — feed it through a set node`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// --- node-specific checks
|
|
101
|
+
for (const n of nodes) {
|
|
102
|
+
const p = n.parameters ?? {};
|
|
103
|
+
const outs = succ[n.id];
|
|
104
|
+
const has = (h) => outs.some((e) => e.handle === h);
|
|
105
|
+
if (n.type === 'approval') {
|
|
106
|
+
if (Array.isArray(p.approvers) && !p.approvers.length) add('ERROR', `${n.id}: approvers is [] (the builder UI wipes expression approvers — rebuild from source)`);
|
|
107
|
+
if (!has('rejected')) add('NOTE', `${n.id}: a rejection ends the run here — intended?`);
|
|
108
|
+
if (!has('approved')) add('NOTE', `${n.id}: an approval ends the run here — intended?`);
|
|
109
|
+
}
|
|
110
|
+
if (n.type === 'if' && (!has('true') || !has('false'))) add('NOTE', `${n.id}: ${has('true') ? 'false ends' : has('false') ? 'true ends' : 'true and false end'} the run — intended?`);
|
|
111
|
+
if (n.type === 'switch') for (const r of p.rules || []) if (!has(r.output)) add('NOTE', `${n.id}: output "${r.output}" is not connected`);
|
|
112
|
+
if (n.type === 'switch') for (const r of p.rules || []) if (/^\d+$/.test(r.output) || /^[a-z]+[A-Z]/.test(r.output)) add('NOTE', `${n.id}: output "${r.output}" — name outputs by the business case (equipment, 1c-rights), they label the lines on the canvas`);
|
|
113
|
+
if (n.type === 'suppa' && p.action === 'select') {
|
|
114
|
+
if (p.limit == null) add('WARN', `${n.id}: select without limit`);
|
|
115
|
+
if (!p.fields) add('WARN', `${n.id}: select without fields loads whole rows`);
|
|
116
|
+
if (!pred[n.id].some((e) => by[e.from].type === 'if') && !outs.some((e) => by[e.to].type === 'merge')) add('NOTE', `${n.id}: 0 rows ends the branch — guard with an if, or fan out to a merge, unless stopping is intended`);
|
|
117
|
+
}
|
|
118
|
+
// Request / form flows: the formSubmission trigger already emits the submission row.
|
|
119
|
+
const formFlow = [...(flowOf[n.id] ?? [])].some((t) => by[t].type === 'formSubmission');
|
|
120
|
+
if (formFlow && n.type === 'suppa' && (p.action === 'getById' || p.action === 'select')) {
|
|
121
|
+
const text = JSON.stringify(p);
|
|
122
|
+
const fieldKeys = Object.keys(p.fields ?? {});
|
|
123
|
+
if (p.entityName === 'FormSubmissions') add('WARN', `${n.id}: re-reads FormSubmissions — the formSubmission trigger already emits the request row (formData, number, requestType, createdBy)`);
|
|
124
|
+
else if (p.entityName === 'Users' && /createdBy/.test(text) && fieldKeys.length && fieldKeys.every((k) => k === 'id' || k === 'fullName')) add('WARN', `${n.id}: reads the submitter's id / fullName — the trigger's createdBy already carries both`);
|
|
125
|
+
else if (/formData/.test(text) && fieldKeys.length && fieldKeys.every((k) => k === 'id')) add('WARN', `${n.id}: reads only id of a record picked in the form — formData already has { id }`);
|
|
126
|
+
}
|
|
127
|
+
if (n.type === 'suppa' && p.entityName === 'AutomationWorkflow' && p.action === 'getById' && !/\$workflow\.id/.test(String(p.id))) add('WARN', `${n.id}: reads another automation's settings by literal id — keep settings in this automation ($workflow.id)`);
|
|
128
|
+
if (n.type === 'triggerEntity') {
|
|
129
|
+
const upd = (p.events || []).some((e) => /update/.test(e));
|
|
130
|
+
if (upd && !(p.watchFields || []).length) add('WARN', `${n.id}: update trigger without watchFields starts a run on every edit`);
|
|
131
|
+
if (!p.conditions || !(p.conditions.filters || []).length) add('WARN', `${n.id}: no conditions — every record of ${p.entityName} starts a run; filter in the trigger`);
|
|
132
|
+
}
|
|
133
|
+
// A set whose every value is a bare reference only reshapes data; one that computes (a rule set:
|
|
134
|
+
// comparisons, ternaries, defaults) is a visible business rule and earns its node.
|
|
135
|
+
const reshapesOnly = (s) => (s.parameters?.assignments || []).every((a) => /^=\{\{\s*(\$json|\$\('[^']*'\)\.(first|item)\(\)\.json)(\??\.[\w$]+)*\s*\}\}$/.test(String(a.value)));
|
|
136
|
+
if (n.type === 'set' && pred[n.id].length === 1 && reshapesOnly(n)) {
|
|
137
|
+
const feedsCode = outs.some((e) => by[e.to].type === 'code' || (by[e.to].type === 'merge' && succ[e.to].some((x) => by[x.to].type === 'code')));
|
|
138
|
+
if (!feedsCode) add('WARN', `${n.id}: a set that feeds no code node only reshapes data — let the next nodes read $('…') directly (a set with several inputs, a join point, is fine)`);
|
|
139
|
+
if (outs.some((e) => by[e.to].type === 'set')) add('WARN', `${n.id}: set → set — fold them into one`);
|
|
140
|
+
}
|
|
141
|
+
if (n.type === 'suppa' && p.action === 'updateById') for (const e of outs) {
|
|
142
|
+
const q = by[e.to].parameters ?? {};
|
|
143
|
+
if (by[e.to].type === 'suppa' && q.action === 'updateById' && q.entityName === p.entityName && String(q.id) === String(p.id)) add('WARN', `${n.id} → ${e.to}: two updates of the same ${p.entityName} record in a row — merge them into one write`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// --- one read per entity per flow: reads of one entity on the same path are one query split in parts,
|
|
148
|
+
// unless a later read needs the earlier one's result (a task, then its parent) — exclusive branches never pair.
|
|
149
|
+
const isRead = (n) => n.type === 'suppa' && (n.parameters?.action === 'getById' || n.parameters?.action === 'select') && n.parameters?.entityName;
|
|
150
|
+
for (const t of triggers) {
|
|
151
|
+
const groups = {};
|
|
152
|
+
for (const n of nodes) if (flowOf[n.id]?.has(t.id) && isRead(n)) (groups[n.parameters.entityName] ??= []).push(n);
|
|
153
|
+
for (const [entity, list] of Object.entries(groups)) {
|
|
154
|
+
if (list.length < 2) continue;
|
|
155
|
+
const anc = Object.fromEntries(list.map((n) => [n.id, ancestors(n.id)]));
|
|
156
|
+
const needs = (b, a) => JSON.stringify(b.parameters).includes(`$('${a.name}')`);
|
|
157
|
+
const split = new Set();
|
|
158
|
+
for (const a of list) for (const b of list) if (a !== b && anc[b.id].has(a.id) && !needs(b, a)) { split.add(a.id); split.add(b.id); }
|
|
159
|
+
if (split.size >= 2) add('WARN', `flow of ${t.id}: ${split.size} reads of ${entity} (${[...split].join(', ')}) — fold into one query: one getById with nested fields, or one select with id in [...] and rows picked by id`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// --- safe runs and data in expressions
|
|
164
|
+
const TITLE_COMPARE = /\.title\??\s*(?:===|!==|==|!=)|\.title\??\.(?:startsWith|endsWith|includes|indexOf)\(/;
|
|
165
|
+
const FIXED_OFFSET = /T\d{2}:\d{2}(?::\d{2})?[+-]\d{2}:\d{2}/;
|
|
166
|
+
const BARE_ID = /^=\{\{[^{}[\]]*(?:\.id|Id)\s*\}\}$/;
|
|
167
|
+
for (const n of nodes) {
|
|
168
|
+
const p = n.parameters ?? {};
|
|
169
|
+
const text = n.type === 'code' ? String(p.code ?? '') : JSON.stringify(p);
|
|
170
|
+
if (TITLE_COMPARE.test(text)) add('WARN', `${n.id}: compares a title — titles are localized and may be null; compare value / id / code`);
|
|
171
|
+
if (FIXED_OFFSET.test(text)) add('WARN', `${n.id}: a datetime with a fixed UTC offset — wrong for half the year; compute it with references/tenant-time.md`);
|
|
172
|
+
if (n.type === 'code' && /return\s*\[\s*\]/.test(text) && /settings|cfg|config/i.test(text) && !/\bthrow\b/.test(text)) add('NOTE', `${n.id}: returns [] and never throws — if that [] means a missing setting, throw 'Not configured: …' so the run fails visibly`);
|
|
173
|
+
if (n.type === 'suppa' && (p.action === 'insert' || p.action === 'updateById')) {
|
|
174
|
+
for (const [k, v] of Object.entries(p.fields ?? {})) if (typeof v === 'string' && BARE_ID.test(v.trim())) add('WARN', `${n.id}: field ${k} gets a bare id — a relation is written as { id } (a bare id stores null); a plain number field can ignore this`);
|
|
175
|
+
}
|
|
176
|
+
if (n.type === 'notification') for (const key of ['subjectTemplate', 'bodyTemplate']) {
|
|
177
|
+
const t = p[key];
|
|
178
|
+
if (t && typeof t === 'object' && !('uk' in t)) add('WARN', `${n.id}: ${key} has no uk — notifications carry the users' language next to en`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (previous) {
|
|
182
|
+
const now = new Set(nodes.map((n) => n.id));
|
|
183
|
+
for (const n of previous.nodes ?? []) if (n.type === 'approval' && !now.has(n.id)) add('WARN', `approval ${n.id} («${n.name}») is published now and missing from the new graph — runs waiting there cannot continue; keep its id, or check status:"waiting" runs before publishing`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// --- size
|
|
187
|
+
for (const t of triggers) {
|
|
188
|
+
const members = nodes.filter((n) => flowOf[n.id]?.has(t.id));
|
|
189
|
+
if (members.length > 25) add('NOTE', `flow of ${t.id}: ${members.length} nodes — over ~25, check each node earns its place`);
|
|
190
|
+
const cols = new Set(members.filter((n) => n.position).map((n) => Math.round(n.position.x / 340)));
|
|
191
|
+
if (cols.size > 20) add('NOTE', `flow of ${t.id}: ${cols.size} columns wide — over ~20 the canvas no longer reads at a glance`);
|
|
192
|
+
}
|
|
193
|
+
return out;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
197
|
+
const args = process.argv.slice(2);
|
|
198
|
+
const prevAt = args.indexOf('--previous');
|
|
199
|
+
const previous = prevAt >= 0 ? readGraph(args[prevAt + 1], { side: 'published' }) : undefined;
|
|
200
|
+
const res = lint(readGraph(args[0]), { previous });
|
|
201
|
+
const order = { ERROR: 0, WARN: 1, NOTE: 2 };
|
|
202
|
+
res.sort((a, b) => order[a.level] - order[b.level]);
|
|
203
|
+
for (const r of res) console.log(`${r.level.padEnd(5)} ${r.msg}`);
|
|
204
|
+
const count = (l) => res.filter((r) => r.level === l).length;
|
|
205
|
+
console.log(`\n${count('ERROR')} errors, ${count('WARN')} warnings, ${count('NOTE')} notes`);
|
|
206
|
+
process.exit(count('ERROR') ? 1 : 0);
|
|
207
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Draws the canvas the way the builder will (same node geometry, step lines, handle colours) so the layout
|
|
2
|
+
// can be reviewed before publishing — without opening the builder, which autosaves its own copy.
|
|
3
|
+
// usage: node render-graph.mjs <graph.json> <out.svg> [--png out.png] [--width 2400]
|
|
4
|
+
// graph.json: the stored shape or a suppa_get_automation answer.
|
|
5
|
+
// --png renders through headless Chrome / Chromium / Edge (macOS, Linux, Windows), falling back to macOS Quick Look;
|
|
6
|
+
// with none of them it says so and exits 2 — the SVG is written either way.
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { execFileSync } from 'node:child_process';
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
11
|
+
import { MAX_WIDTH, height, inOffset, outOffset } from './geometry.mjs';
|
|
12
|
+
import { edges } from './edges.mjs';
|
|
13
|
+
import { readGraph } from './graph.mjs';
|
|
14
|
+
|
|
15
|
+
const FILL = { formSubmission: '#e0f2fe', triggerEntity: '#e0f2fe', triggerWebhook: '#e0f2fe', triggerSchedule: '#e0f2fe', triggerManual: '#e0f2fe', suppa: '#eef2ff', set: '#f3e8ff', code: '#dcfce7', if: '#fef3c7', switch: '#fef3c7', approval: '#ffe4e6', merge: '#f1f5f9', notification: '#fae8ff' };
|
|
16
|
+
const LINE = (h) => (h === 'false' || h === 'rejected' ? '#ef4444' : h === 'true' || h === 'approved' ? '#16a34a' : h === 'error' ? '#f97316' : '#94a3b8');
|
|
17
|
+
const esc = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
18
|
+
const fit = (s, px) => { const max = Math.floor(px / 6.4); return s.length > max ? s.slice(0, max - 1) + '…' : s; };
|
|
19
|
+
const outputs = (n) => (n.type === 'if' ? ['true', 'false'] : n.type === 'approval' ? ['approved', 'rejected'] : n.type === 'switch' ? (n.parameters?.rules || []).map((r) => r.output) : []);
|
|
20
|
+
|
|
21
|
+
export const renderSvg = (graph, width = 2400) => {
|
|
22
|
+
const { nodes } = graph;
|
|
23
|
+
const xs = nodes.flatMap((n) => [n.position.x, n.position.x + MAX_WIDTH]);
|
|
24
|
+
const ys = nodes.flatMap((n) => [n.position.y, n.position.y + height(n)]);
|
|
25
|
+
const pad = 60;
|
|
26
|
+
const minX = Math.min(...xs) - pad, minY = Math.min(...ys) - pad;
|
|
27
|
+
const W = Math.max(...xs) + pad - minX, H = Math.max(...ys) + pad - minY;
|
|
28
|
+
const parts = [];
|
|
29
|
+
for (const e of edges(graph)) {
|
|
30
|
+
const mx = (e.sx + e.tx) / 2;
|
|
31
|
+
parts.push(`<path d="M${e.sx} ${e.sy} H${mx} V${e.ty} H${e.tx}" fill="none" stroke="${LINE(e.handle)}" stroke-width="2"/>`);
|
|
32
|
+
}
|
|
33
|
+
for (const n of nodes) {
|
|
34
|
+
const { x, y } = n.position, h = height(n);
|
|
35
|
+
parts.push(`<rect x="${x}" y="${y}" width="${MAX_WIDTH}" height="${h}" rx="8" fill="${FILL[n.type] ?? '#ffffff'}" stroke="#94a3b8" stroke-width="1.5"/>`);
|
|
36
|
+
parts.push(`<text x="${x + 12}" y="${y + 20}" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1e293b">${esc(fit(n.name, MAX_WIDTH - 24))}</text>`);
|
|
37
|
+
parts.push(`<text x="${x + 12}" y="${y + 37}" font-family="Helvetica, Arial, sans-serif" font-size="10" fill="#64748b">${esc(n.type)}${n.parameters?.action ? ' · ' + esc(n.parameters.action) : ''}${n.parameters?.entityName ? ' · ' + esc(n.parameters.entityName) : ''}</text>`);
|
|
38
|
+
if (!/^(formSubmission|trigger)/.test(n.type)) parts.push(`<circle cx="${x}" cy="${y + inOffset(n)}" r="4" fill="#fff" stroke="#64748b"/>`);
|
|
39
|
+
const outs = outputs(n);
|
|
40
|
+
if (outs.length) for (const o of outs) {
|
|
41
|
+
const oy = y + outOffset(n, o);
|
|
42
|
+
parts.push(`<text x="${x + MAX_WIDTH - 12}" y="${oy + 3}" text-anchor="end" font-family="Helvetica, Arial, sans-serif" font-size="9" fill="${LINE(o)}">${esc(o)}</text>`);
|
|
43
|
+
parts.push(`<circle cx="${x + MAX_WIDTH - 16}" cy="${oy}" r="4" fill="#fff" stroke="${LINE(o)}"/>`);
|
|
44
|
+
} else parts.push(`<circle cx="${x + MAX_WIDTH - 16}" cy="${y + outOffset(n, 'main')}" r="4" fill="#fff" stroke="#64748b"/>`);
|
|
45
|
+
}
|
|
46
|
+
const outH = Math.round((width * H) / W);
|
|
47
|
+
return { svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${outH}" viewBox="${minX} ${minY} ${W} ${H}"><rect x="${minX}" y="${minY}" width="${W}" height="${H}" fill="#f8fafc"/>${parts.join('')}</svg>`, width, height: outH };
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// Where a headless-capable browser lives on each OS; Edge ships with every Windows.
|
|
51
|
+
export const browserCandidates = (env = process.env) => [
|
|
52
|
+
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',
|
|
53
|
+
...[env.PROGRAMFILES, env['PROGRAMFILES(X86)'], env.LOCALAPPDATA].filter(Boolean).flatMap((dir) => [
|
|
54
|
+
path.join(dir, 'Google', 'Chrome', 'Application', 'chrome.exe'),
|
|
55
|
+
path.join(dir, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
|
|
56
|
+
]),
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
60
|
+
const [graphFile, svgFile, ...rest] = process.argv.slice(2);
|
|
61
|
+
if (!graphFile || !svgFile) { console.error('usage: node render-graph.mjs <graph.json> <out.svg> [--png out.png] [--width 2400]'); process.exit(2); }
|
|
62
|
+
const opt = (k) => { const i = rest.indexOf(`--${k}`); return i >= 0 ? rest[i + 1] : undefined; };
|
|
63
|
+
const { svg, width, height: h } = renderSvg(readGraph(graphFile), Number(opt('width') ?? 2400));
|
|
64
|
+
fs.writeFileSync(svgFile, svg);
|
|
65
|
+
console.log(`svg ${svgFile} (${width}×${h})`);
|
|
66
|
+
const png = opt('png');
|
|
67
|
+
if (png) {
|
|
68
|
+
const bin = browserCandidates().find((p) => fs.existsSync(p));
|
|
69
|
+
const abs = path.resolve(svgFile);
|
|
70
|
+
const out = path.resolve(png);
|
|
71
|
+
if (bin) execFileSync(bin, ['--headless=new', '--disable-gpu', '--hide-scrollbars', `--window-size=${width},${h}`, `--screenshot=${out}`, pathToFileURL(abs).href], { stdio: 'ignore' });
|
|
72
|
+
else if (process.platform === 'darwin') { execFileSync('qlmanage', ['-t', '-s', String(width), '-o', path.dirname(out), abs], { stdio: 'ignore' }); fs.renameSync(path.join(path.dirname(out), path.basename(abs) + '.png'), out); }
|
|
73
|
+
else { console.error(`no Chrome, Chromium or Edge found for --png — open ${svgFile} in a browser instead`); process.exit(2); }
|
|
74
|
+
if (!fs.existsSync(out)) { console.error(`the browser wrote no ${png}`); process.exit(1); }
|
|
75
|
+
console.log(`png ${png}`);
|
|
76
|
+
}
|
|
77
|
+
}
|