@hogsend/engine 0.38.1 → 0.39.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/package.json +10 -7
- package/src/container.ts +133 -10
- package/src/index.ts +23 -0
- package/src/journeys/constants.ts +9 -0
- package/src/journeys/define-journey.ts +167 -6
- package/src/journeys/graph/build-graph.ts +1159 -0
- package/src/journeys/journey-boundary.ts +33 -0
- package/src/journeys/journey-context.ts +58 -8
- package/src/journeys/journey-log.ts +64 -0
- package/src/journeys/journey-source-locations-singleton.ts +19 -0
- package/src/journeys/journey-sources-singleton.ts +14 -0
- package/src/journeys/registry.ts +148 -5
- package/src/lib/email.ts +17 -6
- package/src/lib/ingestion.ts +13 -0
- package/src/lib/tracked.ts +32 -0
- package/src/lists/define-list.ts +19 -3
- package/src/routes/admin/index.ts +2 -0
- package/src/routes/admin/journeys.ts +278 -0
- package/src/routes/admin/open-editor.ts +106 -0
- package/src/routes/emails/index.ts +25 -1
- package/src/worker.ts +15 -2
|
@@ -0,0 +1,1159 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
JourneyEdge,
|
|
3
|
+
JourneyGraph,
|
|
4
|
+
JourneyMeta,
|
|
5
|
+
JourneyNode,
|
|
6
|
+
JourneyNodeType,
|
|
7
|
+
} from "@hogsend/core";
|
|
8
|
+
import * as acorn from "acorn";
|
|
9
|
+
import * as walk from "acorn-walk";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Runtime AST extractor: turn a journey's captured `run` source into a
|
|
13
|
+
* {@link JourneyGraph} for Studio's visual workflow.
|
|
14
|
+
*
|
|
15
|
+
* Two independent passes (see docs/studio-journey-flow-plan.md Phase 1):
|
|
16
|
+
*
|
|
17
|
+
* NODES — every recognized side-effect / durable primitive call in the `run`
|
|
18
|
+
* body becomes a node. Detection is STRUCTURAL, not name-based, so
|
|
19
|
+
* bundler-renamed imports (`sendEmail2`) still resolve: a `send` is any call
|
|
20
|
+
* whose first arg object carries `template`/`to`; a `connector` any whose first
|
|
21
|
+
* arg object carries `connectorId`/`action`. `ctx.*` primitives are detected by
|
|
22
|
+
* the property applied directly to the detected `ctx` binding (which may be
|
|
23
|
+
* `ctx`, `_ctx`, or absent). Node ids follow the A2 rule so they join to the
|
|
24
|
+
* runtime `journeyStates.currentNodeId`.
|
|
25
|
+
*
|
|
26
|
+
* EDGES — a real CONTROL-FLOW graph with forks + convergence, walked from the
|
|
27
|
+
* AST statement tree (NOT a flat linear chain). A branching `if`/`if-else`
|
|
28
|
+
* becomes an explicit `decision` node with a HUMANIZED question title
|
|
29
|
+
* (`Plan is pro?`, `Feature used?`, `Score ≤ 6?` — traced from the test
|
|
30
|
+
* expression, resolving `const` bindings back to `ctx.history.hasEvent` /
|
|
31
|
+
* `ctx.guard.isSubscribed` / property comparisons); the preceding node flows
|
|
32
|
+
* into the decision, whose `yes` edge (conditional-true) enters the consequent
|
|
33
|
+
* and whose `no` edge (conditional-false) enters the alternate (or skips to the
|
|
34
|
+
* convergence point when there is no else); both branches converge onto the node
|
|
35
|
+
* after the `if`. A `waitForEvent` followed by `if (<result>.timedOut)` forks the
|
|
36
|
+
* WAIT node itself into `timedOut` / `answered` (no decision node). A guard
|
|
37
|
+
* `if (cond) return/throw` (no else) routes that path to `end-completed` and
|
|
38
|
+
* continues. Loops / try-catch fall back to a linear sub-region + a warning; if
|
|
39
|
+
* the whole control-flow walk throws it degrades to a linear chain + a warning.
|
|
40
|
+
*
|
|
41
|
+
* The WHOLE extraction is wrapped in try/catch: any parse/walk failure returns
|
|
42
|
+
* {@link degradedGraphFromMeta}. It must NEVER throw.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
type Node = acorn.AnyNode;
|
|
46
|
+
type EdgeKind = NonNullable<JourneyEdge["kind"]>;
|
|
47
|
+
|
|
48
|
+
/** A dangling graph edge waiting to connect to the next node it flows into. */
|
|
49
|
+
interface OpenEnd {
|
|
50
|
+
id: string;
|
|
51
|
+
kind: EdgeKind;
|
|
52
|
+
label?: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** ctx namespaces/methods that are decision inputs / utilities, not nodes. */
|
|
56
|
+
const CTX_SKIP = new Set(["history", "guard", "when", "once", "now"]);
|
|
57
|
+
/** ctx primitives that DO become nodes, mapped to their node type. */
|
|
58
|
+
const CTX_NODE: Record<string, JourneyNodeType> = {
|
|
59
|
+
sleep: "sleep",
|
|
60
|
+
sleepUntil: "sleepUntil",
|
|
61
|
+
waitForEvent: "wait",
|
|
62
|
+
checkpoint: "checkpoint",
|
|
63
|
+
trigger: "trigger",
|
|
64
|
+
};
|
|
65
|
+
/** Bare identifier calls that are pure utilities, never `unknown` nodes. */
|
|
66
|
+
const UTIL_CALLS = new Set([
|
|
67
|
+
"days",
|
|
68
|
+
"hours",
|
|
69
|
+
"minutes",
|
|
70
|
+
"String",
|
|
71
|
+
"Boolean",
|
|
72
|
+
"Number",
|
|
73
|
+
"getPostHog",
|
|
74
|
+
]);
|
|
75
|
+
/**
|
|
76
|
+
* Duration-helper name → the ACTUAL `DurationObject` it produces at runtime
|
|
77
|
+
* (`@hogsend/core`: `days(n) = { hours: n*24 }`, `hours(n) = { hours: n }`,
|
|
78
|
+
* `minutes(n) = { minutes: n }`). Reconstructing the real object — not a
|
|
79
|
+
* fabricated `{ days: n }` — is what makes an unlabeled sleep's synthetic id
|
|
80
|
+
* (`wait:${JSON.stringify(duration)}`) BYTE-IDENTICAL to the engine's runtime
|
|
81
|
+
* `journeyStates.currentNodeId`, so the metrics join actually lands. There is
|
|
82
|
+
* no `days`/`weeks`/`seconds` key on `DurationObject`, and no `weeks()`/
|
|
83
|
+
* `seconds()` helper exists.
|
|
84
|
+
*/
|
|
85
|
+
const DURATION_HELPER: Record<string, (n: number) => Record<string, number>> = {
|
|
86
|
+
days: (n) => ({ hours: n * 24 }),
|
|
87
|
+
hours: (n) => ({ hours: n }),
|
|
88
|
+
minutes: (n) => ({ minutes: n }),
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/** Internal pre-node: a classified call plus its best-effort extracted fields. */
|
|
92
|
+
interface Raw {
|
|
93
|
+
kind: JourneyNodeType;
|
|
94
|
+
start: number;
|
|
95
|
+
line?: number;
|
|
96
|
+
authoredLabel?: string;
|
|
97
|
+
labelUnstable?: boolean;
|
|
98
|
+
duration?: Record<string, number>;
|
|
99
|
+
timeout?: Record<string, number>;
|
|
100
|
+
eventLiteral?: string;
|
|
101
|
+
eventIdent?: string;
|
|
102
|
+
templateLiteral?: string;
|
|
103
|
+
templateIdent?: string;
|
|
104
|
+
connectorId?: string;
|
|
105
|
+
action?: string;
|
|
106
|
+
idempotencyLabel?: string;
|
|
107
|
+
captureMethod?: string;
|
|
108
|
+
calleeName?: string;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function buildJourneyGraph({
|
|
112
|
+
runSource,
|
|
113
|
+
meta,
|
|
114
|
+
}: {
|
|
115
|
+
runSource?: string;
|
|
116
|
+
meta: JourneyMeta;
|
|
117
|
+
}): JourneyGraph {
|
|
118
|
+
if (!runSource) return degradedGraphFromMeta(meta);
|
|
119
|
+
try {
|
|
120
|
+
return extract(runSource, meta);
|
|
121
|
+
} catch {
|
|
122
|
+
return degradedGraphFromMeta(meta);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The meta-only fallback graph: `start → end-completed`, `degraded: true`. Used
|
|
128
|
+
* when the source is missing or extraction throws.
|
|
129
|
+
*/
|
|
130
|
+
export function degradedGraphFromMeta(meta: JourneyMeta): JourneyGraph {
|
|
131
|
+
return {
|
|
132
|
+
journeyId: meta.id,
|
|
133
|
+
degraded: true,
|
|
134
|
+
nodes: [startNode(meta), endNode()],
|
|
135
|
+
edges: [
|
|
136
|
+
{
|
|
137
|
+
id: "edge-0",
|
|
138
|
+
source: "start",
|
|
139
|
+
target: "end-completed",
|
|
140
|
+
kind: "default",
|
|
141
|
+
},
|
|
142
|
+
],
|
|
143
|
+
warnings: ["journey source unavailable — showing trigger only"],
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function extract(runSource: string, meta: JourneyMeta): JourneyGraph {
|
|
148
|
+
const wrapped = `(${runSource})`;
|
|
149
|
+
const ast = acorn.parse(wrapped, {
|
|
150
|
+
ecmaVersion: "latest",
|
|
151
|
+
locations: true,
|
|
152
|
+
allowReturnOutsideFunction: true,
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
const fn = findRunFunction(ast);
|
|
156
|
+
if (!fn) throw new Error("run function not found");
|
|
157
|
+
|
|
158
|
+
const ctxName =
|
|
159
|
+
fn.params[1]?.type === "Identifier" ? fn.params[1].name : undefined;
|
|
160
|
+
|
|
161
|
+
const warnings: string[] = [];
|
|
162
|
+
|
|
163
|
+
// --- Pass A: collect + classify every call in source order ---
|
|
164
|
+
const raws: Raw[] = [];
|
|
165
|
+
walk.fullAncestor(ast, (node, _state, ancestors) => {
|
|
166
|
+
if (node.type !== "CallExpression") return;
|
|
167
|
+
const raw = classifyCall(node, ctxName, ancestors, warnings);
|
|
168
|
+
if (raw) raws.push(raw);
|
|
169
|
+
});
|
|
170
|
+
raws.sort((a, b) => a.start - b.start);
|
|
171
|
+
|
|
172
|
+
// --- Pass B: assign ids (A2 join-key rules) ---
|
|
173
|
+
const emitted = assignNodes(raws);
|
|
174
|
+
dedupeIds(emitted);
|
|
175
|
+
|
|
176
|
+
const start = startNode(meta);
|
|
177
|
+
const end = endNode();
|
|
178
|
+
|
|
179
|
+
// --- Edges: real control-flow graph (forks + convergence) from the AST,
|
|
180
|
+
// minting `decision` nodes for branching ifs. If the walk throws on some
|
|
181
|
+
// exotic shape, degrade to a linear chain (never fail).
|
|
182
|
+
let edges: JourneyEdge[];
|
|
183
|
+
let decisions: JourneyNode[] = [];
|
|
184
|
+
try {
|
|
185
|
+
const flow = buildFlowEdges(fn, wrapped, ctxName, emitted, raws, warnings);
|
|
186
|
+
edges = flow.edges;
|
|
187
|
+
decisions = flow.decisions;
|
|
188
|
+
} catch {
|
|
189
|
+
warnings.push("control-flow analysis failed — showing linear path");
|
|
190
|
+
edges = buildLinearEdges([start, ...emitted, end]);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const nodes = [start, ...emitted, ...decisions, end];
|
|
194
|
+
|
|
195
|
+
// NB: exit conditions are intentionally NOT surfaced as a warning — they are
|
|
196
|
+
// already shown in the Studio's journey Definition card (and as end-exited
|
|
197
|
+
// terminal nodes in the graph), so a banner line here just duplicates them.
|
|
198
|
+
|
|
199
|
+
// Same helper / warning at N sites emits N identical strings — collapse them.
|
|
200
|
+
const uniqueWarnings = [...new Set(warnings)];
|
|
201
|
+
|
|
202
|
+
return {
|
|
203
|
+
journeyId: meta.id,
|
|
204
|
+
nodes,
|
|
205
|
+
edges,
|
|
206
|
+
...(uniqueWarnings.length ? { warnings: uniqueWarnings } : {}),
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// ---------------------------------------------------------------------------
|
|
211
|
+
// AST location / navigation
|
|
212
|
+
// ---------------------------------------------------------------------------
|
|
213
|
+
|
|
214
|
+
function findRunFunction(
|
|
215
|
+
ast: acorn.Program,
|
|
216
|
+
): acorn.ArrowFunctionExpression | acorn.FunctionExpression | undefined {
|
|
217
|
+
const stmt = ast.body[0];
|
|
218
|
+
if (stmt?.type === "ExpressionStatement") {
|
|
219
|
+
const e = stmt.expression;
|
|
220
|
+
if (
|
|
221
|
+
e.type === "ArrowFunctionExpression" ||
|
|
222
|
+
e.type === "FunctionExpression"
|
|
223
|
+
) {
|
|
224
|
+
return e;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
// Fallback: find the first function anywhere in the tree.
|
|
228
|
+
let found:
|
|
229
|
+
| acorn.ArrowFunctionExpression
|
|
230
|
+
| acorn.FunctionExpression
|
|
231
|
+
| undefined;
|
|
232
|
+
walk.simple(ast, {
|
|
233
|
+
ArrowFunctionExpression(n) {
|
|
234
|
+
found ??= n;
|
|
235
|
+
},
|
|
236
|
+
FunctionExpression(n) {
|
|
237
|
+
found ??= n;
|
|
238
|
+
},
|
|
239
|
+
});
|
|
240
|
+
return found;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Line number from acorn's `locations`; source is single-`(`-prefixed so it maps 1:1. */
|
|
244
|
+
function lineOf(node: Node): number | undefined {
|
|
245
|
+
return node.loc?.start.line;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* If `callee`'s base identifier is `ctxName`, return the property applied
|
|
250
|
+
* DIRECTLY to it (`ctx.sleep` → "sleep", `ctx.history.hasEvent` → "history").
|
|
251
|
+
* Otherwise null.
|
|
252
|
+
*/
|
|
253
|
+
function ctxFirstProp(callee: Node, ctxName: string): string | null {
|
|
254
|
+
let node: Node = callee;
|
|
255
|
+
while (node.type === "MemberExpression") {
|
|
256
|
+
const obj = node.object;
|
|
257
|
+
if (obj.type === "Identifier" && obj.name === ctxName) {
|
|
258
|
+
return node.property.type === "Identifier" ? node.property.name : null;
|
|
259
|
+
}
|
|
260
|
+
node = obj as Node;
|
|
261
|
+
}
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** The base identifier name of a member/call chain (`getPostHog()?.capture` → "getPostHog"). */
|
|
266
|
+
function rootIdentName(node: Node): string | undefined {
|
|
267
|
+
let n: Node = node;
|
|
268
|
+
for (;;) {
|
|
269
|
+
if (n.type === "Identifier") return n.name;
|
|
270
|
+
if (n.type === "MemberExpression") {
|
|
271
|
+
n = n.object as Node;
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (n.type === "CallExpression") {
|
|
275
|
+
n = n.callee as Node;
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
if (n.type === "ChainExpression") {
|
|
279
|
+
n = n.expression as Node;
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
return undefined;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** The last identifier of an expression (`Templates.NPS_SURVEY` → "NPS_SURVEY"). */
|
|
287
|
+
function lastIdentOf(node: Node | undefined): string | undefined {
|
|
288
|
+
if (!node) return undefined;
|
|
289
|
+
if (node.type === "Identifier") return node.name;
|
|
290
|
+
if (node.type === "MemberExpression") {
|
|
291
|
+
return node.property.type === "Identifier"
|
|
292
|
+
? node.property.name
|
|
293
|
+
: lastIdentOf(node.object as Node);
|
|
294
|
+
}
|
|
295
|
+
return undefined;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function objectProp(
|
|
299
|
+
obj: acorn.ObjectExpression,
|
|
300
|
+
key: string,
|
|
301
|
+
): Node | undefined {
|
|
302
|
+
for (const p of obj.properties) {
|
|
303
|
+
if (p.type !== "Property" || p.computed) continue;
|
|
304
|
+
const k = p.key;
|
|
305
|
+
const name =
|
|
306
|
+
k.type === "Identifier"
|
|
307
|
+
? k.name
|
|
308
|
+
: k.type === "Literal" && typeof k.value === "string"
|
|
309
|
+
? k.value
|
|
310
|
+
: undefined;
|
|
311
|
+
if (name === key) return p.value as Node;
|
|
312
|
+
}
|
|
313
|
+
return undefined;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function objectExprArg(
|
|
317
|
+
call: acorn.CallExpression,
|
|
318
|
+
): acorn.ObjectExpression | undefined {
|
|
319
|
+
const first = call.arguments[0];
|
|
320
|
+
return first && first.type === "ObjectExpression" ? first : undefined;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// ---------------------------------------------------------------------------
|
|
324
|
+
// Literal extraction
|
|
325
|
+
// ---------------------------------------------------------------------------
|
|
326
|
+
|
|
327
|
+
function stringLiteral(node: Node | undefined): string | undefined {
|
|
328
|
+
return node && node.type === "Literal" && typeof node.value === "string"
|
|
329
|
+
? node.value
|
|
330
|
+
: undefined;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** Cook a template literal to `"scored-${…}"`; `dynamic` when it has expressions. */
|
|
334
|
+
function cookTemplate(t: acorn.TemplateLiteral): {
|
|
335
|
+
text: string;
|
|
336
|
+
dynamic: boolean;
|
|
337
|
+
} {
|
|
338
|
+
let out = "";
|
|
339
|
+
t.quasis.forEach((q, i) => {
|
|
340
|
+
out += q.value.cooked ?? q.value.raw ?? "";
|
|
341
|
+
if (i < t.expressions.length) out += "${…}";
|
|
342
|
+
});
|
|
343
|
+
return { text: out, dynamic: t.expressions.length > 0 };
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Extract a label-like value: string literal, or cooked template (→ unstable). */
|
|
347
|
+
function extractLabel(
|
|
348
|
+
node: Node | undefined,
|
|
349
|
+
): { value: string; unstable: boolean } | undefined {
|
|
350
|
+
if (!node) return undefined;
|
|
351
|
+
const s = stringLiteral(node);
|
|
352
|
+
if (s !== undefined) return { value: s, unstable: false };
|
|
353
|
+
if (node.type === "TemplateLiteral") {
|
|
354
|
+
const { text, dynamic } = cookTemplate(node);
|
|
355
|
+
return { value: text, unstable: dynamic };
|
|
356
|
+
}
|
|
357
|
+
return undefined;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Extract a DurationObject from either a literal object (`{ hours: 336 }`,
|
|
362
|
+
* `{ days: 14 }` — passed through verbatim, matching whatever the author wrote)
|
|
363
|
+
* or a `days(14)`/`hours(1)`/`minutes(30)` helper call (reconstructed to the
|
|
364
|
+
* REAL runtime object via {@link DURATION_HELPER}). Non-literal → undefined.
|
|
365
|
+
*/
|
|
366
|
+
function extractDuration(
|
|
367
|
+
node: Node | undefined,
|
|
368
|
+
): Record<string, number> | undefined {
|
|
369
|
+
if (!node) return undefined;
|
|
370
|
+
if (node.type === "ObjectExpression") {
|
|
371
|
+
const out: Record<string, number> = {};
|
|
372
|
+
for (const p of node.properties) {
|
|
373
|
+
if (p.type !== "Property" || p.computed) continue;
|
|
374
|
+
const key =
|
|
375
|
+
p.key.type === "Identifier"
|
|
376
|
+
? p.key.name
|
|
377
|
+
: p.key.type === "Literal" && typeof p.key.value === "string"
|
|
378
|
+
? p.key.value
|
|
379
|
+
: undefined;
|
|
380
|
+
const val = p.value;
|
|
381
|
+
if (key && val.type === "Literal" && typeof val.value === "number") {
|
|
382
|
+
out[key] = val.value;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
return Object.keys(out).length ? out : undefined;
|
|
386
|
+
}
|
|
387
|
+
if (node.type === "CallExpression" && node.callee.type === "Identifier") {
|
|
388
|
+
const build = DURATION_HELPER[node.callee.name];
|
|
389
|
+
const arg = node.arguments[0];
|
|
390
|
+
if (
|
|
391
|
+
build &&
|
|
392
|
+
arg &&
|
|
393
|
+
arg.type === "Literal" &&
|
|
394
|
+
typeof arg.value === "number"
|
|
395
|
+
) {
|
|
396
|
+
return build(arg.value);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
return undefined;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// ---------------------------------------------------------------------------
|
|
403
|
+
// Classification
|
|
404
|
+
// ---------------------------------------------------------------------------
|
|
405
|
+
|
|
406
|
+
function classifyCall(
|
|
407
|
+
call: acorn.CallExpression,
|
|
408
|
+
ctxName: string | undefined,
|
|
409
|
+
ancestors: Node[],
|
|
410
|
+
warnings: string[],
|
|
411
|
+
): Raw | undefined {
|
|
412
|
+
const callee = call.callee;
|
|
413
|
+
if (callee.type === "Super") return undefined;
|
|
414
|
+
|
|
415
|
+
const base: Pick<Raw, "start" | "line"> = {
|
|
416
|
+
start: call.start,
|
|
417
|
+
line: lineOf(call),
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
// 1. ctx.* primitives (detected by the property applied directly to ctx).
|
|
421
|
+
if (ctxName) {
|
|
422
|
+
const prop = ctxFirstProp(callee, ctxName);
|
|
423
|
+
if (prop !== null) {
|
|
424
|
+
if (CTX_SKIP.has(prop)) return undefined;
|
|
425
|
+
const kind = CTX_NODE[prop];
|
|
426
|
+
if (!kind) return undefined; // unrecognized ctx member → not a node
|
|
427
|
+
return { ...base, ...ctxNodeFields(kind, call) };
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// 2. getPostHog()?.capture()/.identify()
|
|
432
|
+
if (callee.type === "MemberExpression") {
|
|
433
|
+
const method =
|
|
434
|
+
callee.property.type === "Identifier" ? callee.property.name : undefined;
|
|
435
|
+
if (
|
|
436
|
+
(method === "capture" || method === "identify") &&
|
|
437
|
+
rootIdentName(callee.object as Node) === "getPostHog"
|
|
438
|
+
) {
|
|
439
|
+
return { ...base, kind: "capture", captureMethod: method };
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// 3. Structural send / connector detection on the first-arg object.
|
|
444
|
+
const arg = objectExprArg(call);
|
|
445
|
+
if (arg) {
|
|
446
|
+
if (objectProp(arg, "connectorId") || objectProp(arg, "action")) {
|
|
447
|
+
const cid = stringLiteral(objectProp(arg, "connectorId"));
|
|
448
|
+
const act = stringLiteral(objectProp(arg, "action"));
|
|
449
|
+
return { ...base, kind: "connector", connectorId: cid, action: act };
|
|
450
|
+
}
|
|
451
|
+
if (objectProp(arg, "template") || objectProp(arg, "to")) {
|
|
452
|
+
return { ...base, ...sendFields(arg) };
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// 4. Awaited unknown bare-identifier call (a helper) → honest `unknown` node.
|
|
457
|
+
// An OPTIONAL call (`await helper?.()`) nests an extra ChainExpression between
|
|
458
|
+
// the AwaitExpression and the CallExpression — unwrap it so the optional form
|
|
459
|
+
// is treated identically to the plain one (else the side effect is dropped).
|
|
460
|
+
let parent = ancestors[ancestors.length - 2];
|
|
461
|
+
if (parent?.type === "ChainExpression") {
|
|
462
|
+
parent = ancestors[ancestors.length - 3];
|
|
463
|
+
}
|
|
464
|
+
const awaited = parent?.type === "AwaitExpression";
|
|
465
|
+
if (awaited && callee.type === "Identifier" && !UTIL_CALLS.has(callee.name)) {
|
|
466
|
+
warnings.push(
|
|
467
|
+
`'${callee.name}' is a helper call — its side effects are not expanded`,
|
|
468
|
+
);
|
|
469
|
+
return { ...base, kind: "unknown", calleeName: callee.name };
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
return undefined;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
type ClassifiedFields = Partial<Raw> & { kind: JourneyNodeType };
|
|
476
|
+
|
|
477
|
+
function ctxNodeFields(
|
|
478
|
+
kind: JourneyNodeType,
|
|
479
|
+
call: acorn.CallExpression,
|
|
480
|
+
): ClassifiedFields {
|
|
481
|
+
if (kind === "checkpoint") {
|
|
482
|
+
// ctx.checkpoint(label) — the label is the first positional arg.
|
|
483
|
+
const label = extractLabel(call.arguments[0] as Node | undefined);
|
|
484
|
+
return {
|
|
485
|
+
kind,
|
|
486
|
+
authoredLabel: label?.value,
|
|
487
|
+
labelUnstable: label?.unstable,
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
const arg = objectExprArg(call);
|
|
492
|
+
if (kind === "sleep") {
|
|
493
|
+
const label = extractLabel(arg && objectProp(arg, "label"));
|
|
494
|
+
return {
|
|
495
|
+
kind,
|
|
496
|
+
authoredLabel: label?.value,
|
|
497
|
+
labelUnstable: label?.unstable,
|
|
498
|
+
duration: arg ? extractDuration(objectProp(arg, "duration")) : undefined,
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
if (kind === "sleepUntil") {
|
|
502
|
+
const label = extractLabel(arg && objectProp(arg, "label"));
|
|
503
|
+
return {
|
|
504
|
+
kind,
|
|
505
|
+
authoredLabel: label?.value,
|
|
506
|
+
labelUnstable: label?.unstable,
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
if (kind === "wait") {
|
|
510
|
+
const label = extractLabel(arg && objectProp(arg, "label"));
|
|
511
|
+
const eventNode = arg ? objectProp(arg, "event") : undefined;
|
|
512
|
+
return {
|
|
513
|
+
kind,
|
|
514
|
+
authoredLabel: label?.value,
|
|
515
|
+
labelUnstable: label?.unstable,
|
|
516
|
+
eventLiteral: stringLiteral(eventNode),
|
|
517
|
+
eventIdent: lastIdentOf(eventNode),
|
|
518
|
+
timeout: arg ? extractDuration(objectProp(arg, "timeout")) : undefined,
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
// trigger
|
|
522
|
+
const eventNode = arg ? objectProp(arg, "event") : undefined;
|
|
523
|
+
return {
|
|
524
|
+
kind,
|
|
525
|
+
eventLiteral: stringLiteral(eventNode),
|
|
526
|
+
eventIdent: lastIdentOf(eventNode),
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function sendFields(arg: acorn.ObjectExpression): ClassifiedFields {
|
|
531
|
+
const templateNode = objectProp(arg, "template");
|
|
532
|
+
const idem = extractLabel(objectProp(arg, "idempotencyLabel"));
|
|
533
|
+
return {
|
|
534
|
+
kind: "send",
|
|
535
|
+
templateLiteral: stringLiteral(templateNode),
|
|
536
|
+
templateIdent: lastIdentOf(templateNode),
|
|
537
|
+
// Only a literal idempotencyLabel is a stable id "site".
|
|
538
|
+
idempotencyLabel: idem && !idem.unstable ? idem.value : undefined,
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// ---------------------------------------------------------------------------
|
|
543
|
+
// Node id assignment (A2)
|
|
544
|
+
// ---------------------------------------------------------------------------
|
|
545
|
+
|
|
546
|
+
function assignNodes(raws: Raw[]): JourneyNode[] {
|
|
547
|
+
const nodes: JourneyNode[] = [];
|
|
548
|
+
// The nearest preceding boundary label — the "site" a send inherits when it
|
|
549
|
+
// has no idempotencyLabel (mirrors the engine's boundary.currentLabel, which
|
|
550
|
+
// advances even on the engine's DETERMINISTIC default labels).
|
|
551
|
+
let currentLabel: string | undefined;
|
|
552
|
+
|
|
553
|
+
raws.forEach((raw, idx) => {
|
|
554
|
+
const { node, boundaryLabel } = nodeFromRaw(raw, idx, currentLabel);
|
|
555
|
+
if (boundaryLabel !== undefined) currentLabel = boundaryLabel;
|
|
556
|
+
nodes.push(node);
|
|
557
|
+
});
|
|
558
|
+
return nodes;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function nodeFromRaw(
|
|
562
|
+
raw: Raw,
|
|
563
|
+
idx: number,
|
|
564
|
+
currentLabel: string | undefined,
|
|
565
|
+
): { node: JourneyNode; boundaryLabel?: string } {
|
|
566
|
+
const meta: NonNullable<JourneyNode["meta"]> = {};
|
|
567
|
+
let id: string;
|
|
568
|
+
let title: string;
|
|
569
|
+
let subtitle: string | undefined;
|
|
570
|
+
let boundaryLabel: string | undefined;
|
|
571
|
+
|
|
572
|
+
switch (raw.kind) {
|
|
573
|
+
case "sleep": {
|
|
574
|
+
if (raw.authoredLabel !== undefined) {
|
|
575
|
+
id = raw.authoredLabel;
|
|
576
|
+
boundaryLabel = raw.labelUnstable ? undefined : raw.authoredLabel;
|
|
577
|
+
} else if (raw.duration) {
|
|
578
|
+
// DETERMINISTIC synthetic id — byte-identical to the engine's default
|
|
579
|
+
// `currentNodeId`. Advance currentLabel exactly as the engine's
|
|
580
|
+
// setBoundaryLabel does, so a following label-less send inherits it.
|
|
581
|
+
id = `wait:${JSON.stringify(raw.duration)}`;
|
|
582
|
+
boundaryLabel = id;
|
|
583
|
+
} else {
|
|
584
|
+
id = `sleep:${idx}`;
|
|
585
|
+
meta.unstable = true;
|
|
586
|
+
}
|
|
587
|
+
if (raw.duration) meta.duration = raw.duration;
|
|
588
|
+
if (raw.labelUnstable) meta.unstable = true;
|
|
589
|
+
title = raw.authoredLabel ?? "Sleep";
|
|
590
|
+
subtitle = raw.duration ? formatDuration(raw.duration) : undefined;
|
|
591
|
+
break;
|
|
592
|
+
}
|
|
593
|
+
case "sleepUntil": {
|
|
594
|
+
if (raw.authoredLabel !== undefined) {
|
|
595
|
+
id = raw.authoredLabel;
|
|
596
|
+
boundaryLabel = raw.labelUnstable ? undefined : raw.authoredLabel;
|
|
597
|
+
if (raw.labelUnstable) meta.unstable = true;
|
|
598
|
+
} else {
|
|
599
|
+
id = `wait-until:${idx}`;
|
|
600
|
+
meta.unstable = true;
|
|
601
|
+
}
|
|
602
|
+
title = raw.authoredLabel ?? "Sleep until";
|
|
603
|
+
break;
|
|
604
|
+
}
|
|
605
|
+
case "wait": {
|
|
606
|
+
if (raw.authoredLabel !== undefined) {
|
|
607
|
+
id = raw.authoredLabel;
|
|
608
|
+
boundaryLabel = raw.labelUnstable ? undefined : raw.authoredLabel;
|
|
609
|
+
if (raw.labelUnstable) meta.unstable = true;
|
|
610
|
+
} else if (raw.eventLiteral !== undefined) {
|
|
611
|
+
// DETERMINISTIC synthetic id (engine default `wait-event:${event}`) —
|
|
612
|
+
// advance currentLabel so a following label-less send inherits it.
|
|
613
|
+
id = `wait-event:${raw.eventLiteral}`;
|
|
614
|
+
boundaryLabel = id;
|
|
615
|
+
} else {
|
|
616
|
+
id = `wait-event:${idx}`;
|
|
617
|
+
meta.unstable = true;
|
|
618
|
+
}
|
|
619
|
+
if (raw.eventLiteral) meta.event = raw.eventLiteral;
|
|
620
|
+
if (raw.timeout) meta.timeout = raw.timeout;
|
|
621
|
+
subtitle = raw.eventLiteral ?? raw.eventIdent;
|
|
622
|
+
title = raw.authoredLabel ?? subtitle ?? "Wait for event";
|
|
623
|
+
break;
|
|
624
|
+
}
|
|
625
|
+
case "checkpoint": {
|
|
626
|
+
id = raw.authoredLabel ?? `checkpoint:${idx}`;
|
|
627
|
+
if (raw.authoredLabel === undefined || raw.labelUnstable) {
|
|
628
|
+
meta.unstable = true;
|
|
629
|
+
}
|
|
630
|
+
if (raw.authoredLabel !== undefined && !raw.labelUnstable) {
|
|
631
|
+
boundaryLabel = raw.authoredLabel;
|
|
632
|
+
}
|
|
633
|
+
title = "Checkpoint";
|
|
634
|
+
subtitle = raw.authoredLabel;
|
|
635
|
+
break;
|
|
636
|
+
}
|
|
637
|
+
case "trigger": {
|
|
638
|
+
const key = raw.eventLiteral ?? raw.eventIdent ?? String(idx);
|
|
639
|
+
id = `trigger:${key}`;
|
|
640
|
+
if (raw.eventLiteral) meta.event = raw.eventLiteral;
|
|
641
|
+
title = "Trigger";
|
|
642
|
+
subtitle = raw.eventLiteral ?? raw.eventIdent;
|
|
643
|
+
break;
|
|
644
|
+
}
|
|
645
|
+
case "send": {
|
|
646
|
+
const site =
|
|
647
|
+
raw.idempotencyLabel ??
|
|
648
|
+
currentLabel ??
|
|
649
|
+
raw.templateLiteral ??
|
|
650
|
+
raw.templateIdent ??
|
|
651
|
+
"send";
|
|
652
|
+
id = `send:${site}`;
|
|
653
|
+
if (raw.templateLiteral) meta.template = raw.templateLiteral;
|
|
654
|
+
if (raw.idempotencyLabel) meta.idempotencyLabel = raw.idempotencyLabel;
|
|
655
|
+
title = "Send email";
|
|
656
|
+
subtitle =
|
|
657
|
+
raw.templateLiteral ?? raw.templateIdent ?? raw.idempotencyLabel;
|
|
658
|
+
break;
|
|
659
|
+
}
|
|
660
|
+
case "connector": {
|
|
661
|
+
id = `connector:${raw.connectorId ?? idx}:${raw.action ?? idx}`;
|
|
662
|
+
if (raw.connectorId) meta.connectorId = raw.connectorId;
|
|
663
|
+
if (raw.action) meta.action = raw.action;
|
|
664
|
+
title = raw.action ?? "Connector action";
|
|
665
|
+
subtitle =
|
|
666
|
+
[raw.connectorId, raw.action].filter(Boolean).join(" · ") || undefined;
|
|
667
|
+
break;
|
|
668
|
+
}
|
|
669
|
+
case "capture": {
|
|
670
|
+
id = `capture:${idx}`;
|
|
671
|
+
title = raw.captureMethod === "identify" ? "Identify" : "Capture";
|
|
672
|
+
subtitle = raw.captureMethod;
|
|
673
|
+
break;
|
|
674
|
+
}
|
|
675
|
+
default: {
|
|
676
|
+
// unknown
|
|
677
|
+
id = `unknown:${raw.calleeName ?? "call"}:${idx}`;
|
|
678
|
+
title = raw.calleeName ?? "Unknown call";
|
|
679
|
+
subtitle = "helper call";
|
|
680
|
+
break;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const node: JourneyNode = {
|
|
685
|
+
id,
|
|
686
|
+
type: raw.kind,
|
|
687
|
+
title,
|
|
688
|
+
...(subtitle ? { subtitle } : {}),
|
|
689
|
+
...(Object.keys(meta).length ? { meta } : {}),
|
|
690
|
+
...(raw.line ? { line: raw.line } : {}),
|
|
691
|
+
};
|
|
692
|
+
return { node, boundaryLabel };
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/** Suffix `#2`, `#3`, … onto any duplicate emitted ids to keep them unique. */
|
|
696
|
+
function dedupeIds(nodes: JourneyNode[]): void {
|
|
697
|
+
const used = new Set<string>(["start", "end-completed"]);
|
|
698
|
+
for (const node of nodes) {
|
|
699
|
+
if (!used.has(node.id)) {
|
|
700
|
+
used.add(node.id);
|
|
701
|
+
continue;
|
|
702
|
+
}
|
|
703
|
+
let k = 2;
|
|
704
|
+
while (used.has(`${node.id}#${k}`)) k++;
|
|
705
|
+
node.id = `${node.id}#${k}`;
|
|
706
|
+
used.add(node.id);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
// ---------------------------------------------------------------------------
|
|
711
|
+
// Terminals
|
|
712
|
+
// ---------------------------------------------------------------------------
|
|
713
|
+
|
|
714
|
+
function startNode(meta: JourneyMeta): JourneyNode {
|
|
715
|
+
return {
|
|
716
|
+
id: "start",
|
|
717
|
+
type: "start",
|
|
718
|
+
title: "Start",
|
|
719
|
+
...(meta.trigger.event ? { subtitle: meta.trigger.event } : {}),
|
|
720
|
+
...(meta.trigger.where?.length
|
|
721
|
+
? { meta: { conditions: meta.trigger.where } }
|
|
722
|
+
: {}),
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
function endNode(): JourneyNode {
|
|
727
|
+
return { id: "end-completed", type: "end-completed", title: "Completed" };
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/** Ultimate fallback: a flat `start → … → end-completed` chain. */
|
|
731
|
+
function buildLinearEdges(nodes: JourneyNode[]): JourneyEdge[] {
|
|
732
|
+
const edges: JourneyEdge[] = [];
|
|
733
|
+
for (let i = 0; i < nodes.length - 1; i++) {
|
|
734
|
+
const from = nodes[i];
|
|
735
|
+
const to = nodes[i + 1];
|
|
736
|
+
if (!from || !to) continue;
|
|
737
|
+
edges.push({
|
|
738
|
+
id: `edge-${i}`,
|
|
739
|
+
source: from.id,
|
|
740
|
+
target: to.id,
|
|
741
|
+
kind: "default",
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
return edges;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// ---------------------------------------------------------------------------
|
|
748
|
+
// Control-flow edges — walk the statement tree; branching ifs become decision
|
|
749
|
+
// nodes, waitForEvent `.timedOut` ifs fork the wait node, guards early-exit.
|
|
750
|
+
// ---------------------------------------------------------------------------
|
|
751
|
+
|
|
752
|
+
/** Is a test the `<x>.timedOut` shape that turns a wait into a fork? */
|
|
753
|
+
function testIsTimedOut(test: Node): boolean {
|
|
754
|
+
const t = test.type === "ChainExpression" ? test.expression : test;
|
|
755
|
+
return (
|
|
756
|
+
t.type === "MemberExpression" &&
|
|
757
|
+
t.property.type === "Identifier" &&
|
|
758
|
+
t.property.name === "timedOut"
|
|
759
|
+
);
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* Is the test a `!X` negation? The decision title is the POSITIVE question, so a
|
|
764
|
+
* negated test routes the consequent (which runs when the positive condition is
|
|
765
|
+
* FALSE) onto the `no` edge and the alternate/bypass onto `yes`.
|
|
766
|
+
*/
|
|
767
|
+
function testIsNegated(test: Node): boolean {
|
|
768
|
+
const t = test.type === "ChainExpression" ? test.expression : test;
|
|
769
|
+
return t.type === "UnaryExpression" && t.operator === "!";
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/** Comparison operator → readable phrasing for a decision question. */
|
|
773
|
+
const COMPARISON_OPS: Record<string, string> = {
|
|
774
|
+
"===": "is",
|
|
775
|
+
"==": "is",
|
|
776
|
+
"!==": "is not",
|
|
777
|
+
"!=": "is not",
|
|
778
|
+
">=": "≥",
|
|
779
|
+
"<=": "≤",
|
|
780
|
+
">": ">",
|
|
781
|
+
"<": "<",
|
|
782
|
+
};
|
|
783
|
+
|
|
784
|
+
function cap(s: string): string {
|
|
785
|
+
return s ? s.charAt(0).toUpperCase() + s.slice(1) : s;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/** `FEATURE_USED` → "feature used"; `hasUsedFeature` → "has used feature". */
|
|
789
|
+
function humanizeIdent(name: string): string {
|
|
790
|
+
if (/^[A-Z0-9_]+$/.test(name)) return name.toLowerCase().replace(/_/g, " ");
|
|
791
|
+
return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase();
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/** An event name → a short yes/no question, `FEATURE_USED` → "Feature used?". */
|
|
795
|
+
function eventTitle(name: string): string {
|
|
796
|
+
return `${cap(humanizeIdent(name))}?`;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/** The identifiers a `const`/`let` pattern binds (`{ found: x }` → ["x"]). */
|
|
800
|
+
function patternNames(pat: Node): string[] {
|
|
801
|
+
if (pat.type === "Identifier") return [pat.name];
|
|
802
|
+
if (pat.type === "ObjectPattern") {
|
|
803
|
+
const names: string[] = [];
|
|
804
|
+
for (const p of pat.properties) {
|
|
805
|
+
if (p.type !== "Property") continue;
|
|
806
|
+
const v = p.value;
|
|
807
|
+
if (v.type === "Identifier") names.push(v.name);
|
|
808
|
+
else if (v.type === "AssignmentPattern" && v.left.type === "Identifier") {
|
|
809
|
+
names.push(v.left.name);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
return names;
|
|
813
|
+
}
|
|
814
|
+
return [];
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
function buildFlowEdges(
|
|
818
|
+
fn: acorn.ArrowFunctionExpression | acorn.FunctionExpression,
|
|
819
|
+
source: string,
|
|
820
|
+
ctxName: string | undefined,
|
|
821
|
+
emitted: JourneyNode[],
|
|
822
|
+
raws: Raw[],
|
|
823
|
+
warnings: string[],
|
|
824
|
+
): { edges: JourneyEdge[]; decisions: JourneyNode[] } {
|
|
825
|
+
const edges: JourneyEdge[] = [];
|
|
826
|
+
const seen = new Set<string>();
|
|
827
|
+
let counter = 0;
|
|
828
|
+
|
|
829
|
+
const nodeType = new Map<string, JourneyNodeType>();
|
|
830
|
+
for (const n of emitted) nodeType.set(n.id, n.type);
|
|
831
|
+
|
|
832
|
+
// Synthetic `decision` nodes minted for branching ifs (unique ids, appended
|
|
833
|
+
// to the graph's node list by the caller).
|
|
834
|
+
const used = new Set<string>(["start", "end-completed"]);
|
|
835
|
+
for (const n of emitted) used.add(n.id);
|
|
836
|
+
const decisions: JourneyNode[] = [];
|
|
837
|
+
let decisionCounter = 0;
|
|
838
|
+
const mintDecision = (title: string): JourneyNode => {
|
|
839
|
+
let id = `decision:${decisionCounter++}`;
|
|
840
|
+
while (used.has(id)) id = `decision:${decisionCounter++}`;
|
|
841
|
+
used.add(id);
|
|
842
|
+
// Decisions don't join to currentNodeId — the id is purely a React key, so
|
|
843
|
+
// it is always synthetic (unstable).
|
|
844
|
+
const node: JourneyNode = {
|
|
845
|
+
id,
|
|
846
|
+
type: "decision",
|
|
847
|
+
title,
|
|
848
|
+
meta: { unstable: true },
|
|
849
|
+
};
|
|
850
|
+
decisions.push(node);
|
|
851
|
+
return node;
|
|
852
|
+
};
|
|
853
|
+
|
|
854
|
+
const addEdge = (oe: OpenEnd, targetId: string): void => {
|
|
855
|
+
// Dedupe by (source, target, kind): guards can otherwise emit the same edge
|
|
856
|
+
// from several early-return sites.
|
|
857
|
+
const key = `${oe.id}${targetId}${oe.kind}`;
|
|
858
|
+
if (seen.has(key)) return;
|
|
859
|
+
seen.add(key);
|
|
860
|
+
edges.push({
|
|
861
|
+
id: `edge-${counter++}`,
|
|
862
|
+
source: oe.id,
|
|
863
|
+
target: targetId,
|
|
864
|
+
kind: oe.kind,
|
|
865
|
+
...(oe.label ? { label: oe.label } : {}),
|
|
866
|
+
});
|
|
867
|
+
};
|
|
868
|
+
|
|
869
|
+
/** Emitted nodes whose call.start ∈ [lo, hi), in source order. */
|
|
870
|
+
const nodesInRange = (lo: number, hi: number): JourneyNode[] => {
|
|
871
|
+
const out: JourneyNode[] = [];
|
|
872
|
+
for (let i = 0; i < raws.length; i++) {
|
|
873
|
+
const r = raws[i];
|
|
874
|
+
const n = emitted[i];
|
|
875
|
+
if (r && n && r.start >= lo && r.start < hi) out.push(n);
|
|
876
|
+
}
|
|
877
|
+
return out;
|
|
878
|
+
};
|
|
879
|
+
const hasNodesInRange = (lo: number, hi: number): boolean =>
|
|
880
|
+
raws.some((r) => r.start >= lo && r.start < hi);
|
|
881
|
+
|
|
882
|
+
/** Chain preds through the node-worthy calls in [lo, hi) linearly. */
|
|
883
|
+
const chainRange = (lo: number, hi: number, preds: OpenEnd[]): OpenEnd[] => {
|
|
884
|
+
let cur = preds;
|
|
885
|
+
for (const n of nodesInRange(lo, hi)) {
|
|
886
|
+
for (const oe of cur) addEdge(oe, n.id);
|
|
887
|
+
cur = [{ id: n.id, kind: "default" }];
|
|
888
|
+
}
|
|
889
|
+
return cur;
|
|
890
|
+
};
|
|
891
|
+
|
|
892
|
+
/** A pass-through guard: `if (cond) return/throw` — no else, no nodes inside. */
|
|
893
|
+
const isPureExitGuard = (consequent: Node): boolean => {
|
|
894
|
+
if (hasNodesInRange(consequent.start, consequent.end)) return false;
|
|
895
|
+
if (
|
|
896
|
+
consequent.type === "ReturnStatement" ||
|
|
897
|
+
consequent.type === "ThrowStatement"
|
|
898
|
+
) {
|
|
899
|
+
return true;
|
|
900
|
+
}
|
|
901
|
+
if (consequent.type === "BlockStatement") {
|
|
902
|
+
const last = consequent.body[consequent.body.length - 1];
|
|
903
|
+
return (
|
|
904
|
+
!!last &&
|
|
905
|
+
(last.type === "ReturnStatement" || last.type === "ThrowStatement")
|
|
906
|
+
);
|
|
907
|
+
}
|
|
908
|
+
return false;
|
|
909
|
+
};
|
|
910
|
+
|
|
911
|
+
// --- Humanizers: trace the test expression into a readable question. ---
|
|
912
|
+
const sourceSlice = (n: Node): string => source.slice(n.start, n.end);
|
|
913
|
+
|
|
914
|
+
const operandText = (n: Node): string => {
|
|
915
|
+
if (n.type === "MemberExpression") return lastIdentOf(n) ?? sourceSlice(n);
|
|
916
|
+
if (n.type === "Literal") {
|
|
917
|
+
return typeof n.value === "string"
|
|
918
|
+
? n.value
|
|
919
|
+
: String(n.value ?? sourceSlice(n));
|
|
920
|
+
}
|
|
921
|
+
if (n.type === "Identifier") return humanizeIdent(n.name);
|
|
922
|
+
return sourceSlice(n);
|
|
923
|
+
};
|
|
924
|
+
|
|
925
|
+
const humanizeComparison = (
|
|
926
|
+
bin: acorn.BinaryExpression,
|
|
927
|
+
): string | undefined => {
|
|
928
|
+
const op = COMPARISON_OPS[bin.operator];
|
|
929
|
+
if (!op) return undefined;
|
|
930
|
+
const left = cap(operandText(bin.left as Node));
|
|
931
|
+
return `${left} ${op} ${operandText(bin.right as Node)}?`;
|
|
932
|
+
};
|
|
933
|
+
|
|
934
|
+
/** Resolve a binding init (`ctx.history.hasEvent` / `isSubscribed` / compare). */
|
|
935
|
+
const traceHint = (init: Node): string | undefined => {
|
|
936
|
+
let n = init;
|
|
937
|
+
if (n.type === "AwaitExpression") n = n.argument as Node;
|
|
938
|
+
if (n.type === "ChainExpression") n = n.expression as Node;
|
|
939
|
+
if (n.type === "BinaryExpression") return humanizeComparison(n);
|
|
940
|
+
let call: Node = n;
|
|
941
|
+
if (call.type === "MemberExpression") call = call.object as Node;
|
|
942
|
+
if (call.type === "AwaitExpression") call = call.argument as Node;
|
|
943
|
+
if (call.type === "ChainExpression") call = call.expression as Node;
|
|
944
|
+
if (call.type === "CallExpression" && ctxName) {
|
|
945
|
+
const first = ctxFirstProp(call.callee as Node, ctxName);
|
|
946
|
+
const method = lastIdentOf(call.callee as Node);
|
|
947
|
+
if (first === "history" && method === "hasEvent") {
|
|
948
|
+
const arg = objectExprArg(call);
|
|
949
|
+
const ev = arg ? objectProp(arg, "event") : undefined;
|
|
950
|
+
const name = stringLiteral(ev) ?? lastIdentOf(ev);
|
|
951
|
+
return name ? eventTitle(name) : "Event occurred?";
|
|
952
|
+
}
|
|
953
|
+
if (first === "guard" && method === "isSubscribed") {
|
|
954
|
+
return "Still subscribed?";
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
return undefined;
|
|
958
|
+
};
|
|
959
|
+
|
|
960
|
+
// Track simple boolean bindings so `if (isPro)` resolves to its real criteria.
|
|
961
|
+
const bindingMap = new Map<string, string>();
|
|
962
|
+
walk.simple(fn, {
|
|
963
|
+
VariableDeclarator(d) {
|
|
964
|
+
if (!d.init) return;
|
|
965
|
+
const hint = traceHint(d.init as Node);
|
|
966
|
+
if (!hint) return;
|
|
967
|
+
for (const name of patternNames(d.id as Node)) bindingMap.set(name, hint);
|
|
968
|
+
},
|
|
969
|
+
});
|
|
970
|
+
|
|
971
|
+
/** The humanized question for an `if` test (best-effort; falls back to code). */
|
|
972
|
+
const humanizeCondition = (test: Node): string => {
|
|
973
|
+
let t = test;
|
|
974
|
+
if (t.type === "ChainExpression") t = t.expression as Node;
|
|
975
|
+
// Strip a single leading `!` — the yes/no edges carry the branch selection,
|
|
976
|
+
// so the title stays the positive question.
|
|
977
|
+
if (t.type === "UnaryExpression" && t.operator === "!") {
|
|
978
|
+
t = t.argument as Node;
|
|
979
|
+
}
|
|
980
|
+
if (t.type === "AwaitExpression") t = t.argument as Node;
|
|
981
|
+
if (t.type === "ChainExpression") t = t.expression as Node;
|
|
982
|
+
if (t.type === "Identifier") {
|
|
983
|
+
return bindingMap.get(t.name) ?? `${cap(humanizeIdent(t.name))}?`;
|
|
984
|
+
}
|
|
985
|
+
if (t.type === "BinaryExpression") {
|
|
986
|
+
const c = humanizeComparison(t);
|
|
987
|
+
if (c) return c;
|
|
988
|
+
}
|
|
989
|
+
if (t.type === "CallExpression") {
|
|
990
|
+
const h = traceHint(t);
|
|
991
|
+
if (h) return h;
|
|
992
|
+
}
|
|
993
|
+
return `${truncate(sourceSlice(t))}?`;
|
|
994
|
+
};
|
|
995
|
+
|
|
996
|
+
function flowSeq(stmts: Node[], preds: OpenEnd[]): OpenEnd[] {
|
|
997
|
+
let cur = preds;
|
|
998
|
+
for (const s of stmts) cur = flowStatement(s, cur);
|
|
999
|
+
return cur;
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
function flowStatement(stmt: Node, preds: OpenEnd[]): OpenEnd[] {
|
|
1003
|
+
switch (stmt.type) {
|
|
1004
|
+
case "BlockStatement":
|
|
1005
|
+
return flowSeq(stmt.body, preds);
|
|
1006
|
+
case "IfStatement":
|
|
1007
|
+
return flowIf(stmt, preds);
|
|
1008
|
+
case "ReturnStatement":
|
|
1009
|
+
case "ThrowStatement": {
|
|
1010
|
+
// Any node in the return argument connects first, then → terminal.
|
|
1011
|
+
const cur = chainRange(stmt.start, stmt.end, preds);
|
|
1012
|
+
for (const oe of cur) addEdge(oe, "end-completed");
|
|
1013
|
+
return [];
|
|
1014
|
+
}
|
|
1015
|
+
case "TryStatement": {
|
|
1016
|
+
warnings.push("try/catch shown as a linear region");
|
|
1017
|
+
let out = flowStatement(stmt.block, preds);
|
|
1018
|
+
if (stmt.handler) {
|
|
1019
|
+
out = [...out, ...flowStatement(stmt.handler.body, preds)];
|
|
1020
|
+
}
|
|
1021
|
+
if (stmt.finalizer) out = flowStatement(stmt.finalizer, out);
|
|
1022
|
+
return out;
|
|
1023
|
+
}
|
|
1024
|
+
case "WhileStatement":
|
|
1025
|
+
case "DoWhileStatement":
|
|
1026
|
+
case "ForStatement":
|
|
1027
|
+
case "ForInStatement":
|
|
1028
|
+
case "ForOfStatement": {
|
|
1029
|
+
warnings.push("loop body shown once (not expanded)");
|
|
1030
|
+
return flowStatement(stmt.body, preds);
|
|
1031
|
+
}
|
|
1032
|
+
case "LabeledStatement":
|
|
1033
|
+
return flowStatement(stmt.body, preds);
|
|
1034
|
+
default:
|
|
1035
|
+
// Expression / variable / etc: chain its direct node-worthy calls.
|
|
1036
|
+
return chainRange(stmt.start, stmt.end, preds);
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
function flowIf(stmt: acorn.IfStatement, predsIn: OpenEnd[]): OpenEnd[] {
|
|
1041
|
+
// Node-worthy calls in the TEST run BEFORE the fork (rare, but honest).
|
|
1042
|
+
const preds = chainRange(stmt.test.start, stmt.test.end, predsIn);
|
|
1043
|
+
|
|
1044
|
+
const firstPred = preds[0];
|
|
1045
|
+
const waitFork =
|
|
1046
|
+
preds.length === 1 &&
|
|
1047
|
+
firstPred !== undefined &&
|
|
1048
|
+
nodeType.get(firstPred.id) === "wait" &&
|
|
1049
|
+
testIsTimedOut(stmt.test);
|
|
1050
|
+
|
|
1051
|
+
// Guard `if (cond) return;` — no else, consequent is a pure return/throw.
|
|
1052
|
+
// The TRUE path exits to the terminal; the FALSE path continues with the
|
|
1053
|
+
// predecessors' kinds PRESERVED (so an upstream branch label — e.g. a wait's
|
|
1054
|
+
// "answered" — survives the guard instead of being re-labeled). No decision
|
|
1055
|
+
// node: a guard is a one-way filter, not a two-way branch.
|
|
1056
|
+
if (!stmt.alternate && isPureExitGuard(stmt.consequent)) {
|
|
1057
|
+
if (waitFork && firstPred) {
|
|
1058
|
+
addEdge(
|
|
1059
|
+
{ id: firstPred.id, kind: "timedOut", label: "timed out" },
|
|
1060
|
+
"end-completed",
|
|
1061
|
+
);
|
|
1062
|
+
return [{ id: firstPred.id, kind: "answered", label: "answered" }];
|
|
1063
|
+
}
|
|
1064
|
+
const label = testIsTimedOut(stmt.test)
|
|
1065
|
+
? "timed out"
|
|
1066
|
+
: humanizeCondition(stmt.test);
|
|
1067
|
+
for (const oe of preds) {
|
|
1068
|
+
if (oe.kind === "default") {
|
|
1069
|
+
addEdge(
|
|
1070
|
+
{ id: oe.id, kind: "conditional-true", label },
|
|
1071
|
+
"end-completed",
|
|
1072
|
+
);
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
return preds;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
// waitForEvent `.timedOut` branch → fork the WAIT node itself (no decision).
|
|
1079
|
+
if (waitFork && firstPred) {
|
|
1080
|
+
const trueExits = flowStatement(stmt.consequent, [
|
|
1081
|
+
{ id: firstPred.id, kind: "timedOut", label: "timed out" },
|
|
1082
|
+
]);
|
|
1083
|
+
const answered: OpenEnd = {
|
|
1084
|
+
id: firstPred.id,
|
|
1085
|
+
kind: "answered",
|
|
1086
|
+
label: "answered",
|
|
1087
|
+
};
|
|
1088
|
+
const falseExits = stmt.alternate
|
|
1089
|
+
? flowStatement(stmt.alternate, [answered])
|
|
1090
|
+
: [answered];
|
|
1091
|
+
return [...trueExits, ...falseExits];
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
// Plain branching if → an explicit DECISION node with a humanized question.
|
|
1095
|
+
// The `yes` edge = the positive condition is TRUE, `no` = FALSE. The title is
|
|
1096
|
+
// the POSITIVE form, so a negated test (`!X`) attaches the consequent — which
|
|
1097
|
+
// runs when the positive condition is FALSE — to the `no` edge, and the
|
|
1098
|
+
// alternate/bypass to `yes`. (Non-negated: consequent on `yes` as usual.)
|
|
1099
|
+
const decision = mintDecision(humanizeCondition(stmt.test));
|
|
1100
|
+
for (const oe of preds) addEdge(oe, decision.id);
|
|
1101
|
+
const yes: OpenEnd = {
|
|
1102
|
+
id: decision.id,
|
|
1103
|
+
kind: "conditional-true",
|
|
1104
|
+
label: "yes",
|
|
1105
|
+
};
|
|
1106
|
+
const no: OpenEnd = {
|
|
1107
|
+
id: decision.id,
|
|
1108
|
+
kind: "conditional-false",
|
|
1109
|
+
label: "no",
|
|
1110
|
+
};
|
|
1111
|
+
const negated = testIsNegated(stmt.test);
|
|
1112
|
+
const consequentEntry = negated ? no : yes;
|
|
1113
|
+
const bypassEntry = negated ? yes : no;
|
|
1114
|
+
const trueExits = flowStatement(stmt.consequent, [consequentEntry]);
|
|
1115
|
+
const falseExits = stmt.alternate
|
|
1116
|
+
? flowStatement(stmt.alternate, [bypassEntry])
|
|
1117
|
+
: [bypassEntry];
|
|
1118
|
+
return [...trueExits, ...falseExits];
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
// Drive from the start node through the function body; converge the tail.
|
|
1122
|
+
let preds: OpenEnd[] = [{ id: "start", kind: "default" }];
|
|
1123
|
+
const body = fn.body;
|
|
1124
|
+
preds =
|
|
1125
|
+
body.type === "BlockStatement"
|
|
1126
|
+
? flowSeq(body.body, preds)
|
|
1127
|
+
: chainRange(body.start, body.end, preds);
|
|
1128
|
+
for (const oe of preds) addEdge(oe, "end-completed");
|
|
1129
|
+
|
|
1130
|
+
return { edges, decisions };
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
// ---------------------------------------------------------------------------
|
|
1134
|
+
// Formatting helpers
|
|
1135
|
+
// ---------------------------------------------------------------------------
|
|
1136
|
+
|
|
1137
|
+
function formatDuration(d: Record<string, number>): string {
|
|
1138
|
+
return (
|
|
1139
|
+
Object.entries(d)
|
|
1140
|
+
.map(([unit, n]) => {
|
|
1141
|
+
// The core helpers store days as hours (`days(14) = { hours: 336 }`) —
|
|
1142
|
+
// fold whole-day hour counts back to days so subtitles read naturally.
|
|
1143
|
+
if (unit === "hours" && n >= 24 && n % 24 === 0) {
|
|
1144
|
+
return plural(n / 24, "day");
|
|
1145
|
+
}
|
|
1146
|
+
return plural(n, unit.replace(/s$/, ""));
|
|
1147
|
+
})
|
|
1148
|
+
.join(", ") || "duration"
|
|
1149
|
+
);
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
function plural(n: number, unit: string): string {
|
|
1153
|
+
return `${n} ${n === 1 ? unit : `${unit}s`}`;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
function truncate(s: string, max = 48): string {
|
|
1157
|
+
const t = s.trim();
|
|
1158
|
+
return t.length > max ? `${t.slice(0, max - 1)}…` : t;
|
|
1159
|
+
}
|