@shware/workflow 0.3.0 → 1.0.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 +48 -38
- package/dist/client.d.cts +1 -0
- package/dist/client.d.mts +1 -0
- package/dist/cloudflare/channels.cjs +12 -14
- package/dist/cloudflare/channels.cjs.map +1 -1
- package/dist/cloudflare/channels.d.cts.map +1 -1
- package/dist/cloudflare/channels.d.mts.map +1 -1
- package/dist/cloudflare/channels.mjs +13 -15
- package/dist/cloudflare/channels.mjs.map +1 -1
- package/dist/config.cjs +61 -36
- package/dist/config.cjs.map +1 -1
- package/dist/config.d.cts +19 -15
- package/dist/config.d.cts.map +1 -1
- package/dist/config.d.mts +19 -15
- package/dist/config.d.mts.map +1 -1
- package/dist/config.mjs +61 -36
- package/dist/config.mjs.map +1 -1
- package/dist/contract.d.cts +1 -0
- package/dist/contract.d.mts +1 -0
- package/dist/dsl/action.cjs +1 -1
- package/dist/dsl/action.cjs.map +1 -1
- package/dist/dsl/action.d.cts +1 -1
- package/dist/dsl/action.d.mts +1 -1
- package/dist/dsl/action.mjs +1 -1
- package/dist/dsl/action.mjs.map +1 -1
- package/dist/dsl/bundle.cjs +3 -2
- package/dist/dsl/bundle.cjs.map +1 -1
- package/dist/dsl/bundle.d.cts +3 -2
- package/dist/dsl/bundle.d.cts.map +1 -1
- package/dist/dsl/bundle.d.mts +3 -2
- package/dist/dsl/bundle.d.mts.map +1 -1
- package/dist/dsl/bundle.mjs +3 -2
- package/dist/dsl/bundle.mjs.map +1 -1
- package/dist/dsl/condition.cjs +1 -1
- package/dist/dsl/condition.cjs.map +1 -1
- package/dist/dsl/condition.d.cts +2 -1
- package/dist/dsl/condition.d.mts +2 -1
- package/dist/dsl/condition.mjs +1 -1
- package/dist/dsl/condition.mjs.map +1 -1
- package/dist/dsl/flow.cjs +45 -17
- package/dist/dsl/flow.cjs.map +1 -1
- package/dist/dsl/flow.d.cts +31 -17
- package/dist/dsl/flow.d.cts.map +1 -1
- package/dist/dsl/flow.d.mts +31 -17
- package/dist/dsl/flow.d.mts.map +1 -1
- package/dist/dsl/flow.mjs +45 -18
- package/dist/dsl/flow.mjs.map +1 -1
- package/dist/dsl/index.cjs +0 -1
- package/dist/dsl/index.d.cts +2 -2
- package/dist/dsl/index.d.mts +2 -2
- package/dist/dsl/index.mjs +2 -2
- package/dist/dsl/template.cjs +2 -47
- package/dist/dsl/template.cjs.map +1 -1
- package/dist/dsl/template.d.cts +4 -53
- package/dist/dsl/template.d.cts.map +1 -1
- package/dist/dsl/template.d.mts +4 -53
- package/dist/dsl/template.d.mts.map +1 -1
- package/dist/dsl/template.mjs +3 -47
- package/dist/dsl/template.mjs.map +1 -1
- package/dist/dsl/workflow.cjs +1 -1
- package/dist/dsl/workflow.cjs.map +1 -1
- package/dist/dsl/workflow.d.cts +1 -1
- package/dist/dsl/workflow.d.mts +1 -1
- package/dist/dsl/workflow.mjs +1 -1
- package/dist/dsl/workflow.mjs.map +1 -1
- package/dist/index.cjs +5 -2
- package/dist/index.d.cts +3 -3
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +3 -3
- package/dist/ir.d.cts +1 -0
- package/dist/ir.d.mts +1 -0
- package/dist/provenance.d.cts +1 -0
- package/dist/provenance.d.mts +1 -0
- package/dist/push.cjs +3 -5
- package/dist/push.cjs.map +1 -1
- package/dist/push.d.cts +2 -2
- package/dist/push.d.cts.map +1 -1
- package/dist/push.d.mts +2 -2
- package/dist/push.d.mts.map +1 -1
- package/dist/push.mjs +4 -6
- package/dist/push.mjs.map +1 -1
- package/dist/react-email.cjs +5 -5
- package/dist/react-email.cjs.map +1 -1
- package/dist/react-email.d.cts +1 -1
- package/dist/react-email.d.cts.map +1 -1
- package/dist/react-email.d.mts +1 -1
- package/dist/react-email.d.mts.map +1 -1
- package/dist/react-email.mjs +6 -6
- package/dist/react-email.mjs.map +1 -1
- package/dist/templates.cjs +84 -29
- package/dist/templates.cjs.map +1 -1
- package/dist/templates.d.cts +50 -11
- package/dist/templates.d.cts.map +1 -1
- package/dist/templates.d.mts +50 -11
- package/dist/templates.d.mts.map +1 -1
- package/dist/templates.mjs +81 -30
- package/dist/templates.mjs.map +1 -1
- package/dist/webpush.d.cts +1 -0
- package/dist/webpush.d.mts +1 -0
- package/package.json +13 -12
package/dist/dsl/flow.cjs
CHANGED
|
@@ -2,16 +2,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
2
2
|
const require_provenance = require("../provenance.cjs");
|
|
3
3
|
const require_dsl_base = require("./base.cjs");
|
|
4
4
|
const require_dsl_condition = require("./condition.cjs");
|
|
5
|
+
const require_templates = require("../templates.cjs");
|
|
5
6
|
//#region src/dsl/flow.ts
|
|
6
|
-
const PREFER_CHANNELS = /* @__PURE__ */ new Set(["push", "email"]);
|
|
7
7
|
/** prefer() is typed strictly, but a JS caller (or an `any`) reaches it unchecked — fail at the call, not at send time. */
|
|
8
8
|
function checkPreferArgs(candidates, props, options) {
|
|
9
9
|
if (!Array.isArray(candidates) || candidates.length !== 2) throw new TypeError("prefer(): candidates must be exactly two templates — one push, one email");
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
}
|
|
14
|
-
if (candidates[0].channel === candidates[1].channel) throw new TypeError("prefer(): candidates must be one push and one email template");
|
|
10
|
+
const channels = candidates.map((candidate) => require_templates.isTemplate(candidate) ? require_templates.CHANNEL_OF[candidate.kind] : void 0);
|
|
11
|
+
if (!channels.every((channel) => channel === "push" || channel === "email")) throw new TypeError("prefer(): each candidate must be a pushTemplate or an emailTemplate");
|
|
12
|
+
if (channels[0] === channels[1]) throw new TypeError("prefer(): candidates must be one push and one email template");
|
|
15
13
|
if (typeof props !== "object" || props === null || Array.isArray(props)) throw new TypeError("prefer(): props must be an object — pass {} when the templates declare none");
|
|
16
14
|
if (options === void 0) return;
|
|
17
15
|
if (typeof options !== "object" || options === null || Array.isArray(options)) throw new TypeError("prefer(): options must be an object");
|
|
@@ -20,6 +18,10 @@ function checkPreferArgs(candidates, props, options) {
|
|
|
20
18
|
if (typeof value !== "string") throw new TypeError("prefer(): 'label' must be a string");
|
|
21
19
|
}
|
|
22
20
|
}
|
|
21
|
+
/** @internal The template definitions a workflow sends, sub-flows and fragments included. */
|
|
22
|
+
function templateUses(builder) {
|
|
23
|
+
return builder instanceof FlowBuilderImpl ? builder.uses : [];
|
|
24
|
+
}
|
|
23
25
|
/**
|
|
24
26
|
* A cohort arm name has two jobs, and both constrain its spelling:
|
|
25
27
|
* - it is interpolated into the node ids of the arm's flow ('{id}.{name}.{j}'),
|
|
@@ -32,20 +34,29 @@ function checkPreferArgs(candidates, props, options) {
|
|
|
32
34
|
* experiment would prepend itself and re-bucket everyone already in it.
|
|
33
35
|
*/
|
|
34
36
|
const ARM_NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/;
|
|
35
|
-
|
|
37
|
+
/** A sub-flow's nodes; the template definitions it sends are added to `uses`. */
|
|
38
|
+
function resolveSubFlow(sub, uses) {
|
|
36
39
|
if (typeof sub === "function") {
|
|
37
40
|
const builder = new FlowBuilderImpl();
|
|
38
41
|
if (typeof sub(builder)?.then === "function") throw new TypeError("sub-flow callbacks must be synchronous: they run once, while the workflow is defined");
|
|
42
|
+
uses.push(...builder.uses);
|
|
39
43
|
return builder.nodes;
|
|
40
44
|
}
|
|
45
|
+
uses.push(...sub.uses);
|
|
41
46
|
return structuredClone(sub.nodes);
|
|
42
47
|
}
|
|
48
|
+
const DEFINED_CHANNELS = new Set(Object.values(require_templates.CHANNEL_OF));
|
|
49
|
+
function templateKey(channel, tpl) {
|
|
50
|
+
if (!DEFINED_CHANNELS.has(channel)) return tpl.key;
|
|
51
|
+
if (!require_templates.isTemplate(tpl) || require_templates.CHANNEL_OF[tpl.kind] !== channel) throw new TypeError(`${channel}(): expects a ${channel} template definition`);
|
|
52
|
+
return tpl.id;
|
|
53
|
+
}
|
|
43
54
|
function messageNode(channel, tpl, props, devices) {
|
|
44
55
|
return {
|
|
45
56
|
id: "",
|
|
46
57
|
type: "message",
|
|
47
58
|
channel,
|
|
48
|
-
template: tpl
|
|
59
|
+
template: templateKey(channel, tpl),
|
|
49
60
|
props: props ?? {},
|
|
50
61
|
...devices !== void 0 ? { devices } : {}
|
|
51
62
|
};
|
|
@@ -54,6 +65,8 @@ function messageNode(channel, tpl, props, devices) {
|
|
|
54
65
|
var FlowBuilderImpl = class {
|
|
55
66
|
/** Nodes as collected; ids are assigned in one pass inside toIR, so '' is a placeholder here. */
|
|
56
67
|
nodes = [];
|
|
68
|
+
/** The template definitions sent, with where: compile-time only, never in the IR. */
|
|
69
|
+
uses = [];
|
|
57
70
|
/** Provenance: the callsite (captured in the public method) lands in meta.loc, outside the hash. */
|
|
58
71
|
pushNode(node, loc) {
|
|
59
72
|
this.nodes.push({
|
|
@@ -63,7 +76,12 @@ var FlowBuilderImpl = class {
|
|
|
63
76
|
return this;
|
|
64
77
|
}
|
|
65
78
|
message(channel, tpl, props, loc, devices) {
|
|
66
|
-
|
|
79
|
+
this.pushNode(messageNode(channel, tpl, props, devices), loc);
|
|
80
|
+
if (require_templates.isTemplate(tpl)) this.uses.push({
|
|
81
|
+
template: tpl,
|
|
82
|
+
loc
|
|
83
|
+
});
|
|
84
|
+
return this;
|
|
67
85
|
}
|
|
68
86
|
email(t, ...args) {
|
|
69
87
|
return this.message("email", t, args[0], require_provenance.captureLoc(this.email));
|
|
@@ -93,8 +111,16 @@ var FlowBuilderImpl = class {
|
|
|
93
111
|
const loc = require_provenance.captureLoc(this.prefer);
|
|
94
112
|
const meta = loc !== void 0 ? { meta: { loc } } : {};
|
|
95
113
|
const [first, second] = candidates;
|
|
114
|
+
const channel = (tpl) => require_templates.CHANNEL_OF[tpl.kind];
|
|
115
|
+
this.uses.push({
|
|
116
|
+
template: first,
|
|
117
|
+
loc
|
|
118
|
+
}, {
|
|
119
|
+
template: second,
|
|
120
|
+
loc
|
|
121
|
+
});
|
|
96
122
|
const arm = (tpl) => [{
|
|
97
|
-
...messageNode(tpl
|
|
123
|
+
...messageNode(channel(tpl), tpl, { ...props }),
|
|
98
124
|
...meta
|
|
99
125
|
}];
|
|
100
126
|
return this.pushNode({
|
|
@@ -104,7 +130,7 @@ var FlowBuilderImpl = class {
|
|
|
104
130
|
cases: [{
|
|
105
131
|
condition: {
|
|
106
132
|
type: "reachable",
|
|
107
|
-
channel: first
|
|
133
|
+
channel: channel(first),
|
|
108
134
|
...meta
|
|
109
135
|
},
|
|
110
136
|
flow: arm(first)
|
|
@@ -157,11 +183,11 @@ var FlowBuilderImpl = class {
|
|
|
157
183
|
type: "wait_until",
|
|
158
184
|
condition: require_dsl_condition.condIR(condition),
|
|
159
185
|
timeout: require_dsl_base.durationIR(opts.timeout),
|
|
160
|
-
onTimeout: onTimeout === "continue" || onTimeout === "exit" ? onTimeout : resolveSubFlow(onTimeout)
|
|
186
|
+
onTimeout: onTimeout === "continue" || onTimeout === "exit" ? onTimeout : resolveSubFlow(onTimeout, this.uses)
|
|
161
187
|
}, loc);
|
|
162
188
|
}
|
|
163
189
|
use(fragment) {
|
|
164
|
-
this.nodes.push(...resolveSubFlow(fragment));
|
|
190
|
+
this.nodes.push(...resolveSubFlow(fragment, this.uses));
|
|
165
191
|
return this;
|
|
166
192
|
}
|
|
167
193
|
branch(...args) {
|
|
@@ -176,12 +202,12 @@ var FlowBuilderImpl = class {
|
|
|
176
202
|
const [condition, sub] = arm;
|
|
177
203
|
cases.push({
|
|
178
204
|
condition: require_dsl_condition.condIR(condition),
|
|
179
|
-
flow: resolveSubFlow(sub)
|
|
205
|
+
flow: resolveSubFlow(sub, this.uses)
|
|
180
206
|
});
|
|
181
207
|
} else {
|
|
182
208
|
if (otherwise !== void 0) throw new Error("branch(): only one default arm (bare sub-flow) is allowed");
|
|
183
209
|
if (i !== arms.length - 1) throw new Error("branch(): default arm (bare sub-flow) must be the last argument");
|
|
184
|
-
otherwise = resolveSubFlow(arm);
|
|
210
|
+
otherwise = resolveSubFlow(arm, this.uses);
|
|
185
211
|
}
|
|
186
212
|
});
|
|
187
213
|
return this.pushNode({
|
|
@@ -218,7 +244,7 @@ var FlowBuilderImpl = class {
|
|
|
218
244
|
arms: entries.map(([name, a]) => ({
|
|
219
245
|
name,
|
|
220
246
|
weight: a.weight,
|
|
221
|
-
flow: a.flow ? resolveSubFlow(a.flow) : []
|
|
247
|
+
flow: a.flow ? resolveSubFlow(a.flow, this.uses) : []
|
|
222
248
|
}))
|
|
223
249
|
}, loc);
|
|
224
250
|
}
|
|
@@ -262,11 +288,13 @@ function flow(build) {
|
|
|
262
288
|
build(builder);
|
|
263
289
|
return {
|
|
264
290
|
__flow: true,
|
|
265
|
-
nodes: builder.nodes
|
|
291
|
+
nodes: builder.nodes,
|
|
292
|
+
uses: builder.uses
|
|
266
293
|
};
|
|
267
294
|
}
|
|
268
295
|
//#endregion
|
|
269
296
|
exports.FlowBuilderImpl = FlowBuilderImpl;
|
|
270
297
|
exports.flow = flow;
|
|
298
|
+
exports.templateUses = templateUses;
|
|
271
299
|
|
|
272
300
|
//# sourceMappingURL=flow.cjs.map
|
package/dist/dsl/flow.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow.cjs","names":["captureLoc","durationIR","timeOfDayMinutes","condIR"],"sources":["../../src/dsl/flow.ts"],"sourcesContent":["import type { ChannelIR, ConditionIR, NodeIR, PropValueIR, SourceLocIR } from '../ir';\nimport { captureLoc } from '../provenance';\nimport type { ActionRef } from './action';\nimport { type Duration, type TimeOfDay, type Weekday, durationIR, timeOfDayMinutes } from './base';\nimport { type Condition, condIR } from './condition';\nimport type { EventRef, MessageArgs, PropInput, PropsInput } from './refs';\nimport type { Channel, TemplateRef } from './template';\n\n/**\n * The flow chain — FlowBuilder is the DSL's step surface (messages, delays,\n * flow control, data), and its implementation is the compiler front half: each\n * chained call executes no logic, it just collects one IR node (ids are\n * assigned later, in workflow.toIR()). Sub-flow callbacks run exactly once at\n * construction — builder in, builder out — so the output is always a static\n * tree.\n *\n * Every public method also captures its callsite (provenance): the loc lands\n * in the node's hash-excluded meta and is the anchor for future in-place\n * editing from the studio.\n */\n\ntype Scalar = string | number | boolean;\n\n/** An emitted field: a scalar (or a profile ref to one); a nested field cannot be sent. */\ntype EmitValue<T> = [NonNullable<T>] extends [Scalar] ? PropInput<T> : never;\n\n/** The payload `sendEvent` accepts for an event: its fields, scalar ones only. */\nexport type EmitPayload<P> = { [K in keyof P]: EmitValue<P[K]> };\n\n/** Payload may be omitted when the event declares no required field. */\nexport type EmitArgs<P> =\n Record<never, never> extends P ? [payload?: EmitPayload<P>] : [payload: EmitPayload<P>];\n\n/** Per-node push options. */\nexport interface PushOptions {\n /** Which devices get a copy: 'all' (the default) or only the most recently registered. */\n devices?: 'all' | 'latest';\n}\n\n/** `prefer()` options. */\nexport interface PreferOptions {\n /** The generated branch's name in IR (UI title / observability handle), as `branch(label, …)`. */\n label?: string;\n}\n\n/** The candidates `prefer()` takes: one push and one email template, in priority order. */\ntype PreferPair =\n | readonly [TemplateRef<'push', object>, TemplateRef<'email', object>]\n | readonly [TemplateRef<'email', object>, TemplateRef<'push', object>];\n\ntype RefProps<R> = R extends TemplateRef<infer _C, infer P> ? P : never;\ntype NormalizeProps<P> = { -readonly [K in keyof P]: P[K] };\ntype Equal<A, B> =\n (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;\n\n/** Both candidates render the one props object, so they must declare the same props type — not merely overlap. */\ntype SameProps<T extends PreferPair> =\n Equal<NormalizeProps<RefProps<T[0]>>, NormalizeProps<RefProps<T[1]>>> extends true\n ? unknown\n : { readonly __prefer_error__: 'Both templates must declare the same props type' };\n\n/** Distributes, so a field only one member of a union variable has still counts as extra. */\ntype KeysOfUnion<A> = A extends unknown ? keyof A : never;\n/** Rejects known extra fields, which `{}` (an empty props schema) would otherwise accept. */\ntype NoExtra<A, P> = Record<Exclude<KeysOfUnion<A>, keyof P>, never>;\n\nconst PREFER_CHANNELS: ReadonlySet<unknown> = new Set(['push', 'email']);\n\n/** prefer() is typed strictly, but a JS caller (or an `any`) reaches it unchecked — fail at the call, not at send time. */\nfunction checkPreferArgs(candidates: unknown, props: unknown, options: unknown): void {\n if (!Array.isArray(candidates) || candidates.length !== 2) {\n throw new TypeError('prefer(): candidates must be exactly two templates — one push, one email');\n }\n for (const ref of candidates as unknown[]) {\n const { channel, key } = (ref ?? {}) as Partial<TemplateRef>;\n if (!PREFER_CHANNELS.has(channel) || typeof key !== 'string' || key === '') {\n throw new TypeError(\n 'prefer(): each candidate must be a push or email template reference (t.push.<key> / t.email.<key>)'\n );\n }\n }\n if ((candidates[0] as TemplateRef).channel === (candidates[1] as TemplateRef).channel) {\n throw new TypeError('prefer(): candidates must be one push and one email template');\n }\n if (typeof props !== 'object' || props === null || Array.isArray(props)) {\n throw new TypeError(\n 'prefer(): props must be an object — pass {} when the templates declare none'\n );\n }\n if (options === undefined) return;\n if (typeof options !== 'object' || options === null || Array.isArray(options)) {\n throw new TypeError('prefer(): options must be an object');\n }\n for (const [name, value] of Object.entries(options)) {\n if (name !== 'label') {\n throw new TypeError(\n `prefer(): unknown option '${name}' — props go in the second argument, options take only 'label'`\n );\n }\n if (typeof value !== 'string') throw new TypeError(\"prefer(): 'label' must be a string\");\n }\n}\n\n/** A reusable flow fragment (what `flow(...)` returns), referenced directly by branch arms. */\nexport interface Flow {\n readonly __flow: true;\n}\n\ninterface FlowInternal extends Flow {\n readonly nodes: NodeIR[];\n}\n\n/** Sub-flow: a named fragment, or an inline callback (runs once at construction — builder in, builder out). */\nexport type SubFlow = Flow | ((w: FlowBuilder) => FlowBuilder);\n\n/** A branch arm: the [condition, sub-flow] tuple — an [if, then] ordering convention. */\nexport type BranchCase = readonly [condition: Condition, flow: SubFlow];\n\n/**\n * A branch argument: either a tuple arm, or a bare sub-flow meaning the default\n * arm. The bare form may appear once, and must come last (checked at runtime).\n */\nexport type BranchArm = BranchCase | SubFlow;\n\n/**\n * A cohort arm name has two jobs, and both constrain its spelling:\n * - it is interpolated into the node ids of the arm's flow ('{id}.{name}.{j}'),\n * and an id is a durable step name — a dot would fake a nesting level and can\n * collide with a real one, an empty name gives '{id}..{j}';\n * - it is an object key, and JavaScript lists integer-like keys first in\n * ascending numeric order however the author wrote them. The arms array is\n * documented (and interpreted) as authoring order, and the bucketing walk\n * accumulates weights along it, so an arm named '0' added to a live\n * experiment would prepend itself and re-bucket everyone already in it.\n */\nconst ARM_NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/;\n\nfunction resolveSubFlow(sub: SubFlow): NodeIR[] {\n if (typeof sub === 'function') {\n const builder = new FlowBuilderImpl();\n const returned: unknown = sub(builder);\n // An async callback would add its nodes after construction is over — after ids were assigned\n if (typeof (returned as { then?: unknown } | undefined)?.then === 'function') {\n throw new TypeError(\n 'sub-flow callbacks must be synchronous: they run once, while the workflow is defined'\n );\n }\n return builder.nodes;\n }\n /*\n * A named fragment is a value, and the convention is to reuse it — two branch\n * arms may hold the same one. Handing out its own nodes aliases them into\n * both places, and assignIds writes ids *in place*: the second prefix\n * overwrites the first, so the two placements end up as one object under one\n * id — one durable step name, one message idempotency key, one bucket seed.\n * A copy per placement is what makes a fragment behave like a value.\n */\n return structuredClone((sub as FlowInternal).nodes);\n}\n\nexport interface FlowBuilder {\n /* ---- Messages: every channel is one message node; separate methods buy channel-level typing ---- */\n email<P extends object>(template: TemplateRef<'email', P>, ...props: MessageArgs<P>): this;\n sms<P extends object>(template: TemplateRef<'sms', P>, ...props: MessageArgs<P>): this;\n /**\n * Push to the user's devices — every device the host's directory lists, or\n * only the most recently registered with `{ devices: 'latest' }`. A user with\n * no device is skipped (`prefer([pushTpl, emailTpl], props)` falls back to email).\n */\n push<P extends object>(\n template: TemplateRef<'push', P>,\n ...args: [...props: MessageArgs<P>, options?: PushOptions]\n ): this;\n inApp<P extends object>(template: TemplateRef<'in_app', P>, ...props: MessageArgs<P>): this;\n slack<P extends object>(template: TemplateRef<'slack', P>, ...props: MessageArgs<P>): this;\n discord<P extends object>(template: TemplateRef<'discord', P>, ...props: MessageArgs<P>): this;\n survey<P extends object>(template: TemplateRef<'survey', P>, ...props: MessageArgs<P>): this;\n\n /**\n * Send one message on the first channel the user can be reached on: one push\n * and one email template, in priority order, rendered with the same props.\n * Sugar for the branch it compiles to — same IR, ids and hash as writing\n *\n * .branch(label, [reachable(first.channel), (b) => b.<first>(first, props)], (b) => b.<second>(second, props))\n *\n * so the choice is made once, when the step is reached, and a first choice\n * that fails to send retries as itself — it never falls through to the\n * second. Props are always passed (`{}` for templates that declare none),\n * and both templates must declare the same props type; for differing props\n * or other channels, write the branch.\n *\n * .prefer([t.push.tip, t.email.tip], { name: u.name }, { label: 'tip by channel' })\n */\n prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<RefProps<T[0]>>>>(\n candidates: T & SameProps<NoInfer<T>>,\n props: A & NoInfer<NoExtra<A, RefProps<T[0]>>>,\n options?: PreferOptions\n ): this;\n\n /* --------------------------------- Delays --------------------------------- */\n /** Time Delay; passing { min, max } makes it a Randomized Delay. */\n delay(duration: Duration): this;\n delay(range: { min: Duration; max: Duration }): this;\n\n /** Time Window: hold until inside the window (e.g. weekdays 09:00–17:00). tz: 'user' uses the user's timezone. */\n timeWindow(opts: {\n days?: readonly Weekday[];\n between: readonly [TimeOfDay, TimeOfDay];\n tz?: 'user' | (string & {});\n }): this;\n\n /**\n * Wait Until: continue on the main line once the condition holds, or take\n * onTimeout when it expires (default 'continue'). On the engine side this is\n * \"await event racing a timer\" — a native primitive of durable runtimes.\n */\n waitUntil(\n condition: Condition,\n opts: { timeout: Duration; onTimeout?: 'continue' | 'exit' | SubFlow }\n ): this;\n\n /**\n * Splice a fragment in place: a named `flow(...)` or a callback, expanded\n * once while the workflow is defined — a composition step before compiling,\n * not a node (the IR has no trace of it, and ids are assigned over the whole\n * workflow as if the steps were written inline). Each use gets its own copy,\n * so one fragment can be used in several places and workflows.\n *\n * const officeHours = flow((w) => w.timeWindow({ days: ['mon', 'tue', 'wed', 'thu', 'fri'], between: ['09:00', '17:00'] }));\n * workflow({ id: 'onboarding', ... }).delay('1 day').use(officeHours).email(t.email.tip, { name: u.name })\n */\n use(fragment: SubFlow): this;\n\n /* ------------------------------ Flow Control ------------------------------ */\n /**\n * Conditional branch: ordered first-match (same semantics as Step Functions\n * Choice / Knock branch). This one primitive covers both the UI's True/False\n * Branch (two arms) and Multi-Split Branch (N arms). Arms are\n * [condition, sub-flow] tuples; a bare sub-flow in tail position is the\n * default arm. With no match and no default, execution simply continues.\n * Rejoin is structural: after the matching arm finishes, execution resumes\n * at the node following the branch — to opt out, call .exit() inside the arm.\n *\n * .branch([activeSubscriber, upgradeFlow], firstTimeFlow) // True/False\n * .branch([vip, vipFlow], [trial, trialFlow], defaultFlow) // Multi-Split\n * .branch([not(usedStaging), eduFlow]) // single arm: no match continues\n *\n * The optional first argument `label` becomes the node's name in IR (UI title\n * / observability handle). It is not a jump target — there is no goto here;\n * looping is a future re-entry-policy topic (see sendEvent). Arm labels in\n * the UI are derived from the condition.\n */\n branch(...arms: readonly BranchArm[]): this;\n branch(label: string, ...arms: readonly BranchArm[]): this;\n\n /**\n * Gate: exit unless the condition holds, otherwise continue. A first-class\n * node rather than sugar over branch — same semantics as Zapier's \"only\n * continue if\" / Iterable's Filter tile, and rendered on its own in the UI.\n * `reason` is the audit-log line — metadata, so rewording it is free\n * (excluded from contentHash, see hash.ts).\n */\n filter(condition: Condition, opts?: { reason?: string }): this;\n\n /**\n * Random Cohort Branch (A/B): weights must sum to 100 (checked at runtime).\n * `key` names the experiment: bucketing hashes `userId:key` instead of the\n * structural node id, so assignments survive node insertion/moves and the\n * experiment keeps one identity across workflow versions — set it for any\n * A/B whose results you intend to read.\n *\n * Arm names become node id segments and are read back in authoring order, so\n * they are restricted to letters, digits, '_' and '-', never starting with a\n * digit (checked at runtime).\n */\n cohort(arms: Record<string, { weight: number; flow?: SubFlow }>, opts?: { key?: string }): this;\n\n /**\n * Exit: end the whole workflow immediately (the UI's Exit node); `reason`\n * goes into the audit log and is metadata, so rewording it neither repins\n * in-flight journeys nor shows up in plan. Inside a branch arm this means\n * \"terminate, do not rejoin\" — it stops here instead of falling through,\n * while an arm without exit rejoins naturally.\n */\n exit(reason?: string): this;\n\n /* ---------------------------------- Data ---------------------------------- */\n /**\n * Emit a typed event (customer.io's Send Event). The event comes from an\n * e.xxx reference, so payload types flow in the same way trigger.event works.\n * This is how workflows compose: an event can trigger another workflow, and\n * the resulting call graph is statically analyzable. Payload values may\n * reference u.xxx. Only scalar fields can be sent (IR carries literals and\n * profile refs, not nested JSON): an event whose payload requires a nested\n * field cannot be emitted from a journey, and the types say so.\n *\n * Note on loops: a trailing self-triggering sendEvent will become the\n * official periodic-flow shape *once a re-entry policy exists* — today the\n * entry policy is once-per-user, so a self-trigger cannot re-enter and does\n * not loop.\n * TODO: the rest of the Data category — outbound webhook / profile update /\n * journey attributes.\n */\n sendEvent<P extends object>(event: EventRef<P>, ...payload: EmitArgs<P>): this;\n\n /**\n * Run a custom action (see dsl/action.ts for the model). The chain records\n * identity only — name, args, codeHash — never the code: the implementation\n * ships inside the deployed Worker bundle and is resolved by name from the\n * runtime registry. Args are typed by the ActionRef and may reference u.xxx,\n * resolved at run time exactly like message props. Executed inside a durable\n * step: retried on throw, checkpointed on success.\n */\n run<A extends object>(action: ActionRef<A>, ...args: MessageArgs<A>): this;\n}\n\nfunction messageNode(\n channel: ChannelIR,\n tpl: TemplateRef<Channel, object>,\n props: object | undefined,\n devices?: 'latest'\n): NodeIR {\n return {\n id: '',\n type: 'message',\n channel,\n template: tpl.key,\n props: (props ?? {}) as Record<string, PropValueIR>,\n // Absent for 'all', so adding the option left every existing push's hash as it was\n ...(devices !== undefined ? { devices } : {}),\n };\n}\n\n/* oxlint-disable typescript/unbound-method --\n * `captureLoc(this.xxx)` passes the method by identity as the stack-trace\n * boundary for Error.captureStackTrace; it is never invoked, so `this`\n * scoping cannot go wrong. */\n/** @internal extended by WorkflowBuilderImpl; not part of the public API */\nexport class FlowBuilderImpl implements FlowBuilder {\n /** Nodes as collected; ids are assigned in one pass inside toIR, so '' is a placeholder here. */\n readonly nodes: NodeIR[] = [];\n\n /** Provenance: the callsite (captured in the public method) lands in meta.loc, outside the hash. */\n private pushNode(node: NodeIR, loc: SourceLocIR | undefined): this {\n this.nodes.push({ ...node, ...(loc !== undefined ? { meta: { loc } } : {}) });\n return this;\n }\n\n private message(\n channel: ChannelIR,\n tpl: TemplateRef<Channel, object>,\n props: object | undefined,\n loc: SourceLocIR | undefined,\n devices?: 'latest'\n ): this {\n return this.pushNode(messageNode(channel, tpl, props, devices), loc);\n }\n\n email<P extends object>(t: TemplateRef<'email', P>, ...args: MessageArgs<P>): this {\n return this.message('email', t, args[0], captureLoc(this.email));\n }\n sms<P extends object>(t: TemplateRef<'sms', P>, ...args: MessageArgs<P>): this {\n return this.message('sms', t, args[0], captureLoc(this.sms));\n }\n push<P extends object>(\n t: TemplateRef<'push', P>,\n ...args: [...props: MessageArgs<P>, options?: PushOptions]\n ): this {\n const [props, options] = args as unknown as [object | undefined, PushOptions | undefined];\n const devices = options?.devices === 'latest' ? 'latest' : undefined;\n return this.message('push', t, props, captureLoc(this.push), devices);\n }\n inApp<P extends object>(t: TemplateRef<'in_app', P>, ...args: MessageArgs<P>): this {\n return this.message('in_app', t, args[0], captureLoc(this.inApp));\n }\n slack<P extends object>(t: TemplateRef<'slack', P>, ...args: MessageArgs<P>): this {\n return this.message('slack', t, args[0], captureLoc(this.slack));\n }\n discord<P extends object>(t: TemplateRef<'discord', P>, ...args: MessageArgs<P>): this {\n return this.message('discord', t, args[0], captureLoc(this.discord));\n }\n survey<P extends object>(t: TemplateRef<'survey', P>, ...args: MessageArgs<P>): this {\n return this.message('survey', t, args[0], captureLoc(this.survey));\n }\n\n prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<RefProps<T[0]>>>>(\n candidates: T & SameProps<NoInfer<T>>,\n props: A & NoInfer<NoExtra<A, RefProps<T[0]>>>,\n options?: PreferOptions\n ): this {\n checkPreferArgs(candidates, props, options);\n // Every generated node points at the author's prefer() call, not at this method's body\n const loc = captureLoc(this.prefer);\n const meta = loc !== undefined ? { meta: { loc } } : {};\n const [first, second] = candidates as readonly TemplateRef<'push' | 'email', object>[];\n // A copy per message, as two separately written calls would hold\n const arm = (tpl: TemplateRef<'push' | 'email', object>): NodeIR[] => [\n { ...messageNode(tpl.channel, tpl, { ...props }), ...meta },\n ];\n return this.pushNode(\n {\n id: '',\n type: 'branch',\n ...(options?.label !== undefined ? { label: options.label } : {}),\n cases: [\n { condition: { type: 'reachable', channel: first.channel, ...meta }, flow: arm(first) },\n ],\n otherwise: arm(second),\n },\n loc\n );\n }\n\n delay(duration: Duration): this;\n delay(range: { min: Duration; max: Duration }): this;\n delay(d: Duration | { min: Duration; max: Duration }): this {\n const loc = captureLoc(this.delay);\n if (typeof d === 'string') {\n return this.pushNode({ id: '', type: 'delay', duration: durationIR(d) }, loc);\n }\n const min = durationIR(d.min);\n const max = durationIR(d.max);\n /*\n * The interpreter draws `min + random(max - min)` with the span clamped at\n * zero, so a backwards range does not fail — it quietly collapses into a\n * fixed `min` sleep. Reject it here, where the author can still see it.\n */\n if (max.ms < min.ms) {\n throw new Error(\n `delay(): 'max' must not be shorter than 'min', got { min: '${d.min}', max: '${d.max}' }`\n );\n }\n return this.pushNode({ id: '', type: 'random_delay', min, max }, loc);\n }\n\n timeWindow(opts: {\n days?: readonly Weekday[];\n between: readonly [TimeOfDay, TimeOfDay];\n tz?: 'user' | (string & {});\n }): this {\n const loc = captureLoc(this.timeWindow);\n const start = timeOfDayMinutes(opts.between[0]);\n const end = timeOfDayMinutes(opts.between[1]);\n if (end <= start) {\n throw new Error(\n `timeWindow(): 'between' must open before it closes within one day, got [${opts.between[0]}, ${opts.between[1]}] (overnight windows are not supported yet)`\n );\n }\n return this.pushNode(\n {\n id: '',\n type: 'time_window',\n days: [...(opts.days ?? (['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const))],\n between: [opts.between[0], opts.between[1]],\n tz: opts.tz ?? 'user',\n },\n loc\n );\n }\n\n waitUntil(\n condition: Condition,\n opts: { timeout: Duration; onTimeout?: 'continue' | 'exit' | SubFlow }\n ): this {\n const loc = captureLoc(this.waitUntil);\n const onTimeout = opts.onTimeout ?? 'continue';\n return this.pushNode(\n {\n id: '',\n type: 'wait_until',\n condition: condIR(condition),\n timeout: durationIR(opts.timeout),\n onTimeout:\n onTimeout === 'continue' || onTimeout === 'exit' ? onTimeout : resolveSubFlow(onTimeout),\n },\n loc\n );\n }\n\n use(fragment: SubFlow): this {\n // The fragment's nodes carry their own provenance (where the fragment was written)\n this.nodes.push(...resolveSubFlow(fragment));\n return this;\n }\n\n branch(...arms: readonly BranchArm[]): this;\n branch(label: string, ...arms: readonly BranchArm[]): this;\n branch(...args: readonly (string | BranchArm)[]): this {\n const loc = captureLoc(this.branch);\n const label = typeof args[0] === 'string' ? args[0] : undefined;\n const arms = (label === undefined ? args : args.slice(1)) as readonly BranchArm[];\n\n const cases: { condition: ConditionIR; flow: NodeIR[] }[] = [];\n let otherwise: NodeIR[] | undefined;\n arms.forEach((arm, i) => {\n if (Array.isArray(arm)) {\n if (otherwise !== undefined) {\n throw new Error('branch(): default arm (bare sub-flow) must be the last argument');\n }\n const [condition, sub] = arm as BranchCase;\n cases.push({ condition: condIR(condition), flow: resolveSubFlow(sub) });\n } else {\n if (otherwise !== undefined) {\n throw new Error('branch(): only one default arm (bare sub-flow) is allowed');\n }\n if (i !== arms.length - 1) {\n throw new Error('branch(): default arm (bare sub-flow) must be the last argument');\n }\n otherwise = resolveSubFlow(arm as SubFlow);\n }\n });\n\n return this.pushNode(\n {\n id: '',\n type: 'branch',\n ...(label !== undefined ? { label } : {}),\n cases,\n ...(otherwise !== undefined ? { otherwise } : {}),\n },\n loc\n );\n }\n\n filter(condition: Condition, opts?: { reason?: string }): this {\n return this.pushNode(\n {\n id: '',\n type: 'filter',\n condition: condIR(condition),\n ...(opts?.reason !== undefined ? { reason: opts.reason } : {}),\n },\n captureLoc(this.filter)\n );\n }\n\n cohort(arms: Record<string, { weight: number; flow?: SubFlow }>, opts?: { key?: string }): this {\n const loc = captureLoc(this.cohort);\n const entries = Object.entries(arms);\n /*\n * Weights live on a 0.01% grid: the runtime buckets into 10,000 slots\n * (basis points), so anything finer would be silently quantized — reject\n * it here instead. Converting to integer basis points also makes the\n * sum check exact; no epsilon needed.\n */\n const basisPoints = entries.map(([name, a]) => {\n if (!ARM_NAME.test(name)) {\n throw new Error(\n `cohort(): arm name '${name}' must start with a letter or '_' and contain only letters, digits, '_' or '-' — arm names become node id segments, and integer-like names would silently reorder the arms`\n );\n }\n const bp = a.weight * 100;\n if (Math.abs(bp - Math.round(bp)) > 1e-6) {\n throw new Error(\n `cohort(): arm '${name}' weight ${a.weight} is finer than the 0.01% bucketing grid — use at most two decimal places`\n );\n }\n /*\n * The sum check alone accepts -50 / 150: the runtime walks the arms\n * accumulating basis points and takes the first whose cumulative total\n * clears the bucket, so a negative weight hands 100% of users to its\n * neighbour instead of splitting anything.\n */\n if (bp < 0) {\n throw new Error(`cohort(): arm '${name}' weight ${a.weight} must not be negative`);\n }\n return Math.round(bp);\n });\n const total = basisPoints.reduce((sum, bp) => sum + bp, 0);\n if (total !== 10_000) {\n throw new Error(`cohort(): weights must sum to 100, got ${total / 100}`);\n }\n return this.pushNode(\n {\n id: '',\n type: 'cohort',\n ...(opts?.key !== undefined ? { key: opts.key } : {}),\n arms: entries.map(([name, a]) => ({\n name,\n weight: a.weight,\n flow: a.flow ? resolveSubFlow(a.flow) : [],\n })),\n },\n loc\n );\n }\n\n exit(reason?: string): this {\n return this.pushNode(\n { id: '', type: 'exit', ...(reason !== undefined ? { reason } : {}) },\n captureLoc(this.exit)\n );\n }\n\n sendEvent<P extends object>(ev: EventRef<P>, ...payload: EmitArgs<P>): this {\n const values = (payload[0] ?? {}) as Record<string, unknown>;\n for (const [field, value] of Object.entries(values)) {\n const ref =\n typeof value === 'object' &&\n value !== null &&\n (value as { type?: unknown }).type === 'user_property';\n if (!ref && !['string', 'number', 'boolean'].includes(typeof value)) {\n throw new TypeError(\n `sendEvent('${ev.name}'): '${field}' is not a scalar or a u.xxx reference — an emitted payload carries scalar fields only`\n );\n }\n }\n return this.pushNode(\n {\n id: '',\n type: 'send_event',\n event: ev.name,\n payload: values as Record<string, PropValueIR>,\n },\n captureLoc(this.sendEvent)\n );\n }\n\n run<A extends object>(a: ActionRef<A>, ...args: MessageArgs<A>): this {\n return this.pushNode(\n {\n id: '',\n type: 'action',\n action: a.name,\n args: (args[0] ?? {}) as Record<string, PropValueIR>,\n codeHash: a.codeHash,\n },\n captureLoc(this.run)\n );\n }\n}\n/* oxlint-enable typescript/unbound-method */\n\n/**\n * A reusable flow fragment: a free function. Once personalization goes through\n * u.xxx and events through e.xxx, the flow layer carries no schema generics.\n */\nexport function flow(build: (w: FlowBuilder) => FlowBuilder): Flow {\n const builder = new FlowBuilderImpl();\n build(builder);\n const impl: FlowInternal = { __flow: true, nodes: builder.nodes };\n return impl;\n}\n"],"mappings":";;;;;AAkEA,MAAM,kCAAwC,IAAI,IAAI,CAAC,QAAQ,OAAO,CAAC;;AAGvE,SAAS,gBAAgB,YAAqB,OAAgB,SAAwB;CACpF,IAAI,CAAC,MAAM,QAAQ,UAAU,KAAK,WAAW,WAAW,GACtD,MAAM,IAAI,UAAU,0EAA0E;CAEhG,KAAK,MAAM,OAAO,YAAyB;EACzC,MAAM,EAAE,SAAS,QAAS,OAAO,CAAC;EAClC,IAAI,CAAC,gBAAgB,IAAI,OAAO,KAAK,OAAO,QAAQ,YAAY,QAAQ,IACtE,MAAM,IAAI,UACR,oGACF;CAEJ;CACA,IAAK,WAAW,EAAE,CAAiB,YAAa,WAAW,EAAE,CAAiB,SAC5E,MAAM,IAAI,UAAU,8DAA8D;CAEpF,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,UACR,6EACF;CAEF,IAAI,YAAY,KAAA,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KAAK,MAAM,CAAC,OAAO,UAAU,OAAO,QAAQ,MAAM,GAKhD,IAAI,EAHF,OAAO,UAAU,YACjB,UAAU,QACT,MAA6B,SAAS,oBAC7B,CAAC;GAAC;GAAU;GAAU;EAAS,CAAC,CAAC,SAAS,OAAO,KAAK,GAChE,MAAM,IAAI,UACR,cAAc,GAAG,KAAK,OAAO,MAAM,uFACrC;EAGJ,OAAO,KAAK,SACV;GACE,IAAI;GACJ,MAAM;GACN,OAAO,GAAG;GACV,SAAS;EACX,GACAA,mBAAAA,WAAW,KAAK,SAAS,CAC3B;CACF;CAEA,IAAsB,GAAiB,GAAG,MAA4B;EACpE,OAAO,KAAK,SACV;GACE,IAAI;GACJ,MAAM;GACN,QAAQ,EAAE;GACV,MAAO,KAAK,MAAM,CAAC;GACnB,UAAU,EAAE;EACd,GACAA,mBAAAA,WAAW,KAAK,GAAG,CACrB;CACF;AACF;;;;;AAOA,SAAgB,KAAK,OAA8C;CACjE,MAAM,UAAU,IAAI,gBAAgB;CACpC,MAAM,OAAO;CAEb,OAAO;EADsB,QAAQ;EAAM,OAAO,QAAQ;CAChD;AACZ"}
|
|
1
|
+
{"version":3,"file":"flow.cjs","names":["isTemplate","CHANNEL_OF","captureLoc","durationIR","timeOfDayMinutes","condIR"],"sources":["../../src/dsl/flow.ts"],"sourcesContent":["import type { ChannelIR, ConditionIR, NodeIR, PropValueIR, SourceLocIR } from '../ir';\nimport { captureLoc } from '../provenance';\nimport {\n type AnyTemplate,\n CHANNEL_OF,\n type DiscordTemplate,\n type EmailTemplate,\n type PropsSchema,\n type PushTemplate,\n type SlackTemplate,\n isTemplate,\n} from '../templates';\nimport type { ActionRef } from './action';\nimport { type Duration, type TimeOfDay, type Weekday, durationIR, timeOfDayMinutes } from './base';\nimport { type Condition, condIR } from './condition';\nimport type { EventRef, MessageArgs, PropInput, PropsInput } from './refs';\nimport type { PropsOf, TemplateRef } from './template';\n\n/**\n * The flow chain — FlowBuilder is the DSL's step surface (messages, delays,\n * flow control, data), and its implementation is the compiler front half: each\n * chained call executes no logic, it just collects one IR node (ids are\n * assigned later, in workflow.toIR()). Sub-flow callbacks run exactly once at\n * construction — builder in, builder out — so the output is always a static\n * tree.\n *\n * Every public method also captures its callsite (provenance): the loc lands\n * in the node's hash-excluded meta and is the anchor for future in-place\n * editing from the studio.\n */\n\ntype Scalar = string | number | boolean;\n\n/** An emitted field: a scalar (or a profile ref to one); a nested field cannot be sent. */\ntype EmitValue<T> = [NonNullable<T>] extends [Scalar] ? PropInput<T> : never;\n\n/** The payload `sendEvent` accepts for an event: its fields, scalar ones only. */\nexport type EmitPayload<P> = { [K in keyof P]: EmitValue<P[K]> };\n\n/** Payload may be omitted when the event declares no required field. */\nexport type EmitArgs<P> =\n Record<never, never> extends P ? [payload?: EmitPayload<P>] : [payload: EmitPayload<P>];\n\n/** Per-node push options. */\nexport interface PushOptions {\n /** Which devices get a copy: 'all' (the default) or only the most recently registered. */\n devices?: 'all' | 'latest';\n}\n\n/** `prefer()` options. */\nexport interface PreferOptions {\n /** The generated branch's name in IR (UI title / observability handle), as `branch(label, …)`. */\n label?: string;\n}\n\n/** The candidates `prefer()` takes: one push and one email template, in priority order. */\ntype PreferPair = readonly [PushTemplate, EmailTemplate] | readonly [EmailTemplate, PushTemplate];\n\ntype NormalizeProps<P> = { -readonly [K in keyof P]: P[K] };\ntype Equal<A, B> =\n (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;\n\n/** Both candidates render the one props object, so they must declare the same props type — not merely overlap. */\ntype SameProps<T extends PreferPair> =\n Equal<NormalizeProps<PropsOf<T[0]>>, NormalizeProps<PropsOf<T[1]>>> extends true\n ? unknown\n : { readonly __prefer_error__: 'Both templates must declare the same props type' };\n\n/** Distributes, so a field only one member of a union variable has still counts as extra. */\ntype KeysOfUnion<A> = A extends unknown ? keyof A : never;\n/** Rejects known extra fields, which `{}` (an empty props schema) would otherwise accept. */\ntype NoExtra<A, P> = Record<Exclude<KeysOfUnion<A>, keyof P>, never>;\n\n/** prefer() is typed strictly, but a JS caller (or an `any`) reaches it unchecked — fail at the call, not at send time. */\nfunction checkPreferArgs(candidates: unknown, props: unknown, options: unknown): void {\n if (!Array.isArray(candidates) || candidates.length !== 2) {\n throw new TypeError('prefer(): candidates must be exactly two templates — one push, one email');\n }\n const channels = (candidates as unknown[]).map((candidate) =>\n isTemplate(candidate) ? CHANNEL_OF[candidate.kind] : undefined\n );\n if (!channels.every((channel) => channel === 'push' || channel === 'email')) {\n throw new TypeError('prefer(): each candidate must be a pushTemplate or an emailTemplate');\n }\n if (channels[0] === channels[1]) {\n throw new TypeError('prefer(): candidates must be one push and one email template');\n }\n if (typeof props !== 'object' || props === null || Array.isArray(props)) {\n throw new TypeError(\n 'prefer(): props must be an object — pass {} when the templates declare none'\n );\n }\n if (options === undefined) return;\n if (typeof options !== 'object' || options === null || Array.isArray(options)) {\n throw new TypeError('prefer(): options must be an object');\n }\n for (const [name, value] of Object.entries(options)) {\n if (name !== 'label') {\n throw new TypeError(\n `prefer(): unknown option '${name}' — props go in the second argument, options take only 'label'`\n );\n }\n if (typeof value !== 'string') throw new TypeError(\"prefer(): 'label' must be a string\");\n }\n}\n\n/** A reusable flow fragment (what `flow(...)` returns), referenced directly by branch arms. */\nexport interface Flow {\n readonly __flow: true;\n}\n\ninterface FlowInternal extends Flow {\n readonly nodes: NodeIR[];\n readonly uses: readonly TemplateUse[];\n}\n\n/**\n * @internal A template definition a flow sends, kept beside the IR (which names it by id only):\n * compileConfig checks that the registered definition under that id is this very object, so the\n * schema that typed the call is the one that renders it. Never part of the IR or its hash.\n */\nexport interface TemplateUse {\n readonly template: AnyTemplate;\n readonly loc: SourceLocIR | undefined;\n}\n\n/** @internal The template definitions a workflow sends, sub-flows and fragments included. */\nexport function templateUses(builder: FlowBuilder): readonly TemplateUse[] {\n return builder instanceof FlowBuilderImpl ? builder.uses : [];\n}\n\n/** Sub-flow: a named fragment, or an inline callback (runs once at construction — builder in, builder out). */\nexport type SubFlow = Flow | ((w: FlowBuilder) => FlowBuilder);\n\n/** A branch arm: the [condition, sub-flow] tuple — an [if, then] ordering convention. */\nexport type BranchCase = readonly [condition: Condition, flow: SubFlow];\n\n/**\n * A branch argument: either a tuple arm, or a bare sub-flow meaning the default\n * arm. The bare form may appear once, and must come last (checked at runtime).\n */\nexport type BranchArm = BranchCase | SubFlow;\n\n/**\n * A cohort arm name has two jobs, and both constrain its spelling:\n * - it is interpolated into the node ids of the arm's flow ('{id}.{name}.{j}'),\n * and an id is a durable step name — a dot would fake a nesting level and can\n * collide with a real one, an empty name gives '{id}..{j}';\n * - it is an object key, and JavaScript lists integer-like keys first in\n * ascending numeric order however the author wrote them. The arms array is\n * documented (and interpreted) as authoring order, and the bucketing walk\n * accumulates weights along it, so an arm named '0' added to a live\n * experiment would prepend itself and re-bucket everyone already in it.\n */\nconst ARM_NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/;\n\n/** A sub-flow's nodes; the template definitions it sends are added to `uses`. */\nfunction resolveSubFlow(sub: SubFlow, uses: TemplateUse[]): NodeIR[] {\n if (typeof sub === 'function') {\n const builder = new FlowBuilderImpl();\n const returned: unknown = sub(builder);\n // An async callback would add its nodes after construction is over — after ids were assigned\n if (typeof (returned as { then?: unknown } | undefined)?.then === 'function') {\n throw new TypeError(\n 'sub-flow callbacks must be synchronous: they run once, while the workflow is defined'\n );\n }\n uses.push(...builder.uses);\n return builder.nodes;\n }\n uses.push(...(sub as FlowInternal).uses);\n /*\n * A named fragment is a value, and the convention is to reuse it — two branch\n * arms may hold the same one. Handing out its own nodes aliases them into\n * both places, and assignIds writes ids *in place*: the second prefix\n * overwrites the first, so the two placements end up as one object under one\n * id — one durable step name, one message idempotency key, one bucket seed.\n * A copy per placement is what makes a fragment behave like a value.\n */\n return structuredClone((sub as FlowInternal).nodes);\n}\n\nexport interface FlowBuilder {\n /* ---- Messages: every channel is one message node; separate methods buy channel-level typing ---- */\n email<T extends EmailTemplate>(template: T, ...props: MessageArgs<PropsOf<T>>): this;\n sms<P extends object>(template: TemplateRef<'sms', P>, ...props: MessageArgs<P>): this;\n /**\n * Push to the user's devices — every device the host's directory lists, or\n * only the most recently registered with `{ devices: 'latest' }`. A user with\n * no device is skipped (`prefer([pushTpl, emailTpl], props)` falls back to email).\n */\n push<T extends PushTemplate>(\n template: T,\n ...args: [...props: MessageArgs<PropsOf<T>>, options?: PushOptions]\n ): this;\n inApp<P extends object>(template: TemplateRef<'in_app', P>, ...props: MessageArgs<P>): this;\n slack<T extends SlackTemplate<PropsSchema, never>>(\n template: T,\n ...props: MessageArgs<PropsOf<T>>\n ): this;\n discord<T extends DiscordTemplate<PropsSchema, never>>(\n template: T,\n ...props: MessageArgs<PropsOf<T>>\n ): this;\n survey<P extends object>(template: TemplateRef<'survey', P>, ...props: MessageArgs<P>): this;\n\n /**\n * Send one message on the first channel the user can be reached on: one push\n * and one email template, in priority order, rendered with the same props.\n * Sugar for the branch it compiles to — same IR, ids and hash as writing\n *\n * .branch(label, [reachable(first.channel), (b) => b.<first>(first, props)], (b) => b.<second>(second, props))\n *\n * so the choice is made once, when the step is reached, and a first choice\n * that fails to send retries as itself — it never falls through to the\n * second. Props are always passed (`{}` for templates that declare none),\n * and both templates must declare the same props type; for differing props\n * or other channels, write the branch.\n *\n * .prefer([push.tip, email.tip], { name: u.name }, { label: 'tip by channel' })\n */\n prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<PropsOf<T[0]>>>>(\n candidates: T & SameProps<NoInfer<T>>,\n props: A & NoInfer<NoExtra<A, PropsOf<T[0]>>>,\n options?: PreferOptions\n ): this;\n\n /* --------------------------------- Delays --------------------------------- */\n /** Time Delay; passing { min, max } makes it a Randomized Delay. */\n delay(duration: Duration): this;\n delay(range: { min: Duration; max: Duration }): this;\n\n /** Time Window: hold until inside the window (e.g. weekdays 09:00–17:00). tz: 'user' uses the user's timezone. */\n timeWindow(opts: {\n days?: readonly Weekday[];\n between: readonly [TimeOfDay, TimeOfDay];\n tz?: 'user' | (string & {});\n }): this;\n\n /**\n * Wait Until: continue on the main line once the condition holds, or take\n * onTimeout when it expires (default 'continue'). On the engine side this is\n * \"await event racing a timer\" — a native primitive of durable runtimes.\n */\n waitUntil(\n condition: Condition,\n opts: { timeout: Duration; onTimeout?: 'continue' | 'exit' | SubFlow }\n ): this;\n\n /**\n * Splice a fragment in place: a named `flow(...)` or a callback, expanded\n * once while the workflow is defined — a composition step before compiling,\n * not a node (the IR has no trace of it, and ids are assigned over the whole\n * workflow as if the steps were written inline). Each use gets its own copy,\n * so one fragment can be used in several places and workflows.\n *\n * const officeHours = flow((w) => w.timeWindow({ days: ['mon', 'tue', 'wed', 'thu', 'fri'], between: ['09:00', '17:00'] }));\n * workflow({ id: 'onboarding', ... }).delay('1 day').use(officeHours).email(email.tip, { name: u.name })\n */\n use(fragment: SubFlow): this;\n\n /* ------------------------------ Flow Control ------------------------------ */\n /**\n * Conditional branch: ordered first-match (same semantics as Step Functions\n * Choice / Knock branch). This one primitive covers both the UI's True/False\n * Branch (two arms) and Multi-Split Branch (N arms). Arms are\n * [condition, sub-flow] tuples; a bare sub-flow in tail position is the\n * default arm. With no match and no default, execution simply continues.\n * Rejoin is structural: after the matching arm finishes, execution resumes\n * at the node following the branch — to opt out, call .exit() inside the arm.\n *\n * .branch([activeSubscriber, upgradeFlow], firstTimeFlow) // True/False\n * .branch([vip, vipFlow], [trial, trialFlow], defaultFlow) // Multi-Split\n * .branch([not(usedStaging), eduFlow]) // single arm: no match continues\n *\n * The optional first argument `label` becomes the node's name in IR (UI title\n * / observability handle). It is not a jump target — there is no goto here;\n * looping is a future re-entry-policy topic (see sendEvent). Arm labels in\n * the UI are derived from the condition.\n */\n branch(...arms: readonly BranchArm[]): this;\n branch(label: string, ...arms: readonly BranchArm[]): this;\n\n /**\n * Gate: exit unless the condition holds, otherwise continue. A first-class\n * node rather than sugar over branch — same semantics as Zapier's \"only\n * continue if\" / Iterable's Filter tile, and rendered on its own in the UI.\n * `reason` is the audit-log line — metadata, so rewording it is free\n * (excluded from contentHash, see hash.ts).\n */\n filter(condition: Condition, opts?: { reason?: string }): this;\n\n /**\n * Random Cohort Branch (A/B): weights must sum to 100 (checked at runtime).\n * `key` names the experiment: bucketing hashes `userId:key` instead of the\n * structural node id, so assignments survive node insertion/moves and the\n * experiment keeps one identity across workflow versions — set it for any\n * A/B whose results you intend to read.\n *\n * Arm names become node id segments and are read back in authoring order, so\n * they are restricted to letters, digits, '_' and '-', never starting with a\n * digit (checked at runtime).\n */\n cohort(arms: Record<string, { weight: number; flow?: SubFlow }>, opts?: { key?: string }): this;\n\n /**\n * Exit: end the whole workflow immediately (the UI's Exit node); `reason`\n * goes into the audit log and is metadata, so rewording it neither repins\n * in-flight journeys nor shows up in plan. Inside a branch arm this means\n * \"terminate, do not rejoin\" — it stops here instead of falling through,\n * while an arm without exit rejoins naturally.\n */\n exit(reason?: string): this;\n\n /* ---------------------------------- Data ---------------------------------- */\n /**\n * Emit a typed event (customer.io's Send Event). The event comes from an\n * e.xxx reference, so payload types flow in the same way trigger.event works.\n * This is how workflows compose: an event can trigger another workflow, and\n * the resulting call graph is statically analyzable. Payload values may\n * reference u.xxx. Only scalar fields can be sent (IR carries literals and\n * profile refs, not nested JSON): an event whose payload requires a nested\n * field cannot be emitted from a journey, and the types say so.\n *\n * Note on loops: a trailing self-triggering sendEvent will become the\n * official periodic-flow shape *once a re-entry policy exists* — today the\n * entry policy is once-per-user, so a self-trigger cannot re-enter and does\n * not loop.\n * TODO: the rest of the Data category — outbound webhook / profile update /\n * journey attributes.\n */\n sendEvent<P extends object>(event: EventRef<P>, ...payload: EmitArgs<P>): this;\n\n /**\n * Run a custom action (see dsl/action.ts for the model). The chain records\n * identity only — name, args, codeHash — never the code: the implementation\n * ships inside the deployed Worker bundle and is resolved by name from the\n * runtime registry. Args are typed by the ActionRef and may reference u.xxx,\n * resolved at run time exactly like message props. Executed inside a durable\n * step: retried on throw, checkpointed on success.\n */\n run<A extends object>(action: ActionRef<A>, ...args: MessageArgs<A>): this;\n}\n\nconst DEFINED_CHANNELS: ReadonlySet<ChannelIR> = new Set(Object.values(CHANNEL_OF));\n\n/** A message's template: a definition of the channel (named by its id), or a reference by key. */\ntype MessageTemplate = AnyTemplate | TemplateRef;\n\nfunction templateKey(channel: ChannelIR, tpl: MessageTemplate): string {\n if (!DEFINED_CHANNELS.has(channel)) return (tpl as TemplateRef).key;\n // Typed, but a JS caller (or an `any`) reaches it unchecked: fail where the workflow is written\n if (!isTemplate(tpl) || CHANNEL_OF[tpl.kind] !== channel) {\n throw new TypeError(`${channel}(): expects a ${channel} template definition`);\n }\n return tpl.id;\n}\n\nfunction messageNode(\n channel: ChannelIR,\n tpl: MessageTemplate,\n props: object | undefined,\n devices?: 'latest'\n): NodeIR {\n return {\n id: '',\n type: 'message',\n channel,\n template: templateKey(channel, tpl),\n props: (props ?? {}) as Record<string, PropValueIR>,\n // Absent for 'all', so adding the option left every existing push's hash as it was\n ...(devices !== undefined ? { devices } : {}),\n };\n}\n\n/* oxlint-disable typescript/unbound-method --\n * `captureLoc(this.xxx)` passes the method by identity as the stack-trace\n * boundary for Error.captureStackTrace; it is never invoked, so `this`\n * scoping cannot go wrong. */\n/** @internal extended by WorkflowBuilderImpl; not part of the public API */\nexport class FlowBuilderImpl implements FlowBuilder {\n /** Nodes as collected; ids are assigned in one pass inside toIR, so '' is a placeholder here. */\n readonly nodes: NodeIR[] = [];\n /** The template definitions sent, with where: compile-time only, never in the IR. */\n readonly uses: TemplateUse[] = [];\n\n /** Provenance: the callsite (captured in the public method) lands in meta.loc, outside the hash. */\n private pushNode(node: NodeIR, loc: SourceLocIR | undefined): this {\n this.nodes.push({ ...node, ...(loc !== undefined ? { meta: { loc } } : {}) });\n return this;\n }\n\n private message(\n channel: ChannelIR,\n tpl: MessageTemplate,\n props: object | undefined,\n loc: SourceLocIR | undefined,\n devices?: 'latest'\n ): this {\n this.pushNode(messageNode(channel, tpl, props, devices), loc);\n if (isTemplate(tpl)) this.uses.push({ template: tpl, loc });\n return this;\n }\n\n email<T extends EmailTemplate>(t: T, ...args: MessageArgs<PropsOf<T>>): this {\n return this.message('email', t, args[0], captureLoc(this.email));\n }\n sms<P extends object>(t: TemplateRef<'sms', P>, ...args: MessageArgs<P>): this {\n return this.message('sms', t, args[0], captureLoc(this.sms));\n }\n push<T extends PushTemplate>(\n t: T,\n ...args: [...props: MessageArgs<PropsOf<T>>, options?: PushOptions]\n ): this {\n const [props, options] = args as unknown as [object | undefined, PushOptions | undefined];\n const devices = options?.devices === 'latest' ? 'latest' : undefined;\n return this.message('push', t, props, captureLoc(this.push), devices);\n }\n inApp<P extends object>(t: TemplateRef<'in_app', P>, ...args: MessageArgs<P>): this {\n return this.message('in_app', t, args[0], captureLoc(this.inApp));\n }\n slack<T extends SlackTemplate<PropsSchema, never>>(t: T, ...args: MessageArgs<PropsOf<T>>): this {\n return this.message('slack', t, args[0], captureLoc(this.slack));\n }\n discord<T extends DiscordTemplate<PropsSchema, never>>(\n t: T,\n ...args: MessageArgs<PropsOf<T>>\n ): this {\n return this.message('discord', t, args[0], captureLoc(this.discord));\n }\n survey<P extends object>(t: TemplateRef<'survey', P>, ...args: MessageArgs<P>): this {\n return this.message('survey', t, args[0], captureLoc(this.survey));\n }\n\n prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<PropsOf<T[0]>>>>(\n candidates: T & SameProps<NoInfer<T>>,\n props: A & NoInfer<NoExtra<A, PropsOf<T[0]>>>,\n options?: PreferOptions\n ): this {\n checkPreferArgs(candidates, props, options);\n // Every generated node points at the author's prefer() call, not at this method's body\n const loc = captureLoc(this.prefer);\n const meta = loc !== undefined ? { meta: { loc } } : {};\n const [first, second] = candidates as readonly (EmailTemplate | PushTemplate)[];\n const channel = (tpl: EmailTemplate | PushTemplate) => CHANNEL_OF[tpl.kind] as 'email' | 'push';\n // Both are sent from here as far as the registry check goes, the fallback included\n this.uses.push({ template: first, loc }, { template: second, loc });\n // A copy per message, as two separately written calls would hold\n const arm = (tpl: EmailTemplate | PushTemplate): NodeIR[] => [\n { ...messageNode(channel(tpl), tpl, { ...props }), ...meta },\n ];\n return this.pushNode(\n {\n id: '',\n type: 'branch',\n ...(options?.label !== undefined ? { label: options.label } : {}),\n cases: [\n { condition: { type: 'reachable', channel: channel(first), ...meta }, flow: arm(first) },\n ],\n otherwise: arm(second),\n },\n loc\n );\n }\n\n delay(duration: Duration): this;\n delay(range: { min: Duration; max: Duration }): this;\n delay(d: Duration | { min: Duration; max: Duration }): this {\n const loc = captureLoc(this.delay);\n if (typeof d === 'string') {\n return this.pushNode({ id: '', type: 'delay', duration: durationIR(d) }, loc);\n }\n const min = durationIR(d.min);\n const max = durationIR(d.max);\n /*\n * The interpreter draws `min + random(max - min)` with the span clamped at\n * zero, so a backwards range does not fail — it quietly collapses into a\n * fixed `min` sleep. Reject it here, where the author can still see it.\n */\n if (max.ms < min.ms) {\n throw new Error(\n `delay(): 'max' must not be shorter than 'min', got { min: '${d.min}', max: '${d.max}' }`\n );\n }\n return this.pushNode({ id: '', type: 'random_delay', min, max }, loc);\n }\n\n timeWindow(opts: {\n days?: readonly Weekday[];\n between: readonly [TimeOfDay, TimeOfDay];\n tz?: 'user' | (string & {});\n }): this {\n const loc = captureLoc(this.timeWindow);\n const start = timeOfDayMinutes(opts.between[0]);\n const end = timeOfDayMinutes(opts.between[1]);\n if (end <= start) {\n throw new Error(\n `timeWindow(): 'between' must open before it closes within one day, got [${opts.between[0]}, ${opts.between[1]}] (overnight windows are not supported yet)`\n );\n }\n return this.pushNode(\n {\n id: '',\n type: 'time_window',\n days: [...(opts.days ?? (['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const))],\n between: [opts.between[0], opts.between[1]],\n tz: opts.tz ?? 'user',\n },\n loc\n );\n }\n\n waitUntil(\n condition: Condition,\n opts: { timeout: Duration; onTimeout?: 'continue' | 'exit' | SubFlow }\n ): this {\n const loc = captureLoc(this.waitUntil);\n const onTimeout = opts.onTimeout ?? 'continue';\n return this.pushNode(\n {\n id: '',\n type: 'wait_until',\n condition: condIR(condition),\n timeout: durationIR(opts.timeout),\n onTimeout:\n onTimeout === 'continue' || onTimeout === 'exit'\n ? onTimeout\n : resolveSubFlow(onTimeout, this.uses),\n },\n loc\n );\n }\n\n use(fragment: SubFlow): this {\n // The fragment's nodes carry their own provenance (where the fragment was written)\n this.nodes.push(...resolveSubFlow(fragment, this.uses));\n return this;\n }\n\n branch(...arms: readonly BranchArm[]): this;\n branch(label: string, ...arms: readonly BranchArm[]): this;\n branch(...args: readonly (string | BranchArm)[]): this {\n const loc = captureLoc(this.branch);\n const label = typeof args[0] === 'string' ? args[0] : undefined;\n const arms = (label === undefined ? args : args.slice(1)) as readonly BranchArm[];\n\n const cases: { condition: ConditionIR; flow: NodeIR[] }[] = [];\n let otherwise: NodeIR[] | undefined;\n arms.forEach((arm, i) => {\n if (Array.isArray(arm)) {\n if (otherwise !== undefined) {\n throw new Error('branch(): default arm (bare sub-flow) must be the last argument');\n }\n const [condition, sub] = arm as BranchCase;\n cases.push({ condition: condIR(condition), flow: resolveSubFlow(sub, this.uses) });\n } else {\n if (otherwise !== undefined) {\n throw new Error('branch(): only one default arm (bare sub-flow) is allowed');\n }\n if (i !== arms.length - 1) {\n throw new Error('branch(): default arm (bare sub-flow) must be the last argument');\n }\n otherwise = resolveSubFlow(arm as SubFlow, this.uses);\n }\n });\n\n return this.pushNode(\n {\n id: '',\n type: 'branch',\n ...(label !== undefined ? { label } : {}),\n cases,\n ...(otherwise !== undefined ? { otherwise } : {}),\n },\n loc\n );\n }\n\n filter(condition: Condition, opts?: { reason?: string }): this {\n return this.pushNode(\n {\n id: '',\n type: 'filter',\n condition: condIR(condition),\n ...(opts?.reason !== undefined ? { reason: opts.reason } : {}),\n },\n captureLoc(this.filter)\n );\n }\n\n cohort(arms: Record<string, { weight: number; flow?: SubFlow }>, opts?: { key?: string }): this {\n const loc = captureLoc(this.cohort);\n const entries = Object.entries(arms);\n /*\n * Weights live on a 0.01% grid: the runtime buckets into 10,000 slots\n * (basis points), so anything finer would be silently quantized — reject\n * it here instead. Converting to integer basis points also makes the\n * sum check exact; no epsilon needed.\n */\n const basisPoints = entries.map(([name, a]) => {\n if (!ARM_NAME.test(name)) {\n throw new Error(\n `cohort(): arm name '${name}' must start with a letter or '_' and contain only letters, digits, '_' or '-' — arm names become node id segments, and integer-like names would silently reorder the arms`\n );\n }\n const bp = a.weight * 100;\n if (Math.abs(bp - Math.round(bp)) > 1e-6) {\n throw new Error(\n `cohort(): arm '${name}' weight ${a.weight} is finer than the 0.01% bucketing grid — use at most two decimal places`\n );\n }\n /*\n * The sum check alone accepts -50 / 150: the runtime walks the arms\n * accumulating basis points and takes the first whose cumulative total\n * clears the bucket, so a negative weight hands 100% of users to its\n * neighbour instead of splitting anything.\n */\n if (bp < 0) {\n throw new Error(`cohort(): arm '${name}' weight ${a.weight} must not be negative`);\n }\n return Math.round(bp);\n });\n const total = basisPoints.reduce((sum, bp) => sum + bp, 0);\n if (total !== 10_000) {\n throw new Error(`cohort(): weights must sum to 100, got ${total / 100}`);\n }\n return this.pushNode(\n {\n id: '',\n type: 'cohort',\n ...(opts?.key !== undefined ? { key: opts.key } : {}),\n arms: entries.map(([name, a]) => ({\n name,\n weight: a.weight,\n flow: a.flow ? resolveSubFlow(a.flow, this.uses) : [],\n })),\n },\n loc\n );\n }\n\n exit(reason?: string): this {\n return this.pushNode(\n { id: '', type: 'exit', ...(reason !== undefined ? { reason } : {}) },\n captureLoc(this.exit)\n );\n }\n\n sendEvent<P extends object>(ev: EventRef<P>, ...payload: EmitArgs<P>): this {\n const values = (payload[0] ?? {}) as Record<string, unknown>;\n for (const [field, value] of Object.entries(values)) {\n const ref =\n typeof value === 'object' &&\n value !== null &&\n (value as { type?: unknown }).type === 'user_property';\n if (!ref && !['string', 'number', 'boolean'].includes(typeof value)) {\n throw new TypeError(\n `sendEvent('${ev.name}'): '${field}' is not a scalar or a u.xxx reference — an emitted payload carries scalar fields only`\n );\n }\n }\n return this.pushNode(\n {\n id: '',\n type: 'send_event',\n event: ev.name,\n payload: values as Record<string, PropValueIR>,\n },\n captureLoc(this.sendEvent)\n );\n }\n\n run<A extends object>(a: ActionRef<A>, ...args: MessageArgs<A>): this {\n return this.pushNode(\n {\n id: '',\n type: 'action',\n action: a.name,\n args: (args[0] ?? {}) as Record<string, PropValueIR>,\n codeHash: a.codeHash,\n },\n captureLoc(this.run)\n );\n }\n}\n/* oxlint-enable typescript/unbound-method */\n\n/**\n * A reusable flow fragment: a free function. Once personalization goes through\n * u.xxx and events through e.xxx, the flow layer carries no schema generics.\n */\nexport function flow(build: (w: FlowBuilder) => FlowBuilder): Flow {\n const builder = new FlowBuilderImpl();\n build(builder);\n const impl: FlowInternal = { __flow: true, nodes: builder.nodes, uses: builder.uses };\n return impl;\n}\n"],"mappings":";;;;;;;AA0EA,SAAS,gBAAgB,YAAqB,OAAgB,SAAwB;CACpF,IAAI,CAAC,MAAM,QAAQ,UAAU,KAAK,WAAW,WAAW,GACtD,MAAM,IAAI,UAAU,0EAA0E;CAEhG,MAAM,WAAY,WAAyB,KAAK,cAC9CA,kBAAAA,WAAW,SAAS,IAAIC,kBAAAA,WAAW,UAAU,QAAQ,KAAA,CACvD;CACA,IAAI,CAAC,SAAS,OAAO,YAAY,YAAY,UAAU,YAAY,OAAO,GACxE,MAAM,IAAI,UAAU,qEAAqE;CAE3F,IAAI,SAAS,OAAO,SAAS,IAC3B,MAAM,IAAI,UAAU,8DAA8D;CAEpF,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,UACR,6EACF;CAEF,IAAI,YAAY,KAAA,GAAW;CAC3B,IAAI,OAAO,YAAY,YAAY,YAAY,QAAQ,MAAM,QAAQ,OAAO,GAC1E,MAAM,IAAI,UAAU,qCAAqC;CAE3D,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,OAAO,GAAG;EACnD,IAAI,SAAS,SACX,MAAM,IAAI,UACR,6BAA6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,OAAO;CAEb,OAAO;EADsB,QAAQ;EAAM,OAAO,QAAQ;EAAO,MAAM,QAAQ;CACrE;AACZ"}
|
package/dist/dsl/flow.d.cts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { NodeIR } from "../ir.cjs";
|
|
1
|
+
import { NodeIR, SourceLocIR } from "../ir.cjs";
|
|
2
|
+
import { AnyTemplate, DiscordTemplate, EmailTemplate, PropsSchema, PushTemplate, SlackTemplate } from "../templates.cjs";
|
|
2
3
|
import { ActionRef } from "./action.cjs";
|
|
3
4
|
import { Duration, TimeOfDay, Weekday } from "./base.cjs";
|
|
4
5
|
import { EventRef, MessageArgs, PropInput, PropsInput } from "./refs.cjs";
|
|
5
|
-
import { TemplateRef } from "./template.cjs";
|
|
6
|
+
import { PropsOf, TemplateRef } from "./template.cjs";
|
|
6
7
|
import { Condition } from "./condition.cjs";
|
|
7
8
|
//#region src/dsl/flow.d.ts
|
|
8
9
|
/**
|
|
@@ -35,12 +36,11 @@ export interface PreferOptions {
|
|
|
35
36
|
label?: string;
|
|
36
37
|
}
|
|
37
38
|
/** The candidates `prefer()` takes: one push and one email template, in priority order. */
|
|
38
|
-
type PreferPair = readonly [
|
|
39
|
-
type RefProps<R> = R extends TemplateRef<infer _C, infer P> ? P : never;
|
|
39
|
+
type PreferPair = readonly [PushTemplate, EmailTemplate] | readonly [EmailTemplate, PushTemplate];
|
|
40
40
|
type NormalizeProps<P> = { -readonly [K in keyof P]: P[K]; };
|
|
41
41
|
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => (T extends B ? 1 : 2)) ? true : false;
|
|
42
42
|
/** Both candidates render the one props object, so they must declare the same props type — not merely overlap. */
|
|
43
|
-
type SameProps<T extends PreferPair> = Equal<NormalizeProps<
|
|
43
|
+
type SameProps<T extends PreferPair> = Equal<NormalizeProps<PropsOf<T[0]>>, NormalizeProps<PropsOf<T[1]>>> extends true ? unknown : {
|
|
44
44
|
readonly __prefer_error__: 'Both templates must declare the same props type';
|
|
45
45
|
};
|
|
46
46
|
/** Distributes, so a field only one member of a union variable has still counts as extra. */
|
|
@@ -51,6 +51,17 @@ type NoExtra<A, P> = Record<Exclude<KeysOfUnion<A>, keyof P>, never>;
|
|
|
51
51
|
export interface Flow {
|
|
52
52
|
readonly __flow: true;
|
|
53
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* @internal A template definition a flow sends, kept beside the IR (which names it by id only):
|
|
56
|
+
* compileConfig checks that the registered definition under that id is this very object, so the
|
|
57
|
+
* schema that typed the call is the one that renders it. Never part of the IR or its hash.
|
|
58
|
+
*/
|
|
59
|
+
export interface TemplateUse {
|
|
60
|
+
readonly template: AnyTemplate;
|
|
61
|
+
readonly loc: SourceLocIR | undefined;
|
|
62
|
+
}
|
|
63
|
+
/** @internal The template definitions a workflow sends, sub-flows and fragments included. */
|
|
64
|
+
export declare function templateUses(builder: FlowBuilder): readonly TemplateUse[];
|
|
54
65
|
/** Sub-flow: a named fragment, or an inline callback (runs once at construction — builder in, builder out). */
|
|
55
66
|
export type SubFlow = Flow | ((w: FlowBuilder) => FlowBuilder);
|
|
56
67
|
/** A branch arm: the [condition, sub-flow] tuple — an [if, then] ordering convention. */
|
|
@@ -61,17 +72,17 @@ export type BranchCase = readonly [condition: Condition, flow: SubFlow];
|
|
|
61
72
|
*/
|
|
62
73
|
export type BranchArm = BranchCase | SubFlow;
|
|
63
74
|
export interface FlowBuilder {
|
|
64
|
-
email<
|
|
75
|
+
email<T extends EmailTemplate>(template: T, ...props: MessageArgs<PropsOf<T>>): this;
|
|
65
76
|
sms<P extends object>(template: TemplateRef<'sms', P>, ...props: MessageArgs<P>): this;
|
|
66
77
|
/**
|
|
67
78
|
* Push to the user's devices — every device the host's directory lists, or
|
|
68
79
|
* only the most recently registered with `{ devices: 'latest' }`. A user with
|
|
69
80
|
* no device is skipped (`prefer([pushTpl, emailTpl], props)` falls back to email).
|
|
70
81
|
*/
|
|
71
|
-
push<
|
|
82
|
+
push<T extends PushTemplate>(template: T, ...args: [...props: MessageArgs<PropsOf<T>>, options?: PushOptions]): this;
|
|
72
83
|
inApp<P extends object>(template: TemplateRef<'in_app', P>, ...props: MessageArgs<P>): this;
|
|
73
|
-
slack<
|
|
74
|
-
discord<
|
|
84
|
+
slack<T extends SlackTemplate<PropsSchema, never>>(template: T, ...props: MessageArgs<PropsOf<T>>): this;
|
|
85
|
+
discord<T extends DiscordTemplate<PropsSchema, never>>(template: T, ...props: MessageArgs<PropsOf<T>>): this;
|
|
75
86
|
survey<P extends object>(template: TemplateRef<'survey', P>, ...props: MessageArgs<P>): this;
|
|
76
87
|
/**
|
|
77
88
|
* Send one message on the first channel the user can be reached on: one push
|
|
@@ -86,9 +97,9 @@ export interface FlowBuilder {
|
|
|
86
97
|
* and both templates must declare the same props type; for differing props
|
|
87
98
|
* or other channels, write the branch.
|
|
88
99
|
*
|
|
89
|
-
* .prefer([
|
|
100
|
+
* .prefer([push.tip, email.tip], { name: u.name }, { label: 'tip by channel' })
|
|
90
101
|
*/
|
|
91
|
-
prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<
|
|
102
|
+
prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<PropsOf<T[0]>>>>(candidates: T & SameProps<NoInfer<T>>, props: A & NoInfer<NoExtra<A, PropsOf<T[0]>>>, options?: PreferOptions): this;
|
|
92
103
|
/** Time Delay; passing { min, max } makes it a Randomized Delay. */
|
|
93
104
|
delay(duration: Duration): this;
|
|
94
105
|
delay(range: {
|
|
@@ -118,7 +129,7 @@ export interface FlowBuilder {
|
|
|
118
129
|
* so one fragment can be used in several places and workflows.
|
|
119
130
|
*
|
|
120
131
|
* const officeHours = flow((w) => w.timeWindow({ days: ['mon', 'tue', 'wed', 'thu', 'fri'], between: ['09:00', '17:00'] }));
|
|
121
|
-
* workflow({ id: 'onboarding', ... }).delay('1 day').use(officeHours).email(
|
|
132
|
+
* workflow({ id: 'onboarding', ... }).delay('1 day').use(officeHours).email(email.tip, { name: u.name })
|
|
122
133
|
*/
|
|
123
134
|
use(fragment: SubFlow): this;
|
|
124
135
|
/**
|
|
@@ -207,17 +218,19 @@ export interface FlowBuilder {
|
|
|
207
218
|
export declare class FlowBuilderImpl implements FlowBuilder {
|
|
208
219
|
/** Nodes as collected; ids are assigned in one pass inside toIR, so '' is a placeholder here. */
|
|
209
220
|
readonly nodes: NodeIR[];
|
|
221
|
+
/** The template definitions sent, with where: compile-time only, never in the IR. */
|
|
222
|
+
readonly uses: TemplateUse[];
|
|
210
223
|
/** Provenance: the callsite (captured in the public method) lands in meta.loc, outside the hash. */
|
|
211
224
|
private pushNode;
|
|
212
225
|
private message;
|
|
213
|
-
email<
|
|
226
|
+
email<T extends EmailTemplate>(t: T, ...args: MessageArgs<PropsOf<T>>): this;
|
|
214
227
|
sms<P extends object>(t: TemplateRef<'sms', P>, ...args: MessageArgs<P>): this;
|
|
215
|
-
push<
|
|
228
|
+
push<T extends PushTemplate>(t: T, ...args: [...props: MessageArgs<PropsOf<T>>, options?: PushOptions]): this;
|
|
216
229
|
inApp<P extends object>(t: TemplateRef<'in_app', P>, ...args: MessageArgs<P>): this;
|
|
217
|
-
slack<
|
|
218
|
-
discord<
|
|
230
|
+
slack<T extends SlackTemplate<PropsSchema, never>>(t: T, ...args: MessageArgs<PropsOf<T>>): this;
|
|
231
|
+
discord<T extends DiscordTemplate<PropsSchema, never>>(t: T, ...args: MessageArgs<PropsOf<T>>): this;
|
|
219
232
|
survey<P extends object>(t: TemplateRef<'survey', P>, ...args: MessageArgs<P>): this;
|
|
220
|
-
prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<
|
|
233
|
+
prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<PropsOf<T[0]>>>>(candidates: T & SameProps<NoInfer<T>>, props: A & NoInfer<NoExtra<A, PropsOf<T[0]>>>, options?: PreferOptions): this;
|
|
221
234
|
delay(duration: Duration): this;
|
|
222
235
|
delay(range: {
|
|
223
236
|
min: Duration;
|
|
@@ -254,4 +267,5 @@ export declare class FlowBuilderImpl implements FlowBuilder {
|
|
|
254
267
|
*/
|
|
255
268
|
export declare function flow(build: (w: FlowBuilder) => FlowBuilder): Flow;
|
|
256
269
|
//#endregion
|
|
270
|
+
export {};
|
|
257
271
|
//# sourceMappingURL=flow.d.cts.map
|
package/dist/dsl/flow.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow.d.cts","names":[],"sources":["../../src/dsl/flow.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"flow.d.cts","names":[],"sources":["../../src/dsl/flow.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;KA+BK;;KAGA,UAAU,MAAM,YAAY,aAAa,UAAU,UAAU;;YAGtD,YAAY,QAAQ,WAAW,IAAI,UAAU,EAAE;;YAG/C,SAAS,KACnB,6BAA6B,KAAK,UAAU,YAAY,OAAO,SAAS,YAAY;;iBAGrE;;EAEf;;;iBAIe;;EAEf;;;KAIG,uBAAuB,cAAc,2BAA2B,eAAe;KAE/E,eAAe,kBAAkB,WAAW,IAAI,EAAE;KAClD,MAAM,GAAG,OACV,QAAQ,UAAU,qBAAoB,SAAQ,UAAU;;KAGvD,UAAU,UAAU,cACvB,MAAM,eAAe,QAAQ,QAAQ,eAAe,QAAQ;WAE7C;;;KAGZ,YAAY,KAAK,0BAA0B;;KAE3C,QAAQ,GAAG,KAAK,OAAO,QAAQ,YAAY,UAAU;;iBAoCzC;WACN;;;;;;;iBAaM;WACN,UAAU;WACV,KAAK;;;wBAIA,aAAa,SAAS,uBAAuB;;YAKjD,UAAU,SAAS,GAAG,gBAAgB;;YAGtC,uBAAuB,WAAW,WAAW,MAAM;;;;;YAMnD,YAAY,aAAa;iBAyCpB;EAEf,MAAM,UAAU,eAAe,UAAU,MAAM,OAAO,YAAY,QAAQ;EAC1E,IAAI,kBAAkB,UAAU,mBAAmB,OAAO,OAAO,YAAY;;;;;;EAM7E,KAAK,UAAU,cACb,UAAU,MACP,UAAU,OAAO,YAAY,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O,MAAM,YAAY;EAG1E,MAAM,UAAU,cAAc,qBAAqB,GAAG,MAAM,MAAM,YAAY,QAAQ;EAGtF,QAAQ,UAAU,gBAAgB,qBAChC,GAAG,MACA,MAAM,YAAY,QAAQ;EAI/B,OAAO,kBAAkB,GAAG,sBAAsB,OAAO,MAAM,YAAY;EAI3E,aAAa,UAAU,kBAAkB,UAAU,WAAW,QAAQ,QAAQ,SAC5E,YAAY,IAAI,UAAU,QAAQ,KAClC,OAAO,IAAI,QAAQ,QAAQ,GAAG,QAAQ,SACtC,UAAU;EA4BZ,MAAM,UAAU;EAChB,MAAM;IAAS,KAAK;IAAU,KAAK;;EAqBnC,WAAW;IACT,gBAAgB;IAChB,mBAAmB,WAAW;IAC9B;;EAsBF,UACE,WAAW,WACX;IAAQ,SAAS;IAAU,kCAAkC;;EAmB/D,IAAI,UAAU;EAMd,UAAU,eAAe;EACzB,OAAO,kBAAkB,eAAe;EAsCxC,OAAO,WAAW,WAAW;IAAS;;EAYtC,OAAO,MAAM;IAAiB;IAAgB,OAAO;MAAY;IAAS;;EAmD1E,KAAK;EAOL,UAAU,kBAAkB,IAAI,SAAS,OAAO,SAAS,SAAS;EAwBlE,IAAI,kBAAkB,GAAG,UAAU,OAAO,MAAM,YAAY;;;;;;wBAmB9C,KAAK,QAAQ,GAAG,gBAAgB,cAAc"}
|
package/dist/dsl/flow.d.mts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { NodeIR } from "../ir.mjs";
|
|
1
|
+
import { NodeIR, SourceLocIR } from "../ir.mjs";
|
|
2
|
+
import { AnyTemplate, DiscordTemplate, EmailTemplate, PropsSchema, PushTemplate, SlackTemplate } from "../templates.mjs";
|
|
2
3
|
import { ActionRef } from "./action.mjs";
|
|
3
4
|
import { Duration, TimeOfDay, Weekday } from "./base.mjs";
|
|
4
5
|
import { EventRef, MessageArgs, PropInput, PropsInput } from "./refs.mjs";
|
|
5
|
-
import { TemplateRef } from "./template.mjs";
|
|
6
|
+
import { PropsOf, TemplateRef } from "./template.mjs";
|
|
6
7
|
import { Condition } from "./condition.mjs";
|
|
7
8
|
//#region src/dsl/flow.d.ts
|
|
8
9
|
/**
|
|
@@ -35,12 +36,11 @@ export interface PreferOptions {
|
|
|
35
36
|
label?: string;
|
|
36
37
|
}
|
|
37
38
|
/** The candidates `prefer()` takes: one push and one email template, in priority order. */
|
|
38
|
-
type PreferPair = readonly [
|
|
39
|
-
type RefProps<R> = R extends TemplateRef<infer _C, infer P> ? P : never;
|
|
39
|
+
type PreferPair = readonly [PushTemplate, EmailTemplate] | readonly [EmailTemplate, PushTemplate];
|
|
40
40
|
type NormalizeProps<P> = { -readonly [K in keyof P]: P[K]; };
|
|
41
41
|
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => (T extends B ? 1 : 2)) ? true : false;
|
|
42
42
|
/** Both candidates render the one props object, so they must declare the same props type — not merely overlap. */
|
|
43
|
-
type SameProps<T extends PreferPair> = Equal<NormalizeProps<
|
|
43
|
+
type SameProps<T extends PreferPair> = Equal<NormalizeProps<PropsOf<T[0]>>, NormalizeProps<PropsOf<T[1]>>> extends true ? unknown : {
|
|
44
44
|
readonly __prefer_error__: 'Both templates must declare the same props type';
|
|
45
45
|
};
|
|
46
46
|
/** Distributes, so a field only one member of a union variable has still counts as extra. */
|
|
@@ -51,6 +51,17 @@ type NoExtra<A, P> = Record<Exclude<KeysOfUnion<A>, keyof P>, never>;
|
|
|
51
51
|
export interface Flow {
|
|
52
52
|
readonly __flow: true;
|
|
53
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* @internal A template definition a flow sends, kept beside the IR (which names it by id only):
|
|
56
|
+
* compileConfig checks that the registered definition under that id is this very object, so the
|
|
57
|
+
* schema that typed the call is the one that renders it. Never part of the IR or its hash.
|
|
58
|
+
*/
|
|
59
|
+
export interface TemplateUse {
|
|
60
|
+
readonly template: AnyTemplate;
|
|
61
|
+
readonly loc: SourceLocIR | undefined;
|
|
62
|
+
}
|
|
63
|
+
/** @internal The template definitions a workflow sends, sub-flows and fragments included. */
|
|
64
|
+
export declare function templateUses(builder: FlowBuilder): readonly TemplateUse[];
|
|
54
65
|
/** Sub-flow: a named fragment, or an inline callback (runs once at construction — builder in, builder out). */
|
|
55
66
|
export type SubFlow = Flow | ((w: FlowBuilder) => FlowBuilder);
|
|
56
67
|
/** A branch arm: the [condition, sub-flow] tuple — an [if, then] ordering convention. */
|
|
@@ -61,17 +72,17 @@ export type BranchCase = readonly [condition: Condition, flow: SubFlow];
|
|
|
61
72
|
*/
|
|
62
73
|
export type BranchArm = BranchCase | SubFlow;
|
|
63
74
|
export interface FlowBuilder {
|
|
64
|
-
email<
|
|
75
|
+
email<T extends EmailTemplate>(template: T, ...props: MessageArgs<PropsOf<T>>): this;
|
|
65
76
|
sms<P extends object>(template: TemplateRef<'sms', P>, ...props: MessageArgs<P>): this;
|
|
66
77
|
/**
|
|
67
78
|
* Push to the user's devices — every device the host's directory lists, or
|
|
68
79
|
* only the most recently registered with `{ devices: 'latest' }`. A user with
|
|
69
80
|
* no device is skipped (`prefer([pushTpl, emailTpl], props)` falls back to email).
|
|
70
81
|
*/
|
|
71
|
-
push<
|
|
82
|
+
push<T extends PushTemplate>(template: T, ...args: [...props: MessageArgs<PropsOf<T>>, options?: PushOptions]): this;
|
|
72
83
|
inApp<P extends object>(template: TemplateRef<'in_app', P>, ...props: MessageArgs<P>): this;
|
|
73
|
-
slack<
|
|
74
|
-
discord<
|
|
84
|
+
slack<T extends SlackTemplate<PropsSchema, never>>(template: T, ...props: MessageArgs<PropsOf<T>>): this;
|
|
85
|
+
discord<T extends DiscordTemplate<PropsSchema, never>>(template: T, ...props: MessageArgs<PropsOf<T>>): this;
|
|
75
86
|
survey<P extends object>(template: TemplateRef<'survey', P>, ...props: MessageArgs<P>): this;
|
|
76
87
|
/**
|
|
77
88
|
* Send one message on the first channel the user can be reached on: one push
|
|
@@ -86,9 +97,9 @@ export interface FlowBuilder {
|
|
|
86
97
|
* and both templates must declare the same props type; for differing props
|
|
87
98
|
* or other channels, write the branch.
|
|
88
99
|
*
|
|
89
|
-
* .prefer([
|
|
100
|
+
* .prefer([push.tip, email.tip], { name: u.name }, { label: 'tip by channel' })
|
|
90
101
|
*/
|
|
91
|
-
prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<
|
|
102
|
+
prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<PropsOf<T[0]>>>>(candidates: T & SameProps<NoInfer<T>>, props: A & NoInfer<NoExtra<A, PropsOf<T[0]>>>, options?: PreferOptions): this;
|
|
92
103
|
/** Time Delay; passing { min, max } makes it a Randomized Delay. */
|
|
93
104
|
delay(duration: Duration): this;
|
|
94
105
|
delay(range: {
|
|
@@ -118,7 +129,7 @@ export interface FlowBuilder {
|
|
|
118
129
|
* so one fragment can be used in several places and workflows.
|
|
119
130
|
*
|
|
120
131
|
* const officeHours = flow((w) => w.timeWindow({ days: ['mon', 'tue', 'wed', 'thu', 'fri'], between: ['09:00', '17:00'] }));
|
|
121
|
-
* workflow({ id: 'onboarding', ... }).delay('1 day').use(officeHours).email(
|
|
132
|
+
* workflow({ id: 'onboarding', ... }).delay('1 day').use(officeHours).email(email.tip, { name: u.name })
|
|
122
133
|
*/
|
|
123
134
|
use(fragment: SubFlow): this;
|
|
124
135
|
/**
|
|
@@ -207,17 +218,19 @@ export interface FlowBuilder {
|
|
|
207
218
|
export declare class FlowBuilderImpl implements FlowBuilder {
|
|
208
219
|
/** Nodes as collected; ids are assigned in one pass inside toIR, so '' is a placeholder here. */
|
|
209
220
|
readonly nodes: NodeIR[];
|
|
221
|
+
/** The template definitions sent, with where: compile-time only, never in the IR. */
|
|
222
|
+
readonly uses: TemplateUse[];
|
|
210
223
|
/** Provenance: the callsite (captured in the public method) lands in meta.loc, outside the hash. */
|
|
211
224
|
private pushNode;
|
|
212
225
|
private message;
|
|
213
|
-
email<
|
|
226
|
+
email<T extends EmailTemplate>(t: T, ...args: MessageArgs<PropsOf<T>>): this;
|
|
214
227
|
sms<P extends object>(t: TemplateRef<'sms', P>, ...args: MessageArgs<P>): this;
|
|
215
|
-
push<
|
|
228
|
+
push<T extends PushTemplate>(t: T, ...args: [...props: MessageArgs<PropsOf<T>>, options?: PushOptions]): this;
|
|
216
229
|
inApp<P extends object>(t: TemplateRef<'in_app', P>, ...args: MessageArgs<P>): this;
|
|
217
|
-
slack<
|
|
218
|
-
discord<
|
|
230
|
+
slack<T extends SlackTemplate<PropsSchema, never>>(t: T, ...args: MessageArgs<PropsOf<T>>): this;
|
|
231
|
+
discord<T extends DiscordTemplate<PropsSchema, never>>(t: T, ...args: MessageArgs<PropsOf<T>>): this;
|
|
219
232
|
survey<P extends object>(t: TemplateRef<'survey', P>, ...args: MessageArgs<P>): this;
|
|
220
|
-
prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<
|
|
233
|
+
prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<PropsOf<T[0]>>>>(candidates: T & SameProps<NoInfer<T>>, props: A & NoInfer<NoExtra<A, PropsOf<T[0]>>>, options?: PreferOptions): this;
|
|
221
234
|
delay(duration: Duration): this;
|
|
222
235
|
delay(range: {
|
|
223
236
|
min: Duration;
|
|
@@ -254,4 +267,5 @@ export declare class FlowBuilderImpl implements FlowBuilder {
|
|
|
254
267
|
*/
|
|
255
268
|
export declare function flow(build: (w: FlowBuilder) => FlowBuilder): Flow;
|
|
256
269
|
//#endregion
|
|
270
|
+
export {};
|
|
257
271
|
//# sourceMappingURL=flow.d.mts.map
|
package/dist/dsl/flow.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow.d.mts","names":[],"sources":["../../src/dsl/flow.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"flow.d.mts","names":[],"sources":["../../src/dsl/flow.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;KA+BK;;KAGA,UAAU,MAAM,YAAY,aAAa,UAAU,UAAU;;YAGtD,YAAY,QAAQ,WAAW,IAAI,UAAU,EAA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