@shware/workflow 0.4.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.
Files changed (90) hide show
  1. package/README.md +48 -38
  2. package/dist/cloudflare/channels.cjs +12 -14
  3. package/dist/cloudflare/channels.cjs.map +1 -1
  4. package/dist/cloudflare/channels.d.cts.map +1 -1
  5. package/dist/cloudflare/channels.d.mts.map +1 -1
  6. package/dist/cloudflare/channels.mjs +13 -15
  7. package/dist/cloudflare/channels.mjs.map +1 -1
  8. package/dist/config.cjs +61 -36
  9. package/dist/config.cjs.map +1 -1
  10. package/dist/config.d.cts +19 -15
  11. package/dist/config.d.cts.map +1 -1
  12. package/dist/config.d.mts +19 -15
  13. package/dist/config.d.mts.map +1 -1
  14. package/dist/config.mjs +61 -36
  15. package/dist/config.mjs.map +1 -1
  16. package/dist/dsl/action.cjs +1 -1
  17. package/dist/dsl/action.cjs.map +1 -1
  18. package/dist/dsl/action.d.cts +1 -1
  19. package/dist/dsl/action.d.mts +1 -1
  20. package/dist/dsl/action.mjs +1 -1
  21. package/dist/dsl/action.mjs.map +1 -1
  22. package/dist/dsl/bundle.cjs +3 -2
  23. package/dist/dsl/bundle.cjs.map +1 -1
  24. package/dist/dsl/bundle.d.cts +3 -2
  25. package/dist/dsl/bundle.d.cts.map +1 -1
  26. package/dist/dsl/bundle.d.mts +3 -2
  27. package/dist/dsl/bundle.d.mts.map +1 -1
  28. package/dist/dsl/bundle.mjs +3 -2
  29. package/dist/dsl/bundle.mjs.map +1 -1
  30. package/dist/dsl/condition.cjs +1 -1
  31. package/dist/dsl/condition.cjs.map +1 -1
  32. package/dist/dsl/condition.d.cts +1 -1
  33. package/dist/dsl/condition.d.mts +1 -1
  34. package/dist/dsl/condition.mjs +1 -1
  35. package/dist/dsl/condition.mjs.map +1 -1
  36. package/dist/dsl/flow.cjs +45 -17
  37. package/dist/dsl/flow.cjs.map +1 -1
  38. package/dist/dsl/flow.d.cts +30 -17
  39. package/dist/dsl/flow.d.cts.map +1 -1
  40. package/dist/dsl/flow.d.mts +30 -17
  41. package/dist/dsl/flow.d.mts.map +1 -1
  42. package/dist/dsl/flow.mjs +45 -18
  43. package/dist/dsl/flow.mjs.map +1 -1
  44. package/dist/dsl/index.cjs +0 -1
  45. package/dist/dsl/index.d.cts +2 -2
  46. package/dist/dsl/index.d.mts +2 -2
  47. package/dist/dsl/index.mjs +2 -2
  48. package/dist/dsl/template.cjs +2 -47
  49. package/dist/dsl/template.cjs.map +1 -1
  50. package/dist/dsl/template.d.cts +4 -54
  51. package/dist/dsl/template.d.cts.map +1 -1
  52. package/dist/dsl/template.d.mts +4 -54
  53. package/dist/dsl/template.d.mts.map +1 -1
  54. package/dist/dsl/template.mjs +3 -47
  55. package/dist/dsl/template.mjs.map +1 -1
  56. package/dist/dsl/workflow.cjs +1 -1
  57. package/dist/dsl/workflow.cjs.map +1 -1
  58. package/dist/dsl/workflow.d.cts +1 -1
  59. package/dist/dsl/workflow.d.mts +1 -1
  60. package/dist/dsl/workflow.mjs +1 -1
  61. package/dist/dsl/workflow.mjs.map +1 -1
  62. package/dist/index.cjs +5 -2
  63. package/dist/index.d.cts +3 -3
  64. package/dist/index.d.mts +3 -3
  65. package/dist/index.mjs +3 -3
  66. package/dist/push.cjs +3 -5
  67. package/dist/push.cjs.map +1 -1
  68. package/dist/push.d.cts +2 -2
  69. package/dist/push.d.cts.map +1 -1
  70. package/dist/push.d.mts +2 -2
  71. package/dist/push.d.mts.map +1 -1
  72. package/dist/push.mjs +4 -6
  73. package/dist/push.mjs.map +1 -1
  74. package/dist/react-email.cjs +5 -5
  75. package/dist/react-email.cjs.map +1 -1
  76. package/dist/react-email.d.cts +1 -1
  77. package/dist/react-email.d.cts.map +1 -1
  78. package/dist/react-email.d.mts +1 -1
  79. package/dist/react-email.d.mts.map +1 -1
  80. package/dist/react-email.mjs +6 -6
  81. package/dist/react-email.mjs.map +1 -1
  82. package/dist/templates.cjs +84 -29
  83. package/dist/templates.cjs.map +1 -1
  84. package/dist/templates.d.cts +49 -11
  85. package/dist/templates.d.cts.map +1 -1
  86. package/dist/templates.d.mts +49 -11
  87. package/dist/templates.d.mts.map +1 -1
  88. package/dist/templates.mjs +81 -30
  89. package/dist/templates.mjs.map +1 -1
  90. package/package.json +1 -1
package/dist/dsl/flow.mjs CHANGED
@@ -1,16 +1,14 @@
1
1
  import { captureLoc } from "../provenance.mjs";
2
2
  import { durationIR, timeOfDayMinutes } from "./base.mjs";
3
3
  import { condIR } from "./condition.mjs";
4
+ import { CHANNEL_OF, isTemplate } from "../templates.mjs";
4
5
  //#region src/dsl/flow.ts
5
- const PREFER_CHANNELS = /* @__PURE__ */ new Set(["push", "email"]);
6
6
  /** prefer() is typed strictly, but a JS caller (or an `any`) reaches it unchecked — fail at the call, not at send time. */
7
7
  function checkPreferArgs(candidates, props, options) {
8
8
  if (!Array.isArray(candidates) || candidates.length !== 2) throw new TypeError("prefer(): candidates must be exactly two templates — one push, one email");
9
- for (const ref of candidates) {
10
- const { channel, key } = ref ?? {};
11
- if (!PREFER_CHANNELS.has(channel) || typeof key !== "string" || key === "") throw new TypeError("prefer(): each candidate must be a push or email template reference (t.push.<key> / t.email.<key>)");
12
- }
13
- if (candidates[0].channel === candidates[1].channel) throw new TypeError("prefer(): candidates must be one push and one email template");
9
+ const channels = candidates.map((candidate) => isTemplate(candidate) ? CHANNEL_OF[candidate.kind] : void 0);
10
+ if (!channels.every((channel) => channel === "push" || channel === "email")) throw new TypeError("prefer(): each candidate must be a pushTemplate or an emailTemplate");
11
+ if (channels[0] === channels[1]) throw new TypeError("prefer(): candidates must be one push and one email template");
14
12
  if (typeof props !== "object" || props === null || Array.isArray(props)) throw new TypeError("prefer(): props must be an object — pass {} when the templates declare none");
15
13
  if (options === void 0) return;
16
14
  if (typeof options !== "object" || options === null || Array.isArray(options)) throw new TypeError("prefer(): options must be an object");
@@ -19,6 +17,10 @@ function checkPreferArgs(candidates, props, options) {
19
17
  if (typeof value !== "string") throw new TypeError("prefer(): 'label' must be a string");
20
18
  }
21
19
  }
20
+ /** @internal The template definitions a workflow sends, sub-flows and fragments included. */
21
+ function templateUses(builder) {
22
+ return builder instanceof FlowBuilderImpl ? builder.uses : [];
23
+ }
22
24
  /**
23
25
  * A cohort arm name has two jobs, and both constrain its spelling:
24
26
  * - it is interpolated into the node ids of the arm's flow ('{id}.{name}.{j}'),
@@ -31,20 +33,29 @@ function checkPreferArgs(candidates, props, options) {
31
33
  * experiment would prepend itself and re-bucket everyone already in it.
32
34
  */
33
35
  const ARM_NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/;
34
- function resolveSubFlow(sub) {
36
+ /** A sub-flow's nodes; the template definitions it sends are added to `uses`. */
37
+ function resolveSubFlow(sub, uses) {
35
38
  if (typeof sub === "function") {
36
39
  const builder = new FlowBuilderImpl();
37
40
  if (typeof sub(builder)?.then === "function") throw new TypeError("sub-flow callbacks must be synchronous: they run once, while the workflow is defined");
41
+ uses.push(...builder.uses);
38
42
  return builder.nodes;
39
43
  }
44
+ uses.push(...sub.uses);
40
45
  return structuredClone(sub.nodes);
41
46
  }
47
+ const DEFINED_CHANNELS = new Set(Object.values(CHANNEL_OF));
48
+ function templateKey(channel, tpl) {
49
+ if (!DEFINED_CHANNELS.has(channel)) return tpl.key;
50
+ if (!isTemplate(tpl) || CHANNEL_OF[tpl.kind] !== channel) throw new TypeError(`${channel}(): expects a ${channel} template definition`);
51
+ return tpl.id;
52
+ }
42
53
  function messageNode(channel, tpl, props, devices) {
43
54
  return {
44
55
  id: "",
45
56
  type: "message",
46
57
  channel,
47
- template: tpl.key,
58
+ template: templateKey(channel, tpl),
48
59
  props: props ?? {},
49
60
  ...devices !== void 0 ? { devices } : {}
50
61
  };
@@ -53,6 +64,8 @@ function messageNode(channel, tpl, props, devices) {
53
64
  var FlowBuilderImpl = class {
54
65
  /** Nodes as collected; ids are assigned in one pass inside toIR, so '' is a placeholder here. */
55
66
  nodes = [];
67
+ /** The template definitions sent, with where: compile-time only, never in the IR. */
68
+ uses = [];
56
69
  /** Provenance: the callsite (captured in the public method) lands in meta.loc, outside the hash. */
57
70
  pushNode(node, loc) {
58
71
  this.nodes.push({
@@ -62,7 +75,12 @@ var FlowBuilderImpl = class {
62
75
  return this;
63
76
  }
64
77
  message(channel, tpl, props, loc, devices) {
65
- return this.pushNode(messageNode(channel, tpl, props, devices), loc);
78
+ this.pushNode(messageNode(channel, tpl, props, devices), loc);
79
+ if (isTemplate(tpl)) this.uses.push({
80
+ template: tpl,
81
+ loc
82
+ });
83
+ return this;
66
84
  }
67
85
  email(t, ...args) {
68
86
  return this.message("email", t, args[0], captureLoc(this.email));
@@ -92,8 +110,16 @@ var FlowBuilderImpl = class {
92
110
  const loc = captureLoc(this.prefer);
93
111
  const meta = loc !== void 0 ? { meta: { loc } } : {};
94
112
  const [first, second] = candidates;
113
+ const channel = (tpl) => CHANNEL_OF[tpl.kind];
114
+ this.uses.push({
115
+ template: first,
116
+ loc
117
+ }, {
118
+ template: second,
119
+ loc
120
+ });
95
121
  const arm = (tpl) => [{
96
- ...messageNode(tpl.channel, tpl, { ...props }),
122
+ ...messageNode(channel(tpl), tpl, { ...props }),
97
123
  ...meta
98
124
  }];
99
125
  return this.pushNode({
@@ -103,7 +129,7 @@ var FlowBuilderImpl = class {
103
129
  cases: [{
104
130
  condition: {
105
131
  type: "reachable",
106
- channel: first.channel,
132
+ channel: channel(first),
107
133
  ...meta
108
134
  },
109
135
  flow: arm(first)
@@ -156,11 +182,11 @@ var FlowBuilderImpl = class {
156
182
  type: "wait_until",
157
183
  condition: condIR(condition),
158
184
  timeout: durationIR(opts.timeout),
159
- onTimeout: onTimeout === "continue" || onTimeout === "exit" ? onTimeout : resolveSubFlow(onTimeout)
185
+ onTimeout: onTimeout === "continue" || onTimeout === "exit" ? onTimeout : resolveSubFlow(onTimeout, this.uses)
160
186
  }, loc);
161
187
  }
162
188
  use(fragment) {
163
- this.nodes.push(...resolveSubFlow(fragment));
189
+ this.nodes.push(...resolveSubFlow(fragment, this.uses));
164
190
  return this;
165
191
  }
166
192
  branch(...args) {
@@ -175,12 +201,12 @@ var FlowBuilderImpl = class {
175
201
  const [condition, sub] = arm;
176
202
  cases.push({
177
203
  condition: condIR(condition),
178
- flow: resolveSubFlow(sub)
204
+ flow: resolveSubFlow(sub, this.uses)
179
205
  });
180
206
  } else {
181
207
  if (otherwise !== void 0) throw new Error("branch(): only one default arm (bare sub-flow) is allowed");
182
208
  if (i !== arms.length - 1) throw new Error("branch(): default arm (bare sub-flow) must be the last argument");
183
- otherwise = resolveSubFlow(arm);
209
+ otherwise = resolveSubFlow(arm, this.uses);
184
210
  }
185
211
  });
186
212
  return this.pushNode({
@@ -217,7 +243,7 @@ var FlowBuilderImpl = class {
217
243
  arms: entries.map(([name, a]) => ({
218
244
  name,
219
245
  weight: a.weight,
220
- flow: a.flow ? resolveSubFlow(a.flow) : []
246
+ flow: a.flow ? resolveSubFlow(a.flow, this.uses) : []
221
247
  }))
222
248
  }, loc);
223
249
  }
@@ -261,10 +287,11 @@ function flow(build) {
261
287
  build(builder);
262
288
  return {
263
289
  __flow: true,
264
- nodes: builder.nodes
290
+ nodes: builder.nodes,
291
+ uses: builder.uses
265
292
  };
266
293
  }
267
294
  //#endregion
268
- export { FlowBuilderImpl, flow };
295
+ export { FlowBuilderImpl, flow, templateUses };
269
296
 
270
297
  //# sourceMappingURL=flow.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"flow.mjs","names":[],"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,U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AA6B,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,GACA,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,GACA,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.mjs","names":[],"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,cAC9C,WAAW,SAAS,IAAI,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,6BAA6B,KAAK,+DACpC;EAEF,IAAI,OAAO,UAAU,UAAU,MAAM,IAAI,UAAU,oCAAoC;CACzF;AACF;;AAuBA,SAAgB,aAAa,SAA8C;CACzE,OAAO,mBAAmB,kBAAkB,QAAQ,OAAO,CAAC;AAC9D;;;;;;;;;;;;AAyBA,MAAM,WA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CAAC;EAAG,GACpE,WAAW,KAAK,IAAI,CACtB;CACF;CAEA,UAA4B,IAAiB,GAAG,SAA4B;EAC1E,MAAM,SAAU,QAAQ,MAAM,CAAC;EAC/B,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,GACA,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,GACA,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;EAAO,MAAM,QAAQ;CACrE;AACZ"}
@@ -32,7 +32,6 @@ exports.performed = require_dsl_condition.performed;
32
32
  exports.reachable = require_dsl_condition.reachable;
33
33
  exports.segment = require_dsl_condition.segment;
34
34
  exports.template = require_dsl_template.template;
35
- exports.templates = require_dsl_template.templates;
36
35
  exports.trigger = require_dsl_trigger.trigger;
37
36
  exports.user = require_dsl_refs.user;
38
37
  exports.workflow = require_dsl_workflow.workflow;
@@ -1,10 +1,10 @@
1
1
  import { ActionContext, ActionHandler, ActionRef, action } from "./action.cjs";
2
2
  import { Duration, EventMap, TimeOfDay, UserPropertyBase, Weekday } from "./base.cjs";
3
3
  import { EventRef, EventRefs, MessageArgs, PayloadRef, PayloadRefNode, PayloadRefs, PropInput, PropsInput, UserPropertyRef, UserRefs, event, user } from "./refs.cjs";
4
- import { Channel, EmptyProps, PropsOf, TemplateFactory, TemplateRef, TemplateRefTable, TemplateRefs, TemplateRegistry, template, templates } from "./template.cjs";
4
+ import { Channel, EmptyProps, PropsOf, TemplateFactory, TemplateRef, template } from "./template.cjs";
5
5
  import { Condition, PayloadWhere, PerformedOptions, SegmentDefinition, SegmentRef, and, between, contains, eq, exists, gt, gte, inArray, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, performed, reachable, segment } from "./condition.cjs";
6
6
  import { BranchArm, BranchCase, EmitArgs, EmitPayload, Flow, FlowBuilder, PreferOptions, PushOptions, SubFlow, flow } from "./flow.cjs";
7
7
  import { DateTime, EventTriggerOptions, TriggerFactory, TriggerRef, trigger } from "./trigger.cjs";
8
8
  import { GoalOptions, WorkflowBuilder, WorkflowDefinition, workflow } from "./workflow.cjs";
9
9
  import { compileBundle } from "./bundle.cjs";
10
- export { type ActionContext, type ActionHandler, type ActionRef, type BranchArm, type BranchCase, type Channel, type Condition, type DateTime, type Duration, type EmitArgs, type EmitPayload, type EmptyProps, type EventMap, type EventRef, type EventRefs, type EventTriggerOptions, type Flow, type FlowBuilder, type GoalOptions, type MessageArgs, type PayloadRef, type PayloadRefNode, type PayloadRefs, type PayloadWhere, type PerformedOptions, type PreferOptions, type PropInput, type PropsInput, type PropsOf, type PushOptions, type SegmentDefinition, type SegmentRef, type SubFlow, type TemplateFactory, type TemplateRef, type TemplateRefTable, type TemplateRefs, type TemplateRegistry, type TimeOfDay, type TriggerFactory, type TriggerRef, type UserPropertyBase, type UserPropertyRef, type UserRefs, type Weekday, type WorkflowBuilder, type WorkflowDefinition, action, and, between, compileBundle, contains, eq, event, exists, flow, gt, gte, inArray, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, performed, reachable, segment, template, templates, trigger, user, workflow };
10
+ export { type ActionContext, type ActionHandler, type ActionRef, type BranchArm, type BranchCase, type Channel, type Condition, type DateTime, type Duration, type EmitArgs, type EmitPayload, type EmptyProps, type EventMap, type EventRef, type EventRefs, type EventTriggerOptions, type Flow, type FlowBuilder, type GoalOptions, type MessageArgs, type PayloadRef, type PayloadRefNode, type PayloadRefs, type PayloadWhere, type PerformedOptions, type PreferOptions, type PropInput, type PropsInput, type PropsOf, type PushOptions, type SegmentDefinition, type SegmentRef, type SubFlow, type TemplateFactory, type TemplateRef, type TimeOfDay, type TriggerFactory, type TriggerRef, type UserPropertyBase, type UserPropertyRef, type UserRefs, type Weekday, type WorkflowBuilder, type WorkflowDefinition, action, and, between, compileBundle, contains, eq, event, exists, flow, gt, gte, inArray, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, performed, reachable, segment, template, trigger, user, workflow };
@@ -1,10 +1,10 @@
1
1
  import { ActionContext, ActionHandler, ActionRef, action } from "./action.mjs";
2
2
  import { Duration, EventMap, TimeOfDay, UserPropertyBase, Weekday } from "./base.mjs";
3
3
  import { EventRef, EventRefs, MessageArgs, PayloadRef, PayloadRefNode, PayloadRefs, PropInput, PropsInput, UserPropertyRef, UserRefs, event, user } from "./refs.mjs";
4
- import { Channel, EmptyProps, PropsOf, TemplateFactory, TemplateRef, TemplateRefTable, TemplateRefs, TemplateRegistry, template, templates } from "./template.mjs";
4
+ import { Channel, EmptyProps, PropsOf, TemplateFactory, TemplateRef, template } from "./template.mjs";
5
5
  import { Condition, PayloadWhere, PerformedOptions, SegmentDefinition, SegmentRef, and, between, contains, eq, exists, gt, gte, inArray, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, performed, reachable, segment } from "./condition.mjs";
6
6
  import { BranchArm, BranchCase, EmitArgs, EmitPayload, Flow, FlowBuilder, PreferOptions, PushOptions, SubFlow, flow } from "./flow.mjs";
7
7
  import { DateTime, EventTriggerOptions, TriggerFactory, TriggerRef, trigger } from "./trigger.mjs";
8
8
  import { GoalOptions, WorkflowBuilder, WorkflowDefinition, workflow } from "./workflow.mjs";
9
9
  import { compileBundle } from "./bundle.mjs";
10
- export { type ActionContext, type ActionHandler, type ActionRef, type BranchArm, type BranchCase, type Channel, type Condition, type DateTime, type Duration, type EmitArgs, type EmitPayload, type EmptyProps, type EventMap, type EventRef, type EventRefs, type EventTriggerOptions, type Flow, type FlowBuilder, type GoalOptions, type MessageArgs, type PayloadRef, type PayloadRefNode, type PayloadRefs, type PayloadWhere, type PerformedOptions, type PreferOptions, type PropInput, type PropsInput, type PropsOf, type PushOptions, type SegmentDefinition, type SegmentRef, type SubFlow, type TemplateFactory, type TemplateRef, type TemplateRefTable, type TemplateRefs, type TemplateRegistry, type TimeOfDay, type TriggerFactory, type TriggerRef, type UserPropertyBase, type UserPropertyRef, type UserRefs, type Weekday, type WorkflowBuilder, type WorkflowDefinition, action, and, between, compileBundle, contains, eq, event, exists, flow, gt, gte, inArray, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, performed, reachable, segment, template, templates, trigger, user, workflow };
10
+ export { type ActionContext, type ActionHandler, type ActionRef, type BranchArm, type BranchCase, type Channel, type Condition, type DateTime, type Duration, type EmitArgs, type EmitPayload, type EmptyProps, type EventMap, type EventRef, type EventRefs, type EventTriggerOptions, type Flow, type FlowBuilder, type GoalOptions, type MessageArgs, type PayloadRef, type PayloadRefNode, type PayloadRefs, type PayloadWhere, type PerformedOptions, type PreferOptions, type PropInput, type PropsInput, type PropsOf, type PushOptions, type SegmentDefinition, type SegmentRef, type SubFlow, type TemplateFactory, type TemplateRef, type TimeOfDay, type TriggerFactory, type TriggerRef, type UserPropertyBase, type UserPropertyRef, type UserRefs, type Weekday, type WorkflowBuilder, type WorkflowDefinition, action, and, between, compileBundle, contains, eq, event, exists, flow, gt, gte, inArray, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, performed, reachable, segment, template, trigger, user, workflow };
@@ -1,9 +1,9 @@
1
1
  import { action } from "./action.mjs";
2
2
  import { event, user } from "./refs.mjs";
3
- import { template, templates } from "./template.mjs";
3
+ import { template } from "./template.mjs";
4
4
  import { and, between, contains, eq, exists, gt, gte, inArray, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, performed, reachable, segment } from "./condition.mjs";
5
5
  import { flow } from "./flow.mjs";
6
6
  import { trigger } from "./trigger.mjs";
7
7
  import { workflow } from "./workflow.mjs";
8
8
  import { compileBundle } from "./bundle.mjs";
9
- export { action, and, between, compileBundle, contains, eq, event, exists, flow, gt, gte, inArray, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, performed, reachable, segment, template, templates, trigger, user, workflow };
9
+ export { action, and, between, compileBundle, contains, eq, event, exists, flow, gt, gte, inArray, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, performed, reachable, segment, template, trigger, user, workflow };
@@ -1,65 +1,20 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_templates = require("../templates.cjs");
3
2
  //#region src/dsl/template.ts
4
3
  const makeTemplate = (channel) => (key) => ({
5
4
  channel,
6
5
  key
7
6
  });
8
7
  /**
9
- * Unbound template references, props typed by hand. Email and push refs come
10
- * from the registries (`templates<Emails, Pushes>()`), which type both key and
11
- * props; this is the low-level form for channels without a registry (sms,
12
- * slack, …) and for tests.
8
+ * Template references for the channels an app-supplied sender renders:
13
9
  *
14
- * const alert = template.slack<{ plan: string }>('cs_churn_alert');
10
+ * const code = template.sms<{ code: string }>('login_code');
15
11
  */
16
12
  const template = {
17
- email: makeTemplate("email"),
18
13
  sms: makeTemplate("sms"),
19
- push: makeTemplate("push"),
20
14
  inApp: makeTemplate("in_app"),
21
- slack: makeTemplate("slack"),
22
- discord: makeTemplate("discord"),
23
15
  survey: makeTemplate("survey")
24
16
  };
25
- /**
26
- * Template references derived from the registries themselves: **the
27
- * registries type the keys** — an unregistered key fails to compile, and a
28
- * push template is not accepted where an email is — and each template's
29
- * `props` schema types its use sites. Templates are registered once; the
30
- * config takes the registries, the workflows take the references:
31
- *
32
- * export const registry = { email, push };
33
- * export const t = templates(registry);
34
- * flow.email(t.email.welcome, { name: u.name });
35
- *
36
- * Each reference is a plain `{ channel, key }` built from the registry's own
37
- * keys; no template is rendered, and the registries are left untouched.
38
- */
39
- function templates(registry) {
40
- return {
41
- email: refTable("email", registry.email, require_templates.isEmailTemplate),
42
- push: refTable("push", registry.push, require_templates.isPushTemplate),
43
- discord: refTable("discord", registry.discord, require_templates.isDiscordTemplate),
44
- slack: refTable("slack", registry.slack, require_templates.isSlackTemplate)
45
- };
46
- }
47
- const ARTICLE = {
48
- email: "an email",
49
- push: "a push",
50
- discord: "a Discord",
51
- slack: "a Slack"
52
- };
53
- function refTable(channel, entries, is) {
54
- const table = Object.create(null);
55
- for (const [key, entry] of Object.entries(entries ?? {})) {
56
- if (!is(entry)) throw new TypeError(`templates(): '${key}' in the ${channel} registry is not ${ARTICLE[channel]} template`);
57
- table[key] = template[channel](key);
58
- }
59
- return Object.freeze(table);
60
- }
61
17
  //#endregion
62
18
  exports.template = template;
63
- exports.templates = templates;
64
19
 
65
20
  //# sourceMappingURL=template.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"template.cjs","names":["isEmailTemplate","isPushTemplate","isDiscordTemplate","isSlackTemplate"],"sources":["../../src/dsl/template.ts"],"sourcesContent":["/**\n * Templates — named message-content assets. The DSL only ever holds a\n * reference ({ channel, key, phantom props }); the content itself (react-email\n * components) lives in the app and meets the reference again in the studio and\n * at send time via the registry.\n *\n * Type technique: `templates(registry)` derives the references from the\n * registries so **the registries type the keys** — an unregistered key fails\n * to compile — while `PropsOf<M>` reads the props contract off each template's\n * Zod schema, so it is written exactly once.\n */\n\nimport type * as core from 'zod/v4/core';\nimport {\n type DiscordTemplate,\n type EmailTemplate,\n type PropsSchema,\n type PushTemplate,\n type SlackTemplate,\n isDiscordTemplate,\n isEmailTemplate,\n isPushTemplate,\n isSlackTemplate,\n} from '../templates';\n\nexport type Channel = 'email' | 'sms' | 'push' | 'in_app' | 'slack' | 'discord' | 'survey';\n\nexport type EmptyProps = Record<never, never>;\n\n/**\n * Template reference: a top-level named asset, reusable across workflows and\n * versioned on its own. The props shape is declared here and checked at use.\n */\nexport interface TemplateRef<C extends Channel = Channel, P extends object = EmptyProps> {\n readonly channel: C;\n readonly key: string;\n readonly __props?: P;\n}\n\nexport interface TemplateFactory {\n email<P extends object = EmptyProps>(key: string): TemplateRef<'email', P>;\n sms<P extends object = EmptyProps>(key: string): TemplateRef<'sms', P>;\n push<P extends object = EmptyProps>(key: string): TemplateRef<'push', P>;\n inApp<P extends object = EmptyProps>(key: string): TemplateRef<'in_app', P>;\n slack<P extends object = EmptyProps>(key: string): TemplateRef<'slack', P>;\n discord<P extends object = EmptyProps>(key: string): TemplateRef<'discord', P>;\n survey<P extends object = EmptyProps>(key: string): TemplateRef<'survey', P>;\n}\n\nconst makeTemplate =\n <C extends Channel>(channel: C) =>\n <P extends object = EmptyProps>(key: string): TemplateRef<C, P> => ({ channel, key });\n\n/**\n * Unbound template references, props typed by hand. Email and push refs come\n * from the registries (`templates<Emails, Pushes>()`), which type both key and\n * props; this is the low-level form for channels without a registry (sms,\n * slack, …) and for tests.\n *\n * const alert = template.slack<{ plan: string }>('cs_churn_alert');\n */\nexport const template: TemplateFactory = {\n email: makeTemplate('email'),\n sms: makeTemplate('sms'),\n push: makeTemplate('push'),\n inApp: makeTemplate('in_app'),\n slack: makeTemplate('slack'),\n discord: makeTemplate('discord'),\n survey: makeTemplate('survey'),\n};\n\n/* ----------------------------- Template registry ---------------------------- */\n\n/** Template props: the input type of the template's Zod `props` schema — what the DSL passes. */\nexport type PropsOf<M> = M extends\n | EmailTemplate<infer S>\n | PushTemplate<infer S>\n | DiscordTemplate<infer S, never>\n | SlackTemplate<infer S, never>\n ? core.input<S> extends object\n ? core.input<S>\n : EmptyProps\n : never;\n\n/**\n * The channel registries: what the config registers as `templates` and what\n * `templates()` derives the references from — one type for both. Leave it\n * inferred, or check it with `satisfies TemplateRegistry`: annotating a value\n * as the bare type widens the keys to `string`.\n */\nexport interface TemplateRegistry<\n E extends Readonly<Record<string, EmailTemplate>> = Readonly<Record<string, EmailTemplate>>,\n P extends Readonly<Record<string, PushTemplate>> = Readonly<Record<string, PushTemplate>>,\n> {\n readonly email?: E;\n readonly push?: P;\n /** Discord webhook templates, each typed by the host's Env its `webhook` reads. */\n readonly discord?: Readonly<Record<string, DiscordTemplate<PropsSchema, never>>>;\n readonly slack?: Readonly<Record<string, SlackTemplate<PropsSchema, never>>>;\n}\n\n/** One channel's registry in `R`, without the `undefined` of an optional field; `never` when absent. */\ntype ChannelRegistry<R, K extends 'email' | 'push' | 'discord' | 'slack'> = K extends keyof R\n ? Exclude<R[K], undefined>\n : never;\n\n/** One reference per registered key, each typed by its own template's `props`. */\nexport type TemplateRefTable<C extends Channel, R> = {\n readonly [K in keyof R & string]: TemplateRef<C, PropsOf<R[K]>>;\n};\n\n/** `t.email.<key>` / `t.push.<key>`; a channel the registry leaves out is an empty table. */\nexport interface TemplateRefs<R extends TemplateRegistry> {\n readonly email: [ChannelRegistry<R, 'email'>] extends [never]\n ? EmptyProps\n : TemplateRefTable<'email', ChannelRegistry<R, 'email'>>;\n readonly push: [ChannelRegistry<R, 'push'>] extends [never]\n ? EmptyProps\n : TemplateRefTable<'push', ChannelRegistry<R, 'push'>>;\n readonly discord: [ChannelRegistry<R, 'discord'>] extends [never]\n ? EmptyProps\n : TemplateRefTable<'discord', ChannelRegistry<R, 'discord'>>;\n readonly slack: [ChannelRegistry<R, 'slack'>] extends [never]\n ? EmptyProps\n : TemplateRefTable<'slack', ChannelRegistry<R, 'slack'>>;\n}\n\n/**\n * Template references derived from the registries themselves: **the\n * registries type the keys** — an unregistered key fails to compile, and a\n * push template is not accepted where an email is — and each template's\n * `props` schema types its use sites. Templates are registered once; the\n * config takes the registries, the workflows take the references:\n *\n * export const registry = { email, push };\n * export const t = templates(registry);\n * flow.email(t.email.welcome, { name: u.name });\n *\n * Each reference is a plain `{ channel, key }` built from the registry's own\n * keys; no template is rendered, and the registries are left untouched.\n */\nexport function templates<const R extends TemplateRegistry>(registry: R): TemplateRefs<R> {\n return {\n email: refTable('email', registry.email, isEmailTemplate),\n push: refTable('push', registry.push, isPushTemplate),\n discord: refTable('discord', registry.discord, isDiscordTemplate),\n slack: refTable('slack', registry.slack, isSlackTemplate),\n } as unknown as TemplateRefs<R>;\n}\n\nconst ARTICLE: Record<'email' | 'push' | 'discord' | 'slack', string> = {\n email: 'an email',\n push: 'a push',\n discord: 'a Discord',\n slack: 'a Slack',\n};\n\nfunction refTable(\n channel: 'email' | 'push' | 'discord' | 'slack',\n entries: Readonly<Record<string, unknown>> | undefined,\n is: (value: unknown) => boolean\n): Readonly<Record<string, TemplateRef>> {\n const table: Record<string, TemplateRef> = Object.create(null);\n for (const [key, entry] of Object.entries(entries ?? {})) {\n if (!is(entry)) {\n throw new TypeError(\n `templates(): '${key}' in the ${channel} registry is not ${ARTICLE[channel]} template`\n );\n }\n table[key] = template[channel](key);\n }\n return Object.freeze(table);\n}\n"],"mappings":";;;AAiDA,MAAM,gBACgB,aACY,SAAoC;CAAE;CAAS;AAAI;;;;;;;;;AAUrF,MAAa,WAA4B;CACvC,OAAO,aAAa,OAAO;CAC3B,KAAK,aAAa,KAAK;CACvB,MAAM,aAAa,MAAM;CACzB,OAAO,aAAa,QAAQ;CAC5B,OAAO,aAAa,OAAO;CAC3B,SAAS,aAAa,SAAS;CAC/B,QAAQ,aAAa,QAAQ;AAC/B;;;;;;;;;;;;;;;AAwEA,SAAgB,UAA4C,UAA8B;CACxF,OAAO;EACL,OAAO,SAAS,SAAS,SAAS,OAAOA,kBAAAA,eAAe;EACxD,MAAM,SAAS,QAAQ,SAAS,MAAMC,kBAAAA,cAAc;EACpD,SAAS,SAAS,WAAW,SAAS,SAASC,kBAAAA,iBAAiB;EAChE,OAAO,SAAS,SAAS,SAAS,OAAOC,kBAAAA,eAAe;CAC1D;AACF;AAEA,MAAM,UAAkE;CACtE,OAAO;CACP,MAAM;CACN,SAAS;CACT,OAAO;AACT;AAEA,SAAS,SACP,SACA,SACA,IACuC;CACvC,MAAM,QAAqC,OAAO,OAAO,IAAI;CAC7D,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,WAAW,CAAC,CAAC,GAAG;EACxD,IAAI,CAAC,GAAG,KAAK,GACX,MAAM,IAAI,UACR,iBAAiB,IAAI,WAAW,QAAQ,mBAAmB,QAAQ,SAAS,UAC9E;EAEF,MAAM,OAAO,SAAS,QAAQ,CAAC,GAAG;CACpC;CACA,OAAO,OAAO,OAAO,KAAK;AAC5B"}
1
+ {"version":3,"file":"template.cjs","names":[],"sources":["../../src/dsl/template.ts"],"sourcesContent":["/**\n * Templates in the DSL. The four channels with template definitions (email, push, discord,\n * slack) take the definition itself — `.email(welcome, props)` — so its Zod `props` schema types\n * the call (`PropsOf`) and its `id` lands in the IR. The channels rendered by app-supplied\n * senders (sms, in-app, survey) have no definition; they take a hand-typed reference by key.\n */\n\nimport type * as core from 'zod/v4/core';\nimport type { DiscordTemplate, EmailTemplate, PushTemplate, SlackTemplate } from '../templates';\n\nexport type Channel = 'email' | 'sms' | 'push' | 'in_app' | 'slack' | 'discord' | 'survey';\n\nexport type EmptyProps = Record<never, never>;\n\n/** A template by key, its props typed by hand: for the channels without template definitions. */\nexport interface TemplateRef<C extends Channel = Channel, P extends object = EmptyProps> {\n readonly channel: C;\n readonly key: string;\n readonly __props?: P;\n}\n\nexport interface TemplateFactory {\n sms<P extends object = EmptyProps>(key: string): TemplateRef<'sms', P>;\n inApp<P extends object = EmptyProps>(key: string): TemplateRef<'in_app', P>;\n survey<P extends object = EmptyProps>(key: string): TemplateRef<'survey', P>;\n}\n\nconst makeTemplate =\n <C extends Channel>(channel: C) =>\n <P extends object = EmptyProps>(key: string): TemplateRef<C, P> => ({ channel, key });\n\n/**\n * Template references for the channels an app-supplied sender renders:\n *\n * const code = template.sms<{ code: string }>('login_code');\n */\nexport const template: TemplateFactory = {\n sms: makeTemplate('sms'),\n inApp: makeTemplate('in_app'),\n survey: makeTemplate('survey'),\n};\n\n/** Template props: the input type of the template's Zod `props` schema — what the DSL passes. */\nexport type PropsOf<M> = M extends\n | EmailTemplate<infer S>\n | PushTemplate<infer S>\n | DiscordTemplate<infer S, never>\n | SlackTemplate<infer S, never>\n ? core.input<S> extends object\n ? core.input<S>\n : EmptyProps\n : never;\n"],"mappings":";;AA2BA,MAAM,gBACgB,aACY,SAAoC;CAAE;CAAS;AAAI;;;;;;AAOrF,MAAa,WAA4B;CACvC,KAAK,aAAa,KAAK;CACvB,OAAO,aAAa,QAAQ;CAC5B,QAAQ,aAAa,QAAQ;AAC/B"}
@@ -1,76 +1,26 @@
1
- import { DiscordTemplate, EmailTemplate, PropsSchema, PushTemplate, SlackTemplate } from "../templates.cjs";
1
+ import { DiscordTemplate, EmailTemplate, PushTemplate, SlackTemplate } from "../templates.cjs";
2
2
  import * as core from "zod/v4/core";
3
3
  //#region src/dsl/template.d.ts
4
4
  export type Channel = 'email' | 'sms' | 'push' | 'in_app' | 'slack' | 'discord' | 'survey';
5
5
  export type EmptyProps = Record<never, never>;
6
- /**
7
- * Template reference: a top-level named asset, reusable across workflows and
8
- * versioned on its own. The props shape is declared here and checked at use.
9
- */
6
+ /** A template by key, its props typed by hand: for the channels without template definitions. */
10
7
  export interface TemplateRef<C extends Channel = Channel, P extends object = EmptyProps> {
11
8
  readonly channel: C;
12
9
  readonly key: string;
13
10
  readonly __props?: P;
14
11
  }
15
12
  export interface TemplateFactory {
16
- email<P extends object = EmptyProps>(key: string): TemplateRef<'email', P>;
17
13
  sms<P extends object = EmptyProps>(key: string): TemplateRef<'sms', P>;
18
- push<P extends object = EmptyProps>(key: string): TemplateRef<'push', P>;
19
14
  inApp<P extends object = EmptyProps>(key: string): TemplateRef<'in_app', P>;
20
- slack<P extends object = EmptyProps>(key: string): TemplateRef<'slack', P>;
21
- discord<P extends object = EmptyProps>(key: string): TemplateRef<'discord', P>;
22
15
  survey<P extends object = EmptyProps>(key: string): TemplateRef<'survey', P>;
23
16
  }
24
17
  /**
25
- * Unbound template references, props typed by hand. Email and push refs come
26
- * from the registries (`templates<Emails, Pushes>()`), which type both key and
27
- * props; this is the low-level form for channels without a registry (sms,
28
- * slack, …) and for tests.
18
+ * Template references for the channels an app-supplied sender renders:
29
19
  *
30
- * const alert = template.slack<{ plan: string }>('cs_churn_alert');
20
+ * const code = template.sms<{ code: string }>('login_code');
31
21
  */
32
22
  export declare const template: TemplateFactory;
33
23
  /** Template props: the input type of the template's Zod `props` schema — what the DSL passes. */
34
24
  export type PropsOf<M> = M extends EmailTemplate<infer S> | PushTemplate<infer S> | DiscordTemplate<infer S, never> | SlackTemplate<infer S, never> ? core.input<S> extends object ? core.input<S> : EmptyProps : never;
35
- /**
36
- * The channel registries: what the config registers as `templates` and what
37
- * `templates()` derives the references from — one type for both. Leave it
38
- * inferred, or check it with `satisfies TemplateRegistry`: annotating a value
39
- * as the bare type widens the keys to `string`.
40
- */
41
- export interface TemplateRegistry<E extends Readonly<Record<string, EmailTemplate>> = Readonly<Record<string, EmailTemplate>>, P extends Readonly<Record<string, PushTemplate>> = Readonly<Record<string, PushTemplate>>> {
42
- readonly email?: E;
43
- readonly push?: P;
44
- /** Discord webhook templates, each typed by the host's Env its `webhook` reads. */
45
- readonly discord?: Readonly<Record<string, DiscordTemplate<PropsSchema, never>>>;
46
- readonly slack?: Readonly<Record<string, SlackTemplate<PropsSchema, never>>>;
47
- }
48
- /** One channel's registry in `R`, without the `undefined` of an optional field; `never` when absent. */
49
- type ChannelRegistry<R, K extends 'email' | 'push' | 'discord' | 'slack'> = K extends keyof R ? Exclude<R[K], undefined> : never;
50
- /** One reference per registered key, each typed by its own template's `props`. */
51
- export type TemplateRefTable<C extends Channel, R> = { readonly [K in keyof R & string]: TemplateRef<C, PropsOf<R[K]>>; };
52
- /** `t.email.<key>` / `t.push.<key>`; a channel the registry leaves out is an empty table. */
53
- export interface TemplateRefs<R extends TemplateRegistry> {
54
- readonly email: [ChannelRegistry<R, 'email'>] extends [never] ? EmptyProps : TemplateRefTable<'email', ChannelRegistry<R, 'email'>>;
55
- readonly push: [ChannelRegistry<R, 'push'>] extends [never] ? EmptyProps : TemplateRefTable<'push', ChannelRegistry<R, 'push'>>;
56
- readonly discord: [ChannelRegistry<R, 'discord'>] extends [never] ? EmptyProps : TemplateRefTable<'discord', ChannelRegistry<R, 'discord'>>;
57
- readonly slack: [ChannelRegistry<R, 'slack'>] extends [never] ? EmptyProps : TemplateRefTable<'slack', ChannelRegistry<R, 'slack'>>;
58
- }
59
- /**
60
- * Template references derived from the registries themselves: **the
61
- * registries type the keys** — an unregistered key fails to compile, and a
62
- * push template is not accepted where an email is — and each template's
63
- * `props` schema types its use sites. Templates are registered once; the
64
- * config takes the registries, the workflows take the references:
65
- *
66
- * export const registry = { email, push };
67
- * export const t = templates(registry);
68
- * flow.email(t.email.welcome, { name: u.name });
69
- *
70
- * Each reference is a plain `{ channel, key }` built from the registry's own
71
- * keys; no template is rendered, and the registries are left untouched.
72
- */
73
- export declare function templates<const R extends TemplateRegistry>(registry: R): TemplateRefs<R>;
74
25
  //#endregion
75
- export {};
76
26
  //# sourceMappingURL=template.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"template.d.cts","names":[],"sources":["../../src/dsl/template.ts"],"mappings":";;;YAyBY;YAEA,aAAa;;;;;iBAMR,YAAY,UAAU,UAAU,SAAS,mBAAmB;WAClE,SAAS;WACT;WACA,UAAU;;iBAGJ;EACf,MAAM,mBAAmB,YAAY,cAAc,qBAAqB;EACxE,IAAI,mBAAmB,YAAY,cAAc,mBAAmB;EACpE,KAAK,mBAAmB,YAAY,cAAc,oBAAoB;EACtE,MAAM,mBAAmB,YAAY,cAAc,sBAAsB;EACzE,MAAM,mBAAmB,YAAY,cAAc,qBAAqB;EACxE,QAAQ,mBAAmB,YAAY,cAAc,uBAAuB;EAC5E,OAAO,mBAAmB,YAAY,cAAc,sBAAsB;;;;;;;;;;qBAe/D,UAAU;;YAaX,QAAQ,KAAK,UACrB,oBAAoB,KACpB,mBAAmB,KACnB,sBAAs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