@shware/workflow 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +688 -10
- package/dist/cloudflare/bindings.cjs.map +1 -1
- package/dist/cloudflare/bindings.d.cts +11 -0
- package/dist/cloudflare/bindings.d.cts.map +1 -1
- package/dist/cloudflare/bindings.d.mts +11 -0
- package/dist/cloudflare/bindings.d.mts.map +1 -1
- package/dist/cloudflare/bindings.mjs.map +1 -1
- package/dist/cloudflare/index.cjs +1 -0
- package/dist/cloudflare/index.d.cts +3 -3
- package/dist/cloudflare/index.d.mts +3 -3
- package/dist/cloudflare/index.mjs +2 -2
- package/dist/cloudflare/router.cjs +21 -4
- package/dist/cloudflare/router.cjs.map +1 -1
- package/dist/cloudflare/router.d.cts +18 -3
- package/dist/cloudflare/router.d.cts.map +1 -1
- package/dist/cloudflare/router.d.mts +18 -3
- package/dist/cloudflare/router.d.mts.map +1 -1
- package/dist/cloudflare/router.mjs +21 -5
- package/dist/cloudflare/router.mjs.map +1 -1
- package/dist/cloudflare/worker.cjs +37 -1
- package/dist/cloudflare/worker.cjs.map +1 -1
- package/dist/cloudflare/worker.d.cts.map +1 -1
- package/dist/cloudflare/worker.d.mts.map +1 -1
- package/dist/cloudflare/worker.mjs +37 -1
- package/dist/cloudflare/worker.mjs.map +1 -1
- package/dist/dsl/condition.cjs +2 -0
- package/dist/dsl/condition.cjs.map +1 -1
- package/dist/dsl/condition.d.cts +2 -0
- package/dist/dsl/condition.d.cts.map +1 -1
- package/dist/dsl/condition.d.mts +2 -0
- package/dist/dsl/condition.d.mts.map +1 -1
- package/dist/dsl/condition.mjs +2 -0
- package/dist/dsl/condition.mjs.map +1 -1
- package/dist/dsl/flow.cjs +52 -8
- package/dist/dsl/flow.cjs.map +1 -1
- package/dist/dsl/flow.d.cts +39 -5
- package/dist/dsl/flow.d.cts.map +1 -1
- package/dist/dsl/flow.d.mts +39 -5
- package/dist/dsl/flow.d.mts.map +1 -1
- package/dist/dsl/flow.mjs +52 -8
- package/dist/dsl/flow.mjs.map +1 -1
- package/dist/dsl/index.d.cts +2 -2
- package/dist/dsl/index.d.mts +2 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/store/index.cjs.map +1 -1
- package/dist/store/index.d.cts +21 -0
- package/dist/store/index.d.cts.map +1 -1
- package/dist/store/index.d.mts +21 -0
- package/dist/store/index.d.mts.map +1 -1
- package/dist/store/index.mjs.map +1 -1
- package/dist/store/postgres.cjs +45 -20
- package/dist/store/postgres.cjs.map +1 -1
- package/dist/store/postgres.d.cts +4 -1
- package/dist/store/postgres.d.cts.map +1 -1
- package/dist/store/postgres.d.mts +4 -1
- package/dist/store/postgres.d.mts.map +1 -1
- package/dist/store/postgres.mjs +45 -20
- package/dist/store/postgres.mjs.map +1 -1
- package/dist/store/tables.cjs +11 -0
- package/dist/store/tables.cjs.map +1 -1
- package/dist/store/tables.d.cts +1 -0
- package/dist/store/tables.d.cts.map +1 -1
- package/dist/store/tables.d.mts +1 -0
- package/dist/store/tables.d.mts.map +1 -1
- package/dist/store/tables.mjs +11 -0
- package/dist/store/tables.mjs.map +1 -1
- package/package.json +1 -1
package/dist/dsl/flow.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { NodeIR } from "../ir.cjs";
|
|
2
2
|
import { ActionRef } from "./action.cjs";
|
|
3
3
|
import { Duration, TimeOfDay, Weekday } from "./base.cjs";
|
|
4
|
-
import { EventRef, MessageArgs, PropInput } from "./refs.cjs";
|
|
4
|
+
import { EventRef, MessageArgs, PropInput, PropsInput } from "./refs.cjs";
|
|
5
5
|
import { TemplateRef } from "./template.cjs";
|
|
6
6
|
import { Condition } from "./condition.cjs";
|
|
7
7
|
//#region src/dsl/flow.d.ts
|
|
@@ -29,6 +29,24 @@ export interface PushOptions {
|
|
|
29
29
|
/** Which devices get a copy: 'all' (the default) or only the most recently registered. */
|
|
30
30
|
devices?: 'all' | 'latest';
|
|
31
31
|
}
|
|
32
|
+
/** `prefer()` options. */
|
|
33
|
+
export interface PreferOptions {
|
|
34
|
+
/** The generated branch's name in IR (UI title / observability handle), as `branch(label, …)`. */
|
|
35
|
+
label?: string;
|
|
36
|
+
}
|
|
37
|
+
/** The candidates `prefer()` takes: one push and one email template, in priority order. */
|
|
38
|
+
type PreferPair = readonly [TemplateRef<'push', object>, TemplateRef<'email', object>] | readonly [TemplateRef<'email', object>, TemplateRef<'push', object>];
|
|
39
|
+
type RefProps<R> = R extends TemplateRef<infer _C, infer P> ? P : never;
|
|
40
|
+
type NormalizeProps<P> = { -readonly [K in keyof P]: P[K]; };
|
|
41
|
+
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => (T extends B ? 1 : 2)) ? true : false;
|
|
42
|
+
/** Both candidates render the one props object, so they must declare the same props type — not merely overlap. */
|
|
43
|
+
type SameProps<T extends PreferPair> = Equal<NormalizeProps<RefProps<T[0]>>, NormalizeProps<RefProps<T[1]>>> extends true ? unknown : {
|
|
44
|
+
readonly __prefer_error__: 'Both templates must declare the same props type';
|
|
45
|
+
};
|
|
46
|
+
/** Distributes, so a field only one member of a union variable has still counts as extra. */
|
|
47
|
+
type KeysOfUnion<A> = A extends unknown ? keyof A : never;
|
|
48
|
+
/** Rejects known extra fields, which `{}` (an empty props schema) would otherwise accept. */
|
|
49
|
+
type NoExtra<A, P> = Record<Exclude<KeysOfUnion<A>, keyof P>, never>;
|
|
32
50
|
/** A reusable flow fragment (what `flow(...)` returns), referenced directly by branch arms. */
|
|
33
51
|
export interface Flow {
|
|
34
52
|
readonly __flow: true;
|
|
@@ -48,13 +66,29 @@ export interface FlowBuilder {
|
|
|
48
66
|
/**
|
|
49
67
|
* Push to the user's devices — every device the host's directory lists, or
|
|
50
68
|
* only the most recently registered with `{ devices: 'latest' }`. A user with
|
|
51
|
-
* no device is skipped (
|
|
69
|
+
* no device is skipped (`prefer([pushTpl, emailTpl], props)` falls back to email).
|
|
52
70
|
*/
|
|
53
71
|
push<P extends object>(template: TemplateRef<'push', P>, ...args: [...props: MessageArgs<P>, options?: PushOptions]): this;
|
|
54
72
|
inApp<P extends object>(template: TemplateRef<'in_app', P>, ...props: MessageArgs<P>): this;
|
|
55
73
|
slack<P extends object>(template: TemplateRef<'slack', P>, ...props: MessageArgs<P>): this;
|
|
56
74
|
discord<P extends object>(template: TemplateRef<'discord', P>, ...props: MessageArgs<P>): this;
|
|
57
75
|
survey<P extends object>(template: TemplateRef<'survey', P>, ...props: MessageArgs<P>): this;
|
|
76
|
+
/**
|
|
77
|
+
* Send one message on the first channel the user can be reached on: one push
|
|
78
|
+
* and one email template, in priority order, rendered with the same props.
|
|
79
|
+
* Sugar for the branch it compiles to — same IR, ids and hash as writing
|
|
80
|
+
*
|
|
81
|
+
* .branch(label, [reachable(first.channel), (b) => b.<first>(first, props)], (b) => b.<second>(second, props))
|
|
82
|
+
*
|
|
83
|
+
* so the choice is made once, when the step is reached, and a first choice
|
|
84
|
+
* that fails to send retries as itself — it never falls through to the
|
|
85
|
+
* second. Props are always passed (`{}` for templates that declare none),
|
|
86
|
+
* and both templates must declare the same props type; for differing props
|
|
87
|
+
* or other channels, write the branch.
|
|
88
|
+
*
|
|
89
|
+
* .prefer([t.push.tip, t.email.tip], { name: u.name }, { label: 'tip by channel' })
|
|
90
|
+
*/
|
|
91
|
+
prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<RefProps<T[0]>>>>(candidates: T & SameProps<NoInfer<T>>, props: A & NoInfer<NoExtra<A, RefProps<T[0]>>>, options?: PreferOptions): this;
|
|
58
92
|
/** Time Delay; passing { min, max } makes it a Randomized Delay. */
|
|
59
93
|
delay(duration: Duration): this;
|
|
60
94
|
delay(range: {
|
|
@@ -83,9 +117,8 @@ export interface FlowBuilder {
|
|
|
83
117
|
* workflow as if the steps were written inline). Each use gets its own copy,
|
|
84
118
|
* so one fragment can be used in several places and workflows.
|
|
85
119
|
*
|
|
86
|
-
* const
|
|
87
|
-
*
|
|
88
|
-
* workflow({ id: 'onboarding', ... }).use(preferPush(tipPush, tipEmail, { name: u.name }))
|
|
120
|
+
* const officeHours = flow((w) => w.timeWindow({ days: ['mon', 'tue', 'wed', 'thu', 'fri'], between: ['09:00', '17:00'] }));
|
|
121
|
+
* workflow({ id: 'onboarding', ... }).delay('1 day').use(officeHours).email(t.email.tip, { name: u.name })
|
|
89
122
|
*/
|
|
90
123
|
use(fragment: SubFlow): this;
|
|
91
124
|
/**
|
|
@@ -184,6 +217,7 @@ export declare class FlowBuilderImpl implements FlowBuilder {
|
|
|
184
217
|
slack<P extends object>(t: TemplateRef<'slack', P>, ...args: MessageArgs<P>): this;
|
|
185
218
|
discord<P extends object>(t: TemplateRef<'discord', P>, ...args: MessageArgs<P>): this;
|
|
186
219
|
survey<P extends object>(t: TemplateRef<'survey', P>, ...args: MessageArgs<P>): this;
|
|
220
|
+
prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<RefProps<T[0]>>>>(candidates: T & SameProps<NoInfer<T>>, props: A & NoInfer<NoExtra<A, RefProps<T[0]>>>, options?: PreferOptions): this;
|
|
187
221
|
delay(duration: Duration): this;
|
|
188
222
|
delay(range: {
|
|
189
223
|
min: Duration;
|
package/dist/dsl/flow.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow.d.cts","names":[],"sources":["../../src/dsl/flow.ts"],"mappings":";;;;;;;;;;;;;;;;;;;KAqBK;;KAGA,UAAU,MAAM,YAAY,aAAa,UAAU,UAAU;;YAGtD,YAAY,QAAQ,WAAW,IAAI,UAAU,EAAE;;YAG/C,SAAS,KACnB,6BAA6B,KAAK,UAAU,YAAY,OAAO,SAAS,YAAY;;iBAGrE;;EAEf;;;iBAIe;WACN;;;YAQC,UAAU,SAAS,GAAG,gBAAgB;;YAGtC,uBAAuB,WAAW,WAAW,MAAM;;;;;YAMnD,YAAY,aAAa;iBAsCpB;EAEf,MAAM,kBAAkB,UAAU,qBAAq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AAM,YAAY;EAG1E,MAAM,kBAAkB,GAAG,qBAAqB,OAAO,MAAM,YAAY;EAGzE,QAAQ,kBAAkB,GAAG,uBAAuB,OAAO,MAAM,YAAY;EAG7E,OAAO,kBAAkB,GAAG,sBAAsB,OAAO,MAAM,YAAY;EAI3E,aAAa,UAAU,kBAAkB,UAAU,WAAW,QAAQ,SAAS,SAC7E,YAAY,IAAI,UAAU,QAAQ,KAClC,OAAO,IAAI,QAAQ,QAAQ,GAAG,SAAS,SACvC,UAAU;EAyBZ,MAAM,UAAU;EAChB,MAAM;IAAS,KAAK;IAAU,KAAK;;EAqBnC,WAAW;IACT,gBAAgB;IAChB,mBAAmB,WAAW;IAC9B;;EAsBF,UACE,WAAW,WACX;IAAQ,SAAS;IAAU,kCAAkC;;EAiB/D,IAAI,UAAU;EAMd,UAAU,eAAe;EACzB,OAAO,kBAAkB,eAAe;EAsCxC,OAAO,WAAW,WAAW;IAAS;;EAYtC,OAAO,MAAM;IAAiB;IAAgB,OAAO;MAAY;IAAS;;EAmD1E,KAAK;EAOL,UAAU,kBAAkB,IAAI,SAAS,OAAO,SAAS,SAAS;EAwBlE,IAAI,kBAAkB,GAAG,UAAU,OAAO,MAAM,YAAY;;;;;;wBAmB9C,KAAK,QAAQ,GAAG,gBAAgB,cAAc"}
|
package/dist/dsl/flow.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { NodeIR } from "../ir.mjs";
|
|
2
2
|
import { ActionRef } from "./action.mjs";
|
|
3
3
|
import { Duration, TimeOfDay, Weekday } from "./base.mjs";
|
|
4
|
-
import { EventRef, MessageArgs, PropInput } from "./refs.mjs";
|
|
4
|
+
import { EventRef, MessageArgs, PropInput, PropsInput } from "./refs.mjs";
|
|
5
5
|
import { TemplateRef } from "./template.mjs";
|
|
6
6
|
import { Condition } from "./condition.mjs";
|
|
7
7
|
//#region src/dsl/flow.d.ts
|
|
@@ -29,6 +29,24 @@ export interface PushOptions {
|
|
|
29
29
|
/** Which devices get a copy: 'all' (the default) or only the most recently registered. */
|
|
30
30
|
devices?: 'all' | 'latest';
|
|
31
31
|
}
|
|
32
|
+
/** `prefer()` options. */
|
|
33
|
+
export interface PreferOptions {
|
|
34
|
+
/** The generated branch's name in IR (UI title / observability handle), as `branch(label, …)`. */
|
|
35
|
+
label?: string;
|
|
36
|
+
}
|
|
37
|
+
/** The candidates `prefer()` takes: one push and one email template, in priority order. */
|
|
38
|
+
type PreferPair = readonly [TemplateRef<'push', object>, TemplateRef<'email', object>] | readonly [TemplateRef<'email', object>, TemplateRef<'push', object>];
|
|
39
|
+
type RefProps<R> = R extends TemplateRef<infer _C, infer P> ? P : never;
|
|
40
|
+
type NormalizeProps<P> = { -readonly [K in keyof P]: P[K]; };
|
|
41
|
+
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => (T extends B ? 1 : 2)) ? true : false;
|
|
42
|
+
/** Both candidates render the one props object, so they must declare the same props type — not merely overlap. */
|
|
43
|
+
type SameProps<T extends PreferPair> = Equal<NormalizeProps<RefProps<T[0]>>, NormalizeProps<RefProps<T[1]>>> extends true ? unknown : {
|
|
44
|
+
readonly __prefer_error__: 'Both templates must declare the same props type';
|
|
45
|
+
};
|
|
46
|
+
/** Distributes, so a field only one member of a union variable has still counts as extra. */
|
|
47
|
+
type KeysOfUnion<A> = A extends unknown ? keyof A : never;
|
|
48
|
+
/** Rejects known extra fields, which `{}` (an empty props schema) would otherwise accept. */
|
|
49
|
+
type NoExtra<A, P> = Record<Exclude<KeysOfUnion<A>, keyof P>, never>;
|
|
32
50
|
/** A reusable flow fragment (what `flow(...)` returns), referenced directly by branch arms. */
|
|
33
51
|
export interface Flow {
|
|
34
52
|
readonly __flow: true;
|
|
@@ -48,13 +66,29 @@ export interface FlowBuilder {
|
|
|
48
66
|
/**
|
|
49
67
|
* Push to the user's devices — every device the host's directory lists, or
|
|
50
68
|
* only the most recently registered with `{ devices: 'latest' }`. A user with
|
|
51
|
-
* no device is skipped (
|
|
69
|
+
* no device is skipped (`prefer([pushTpl, emailTpl], props)` falls back to email).
|
|
52
70
|
*/
|
|
53
71
|
push<P extends object>(template: TemplateRef<'push', P>, ...args: [...props: MessageArgs<P>, options?: PushOptions]): this;
|
|
54
72
|
inApp<P extends object>(template: TemplateRef<'in_app', P>, ...props: MessageArgs<P>): this;
|
|
55
73
|
slack<P extends object>(template: TemplateRef<'slack', P>, ...props: MessageArgs<P>): this;
|
|
56
74
|
discord<P extends object>(template: TemplateRef<'discord', P>, ...props: MessageArgs<P>): this;
|
|
57
75
|
survey<P extends object>(template: TemplateRef<'survey', P>, ...props: MessageArgs<P>): this;
|
|
76
|
+
/**
|
|
77
|
+
* Send one message on the first channel the user can be reached on: one push
|
|
78
|
+
* and one email template, in priority order, rendered with the same props.
|
|
79
|
+
* Sugar for the branch it compiles to — same IR, ids and hash as writing
|
|
80
|
+
*
|
|
81
|
+
* .branch(label, [reachable(first.channel), (b) => b.<first>(first, props)], (b) => b.<second>(second, props))
|
|
82
|
+
*
|
|
83
|
+
* so the choice is made once, when the step is reached, and a first choice
|
|
84
|
+
* that fails to send retries as itself — it never falls through to the
|
|
85
|
+
* second. Props are always passed (`{}` for templates that declare none),
|
|
86
|
+
* and both templates must declare the same props type; for differing props
|
|
87
|
+
* or other channels, write the branch.
|
|
88
|
+
*
|
|
89
|
+
* .prefer([t.push.tip, t.email.tip], { name: u.name }, { label: 'tip by channel' })
|
|
90
|
+
*/
|
|
91
|
+
prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<RefProps<T[0]>>>>(candidates: T & SameProps<NoInfer<T>>, props: A & NoInfer<NoExtra<A, RefProps<T[0]>>>, options?: PreferOptions): this;
|
|
58
92
|
/** Time Delay; passing { min, max } makes it a Randomized Delay. */
|
|
59
93
|
delay(duration: Duration): this;
|
|
60
94
|
delay(range: {
|
|
@@ -83,9 +117,8 @@ export interface FlowBuilder {
|
|
|
83
117
|
* workflow as if the steps were written inline). Each use gets its own copy,
|
|
84
118
|
* so one fragment can be used in several places and workflows.
|
|
85
119
|
*
|
|
86
|
-
* const
|
|
87
|
-
*
|
|
88
|
-
* workflow({ id: 'onboarding', ... }).use(preferPush(tipPush, tipEmail, { name: u.name }))
|
|
120
|
+
* const officeHours = flow((w) => w.timeWindow({ days: ['mon', 'tue', 'wed', 'thu', 'fri'], between: ['09:00', '17:00'] }));
|
|
121
|
+
* workflow({ id: 'onboarding', ... }).delay('1 day').use(officeHours).email(t.email.tip, { name: u.name })
|
|
89
122
|
*/
|
|
90
123
|
use(fragment: SubFlow): this;
|
|
91
124
|
/**
|
|
@@ -184,6 +217,7 @@ export declare class FlowBuilderImpl implements FlowBuilder {
|
|
|
184
217
|
slack<P extends object>(t: TemplateRef<'slack', P>, ...args: MessageArgs<P>): this;
|
|
185
218
|
discord<P extends object>(t: TemplateRef<'discord', P>, ...args: MessageArgs<P>): this;
|
|
186
219
|
survey<P extends object>(t: TemplateRef<'survey', P>, ...args: MessageArgs<P>): this;
|
|
220
|
+
prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<RefProps<T[0]>>>>(candidates: T & SameProps<NoInfer<T>>, props: A & NoInfer<NoExtra<A, RefProps<T[0]>>>, options?: PreferOptions): this;
|
|
187
221
|
delay(duration: Duration): this;
|
|
188
222
|
delay(range: {
|
|
189
223
|
min: Duration;
|
package/dist/dsl/flow.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow.d.mts","names":[],"sources":["../../src/dsl/flow.ts"],"mappings":";;;;;;;;;;;;;;;;;;;KAqBK;;KAGA,UAAU,MAAM,YAAY,aAAa,UAAU,UAAU;;YAGtD,YAAY,QAAQ,WAAW,IAAI,UAAU,EAAE;;YAG/C,SAAS,KACnB,6BAA6B,KAAK,UAAU,YAAY,OAAO,SAAS,YAAY;;iBAGrE;;EAEf;;;iBAIe;WACN;;;YAQC,UAAU,SAAS,GAAG,gBAAgB;;YAGtC,uBAAuB,WAAW,WAAW,MAAM;;;;;YAMnD,YAAY,a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AU;EAMhD,MAAM,kBAAkB,GAAG,sBAAsB,OAAO,MAAM,YAAY;EAG1E,MAAM,kBAAkB,GAAG,qBAAqB,OAAO,MAAM,YAAY;EAGzE,QAAQ,kBAAkB,GAAG,uBAAuB,OAAO,MAAM,YAAY;EAG7E,OAAO,kBAAkB,GAAG,sBAAsB,OAAO,MAAM,YAAY;EAI3E,aAAa,UAAU,kBAAkB,UAAU,WAAW,QAAQ,SAAS,SAC7E,YAAY,IAAI,UAAU,QAAQ,KAClC,OAAO,IAAI,QAAQ,QAAQ,GAAG,SAAS,SACvC,UAAU;EAyBZ,MAAM,UAAU;EAChB,MAAM;IAAS,KAAK;IAAU,KAAK;;EAqBnC,WAAW;IACT,gBAAgB;IAChB,mBAAmB,WAAW;IAC9B;;EAsBF,UACE,WAAW,WACX;IAAQ,SAAS;IAAU,kCAAkC;;EAiB/D,IAAI,UAAU;EAMd,UAAU,eAAe;EACzB,OAAO,kBAAkB,eAAe;EAsCxC,OAAO,WAAW,WAAW;IAAS;;EAYtC,OAAO,MAAM;IAAiB;IAAgB,OAAO;MAAY;IAAS;;EAmD1E,KAAK;EAOL,UAAU,kBAAkB,IAAI,SAAS,OAAO,SAAS,SAAS;EAwBlE,IAAI,kBAAkB,GAAG,UAAU,OAAO,MAAM,YAAY;;;;;;wBAmB9C,KAAK,QAAQ,GAAG,gBAAgB,cAAc"}
|
package/dist/dsl/flow.mjs
CHANGED
|
@@ -2,6 +2,23 @@ import { captureLoc } from "../provenance.mjs";
|
|
|
2
2
|
import { durationIR, timeOfDayMinutes } from "./base.mjs";
|
|
3
3
|
import { condIR } from "./condition.mjs";
|
|
4
4
|
//#region src/dsl/flow.ts
|
|
5
|
+
const PREFER_CHANNELS = /* @__PURE__ */ new Set(["push", "email"]);
|
|
6
|
+
/** prefer() is typed strictly, but a JS caller (or an `any`) reaches it unchecked — fail at the call, not at send time. */
|
|
7
|
+
function checkPreferArgs(candidates, props, options) {
|
|
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");
|
|
14
|
+
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
|
+
if (options === void 0) return;
|
|
16
|
+
if (typeof options !== "object" || options === null || Array.isArray(options)) throw new TypeError("prefer(): options must be an object");
|
|
17
|
+
for (const [name, value] of Object.entries(options)) {
|
|
18
|
+
if (name !== "label") throw new TypeError(`prefer(): unknown option '${name}' — props go in the second argument, options take only 'label'`);
|
|
19
|
+
if (typeof value !== "string") throw new TypeError("prefer(): 'label' must be a string");
|
|
20
|
+
}
|
|
21
|
+
}
|
|
5
22
|
/**
|
|
6
23
|
* A cohort arm name has two jobs, and both constrain its spelling:
|
|
7
24
|
* - it is interpolated into the node ids of the arm's flow ('{id}.{name}.{j}'),
|
|
@@ -22,6 +39,16 @@ function resolveSubFlow(sub) {
|
|
|
22
39
|
}
|
|
23
40
|
return structuredClone(sub.nodes);
|
|
24
41
|
}
|
|
42
|
+
function messageNode(channel, tpl, props, devices) {
|
|
43
|
+
return {
|
|
44
|
+
id: "",
|
|
45
|
+
type: "message",
|
|
46
|
+
channel,
|
|
47
|
+
template: tpl.key,
|
|
48
|
+
props: props ?? {},
|
|
49
|
+
...devices !== void 0 ? { devices } : {}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
25
52
|
/** @internal extended by WorkflowBuilderImpl; not part of the public API */
|
|
26
53
|
var FlowBuilderImpl = class {
|
|
27
54
|
/** Nodes as collected; ids are assigned in one pass inside toIR, so '' is a placeholder here. */
|
|
@@ -35,14 +62,7 @@ var FlowBuilderImpl = class {
|
|
|
35
62
|
return this;
|
|
36
63
|
}
|
|
37
64
|
message(channel, tpl, props, loc, devices) {
|
|
38
|
-
return this.pushNode(
|
|
39
|
-
id: "",
|
|
40
|
-
type: "message",
|
|
41
|
-
channel,
|
|
42
|
-
template: tpl.key,
|
|
43
|
-
props: props ?? {},
|
|
44
|
-
...devices !== void 0 ? { devices } : {}
|
|
45
|
-
}, loc);
|
|
65
|
+
return this.pushNode(messageNode(channel, tpl, props, devices), loc);
|
|
46
66
|
}
|
|
47
67
|
email(t, ...args) {
|
|
48
68
|
return this.message("email", t, args[0], captureLoc(this.email));
|
|
@@ -67,6 +87,30 @@ var FlowBuilderImpl = class {
|
|
|
67
87
|
survey(t, ...args) {
|
|
68
88
|
return this.message("survey", t, args[0], captureLoc(this.survey));
|
|
69
89
|
}
|
|
90
|
+
prefer(candidates, props, options) {
|
|
91
|
+
checkPreferArgs(candidates, props, options);
|
|
92
|
+
const loc = captureLoc(this.prefer);
|
|
93
|
+
const meta = loc !== void 0 ? { meta: { loc } } : {};
|
|
94
|
+
const [first, second] = candidates;
|
|
95
|
+
const arm = (tpl) => [{
|
|
96
|
+
...messageNode(tpl.channel, tpl, { ...props }),
|
|
97
|
+
...meta
|
|
98
|
+
}];
|
|
99
|
+
return this.pushNode({
|
|
100
|
+
id: "",
|
|
101
|
+
type: "branch",
|
|
102
|
+
...options?.label !== void 0 ? { label: options.label } : {},
|
|
103
|
+
cases: [{
|
|
104
|
+
condition: {
|
|
105
|
+
type: "reachable",
|
|
106
|
+
channel: first.channel,
|
|
107
|
+
...meta
|
|
108
|
+
},
|
|
109
|
+
flow: arm(first)
|
|
110
|
+
}],
|
|
111
|
+
otherwise: arm(second)
|
|
112
|
+
}, loc);
|
|
113
|
+
}
|
|
70
114
|
delay(d) {
|
|
71
115
|
const loc = captureLoc(this.delay);
|
|
72
116
|
if (typeof d === "string") return this.pushNode({
|
package/dist/dsl/flow.mjs.map
CHANGED
|
@@ -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 } 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/** 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 (branch on `reachable('push')` to fall 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 /* --------------------------------- 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 preferPush = (push, email, props) =>\n * flow((w) => w.branch([reachable('push'), (b) => b.push(push, props)], (b) => b.email(email, props)));\n * workflow({ id: 'onboarding', ... }).use(preferPush(tipPush, tipEmail, { 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\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(\n {\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 loc\n );\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 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":";;;;;;;;;;;;;;;AAuEA,MAAM,WAAW;AAEjB,SAAS,eAAe,KAAwB;CAC9C,IAAI,OAAO,QAAQ,YAAY;EAC7B,MAAM,UAAU,IAAI,gBAAgB;EAGpC,IAAI,OAFsB,IAAI,OAEX,CAAC,EAAqC,SAAS,YAChE,MAAM,IAAI,UACR,sFACF;EAEF,OAAO,QAAQ;CACjB;CASA,OAAO,gBAAiB,IAAqB,KAAK;AACpD;;AA+IA,IAAa,kBAAb,MAAoD;;CAElD,QAA2B,CAAC;;CAG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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 type { ActionRef } from './action';\nimport { type Duration, type TimeOfDay, type Weekday, durationIR, timeOfDayMinutes } from './base';\nimport { type Condition, condIR } from './condition';\nimport type { EventRef, MessageArgs, PropInput, PropsInput } from './refs';\nimport type { Channel, TemplateRef } from './template';\n\n/**\n * The flow chain — FlowBuilder is the DSL's step surface (messages, delays,\n * flow control, data), and its implementation is the compiler front half: each\n * chained call executes no logic, it just collects one IR node (ids are\n * assigned later, in workflow.toIR()). Sub-flow callbacks run exactly once at\n * construction — builder in, builder out — so the output is always a static\n * tree.\n *\n * Every public method also captures its callsite (provenance): the loc lands\n * in the node's hash-excluded meta and is the anchor for future in-place\n * editing from the studio.\n */\n\ntype Scalar = string | number | boolean;\n\n/** An emitted field: a scalar (or a profile ref to one); a nested field cannot be sent. */\ntype EmitValue<T> = [NonNullable<T>] extends [Scalar] ? PropInput<T> : never;\n\n/** The payload `sendEvent` accepts for an event: its fields, scalar ones only. */\nexport type EmitPayload<P> = { [K in keyof P]: EmitValue<P[K]> };\n\n/** Payload may be omitted when the event declares no required field. */\nexport type EmitArgs<P> =\n Record<never, never> extends P ? [payload?: EmitPayload<P>] : [payload: EmitPayload<P>];\n\n/** Per-node push options. */\nexport interface PushOptions {\n /** Which devices get a copy: 'all' (the default) or only the most recently registered. */\n devices?: 'all' | 'latest';\n}\n\n/** `prefer()` options. */\nexport interface PreferOptions {\n /** The generated branch's name in IR (UI title / observability handle), as `branch(label, …)`. */\n label?: string;\n}\n\n/** The candidates `prefer()` takes: one push and one email template, in priority order. */\ntype PreferPair =\n | readonly [TemplateRef<'push', object>, TemplateRef<'email', object>]\n | readonly [TemplateRef<'email', object>, TemplateRef<'push', object>];\n\ntype RefProps<R> = R extends TemplateRef<infer _C, infer P> ? P : never;\ntype NormalizeProps<P> = { -readonly [K in keyof P]: P[K] };\ntype Equal<A, B> =\n (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;\n\n/** Both candidates render the one props object, so they must declare the same props type — not merely overlap. */\ntype SameProps<T extends PreferPair> =\n Equal<NormalizeProps<RefProps<T[0]>>, NormalizeProps<RefProps<T[1]>>> extends true\n ? unknown\n : { readonly __prefer_error__: 'Both templates must declare the same props type' };\n\n/** Distributes, so a field only one member of a union variable has still counts as extra. */\ntype KeysOfUnion<A> = A extends unknown ? keyof A : never;\n/** Rejects known extra fields, which `{}` (an empty props schema) would otherwise accept. */\ntype NoExtra<A, P> = Record<Exclude<KeysOfUnion<A>, keyof P>, never>;\n\nconst PREFER_CHANNELS: ReadonlySet<unknown> = new Set(['push', 'email']);\n\n/** prefer() is typed strictly, but a JS caller (or an `any`) reaches it unchecked — fail at the call, not at send time. */\nfunction checkPreferArgs(candidates: unknown, props: unknown, options: unknown): void {\n if (!Array.isArray(candidates) || candidates.length !== 2) {\n throw new TypeError('prefer(): candidates must be exactly two templates — one push, one email');\n }\n for (const ref of candidates as unknown[]) {\n const { channel, key } = (ref ?? {}) as Partial<TemplateRef>;\n if (!PREFER_CHANNELS.has(channel) || typeof key !== 'string' || key === '') {\n throw new TypeError(\n 'prefer(): each candidate must be a push or email template reference (t.push.<key> / t.email.<key>)'\n );\n }\n }\n if ((candidates[0] as TemplateRef).channel === (candidates[1] as TemplateRef).channel) {\n throw new TypeError('prefer(): candidates must be one push and one email template');\n }\n if (typeof props !== 'object' || props === null || Array.isArray(props)) {\n throw new TypeError(\n 'prefer(): props must be an object — pass {} when the templates declare none'\n );\n }\n if (options === undefined) return;\n if (typeof options !== 'object' || options === null || Array.isArray(options)) {\n throw new TypeError('prefer(): options must be an object');\n }\n for (const [name, value] of Object.entries(options)) {\n if (name !== 'label') {\n throw new TypeError(\n `prefer(): unknown option '${name}' — props go in the second argument, options take only 'label'`\n );\n }\n if (typeof value !== 'string') throw new TypeError(\"prefer(): 'label' must be a string\");\n }\n}\n\n/** A reusable flow fragment (what `flow(...)` returns), referenced directly by branch arms. */\nexport interface Flow {\n readonly __flow: true;\n}\n\ninterface FlowInternal extends Flow {\n readonly nodes: NodeIR[];\n}\n\n/** Sub-flow: a named fragment, or an inline callback (runs once at construction — builder in, builder out). */\nexport type SubFlow = Flow | ((w: FlowBuilder) => FlowBuilder);\n\n/** A branch arm: the [condition, sub-flow] tuple — an [if, then] ordering convention. */\nexport type BranchCase = readonly [condition: Condition, flow: SubFlow];\n\n/**\n * A branch argument: either a tuple arm, or a bare sub-flow meaning the default\n * arm. The bare form may appear once, and must come last (checked at runtime).\n */\nexport type BranchArm = BranchCase | SubFlow;\n\n/**\n * A cohort arm name has two jobs, and both constrain its spelling:\n * - it is interpolated into the node ids of the arm's flow ('{id}.{name}.{j}'),\n * and an id is a durable step name — a dot would fake a nesting level and can\n * collide with a real one, an empty name gives '{id}..{j}';\n * - it is an object key, and JavaScript lists integer-like keys first in\n * ascending numeric order however the author wrote them. The arms array is\n * documented (and interpreted) as authoring order, and the bucketing walk\n * accumulates weights along it, so an arm named '0' added to a live\n * experiment would prepend itself and re-bucket everyone already in it.\n */\nconst ARM_NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/;\n\nfunction resolveSubFlow(sub: SubFlow): NodeIR[] {\n if (typeof sub === 'function') {\n const builder = new FlowBuilderImpl();\n const returned: unknown = sub(builder);\n // An async callback would add its nodes after construction is over — after ids were assigned\n if (typeof (returned as { then?: unknown } | undefined)?.then === 'function') {\n throw new TypeError(\n 'sub-flow callbacks must be synchronous: they run once, while the workflow is defined'\n );\n }\n return builder.nodes;\n }\n /*\n * A named fragment is a value, and the convention is to reuse it — two branch\n * arms may hold the same one. Handing out its own nodes aliases them into\n * both places, and assignIds writes ids *in place*: the second prefix\n * overwrites the first, so the two placements end up as one object under one\n * id — one durable step name, one message idempotency key, one bucket seed.\n * A copy per placement is what makes a fragment behave like a value.\n */\n return structuredClone((sub as FlowInternal).nodes);\n}\n\nexport interface FlowBuilder {\n /* ---- Messages: every channel is one message node; separate methods buy channel-level typing ---- */\n email<P extends object>(template: TemplateRef<'email', P>, ...props: MessageArgs<P>): this;\n sms<P extends object>(template: TemplateRef<'sms', P>, ...props: MessageArgs<P>): this;\n /**\n * Push to the user's devices — every device the host's directory lists, or\n * only the most recently registered with `{ devices: 'latest' }`. A user with\n * no device is skipped (`prefer([pushTpl, emailTpl], props)` falls back to email).\n */\n push<P extends object>(\n template: TemplateRef<'push', P>,\n ...args: [...props: MessageArgs<P>, options?: PushOptions]\n ): this;\n inApp<P extends object>(template: TemplateRef<'in_app', P>, ...props: MessageArgs<P>): this;\n slack<P extends object>(template: TemplateRef<'slack', P>, ...props: MessageArgs<P>): this;\n discord<P extends object>(template: TemplateRef<'discord', P>, ...props: MessageArgs<P>): this;\n survey<P extends object>(template: TemplateRef<'survey', P>, ...props: MessageArgs<P>): this;\n\n /**\n * Send one message on the first channel the user can be reached on: one push\n * and one email template, in priority order, rendered with the same props.\n * Sugar for the branch it compiles to — same IR, ids and hash as writing\n *\n * .branch(label, [reachable(first.channel), (b) => b.<first>(first, props)], (b) => b.<second>(second, props))\n *\n * so the choice is made once, when the step is reached, and a first choice\n * that fails to send retries as itself — it never falls through to the\n * second. Props are always passed (`{}` for templates that declare none),\n * and both templates must declare the same props type; for differing props\n * or other channels, write the branch.\n *\n * .prefer([t.push.tip, t.email.tip], { name: u.name }, { label: 'tip by channel' })\n */\n prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<RefProps<T[0]>>>>(\n candidates: T & SameProps<NoInfer<T>>,\n props: A & NoInfer<NoExtra<A, RefProps<T[0]>>>,\n options?: PreferOptions\n ): this;\n\n /* --------------------------------- Delays --------------------------------- */\n /** Time Delay; passing { min, max } makes it a Randomized Delay. */\n delay(duration: Duration): this;\n delay(range: { min: Duration; max: Duration }): this;\n\n /** Time Window: hold until inside the window (e.g. weekdays 09:00–17:00). tz: 'user' uses the user's timezone. */\n timeWindow(opts: {\n days?: readonly Weekday[];\n between: readonly [TimeOfDay, TimeOfDay];\n tz?: 'user' | (string & {});\n }): this;\n\n /**\n * Wait Until: continue on the main line once the condition holds, or take\n * onTimeout when it expires (default 'continue'). On the engine side this is\n * \"await event racing a timer\" — a native primitive of durable runtimes.\n */\n waitUntil(\n condition: Condition,\n opts: { timeout: Duration; onTimeout?: 'continue' | 'exit' | SubFlow }\n ): this;\n\n /**\n * Splice a fragment in place: a named `flow(...)` or a callback, expanded\n * once while the workflow is defined — a composition step before compiling,\n * not a node (the IR has no trace of it, and ids are assigned over the whole\n * workflow as if the steps were written inline). Each use gets its own copy,\n * so one fragment can be used in several places and workflows.\n *\n * const officeHours = flow((w) => w.timeWindow({ days: ['mon', 'tue', 'wed', 'thu', 'fri'], between: ['09:00', '17:00'] }));\n * workflow({ id: 'onboarding', ... }).delay('1 day').use(officeHours).email(t.email.tip, { name: u.name })\n */\n use(fragment: SubFlow): this;\n\n /* ------------------------------ Flow Control ------------------------------ */\n /**\n * Conditional branch: ordered first-match (same semantics as Step Functions\n * Choice / Knock branch). This one primitive covers both the UI's True/False\n * Branch (two arms) and Multi-Split Branch (N arms). Arms are\n * [condition, sub-flow] tuples; a bare sub-flow in tail position is the\n * default arm. With no match and no default, execution simply continues.\n * Rejoin is structural: after the matching arm finishes, execution resumes\n * at the node following the branch — to opt out, call .exit() inside the arm.\n *\n * .branch([activeSubscriber, upgradeFlow], firstTimeFlow) // True/False\n * .branch([vip, vipFlow], [trial, trialFlow], defaultFlow) // Multi-Split\n * .branch([not(usedStaging), eduFlow]) // single arm: no match continues\n *\n * The optional first argument `label` becomes the node's name in IR (UI title\n * / observability handle). It is not a jump target — there is no goto here;\n * looping is a future re-entry-policy topic (see sendEvent). Arm labels in\n * the UI are derived from the condition.\n */\n branch(...arms: readonly BranchArm[]): this;\n branch(label: string, ...arms: readonly BranchArm[]): this;\n\n /**\n * Gate: exit unless the condition holds, otherwise continue. A first-class\n * node rather than sugar over branch — same semantics as Zapier's \"only\n * continue if\" / Iterable's Filter tile, and rendered on its own in the UI.\n * `reason` is the audit-log line — metadata, so rewording it is free\n * (excluded from contentHash, see hash.ts).\n */\n filter(condition: Condition, opts?: { reason?: string }): this;\n\n /**\n * Random Cohort Branch (A/B): weights must sum to 100 (checked at runtime).\n * `key` names the experiment: bucketing hashes `userId:key` instead of the\n * structural node id, so assignments survive node insertion/moves and the\n * experiment keeps one identity across workflow versions — set it for any\n * A/B whose results you intend to read.\n *\n * Arm names become node id segments and are read back in authoring order, so\n * they are restricted to letters, digits, '_' and '-', never starting with a\n * digit (checked at runtime).\n */\n cohort(arms: Record<string, { weight: number; flow?: SubFlow }>, opts?: { key?: string }): this;\n\n /**\n * Exit: end the whole workflow immediately (the UI's Exit node); `reason`\n * goes into the audit log and is metadata, so rewording it neither repins\n * in-flight journeys nor shows up in plan. Inside a branch arm this means\n * \"terminate, do not rejoin\" — it stops here instead of falling through,\n * while an arm without exit rejoins naturally.\n */\n exit(reason?: string): this;\n\n /* ---------------------------------- Data ---------------------------------- */\n /**\n * Emit a typed event (customer.io's Send Event). The event comes from an\n * e.xxx reference, so payload types flow in the same way trigger.event works.\n * This is how workflows compose: an event can trigger another workflow, and\n * the resulting call graph is statically analyzable. Payload values may\n * reference u.xxx. Only scalar fields can be sent (IR carries literals and\n * profile refs, not nested JSON): an event whose payload requires a nested\n * field cannot be emitted from a journey, and the types say so.\n *\n * Note on loops: a trailing self-triggering sendEvent will become the\n * official periodic-flow shape *once a re-entry policy exists* — today the\n * entry policy is once-per-user, so a self-trigger cannot re-enter and does\n * not loop.\n * TODO: the rest of the Data category — outbound webhook / profile update /\n * journey attributes.\n */\n sendEvent<P extends object>(event: EventRef<P>, ...payload: EmitArgs<P>): this;\n\n /**\n * Run a custom action (see dsl/action.ts for the model). The chain records\n * identity only — name, args, codeHash — never the code: the implementation\n * ships inside the deployed Worker bundle and is resolved by name from the\n * runtime registry. Args are typed by the ActionRef and may reference u.xxx,\n * resolved at run time exactly like message props. Executed inside a durable\n * step: retried on throw, checkpointed on success.\n */\n run<A extends object>(action: ActionRef<A>, ...args: MessageArgs<A>): this;\n}\n\nfunction messageNode(\n channel: ChannelIR,\n tpl: TemplateRef<Channel, object>,\n props: object | undefined,\n devices?: 'latest'\n): NodeIR {\n return {\n id: '',\n type: 'message',\n channel,\n template: tpl.key,\n props: (props ?? {}) as Record<string, PropValueIR>,\n // Absent for 'all', so adding the option left every existing push's hash as it was\n ...(devices !== undefined ? { devices } : {}),\n };\n}\n\n/* oxlint-disable typescript/unbound-method --\n * `captureLoc(this.xxx)` passes the method by identity as the stack-trace\n * boundary for Error.captureStackTrace; it is never invoked, so `this`\n * scoping cannot go wrong. */\n/** @internal extended by WorkflowBuilderImpl; not part of the public API */\nexport class FlowBuilderImpl implements FlowBuilder {\n /** Nodes as collected; ids are assigned in one pass inside toIR, so '' is a placeholder here. */\n readonly nodes: NodeIR[] = [];\n\n /** Provenance: the callsite (captured in the public method) lands in meta.loc, outside the hash. */\n private pushNode(node: NodeIR, loc: SourceLocIR | undefined): this {\n this.nodes.push({ ...node, ...(loc !== undefined ? { meta: { loc } } : {}) });\n return this;\n }\n\n private message(\n channel: ChannelIR,\n tpl: TemplateRef<Channel, object>,\n props: object | undefined,\n loc: SourceLocIR | undefined,\n devices?: 'latest'\n ): this {\n return this.pushNode(messageNode(channel, tpl, props, devices), loc);\n }\n\n email<P extends object>(t: TemplateRef<'email', P>, ...args: MessageArgs<P>): this {\n return this.message('email', t, args[0], captureLoc(this.email));\n }\n sms<P extends object>(t: TemplateRef<'sms', P>, ...args: MessageArgs<P>): this {\n return this.message('sms', t, args[0], captureLoc(this.sms));\n }\n push<P extends object>(\n t: TemplateRef<'push', P>,\n ...args: [...props: MessageArgs<P>, options?: PushOptions]\n ): this {\n const [props, options] = args as unknown as [object | undefined, PushOptions | undefined];\n const devices = options?.devices === 'latest' ? 'latest' : undefined;\n return this.message('push', t, props, captureLoc(this.push), devices);\n }\n inApp<P extends object>(t: TemplateRef<'in_app', P>, ...args: MessageArgs<P>): this {\n return this.message('in_app', t, args[0], captureLoc(this.inApp));\n }\n slack<P extends object>(t: TemplateRef<'slack', P>, ...args: MessageArgs<P>): this {\n return this.message('slack', t, args[0], captureLoc(this.slack));\n }\n discord<P extends object>(t: TemplateRef<'discord', P>, ...args: MessageArgs<P>): this {\n return this.message('discord', t, args[0], captureLoc(this.discord));\n }\n survey<P extends object>(t: TemplateRef<'survey', P>, ...args: MessageArgs<P>): this {\n return this.message('survey', t, args[0], captureLoc(this.survey));\n }\n\n prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<RefProps<T[0]>>>>(\n candidates: T & SameProps<NoInfer<T>>,\n props: A & NoInfer<NoExtra<A, RefProps<T[0]>>>,\n options?: PreferOptions\n ): this {\n checkPreferArgs(candidates, props, options);\n // Every generated node points at the author's prefer() call, not at this method's body\n const loc = captureLoc(this.prefer);\n const meta = loc !== undefined ? { meta: { loc } } : {};\n const [first, second] = candidates as readonly TemplateRef<'push' | 'email', object>[];\n // A copy per message, as two separately written calls would hold\n const arm = (tpl: TemplateRef<'push' | 'email', object>): NodeIR[] => [\n { ...messageNode(tpl.channel, tpl, { ...props }), ...meta },\n ];\n return this.pushNode(\n {\n id: '',\n type: 'branch',\n ...(options?.label !== undefined ? { label: options.label } : {}),\n cases: [\n { condition: { type: 'reachable', channel: first.channel, ...meta }, flow: arm(first) },\n ],\n otherwise: arm(second),\n },\n loc\n );\n }\n\n delay(duration: Duration): this;\n delay(range: { min: Duration; max: Duration }): this;\n delay(d: Duration | { min: Duration; max: Duration }): this {\n const loc = captureLoc(this.delay);\n if (typeof d === 'string') {\n return this.pushNode({ id: '', type: 'delay', duration: durationIR(d) }, loc);\n }\n const min = durationIR(d.min);\n const max = durationIR(d.max);\n /*\n * The interpreter draws `min + random(max - min)` with the span clamped at\n * zero, so a backwards range does not fail — it quietly collapses into a\n * fixed `min` sleep. Reject it here, where the author can still see it.\n */\n if (max.ms < min.ms) {\n throw new Error(\n `delay(): 'max' must not be shorter than 'min', got { min: '${d.min}', max: '${d.max}' }`\n );\n }\n return this.pushNode({ id: '', type: 'random_delay', min, max }, loc);\n }\n\n timeWindow(opts: {\n days?: readonly Weekday[];\n between: readonly [TimeOfDay, TimeOfDay];\n tz?: 'user' | (string & {});\n }): this {\n const loc = captureLoc(this.timeWindow);\n const start = timeOfDayMinutes(opts.between[0]);\n const end = timeOfDayMinutes(opts.between[1]);\n if (end <= start) {\n throw new Error(\n `timeWindow(): 'between' must open before it closes within one day, got [${opts.between[0]}, ${opts.between[1]}] (overnight windows are not supported yet)`\n );\n }\n return this.pushNode(\n {\n id: '',\n type: 'time_window',\n days: [...(opts.days ?? (['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const))],\n between: [opts.between[0], opts.between[1]],\n tz: opts.tz ?? 'user',\n },\n loc\n );\n }\n\n waitUntil(\n condition: Condition,\n opts: { timeout: Duration; onTimeout?: 'continue' | 'exit' | SubFlow }\n ): this {\n const loc = captureLoc(this.waitUntil);\n const onTimeout = opts.onTimeout ?? 'continue';\n return this.pushNode(\n {\n id: '',\n type: 'wait_until',\n condition: condIR(condition),\n timeout: durationIR(opts.timeout),\n onTimeout:\n onTimeout === 'continue' || onTimeout === 'exit' ? onTimeout : resolveSubFlow(onTimeout),\n },\n loc\n );\n }\n\n use(fragment: SubFlow): this {\n // The fragment's nodes carry their own provenance (where the fragment was written)\n this.nodes.push(...resolveSubFlow(fragment));\n return this;\n }\n\n branch(...arms: readonly BranchArm[]): this;\n branch(label: string, ...arms: readonly BranchArm[]): this;\n branch(...args: readonly (string | BranchArm)[]): this {\n const loc = captureLoc(this.branch);\n const label = typeof args[0] === 'string' ? args[0] : undefined;\n const arms = (label === undefined ? args : args.slice(1)) as readonly BranchArm[];\n\n const cases: { condition: ConditionIR; flow: NodeIR[] }[] = [];\n let otherwise: NodeIR[] | undefined;\n arms.forEach((arm, i) => {\n if (Array.isArray(arm)) {\n if (otherwise !== undefined) {\n throw new Error('branch(): default arm (bare sub-flow) must be the last argument');\n }\n const [condition, sub] = arm as BranchCase;\n cases.push({ condition: condIR(condition), flow: resolveSubFlow(sub) });\n } else {\n if (otherwise !== undefined) {\n throw new Error('branch(): only one default arm (bare sub-flow) is allowed');\n }\n if (i !== arms.length - 1) {\n throw new Error('branch(): default arm (bare sub-flow) must be the last argument');\n }\n otherwise = resolveSubFlow(arm as SubFlow);\n }\n });\n\n return this.pushNode(\n {\n id: '',\n type: 'branch',\n ...(label !== undefined ? { label } : {}),\n cases,\n ...(otherwise !== undefined ? { otherwise } : {}),\n },\n loc\n );\n }\n\n filter(condition: Condition, opts?: { reason?: string }): this {\n return this.pushNode(\n {\n id: '',\n type: 'filter',\n condition: condIR(condition),\n ...(opts?.reason !== undefined ? { reason: opts.reason } : {}),\n },\n captureLoc(this.filter)\n );\n }\n\n cohort(arms: Record<string, { weight: number; flow?: SubFlow }>, opts?: { key?: string }): this {\n const loc = captureLoc(this.cohort);\n const entries = Object.entries(arms);\n /*\n * Weights live on a 0.01% grid: the runtime buckets into 10,000 slots\n * (basis points), so anything finer would be silently quantized — reject\n * it here instead. Converting to integer basis points also makes the\n * sum check exact; no epsilon needed.\n */\n const basisPoints = entries.map(([name, a]) => {\n if (!ARM_NAME.test(name)) {\n throw new Error(\n `cohort(): arm name '${name}' must start with a letter or '_' and contain only letters, digits, '_' or '-' — arm names become node id segments, and integer-like names would silently reorder the arms`\n );\n }\n const bp = a.weight * 100;\n if (Math.abs(bp - Math.round(bp)) > 1e-6) {\n throw new Error(\n `cohort(): arm '${name}' weight ${a.weight} is finer than the 0.01% bucketing grid — use at most two decimal places`\n );\n }\n /*\n * The sum check alone accepts -50 / 150: the runtime walks the arms\n * accumulating basis points and takes the first whose cumulative total\n * clears the bucket, so a negative weight hands 100% of users to its\n * neighbour instead of splitting anything.\n */\n if (bp < 0) {\n throw new Error(`cohort(): arm '${name}' weight ${a.weight} must not be negative`);\n }\n return Math.round(bp);\n });\n const total = basisPoints.reduce((sum, bp) => sum + bp, 0);\n if (total !== 10_000) {\n throw new Error(`cohort(): weights must sum to 100, got ${total / 100}`);\n }\n return this.pushNode(\n {\n id: '',\n type: 'cohort',\n ...(opts?.key !== undefined ? { key: opts.key } : {}),\n arms: entries.map(([name, a]) => ({\n name,\n weight: a.weight,\n flow: a.flow ? resolveSubFlow(a.flow) : [],\n })),\n },\n loc\n );\n }\n\n exit(reason?: string): this {\n return this.pushNode(\n { id: '', type: 'exit', ...(reason !== undefined ? { reason } : {}) },\n captureLoc(this.exit)\n );\n }\n\n sendEvent<P extends object>(ev: EventRef<P>, ...payload: EmitArgs<P>): this {\n const values = (payload[0] ?? {}) as Record<string, unknown>;\n for (const [field, value] of Object.entries(values)) {\n const ref =\n typeof value === 'object' &&\n value !== null &&\n (value as { type?: unknown }).type === 'user_property';\n if (!ref && !['string', 'number', 'boolean'].includes(typeof value)) {\n throw new TypeError(\n `sendEvent('${ev.name}'): '${field}' is not a scalar or a u.xxx reference — an emitted payload carries scalar fields only`\n );\n }\n }\n return this.pushNode(\n {\n id: '',\n type: 'send_event',\n event: ev.name,\n payload: values as Record<string, PropValueIR>,\n },\n captureLoc(this.sendEvent)\n );\n }\n\n run<A extends object>(a: ActionRef<A>, ...args: MessageArgs<A>): this {\n return this.pushNode(\n {\n id: '',\n type: 'action',\n action: a.name,\n args: (args[0] ?? {}) as Record<string, PropValueIR>,\n codeHash: a.codeHash,\n },\n captureLoc(this.run)\n );\n }\n}\n/* oxlint-enable typescript/unbound-method */\n\n/**\n * A reusable flow fragment: a free function. Once personalization goes through\n * u.xxx and events through e.xxx, the flow layer carries no schema generics.\n */\nexport function flow(build: (w: FlowBuilder) => FlowBuilder): Flow {\n const builder = new FlowBuilderImpl();\n build(builder);\n const impl: FlowInternal = { __flow: true, nodes: builder.nodes };\n return impl;\n}\n"],"mappings":";;;;AAkEA,MAAM,kCAAwC,IAAI,IAAI,CAAC,QAAQ,OAAO,CAAC;;AAGvE,SAAS,gBAAgB,YAAqB,OAAgB,SAAwB;CACpF,IAAI,CAAC,MAAM,QAAQ,UAAU,KAAK,WAAW,WAAW,GACtD,MAAM,IAAI,UAAU,0EAA0E;CAEhG,KAAK,MAAM,OAAO,YAAyB;EACzC,MAAM,EAAE,SAAS,QAAS,OAAO,CAAC;EAClC,IAAI,CAAC,gBAAgB,IAAI,OAAO,KAAK,OAAO,QAAQ,YAAY,QAAQ,IACtE,MAAM,IAAI,UACR,oGACF;CAEJ;CACA,IAAK,WAAW,EAAE,CAAiB,YAAa,WAAW,EAAE,CAAiB,SAC5E,MAAM,IAAI,UAAU,8DAA8D;CAEpF,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,UACR,6EACF;CAEF,IAAI,YAAY,KAAA,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;;;;;;;;;;;;AAkCA,MAAM,WAAW;AAEjB,SAAS,eAAe,KAAwB;CAC9C,IAA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AI,gBAAgB;CACpC,MAAM,OAAO;CAEb,OAAO;EADsB,QAAQ;EAAM,OAAO,QAAQ;CAChD;AACZ"}
|
package/dist/dsl/index.d.cts
CHANGED
|
@@ -3,8 +3,8 @@ import { Duration, EventMap, TimeOfDay, UserPropertyBase, Weekday } from "./base
|
|
|
3
3
|
import { EventRef, EventRefs, MessageArgs, PayloadRef, PayloadRefNode, PayloadRefs, PropInput, PropsInput, UserPropertyRef, UserRefs, event, user } from "./refs.cjs";
|
|
4
4
|
import { Channel, EmptyProps, PropsOf, TemplateFactory, TemplateRef, TemplateRefTable, TemplateRefs, TemplateRegistry, template, templates } 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
|
-
import { BranchArm, BranchCase, EmitArgs, EmitPayload, Flow, FlowBuilder, PushOptions, SubFlow, flow } from "./flow.cjs";
|
|
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 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 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 };
|
package/dist/dsl/index.d.mts
CHANGED
|
@@ -3,8 +3,8 @@ import { Duration, EventMap, TimeOfDay, UserPropertyBase, Weekday } from "./base
|
|
|
3
3
|
import { EventRef, EventRefs, MessageArgs, PayloadRef, PayloadRefNode, PayloadRefs, PropInput, PropsInput, UserPropertyRef, UserRefs, event, user } from "./refs.mjs";
|
|
4
4
|
import { Channel, EmptyProps, PropsOf, TemplateFactory, TemplateRef, TemplateRefTable, TemplateRefs, TemplateRegistry, template, templates } 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
|
-
import { BranchArm, BranchCase, EmitArgs, EmitPayload, Flow, FlowBuilder, PushOptions, SubFlow, flow } from "./flow.mjs";
|
|
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 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 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 };
|
package/dist/index.d.cts
CHANGED
|
@@ -5,7 +5,7 @@ import { Duration, EventMap, TimeOfDay, UserPropertyBase, Weekday } from "./dsl/
|
|
|
5
5
|
import { EventRef, EventRefs, MessageArgs, PayloadRef, PayloadRefNode, PayloadRefs, PropInput, PropsInput, UserPropertyRef, UserRefs, event, user } from "./dsl/refs.cjs";
|
|
6
6
|
import { Channel, EmptyProps, PropsOf, TemplateFactory, TemplateRef, TemplateRefTable, TemplateRefs, TemplateRegistry, template, templates } from "./dsl/template.cjs";
|
|
7
7
|
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 "./dsl/condition.cjs";
|
|
8
|
-
import { BranchArm, BranchCase, EmitArgs, EmitPayload, Flow, FlowBuilder, PushOptions, SubFlow, flow } from "./dsl/flow.cjs";
|
|
8
|
+
import { BranchArm, BranchCase, EmitArgs, EmitPayload, Flow, FlowBuilder, PreferOptions, PushOptions, SubFlow, flow } from "./dsl/flow.cjs";
|
|
9
9
|
import { DateTime, EventTriggerOptions, TriggerFactory, TriggerRef, trigger } from "./dsl/trigger.cjs";
|
|
10
10
|
import { GoalOptions, WorkflowBuilder, WorkflowDefinition, workflow } from "./dsl/workflow.cjs";
|
|
11
11
|
import { compileBundle } from "./dsl/bundle.cjs";
|
|
@@ -15,4 +15,4 @@ import { JourneyMode, JourneyRuntimeConfig, JourneyRuntimeOptions, resolveRuntim
|
|
|
15
15
|
import { ApnsConfig, ConfigCompileError, DatabaseConfig, EmailAddress, EmailConfig, FcmConfig, JourneyConfig, JourneyConfigDefinition, WebPushConfig, apnsEnvironment, compileConfig, defineConfig, formatEmailAddress, isConfig } from "./config.cjs";
|
|
16
16
|
import { canonicalJSON, fullHash, semanticHash, sha256Hex, stripMeta, stripProvenance } from "./hash.cjs";
|
|
17
17
|
import { BundlePlan, ChangeStatus, NodeChange, ResourceChange, WorkflowChange, isSemanticChange, plan } from "./plan.cjs";
|
|
18
|
-
export { type ActionContext, type ActionHandler, ActionIR, type ActionRef, AnyTemplate, ApnsConfig, type BranchArm, type BranchCase, BundleIR, BundlePlan, ChangeStatus, type Channel, ChannelIR, type Condition, ConditionIR, ConfigCompileError, Contract, ContractDefinition, ContractIssue, ContractResult, ContractValidationError, DatabaseConfig, type DateTime, DeclaredOutput, DiscordContent, DiscordTemplate, type Duration, DurationIR, EmailAddress, EmailConfig, EmailTemplate, EmailTemplateDefinition, type EmitArgs, type EmitPayload, type EmptyProps, type EventMap, EventPayload, type EventRef, type EventRefs, type EventTriggerOptions, FcmConfig, type Flow, type FlowBuilder, GoalIR, type GoalOptions, IR_VERSION, JourneyConfig, JourneyConfigDefinition, JourneyMode, JourneyRuntimeConfig, JourneyRuntimeOptions, type MessageArgs, MetaIR, NodeChange, NodeIR, NodeMetaIR, type PayloadRef, type PayloadRefNode, type PayloadRefs, type PayloadWhere, type PerformedOptions, ProfilePatch, type PropInput, PropValueIR, PropertyOperatorIR, type PropsInput, type PropsOf, PropsSchema, PushContent, type PushOptions, PushTemplate, PushTemplateDefinition, ResolvedProps, ResourceChange, ScalarIR, type SegmentDefinition, SegmentIR, type SegmentRef, SlackContent, SlackTemplate, SourceLocIR, type SubFlow, TemplateChannel, type TemplateFactory, TemplateIR, TemplateIssue, type TemplateRef, type TemplateRefTable, type TemplateRefs, type TemplateRegistry, TemplateValidationError, type TimeOfDay, type TriggerFactory, TriggerIR, type TriggerRef, type UserPropertyBase, type UserPropertyRef, UserPropertyRefIR, type UserRefs, WebPushConfig, WebhookTemplateDefinition, type Weekday, WeekdayIR, type WorkflowBuilder, WorkflowChange, type WorkflowDefinition, WorkflowIR, action, and, apnsEnvironment, assertSupportedSchema, between, canonicalJSON, checkEvent, compileBundle, compileConfig, contains, defineConfig, defineContract, discordTemplate, emailTemplate, eq, event, exists, flow, formatEmailAddress, fullHash, gt, gte, inArray, isConfig, isContract, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSemanticChange, isSlackTemplate, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, parseTemplateProps, performed, plan, pushTemplate, reachable, registryValidator, renderDiscordContent, renderPushContent, renderSlackContent, resolveRuntime, segment, semanticHash, sha256Hex, slackTemplate, stripMeta, stripProvenance, template, templates, trigger, user, workflow };
|
|
18
|
+
export { type ActionContext, type ActionHandler, ActionIR, type ActionRef, AnyTemplate, ApnsConfig, type BranchArm, type BranchCase, BundleIR, BundlePlan, ChangeStatus, type Channel, ChannelIR, type Condition, ConditionIR, ConfigCompileError, Contract, ContractDefinition, ContractIssue, ContractResult, ContractValidationError, DatabaseConfig, type DateTime, DeclaredOutput, DiscordContent, DiscordTemplate, type Duration, DurationIR, EmailAddress, EmailConfig, EmailTemplate, EmailTemplateDefinition, type EmitArgs, type EmitPayload, type EmptyProps, type EventMap, EventPayload, type EventRef, type EventRefs, type EventTriggerOptions, FcmConfig, type Flow, type FlowBuilder, GoalIR, type GoalOptions, IR_VERSION, JourneyConfig, JourneyConfigDefinition, JourneyMode, JourneyRuntimeConfig, JourneyRuntimeOptions, type MessageArgs, MetaIR, NodeChange, NodeIR, NodeMetaIR, type PayloadRef, type PayloadRefNode, type PayloadRefs, type PayloadWhere, type PerformedOptions, type PreferOptions, ProfilePatch, type PropInput, PropValueIR, PropertyOperatorIR, type PropsInput, type PropsOf, PropsSchema, PushContent, type PushOptions, PushTemplate, PushTemplateDefinition, ResolvedProps, ResourceChange, ScalarIR, type SegmentDefinition, SegmentIR, type SegmentRef, SlackContent, SlackTemplate, SourceLocIR, type SubFlow, TemplateChannel, type TemplateFactory, TemplateIR, TemplateIssue, type TemplateRef, type TemplateRefTable, type TemplateRefs, type TemplateRegistry, TemplateValidationError, type TimeOfDay, type TriggerFactory, TriggerIR, type TriggerRef, type UserPropertyBase, type UserPropertyRef, UserPropertyRefIR, type UserRefs, WebPushConfig, WebhookTemplateDefinition, type Weekday, WeekdayIR, type WorkflowBuilder, WorkflowChange, type WorkflowDefinition, WorkflowIR, action, and, apnsEnvironment, assertSupportedSchema, between, canonicalJSON, checkEvent, compileBundle, compileConfig, contains, defineConfig, defineContract, discordTemplate, emailTemplate, eq, event, exists, flow, formatEmailAddress, fullHash, gt, gte, inArray, isConfig, isContract, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSemanticChange, isSlackTemplate, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, parseTemplateProps, performed, plan, pushTemplate, reachable, registryValidator, renderDiscordContent, renderPushContent, renderSlackContent, resolveRuntime, segment, semanticHash, sha256Hex, slackTemplate, stripMeta, stripProvenance, template, templates, trigger, user, workflow };
|
package/dist/index.d.mts
CHANGED
|
@@ -5,7 +5,7 @@ import { Duration, EventMap, TimeOfDay, UserPropertyBase, Weekday } from "./dsl/
|
|
|
5
5
|
import { EventRef, EventRefs, MessageArgs, PayloadRef, PayloadRefNode, PayloadRefs, PropInput, PropsInput, UserPropertyRef, UserRefs, event, user } from "./dsl/refs.mjs";
|
|
6
6
|
import { Channel, EmptyProps, PropsOf, TemplateFactory, TemplateRef, TemplateRefTable, TemplateRefs, TemplateRegistry, template, templates } from "./dsl/template.mjs";
|
|
7
7
|
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 "./dsl/condition.mjs";
|
|
8
|
-
import { BranchArm, BranchCase, EmitArgs, EmitPayload, Flow, FlowBuilder, PushOptions, SubFlow, flow } from "./dsl/flow.mjs";
|
|
8
|
+
import { BranchArm, BranchCase, EmitArgs, EmitPayload, Flow, FlowBuilder, PreferOptions, PushOptions, SubFlow, flow } from "./dsl/flow.mjs";
|
|
9
9
|
import { DateTime, EventTriggerOptions, TriggerFactory, TriggerRef, trigger } from "./dsl/trigger.mjs";
|
|
10
10
|
import { GoalOptions, WorkflowBuilder, WorkflowDefinition, workflow } from "./dsl/workflow.mjs";
|
|
11
11
|
import { compileBundle } from "./dsl/bundle.mjs";
|
|
@@ -15,4 +15,4 @@ import { JourneyMode, JourneyRuntimeConfig, JourneyRuntimeOptions, resolveRuntim
|
|
|
15
15
|
import { ApnsConfig, ConfigCompileError, DatabaseConfig, EmailAddress, EmailConfig, FcmConfig, JourneyConfig, JourneyConfigDefinition, WebPushConfig, apnsEnvironment, compileConfig, defineConfig, formatEmailAddress, isConfig } from "./config.mjs";
|
|
16
16
|
import { canonicalJSON, fullHash, semanticHash, sha256Hex, stripMeta, stripProvenance } from "./hash.mjs";
|
|
17
17
|
import { BundlePlan, ChangeStatus, NodeChange, ResourceChange, WorkflowChange, isSemanticChange, plan } from "./plan.mjs";
|
|
18
|
-
export { type ActionContext, type ActionHandler, ActionIR, type ActionRef, AnyTemplate, ApnsConfig, type BranchArm, type BranchCase, BundleIR, BundlePlan, ChangeStatus, type Channel, ChannelIR, type Condition, ConditionIR, ConfigCompileError, Contract, ContractDefinition, ContractIssue, ContractResult, ContractValidationError, DatabaseConfig, type DateTime, DeclaredOutput, DiscordContent, DiscordTemplate, type Duration, DurationIR, EmailAddress, EmailConfig, EmailTemplate, EmailTemplateDefinition, type EmitArgs, type EmitPayload, type EmptyProps, type EventMap, EventPayload, type EventRef, type EventRefs, type EventTriggerOptions, FcmConfig, type Flow, type FlowBuilder, GoalIR, type GoalOptions, IR_VERSION, JourneyConfig, JourneyConfigDefinition, JourneyMode, JourneyRuntimeConfig, JourneyRuntimeOptions, type MessageArgs, MetaIR, NodeChange, NodeIR, NodeMetaIR, type PayloadRef, type PayloadRefNode, type PayloadRefs, type PayloadWhere, type PerformedOptions, ProfilePatch, type PropInput, PropValueIR, PropertyOperatorIR, type PropsInput, type PropsOf, PropsSchema, PushContent, type PushOptions, PushTemplate, PushTemplateDefinition, ResolvedProps, ResourceChange, ScalarIR, type SegmentDefinition, SegmentIR, type SegmentRef, SlackContent, SlackTemplate, SourceLocIR, type SubFlow, TemplateChannel, type TemplateFactory, TemplateIR, TemplateIssue, type TemplateRef, type TemplateRefTable, type TemplateRefs, type TemplateRegistry, TemplateValidationError, type TimeOfDay, type TriggerFactory, TriggerIR, type TriggerRef, type UserPropertyBase, type UserPropertyRef, UserPropertyRefIR, type UserRefs, WebPushConfig, WebhookTemplateDefinition, type Weekday, WeekdayIR, type WorkflowBuilder, WorkflowChange, type WorkflowDefinition, WorkflowIR, action, and, apnsEnvironment, assertSupportedSchema, between, canonicalJSON, checkEvent, compileBundle, compileConfig, contains, defineConfig, defineContract, discordTemplate, emailTemplate, eq, event, exists, flow, formatEmailAddress, fullHash, gt, gte, inArray, isConfig, isContract, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSemanticChange, isSlackTemplate, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, parseTemplateProps, performed, plan, pushTemplate, reachable, registryValidator, renderDiscordContent, renderPushContent, renderSlackContent, resolveRuntime, segment, semanticHash, sha256Hex, slackTemplate, stripMeta, stripProvenance, template, templates, trigger, user, workflow };
|
|
18
|
+
export { type ActionContext, type ActionHandler, ActionIR, type ActionRef, AnyTemplate, ApnsConfig, type BranchArm, type BranchCase, BundleIR, BundlePlan, ChangeStatus, type Channel, ChannelIR, type Condition, ConditionIR, ConfigCompileError, Contract, ContractDefinition, ContractIssue, ContractResult, ContractValidationError, DatabaseConfig, type DateTime, DeclaredOutput, DiscordContent, DiscordTemplate, type Duration, DurationIR, EmailAddress, EmailConfig, EmailTemplate, EmailTemplateDefinition, type EmitArgs, type EmitPayload, type EmptyProps, type EventMap, EventPayload, type EventRef, type EventRefs, type EventTriggerOptions, FcmConfig, type Flow, type FlowBuilder, GoalIR, type GoalOptions, IR_VERSION, JourneyConfig, JourneyConfigDefinition, JourneyMode, JourneyRuntimeConfig, JourneyRuntimeOptions, type MessageArgs, MetaIR, NodeChange, NodeIR, NodeMetaIR, type PayloadRef, type PayloadRefNode, type PayloadRefs, type PayloadWhere, type PerformedOptions, type PreferOptions, ProfilePatch, type PropInput, PropValueIR, PropertyOperatorIR, type PropsInput, type PropsOf, PropsSchema, PushContent, type PushOptions, PushTemplate, PushTemplateDefinition, ResolvedProps, ResourceChange, ScalarIR, type SegmentDefinition, SegmentIR, type SegmentRef, SlackContent, SlackTemplate, SourceLocIR, type SubFlow, TemplateChannel, type TemplateFactory, TemplateIR, TemplateIssue, type TemplateRef, type TemplateRefTable, type TemplateRefs, type TemplateRegistry, TemplateValidationError, type TimeOfDay, type TriggerFactory, TriggerIR, type TriggerRef, type UserPropertyBase, type UserPropertyRef, UserPropertyRefIR, type UserRefs, WebPushConfig, WebhookTemplateDefinition, type Weekday, WeekdayIR, type WorkflowBuilder, WorkflowChange, type WorkflowDefinition, WorkflowIR, action, and, apnsEnvironment, assertSupportedSchema, between, canonicalJSON, checkEvent, compileBundle, compileConfig, contains, defineConfig, defineContract, discordTemplate, emailTemplate, eq, event, exists, flow, formatEmailAddress, fullHash, gt, gte, inArray, isConfig, isContract, isDiscordTemplate, isEmailTemplate, isPushTemplate, isSemanticChange, isSlackTemplate, lt, lte, ne, not, notBetween, notContains, notExists, notInArray, or, parseTemplateProps, performed, plan, pushTemplate, reachable, registryValidator, renderDiscordContent, renderPushContent, renderSlackContent, resolveRuntime, segment, semanticHash, sha256Hex, slackTemplate, stripMeta, stripProvenance, template, templates, trigger, user, workflow };
|
package/dist/store/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/store/index.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport type { BundleIR, ConditionIR, ScalarIR, WorkflowIR } from '../ir';\n\n/**\n * The journey engine's data plane as a port. Everything the ingest router, the\n * runner and the fact source persist or look up goes through this interface,\n * so the storage engine is a deployment choice: D1 + KV (`D1JourneyStore`,\n * the original), Postgres (`PostgresJourneyStore`), or anything else that can\n * satisfy the contract below. Execution (durable steps, sleeps, wake-ups) is\n * the workflow runtime's job and stays out of here.\n *\n * Timestamps are epoch milliseconds throughout; a store may persist them in\n * its native type as long as `sinceMs` comparisons behave.\n */\n\n/**\n * A profile patch or a stored profile. On the way in, `null` means \"remove\n * this property\" (RFC 7386 merge-patch, the only way the API has to unset\n * one); a stored profile never contains null.\n */\nexport type ProfileProps = Record<string, ScalarIR | null | undefined>;\n\nexport interface EventInput {\n /** The occurrence's identity, chosen by the sender; a second insert with the same id is a no-op. */\n id: string;\n userId: string;\n event: string;\n ts: number;\n payload: Record<string, unknown>;\n}\n\nexport interface TriggerRoute {\n workflow: string;\n hash: string;\n /** Payload gate (payload-only condition tree), or null when the trigger has none. */\n where: ConditionIR | null;\n /** Profile gate, or null. */\n filter: ConditionIR | null;\n}\n\nexport interface SegmentTriggerRoute {\n workflow: string;\n hash: string;\n segment: string;\n}\n\nexport interface EntryInput {\n workflow: string;\n userId: string;\n instanceId: string;\n hash: string;\n ts: number;\n}\n\n/**\n * How an entry attempt ended: a fresh row, a 'failed' row of a dead instance\n * taken over (the once policy does not bar a user over one outage), or\n * refused because the pair already entered and is still alive.\n */\nexport type EntryOutcome = 'entered' | 'reclaimed' | null;\n\n/** A device registered for pushes: its provider token belongs to the user who registered it last. */\nexport interface DeviceInput {\n userId: string;\n token: string;\n /** `ios` (APNs) or `android` (FCM): which provider the token belongs to. */\n platform: string;\n ts: number;\n}\n\n/** A store plus how to release what opening it acquired (a connection, say). */\nexport interface StoreLease {\n store: JourneyStore;\n close?: () => Promise<void>;\n}\n\n/**\n * The live database lacks tables or columns the engine reads (an SDK upgrade added them, or the\n * host never ran the migration). Raised before a deploy writes anything.\n */\nexport class SchemaMismatchError extends Error {\n override readonly name = 'SchemaMismatchError';\n\n constructor(readonly problems: readonly string[]) {\n super(\n `the database does not match @shware/workflow's tables — regenerate the drizzle schema (workflow-ui generate) and run your migrations:\\n ${problems.join('\\n ')}`\n );\n }\n}\n\n/** A message copy as reporting records it, before it goes out. */\nexport interface MessageRecord {\n idempotencyKey: string;\n workflow: string;\n instanceId: string;\n nodeId: string;\n template: string;\n /** Where the copy lands: `email`, `push_ios`, `push_android`. */\n channel: string;\n userId: string;\n sentAt: number;\n}\n\n/** What a click is judged by. */\nexport interface ClickContext {\n url: string;\n deliveredAt: number;\n linkCount: number;\n /** The copy's clicks in the window before this one. */\n recent: { position: number; at: number }[];\n}\n\n/** An open or a click, with the verdict on who made it and where it came from. */\nexport interface Engagement {\n at: number;\n machine: boolean;\n /** The rule that called it a machine; null for a person. */\n reason: string | null;\n userAgent: string | null;\n /** The network the request came from (Cloudflare's `cf.asn`, `cf.asOrganization`, `cf.country`), never the address. */\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\n/**\n * Journey reporting: where each instance stands, every copy and how it was engaged with, segment\n * sizes. A store that keeps it (Postgres) exposes it as `reporting`; the Worker then records it\n * and serves email tracking. Every write is idempotent — a retried step reports again.\n */\n/** Bounds on when an event happened, both inclusive (epoch ms); an absent side is open. */\nexport interface EventWindow {\n sinceMs?: number;\n untilMs?: number;\n}\n\nexport interface JourneyReporting {\n /** The instance entered: its row exists from here, so one a guard ends at once still counts. */\n instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void>;\n nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void>;\n instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void>;\n /** The copy's row id; the row a retry already wrote, when there is one. */\n recordMessage(message: MessageRecord): Promise<string>;\n settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void>;\n /** An email's tracked links, in document order. */\n recordLinks(messageId: string, urls: readonly string[]): Promise<void>;\n /**\n * Record an open of the copy, judged by `judge` against the copy (its recipient and when it was\n * delivered — when it was sent, before the transport answered); `undefined` from the judge\n * records nothing. Read and written in one transaction. False for an unknown copy.\n */\n recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean>;\n /**\n * Record a click on the copy's link at `position`, judged by `judge` against the link, how\n * many links the copy has and its clicks of the last `windowMs`. The copy is locked for the\n * transaction, so clicks arriving together (a scanner following every link at once) are\n * judged one after another, each seeing the ones before. When the judge asks to `backdate`,\n * the window's earlier clicks are reclassified with this one's verdict. A click implies an\n * open. Undefined for an unknown link.\n */\n recordClick(\n messageId: string,\n position: number,\n at: number,\n windowMs: number,\n judge: (link: ClickContext) => { engagement: Engagement; backdate: boolean }\n ): Promise<{ url: string; engagement: Engagement } | undefined>;\n /** The email copy's recipient opted out of email: recorded on the copy and as a suppression. False for an unknown copy. */\n recordUnsubscribe(messageId: string, at: number): Promise<boolean>;\n /** A push copy the device reported it received. False for an unknown copy. */\n recordDeviceDelivered(messageId: string, at: number): Promise<boolean>;\n /** Drop members of segments no longer deployed, then record every deployed segment's size. */\n snapshotSegments(at: number): Promise<{ segment: string; size: number }[]>;\n}\n\nexport interface JourneyStore {\n /** Reporting, when the store keeps it (Postgres); D1 stores none. */\n readonly reporting?: JourneyReporting;\n\n /**\n * Record that the user's data must go (a deleted account), before anything is erased: the\n * request outlives a failure to stop their instances, and the sweep retries it.\n */\n requestErasure(userId: string, at: number): Promise<void>;\n /** Users whose erasure was requested and not finished yet. */\n pendingErasures(): Promise<string[]>;\n /** The user's journey instances still running, by the entry ledger. */\n runningInstances(userId: string): Promise<string[]>;\n /**\n * Erase everything kept about the user — profile, devices, events, wake subscriptions, segment\n * memberships, suppressions, entries and reporting — and the erasure request last. Run only\n * once no instance of theirs runs any more, or one could write some of it back.\n */\n forgetUser(userId: string): Promise<void>;\n\n /** The user opted out of the channel (recorded by an unsubscribe); stores without reporting omit it. */\n isSuppressed?(userId: string, channel: string): Promise<boolean>;\n\n /**\n * What the live database lacks against the engine's tables (read-only); a deploy refuses to\n * run while it lists anything. Stores whose schema the engine owns (D1) omit it.\n */\n checkSchema?(): Promise<string[]>;\n\n /* ---------------------------------- events --------------------------------- */\n /** Append the occurrence; false when its id was already in the log (nothing written). */\n insertEvent(input: EventInput): Promise<boolean>;\n /** Occurrences of `event` for the user, optionally only those within the window. */\n countEvents(userId: string, event: string, window?: EventWindow): Promise<number>;\n /** The payloads of those occurrences — the caller filters them with the shared evaluator. */\n listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]>;\n\n /* --------------------------------- profiles -------------------------------- */\n getProfile(userId: string): Promise<ProfileProps | undefined>;\n /**\n * Merge-patch `props` into the stored profile in one statement (a null\n * removes the property) and return the result. One statement, because a\n * read-modify-write loses one of two concurrent identifies.\n */\n mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps>;\n\n /** Every user the engine knows (a profile or an event): who the segment sweep evaluates. */\n listUserIds(): Promise<string[]>;\n\n /* ---------------------------------- devices --------------------------------- */\n /** The user's push devices, most recently registered first. */\n listDevices(userId: string): Promise<PushDevice[]>;\n /**\n * Register a device: one row per token, so a token registered again moves to the user who\n * registered it last (a phone signed into another account) and to the front of their list.\n */\n upsertDevice(device: DeviceInput): Promise<void>;\n /** Forget a token (reported dead by APNs / FCM); the user it belonged to, if any. */\n removeDevice(token: string): Promise<string | undefined>;\n /**\n * The user signed out on the device: the token is kept, bound to nobody, until the next sign-in\n * binds it again. The user it belonged to, if any.\n */\n unbindDevice(token: string): Promise<string | undefined>;\n\n /* ---------------------------- deployed definitions -------------------------- */\n getSegmentCondition(id: string): Promise<ConditionIR | undefined>;\n /** Every deployed segment with its definition: what the segment sweep evaluates. */\n listSegments(): Promise<{ id: string; condition: ConditionIR }[]>;\n findTriggers(event: string): Promise<TriggerRoute[]>;\n listSegmentTriggers(): Promise<SegmentTriggerRoute[]>;\n putWorkflowIR(workflow: WorkflowIR): Promise<void>;\n getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined>;\n /**\n * Swap the routing tables (segments, event triggers, segment triggers) for\n * the bundle's — atomically, so a concurrent ingest never sees them half\n * empty. Workflow bodies are stored separately (`putWorkflowIR`) because they\n * are content-addressed and outlive the routes that point at them.\n */\n replaceRoutes(bundle: BundleIR): Promise<void>;\n\n /* ----------------------------- segment membership --------------------------- */\n isSegmentMember(segment: string, userId: string): Promise<boolean>;\n /** Record the membership, with the workflows its entry has to start (see segment_start). */\n addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void>;\n /** The workflows the member's entry has not started yet. */\n pendingSegmentStarts(segment: string, userId: string): Promise<string[]>;\n completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void>;\n /** Drop the membership and any start it still owed. */\n removeSegmentMember(segment: string, userId: string): Promise<void>;\n\n /* ------------------------------- entry ledger ------------------------------- */\n /**\n * Record the entry (the once policy). Atomic under concurrent ingests: of\n * two racing attempts exactly one is 'entered' (or 'reclaimed', when the\n * pair's previous instance is recorded as 'failed') and the other null.\n */\n enterJourney(entry: EntryInput): Promise<EntryOutcome>;\n removeEntry(instanceId: string): Promise<void>;\n setEntryStatus(instanceId: string, status: string): Promise<void>;\n\n /* ------------------------------ wake subscriptions --------------------------- */\n /** Distinct wake handles registered for (user, event). */\n findWakeHandles(userId: string, event: string): Promise<string[]>;\n /** Register the handle for each event; repeated registrations are idempotent. */\n subscribe(handle: string, userId: string, events: readonly string[], ts: number): Promise<void>;\n /** Drop every registration the handle holds. */\n unsubscribe(handle: string): Promise<void>;\n}\n\nexport { D1JourneyStore } from './d1';\nexport { JourneyFactSource } from './facts';\nexport { PostgresJourneyStore } from './postgres';\nexport { PostgresReporting } from './postgres-reporting';\nexport {\n DEFAULT_SCHEMA,\n TABLES,\n renderDrizzleSchema,\n renderPostgresDdl,\n type TableSpec,\n} from './tables';\nexport type { PostgresJourneyStoreOptions, SqlClientLike } from './postgres';\n"],"mappings":";;;;;;;;;;;AAgFA,IAAa,sBAAb,cAAyC,MAAM;CAGxB;CAFrB,OAAyB;CAEzB,YAAY,UAAsC;EAChD,MACE,4IAA4I,SAAS,KAAK,MAAM,GAClK;EAHmB,KAAA,WAAA;CAIrB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/store/index.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport type { BundleIR, ConditionIR, ScalarIR, WorkflowIR } from '../ir';\n\n/**\n * The journey engine's data plane as a port. Everything the ingest router, the\n * runner and the fact source persist or look up goes through this interface,\n * so the storage engine is a deployment choice: D1 + KV (`D1JourneyStore`,\n * the original), Postgres (`PostgresJourneyStore`), or anything else that can\n * satisfy the contract below. Execution (durable steps, sleeps, wake-ups) is\n * the workflow runtime's job and stays out of here.\n *\n * Timestamps are epoch milliseconds throughout; a store may persist them in\n * its native type as long as `sinceMs` comparisons behave.\n */\n\n/**\n * A profile patch or a stored profile. On the way in, `null` means \"remove\n * this property\" (RFC 7386 merge-patch, the only way the API has to unset\n * one); a stored profile never contains null.\n */\nexport type ProfileProps = Record<string, ScalarIR | null | undefined>;\n\nexport interface EventInput {\n /** The occurrence's identity, chosen by the sender; a second insert with the same id is a no-op. */\n id: string;\n userId: string;\n event: string;\n ts: number;\n payload: Record<string, unknown>;\n}\n\nexport interface TriggerRoute {\n workflow: string;\n hash: string;\n /** Payload gate (payload-only condition tree), or null when the trigger has none. */\n where: ConditionIR | null;\n /** Profile gate, or null. */\n filter: ConditionIR | null;\n}\n\nexport interface SegmentTriggerRoute {\n workflow: string;\n hash: string;\n segment: string;\n}\n\n/**\n * A Worker version, as Cloudflare's version metadata binding names it: the bundle compiled into\n * that version goes live only over an older one (`replaceRoutesIfNewer`).\n */\nexport interface BundleVersion {\n id: string;\n /** When the version was created (epoch ms): later versions are newer. */\n createdAt: number;\n}\n\nexport interface EntryInput {\n workflow: string;\n userId: string;\n instanceId: string;\n hash: string;\n ts: number;\n}\n\n/**\n * How an entry attempt ended: a fresh row, a 'failed' row of a dead instance\n * taken over (the once policy does not bar a user over one outage), or\n * refused because the pair already entered and is still alive.\n */\nexport type EntryOutcome = 'entered' | 'reclaimed' | null;\n\n/** A device registered for pushes: its provider token belongs to the user who registered it last. */\nexport interface DeviceInput {\n userId: string;\n token: string;\n /** `ios` (APNs) or `android` (FCM): which provider the token belongs to. */\n platform: string;\n ts: number;\n}\n\n/** A store plus how to release what opening it acquired (a connection, say). */\nexport interface StoreLease {\n store: JourneyStore;\n close?: () => Promise<void>;\n}\n\n/**\n * The live database lacks tables or columns the engine reads (an SDK upgrade added them, or the\n * host never ran the migration). Raised before a deploy writes anything.\n */\nexport class SchemaMismatchError extends Error {\n override readonly name = 'SchemaMismatchError';\n\n constructor(readonly problems: readonly string[]) {\n super(\n `the database does not match @shware/workflow's tables — regenerate the drizzle schema (workflow-ui generate) and run your migrations:\\n ${problems.join('\\n ')}`\n );\n }\n}\n\n/** A message copy as reporting records it, before it goes out. */\nexport interface MessageRecord {\n idempotencyKey: string;\n workflow: string;\n instanceId: string;\n nodeId: string;\n template: string;\n /** Where the copy lands: `email`, `push_ios`, `push_android`. */\n channel: string;\n userId: string;\n sentAt: number;\n}\n\n/** What a click is judged by. */\nexport interface ClickContext {\n url: string;\n deliveredAt: number;\n linkCount: number;\n /** The copy's clicks in the window before this one. */\n recent: { position: number; at: number }[];\n}\n\n/** An open or a click, with the verdict on who made it and where it came from. */\nexport interface Engagement {\n at: number;\n machine: boolean;\n /** The rule that called it a machine; null for a person. */\n reason: string | null;\n userAgent: string | null;\n /** The network the request came from (Cloudflare's `cf.asn`, `cf.asOrganization`, `cf.country`), never the address. */\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\n/**\n * Journey reporting: where each instance stands, every copy and how it was engaged with, segment\n * sizes. A store that keeps it (Postgres) exposes it as `reporting`; the Worker then records it\n * and serves email tracking. Every write is idempotent — a retried step reports again.\n */\n/** Bounds on when an event happened, both inclusive (epoch ms); an absent side is open. */\nexport interface EventWindow {\n sinceMs?: number;\n untilMs?: number;\n}\n\nexport interface JourneyReporting {\n /** The instance entered: its row exists from here, so one a guard ends at once still counts. */\n instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void>;\n nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void>;\n instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void>;\n /** The copy's row id; the row a retry already wrote, when there is one. */\n recordMessage(message: MessageRecord): Promise<string>;\n settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void>;\n /** An email's tracked links, in document order. */\n recordLinks(messageId: string, urls: readonly string[]): Promise<void>;\n /**\n * Record an open of the copy, judged by `judge` against the copy (its recipient and when it was\n * delivered — when it was sent, before the transport answered); `undefined` from the judge\n * records nothing. Read and written in one transaction. False for an unknown copy.\n */\n recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean>;\n /**\n * Record a click on the copy's link at `position`, judged by `judge` against the link, how\n * many links the copy has and its clicks of the last `windowMs`. The copy is locked for the\n * transaction, so clicks arriving together (a scanner following every link at once) are\n * judged one after another, each seeing the ones before. When the judge asks to `backdate`,\n * the window's earlier clicks are reclassified with this one's verdict. A click implies an\n * open. Undefined for an unknown link.\n */\n recordClick(\n messageId: string,\n position: number,\n at: number,\n windowMs: number,\n judge: (link: ClickContext) => { engagement: Engagement; backdate: boolean }\n ): Promise<{ url: string; engagement: Engagement } | undefined>;\n /** The email copy's recipient opted out of email: recorded on the copy and as a suppression. False for an unknown copy. */\n recordUnsubscribe(messageId: string, at: number): Promise<boolean>;\n /** A push copy the device reported it received. False for an unknown copy. */\n recordDeviceDelivered(messageId: string, at: number): Promise<boolean>;\n /** Drop members of segments no longer deployed, then record every deployed segment's size. */\n snapshotSegments(at: number): Promise<{ segment: string; size: number }[]>;\n}\n\nexport interface JourneyStore {\n /** Reporting, when the store keeps it (Postgres); D1 stores none. */\n readonly reporting?: JourneyReporting;\n\n /**\n * Record that the user's data must go (a deleted account), before anything is erased: the\n * request outlives a failure to stop their instances, and the sweep retries it.\n */\n requestErasure(userId: string, at: number): Promise<void>;\n /** Users whose erasure was requested and not finished yet. */\n pendingErasures(): Promise<string[]>;\n /** The user's journey instances still running, by the entry ledger. */\n runningInstances(userId: string): Promise<string[]>;\n /**\n * Erase everything kept about the user — profile, devices, events, wake subscriptions, segment\n * memberships, suppressions, entries and reporting — and the erasure request last. Run only\n * once no instance of theirs runs any more, or one could write some of it back.\n */\n forgetUser(userId: string): Promise<void>;\n\n /** The user opted out of the channel (recorded by an unsubscribe); stores without reporting omit it. */\n isSuppressed?(userId: string, channel: string): Promise<boolean>;\n\n /**\n * What the live database lacks against the engine's tables (read-only); a deploy refuses to\n * run while it lists anything. Stores whose schema the engine owns (D1) omit it.\n */\n checkSchema?(): Promise<string[]>;\n\n /* ---------------------------------- events --------------------------------- */\n /** Append the occurrence; false when its id was already in the log (nothing written). */\n insertEvent(input: EventInput): Promise<boolean>;\n /** Occurrences of `event` for the user, optionally only those within the window. */\n countEvents(userId: string, event: string, window?: EventWindow): Promise<number>;\n /** The payloads of those occurrences — the caller filters them with the shared evaluator. */\n listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]>;\n\n /* --------------------------------- profiles -------------------------------- */\n getProfile(userId: string): Promise<ProfileProps | undefined>;\n /**\n * Merge-patch `props` into the stored profile in one statement (a null\n * removes the property) and return the result. One statement, because a\n * read-modify-write loses one of two concurrent identifies.\n */\n mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps>;\n\n /** Every user the engine knows (a profile or an event): who the segment sweep evaluates. */\n listUserIds(): Promise<string[]>;\n\n /* ---------------------------------- devices --------------------------------- */\n /** The user's push devices, most recently registered first. */\n listDevices(userId: string): Promise<PushDevice[]>;\n /**\n * Register a device: one row per token, so a token registered again moves to the user who\n * registered it last (a phone signed into another account) and to the front of their list.\n */\n upsertDevice(device: DeviceInput): Promise<void>;\n /** Forget a token (reported dead by APNs / FCM); the user it belonged to, if any. */\n removeDevice(token: string): Promise<string | undefined>;\n /**\n * The user signed out on the device: the token is kept, bound to nobody, until the next sign-in\n * binds it again. The user it belonged to, if any.\n */\n unbindDevice(token: string): Promise<string | undefined>;\n\n /* ---------------------------- deployed definitions -------------------------- */\n getSegmentCondition(id: string): Promise<ConditionIR | undefined>;\n /** Every deployed segment with its definition: what the segment sweep evaluates. */\n listSegments(): Promise<{ id: string; condition: ConditionIR }[]>;\n findTriggers(event: string): Promise<TriggerRoute[]>;\n listSegmentTriggers(): Promise<SegmentTriggerRoute[]>;\n putWorkflowIR(workflow: WorkflowIR): Promise<void>;\n getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined>;\n /**\n * Swap the routing tables (segments, event triggers, segment triggers) for\n * the bundle's — atomically, so a concurrent ingest never sees them half\n * empty. Workflow bodies are stored separately (`putWorkflowIR`) because they\n * are content-addressed and outlive the routes that point at them.\n */\n replaceRoutes(bundle: BundleIR): Promise<void>;\n /**\n * The Worker version whose bundle the routes came from, when one put them there through\n * `replaceRoutesIfNewer` (a forced deploy leaves it as it was). Read from the database itself,\n * not a cache in front of it. Stores without it (D1) leave every deploy to `POST /bundle/deploy`.\n */\n liveBundleVersion?(): Promise<BundleVersion | undefined>;\n /**\n * `replaceRoutes`, only when `version` is newer than the live one, recorded in the same\n * transaction: two versions serving side by side during a rollout cannot leave the older one's\n * routes in force. False, with nothing written, when a version as new or newer is live.\n */\n replaceRoutesIfNewer?(bundle: BundleIR, version: BundleVersion): Promise<boolean>;\n\n /* ----------------------------- segment membership --------------------------- */\n isSegmentMember(segment: string, userId: string): Promise<boolean>;\n /** Record the membership, with the workflows its entry has to start (see segment_start). */\n addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void>;\n /** The workflows the member's entry has not started yet. */\n pendingSegmentStarts(segment: string, userId: string): Promise<string[]>;\n completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void>;\n /** Drop the membership and any start it still owed. */\n removeSegmentMember(segment: string, userId: string): Promise<void>;\n\n /* ------------------------------- entry ledger ------------------------------- */\n /**\n * Record the entry (the once policy). Atomic under concurrent ingests: of\n * two racing attempts exactly one is 'entered' (or 'reclaimed', when the\n * pair's previous instance is recorded as 'failed') and the other null.\n */\n enterJourney(entry: EntryInput): Promise<EntryOutcome>;\n removeEntry(instanceId: string): Promise<void>;\n setEntryStatus(instanceId: string, status: string): Promise<void>;\n\n /* ------------------------------ wake subscriptions --------------------------- */\n /** Distinct wake handles registered for (user, event). */\n findWakeHandles(userId: string, event: string): Promise<string[]>;\n /** Register the handle for each event; repeated registrations are idempotent. */\n subscribe(handle: string, userId: string, events: readonly string[], ts: number): Promise<void>;\n /** Drop every registration the handle holds. */\n unsubscribe(handle: string): Promise<void>;\n}\n\nexport { D1JourneyStore } from './d1';\nexport { JourneyFactSource } from './facts';\nexport { PostgresJourneyStore } from './postgres';\nexport { PostgresReporting } from './postgres-reporting';\nexport {\n DEFAULT_SCHEMA,\n TABLES,\n renderDrizzleSchema,\n renderPostgresDdl,\n type TableSpec,\n} from './tables';\nexport type { PostgresJourneyStoreOptions, SqlClientLike } from './postgres';\n"],"mappings":";;;;;;;;;;;AA0FA,IAAa,sBAAb,cAAyC,MAAM;CAGxB;CAFrB,OAAyB;CAEzB,YAAY,UAAsC;EAChD,MACE,4IAA4I,SAAS,KAAK,MAAM,GAClK;EAHmB,KAAA,WAAA;CAIrB;AACF"}
|