@whitewall/blip-sdk 0.0.191 → 0.0.193

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/cjs/client.js.map +1 -1
  2. package/dist/cjs/index.js +2 -0
  3. package/dist/cjs/index.js.map +1 -1
  4. package/dist/cjs/types/flow.js +46 -8
  5. package/dist/cjs/types/flow.js.map +1 -1
  6. package/dist/cjs/utils/builder.js +34 -34
  7. package/dist/cjs/utils/builder.js.map +1 -1
  8. package/dist/cjs/utils/flow-rules.js +304 -0
  9. package/dist/cjs/utils/flow-rules.js.map +1 -0
  10. package/dist/cjs/utils/minifier.js +410 -0
  11. package/dist/cjs/utils/minifier.js.map +1 -0
  12. package/dist/esm/client.js.map +1 -1
  13. package/dist/esm/index.js +2 -0
  14. package/dist/esm/index.js.map +1 -1
  15. package/dist/esm/types/flow.js +40 -6
  16. package/dist/esm/types/flow.js.map +1 -1
  17. package/dist/esm/utils/builder.js +31 -30
  18. package/dist/esm/utils/builder.js.map +1 -1
  19. package/dist/esm/utils/flow-rules.js +297 -0
  20. package/dist/esm/utils/flow-rules.js.map +1 -0
  21. package/dist/esm/utils/minifier.js +405 -0
  22. package/dist/esm/utils/minifier.js.map +1 -0
  23. package/dist/types/client.d.ts +2 -1
  24. package/dist/types/client.d.ts.map +1 -1
  25. package/dist/types/index.d.ts +2 -0
  26. package/dist/types/index.d.ts.map +1 -1
  27. package/dist/types/namespaces/account.d.ts +20 -20
  28. package/dist/types/types/flow.d.ts +286 -96
  29. package/dist/types/types/flow.d.ts.map +1 -1
  30. package/dist/types/utils/builder.d.ts +33 -30
  31. package/dist/types/utils/builder.d.ts.map +1 -1
  32. package/dist/types/utils/flow-rules.d.ts +50 -0
  33. package/dist/types/utils/flow-rules.d.ts.map +1 -0
  34. package/dist/types/utils/minifier.d.ts +2857 -0
  35. package/dist/types/utils/minifier.d.ts.map +1 -0
  36. package/package.json +1 -1
  37. package/src/client.ts +2 -1
  38. package/src/index.ts +2 -0
  39. package/src/types/flow.ts +52 -6
  40. package/src/utils/builder.ts +61 -73
  41. package/src/utils/flow-rules.ts +453 -0
  42. package/src/utils/minifier.ts +505 -0
@@ -0,0 +1,453 @@
1
+ /**
2
+ * Everything the Builder runtime refuses to run, checked against a minified flow.
3
+ *
4
+ * A port of the runtime's own validation — `Models/Flow.cs::Validate`,
5
+ * `Models/Condition.cs::Validate`, `Models/Input.cs::Validate` and the media type
6
+ * each action deserializes. All of them throw at load or mid-turn, and the runtime
7
+ * validates the whole flow on every message, so one of these takes the bot down
8
+ * for every user rather than breaking one branch.
9
+ *
10
+ * The line is deliberate: this file only holds what makes the runtime throw. A
11
+ * flow that is merely suspect — a quick reply nothing matches, a variable nobody
12
+ * writes — parses fine here, because that is a linter's job and a schema can only
13
+ * say "invalid" where a linter can say "warning".
14
+ *
15
+ * It is one pass over the whole flow, wired into `minifiedFlowSchema` alone. Zod
16
+ * skips a `.check()` on a value that already has issues, so a check per action and
17
+ * a check per state would report the innermost problem and hide the rest.
18
+ */
19
+
20
+ import type { Condition } from '../types/flow.ts'
21
+ import { CUSTOM_ACTION_LISTS, inputOf, ROOT_STATE_ID, resolveEntryPointId } from '../types/flow.ts'
22
+ import type { MinifiedAction, MinifiedInput, MinifiedState } from './minifier.ts'
23
+
24
+ /** Every rule this file can report. */
25
+ export type FlowRule =
26
+ | 'missing-root-state'
27
+ | 'root-must-wait'
28
+ | 'dangling-output'
29
+ | 'input-less-loop'
30
+ | 'transition-loop'
31
+ | 'shadowed-output'
32
+ | 'invalid-condition'
33
+ | 'invalid-input-validation'
34
+ | 'invalid-regex'
35
+ | 'invalid-variable-name'
36
+ | 'unreadable-variable'
37
+ | 'malformed-placeholder'
38
+ | 'missing-media-type'
39
+ | 'content-type-mismatch'
40
+ | 'duplicate-title'
41
+
42
+ /** Reports a failure, tagged with the rule so a caller can group or suppress. */
43
+ export type ReportRule = (rule: FlowRule, path: Array<string | number>, message: string) => void
44
+
45
+ /**
46
+ * The rule a zod issue came from, if it came from one of these checks.
47
+ *
48
+ * The id travels in the issue's `params`, which zod types as `Record<string, any>`,
49
+ * so reading it through here is what keeps `FlowRule` meaning anything on the way
50
+ * out — a caller that reaches into `params` itself gets `any` back.
51
+ */
52
+ export function flowRuleOf(issue: { code: string; params?: Record<string, unknown> }): FlowRule | undefined {
53
+ const rule = issue.code === 'custom' ? issue.params?.rule : undefined
54
+
55
+ return typeof rule === 'string' ? (rule as FlowRule) : undefined
56
+ }
57
+
58
+ type Path = Array<string | number>
59
+
60
+ const UNARY_COMPARISONS = new Set(['exists', 'notExists'])
61
+
62
+ /** `Models/Input.cs`: the runtime rejects an input variable outside this set. */
63
+ const INPUT_VARIABLE_PATTERN = /^[a-zA-Z0-9.]+$/
64
+
65
+ /** `Utils/VariableReplacer.cs`: the only shape the runtime substitutes. */
66
+ const VARIABLE_ALPHABET = '[a-zA-Z0-9.@_-]'
67
+ export const VARIABLE_NAME = new RegExp(`^${VARIABLE_ALPHABET}+$`)
68
+
69
+ /** Anything brace-wrapped, so the shapes the replacer skips can be reported too. */
70
+ const PLACEHOLDER_PATTERN = /{{([^{}]*)}}/g
71
+
72
+ /** `ContextBase.cs`: what `VariableName.Parse` accepts before the `@`. */
73
+ const READABLE_NAME_PATTERN = /^[\w\d]+(\.[\w\d.]+)?$/
74
+
75
+ const MEDIA_TYPE_PATTERN = /^[a-z]+\/[\w.+-]+$/i
76
+
77
+ /** `Variables/VariableSource.cs`: a name whose first segment is one of these reads a provider. */
78
+ export const PROVIDER_NAMESPACES = new Set([
79
+ 'contact',
80
+ 'calendar',
81
+ 'random',
82
+ 'bucket',
83
+ 'config',
84
+ 'input',
85
+ 'state',
86
+ 'tunnel',
87
+ 'application',
88
+ 'ticket',
89
+ 'resource',
90
+ 'aianswers',
91
+ 'secret',
92
+ 'blipfunction',
93
+ 'aiagent',
94
+ ])
95
+
96
+ /** `Models/Flow.cs`: an output names a state, or a `{{variable}}` resolved at runtime. */
97
+ export const isVariableOutput = (stateId: string) => stateId.startsWith('{{') && stateId.endsWith('}}')
98
+
99
+ /**
100
+ * `Models/Flow.cs::Validate`, walked in one pass so every problem in the flow is
101
+ * reported at once.
102
+ */
103
+ export function checkFlow(flow: Record<string, MinifiedState>, report: ReportRule): void {
104
+ checkEntryPoint(flow, report)
105
+
106
+ const titles = new Map<string, string>()
107
+
108
+ for (const [stateId, state] of Object.entries(flow)) {
109
+ // The runtime keys states by id and does not care, but the builder
110
+ // addresses them by title, so a duplicate hides one on the canvas.
111
+ const title = state.$title.toLowerCase()
112
+ const duplicate = titles.get(title)
113
+
114
+ if (duplicate) {
115
+ report(
116
+ 'duplicate-title',
117
+ [stateId, '$title'],
118
+ `Duplicate state title '${state.$title}', already used by '${duplicate}'`,
119
+ )
120
+ } else {
121
+ titles.set(title, stateId)
122
+ }
123
+
124
+ for (const [output, path] of outputsOf(state)) {
125
+ if (!isVariableOutput(output.stateId) && !(output.stateId in flow)) {
126
+ report(
127
+ 'dangling-output',
128
+ [stateId, ...path, 'stateId'],
129
+ `'${output.stateId}' is not a state in this flow, and is not a {{variable}}`,
130
+ )
131
+ }
132
+ }
133
+
134
+ checkLoops(stateId, state, flow, report)
135
+ checkState(stateId, state, report)
136
+ }
137
+ }
138
+
139
+ /** `Models/Flow.cs`: one entry point, and it has to wait for an input. */
140
+ function checkEntryPoint(flow: Record<string, MinifiedState>, report: ReportRule): void {
141
+ const declared = Object.values(flow).filter((state) => state.root).length
142
+
143
+ if (declared > 1) {
144
+ report(
145
+ 'missing-root-state',
146
+ [],
147
+ `${declared} states are marked "root": true, and a flow can only have one entry point`,
148
+ )
149
+ return
150
+ }
151
+
152
+ const stateId = resolveEntryPointId(flow)
153
+
154
+ if (!stateId) {
155
+ report(
156
+ 'missing-root-state',
157
+ [],
158
+ `No state is marked "root": true, and there is no '${ROOT_STATE_ID}' state to fall back to`,
159
+ )
160
+ return
161
+ }
162
+
163
+ const input = inputOf(flow[stateId])
164
+
165
+ if (!input || input.bypass) {
166
+ report(
167
+ 'root-must-wait',
168
+ [stateId],
169
+ 'The entry point has to wait for an input: give it an input that is not bypassed',
170
+ )
171
+ }
172
+
173
+ if (input?.conditions?.length) {
174
+ report('root-must-wait', [stateId], "The entry point's input must not have conditions")
175
+ }
176
+ }
177
+
178
+ /** What one state decides on its own, plus its inputs and actions. */
179
+ function checkState(stateId: string, state: MinifiedState, report: ReportRule): void {
180
+ for (const [index, output] of state.$conditionOutputs.entries()) {
181
+ // `ConditionsExtensions.cs` returns true for an empty list, so an output
182
+ // with no conditions always matches and hides every output after it.
183
+ if (output.conditions.length === 0 && index < state.$conditionOutputs.length - 1) {
184
+ report(
185
+ 'shadowed-output',
186
+ [stateId, '$conditionOutputs', index],
187
+ `This output has no conditions, so it always matches and the ${
188
+ state.$conditionOutputs.length - index - 1
189
+ } output(s) after it can never run`,
190
+ )
191
+ }
192
+
193
+ for (const [conditionIndex, condition] of output.conditions.entries()) {
194
+ checkCondition(condition, [stateId, '$conditionOutputs', index, 'conditions', conditionIndex], report)
195
+ }
196
+ }
197
+
198
+ for (const [index, item] of state.$contentActions.entries()) {
199
+ if (item.input) {
200
+ checkInput(item.input, [stateId, '$contentActions', index, 'input'], report)
201
+ }
202
+ if (item.action) {
203
+ checkAction(item.action, [stateId, '$contentActions', index, 'action'], report)
204
+ }
205
+ }
206
+
207
+ for (const list of CUSTOM_ACTION_LISTS) {
208
+ for (const [index, action] of (state[list] ?? []).entries()) {
209
+ checkAction(action, [stateId, list, index], report)
210
+ }
211
+ }
212
+
213
+ checkVariableReads(stateId, state, report)
214
+ }
215
+
216
+ /** `Models/Condition.cs::Validate`, plus the regex the comparison would compile. */
217
+ function checkCondition(condition: Condition, path: Path, report: ReportRule): void {
218
+ if (condition.source === 'context' && !condition.variable) {
219
+ report('invalid-condition', path, 'A condition on the context has to name a variable')
220
+ }
221
+
222
+ const takesValues = !UNARY_COMPARISONS.has(condition.comparison)
223
+
224
+ if (takesValues !== condition.values.length > 0) {
225
+ report(
226
+ 'invalid-condition',
227
+ [...path, 'values'],
228
+ takesValues
229
+ ? `'${condition.comparison}' has no values to compare against`
230
+ : `'${condition.comparison}' is rejected by the runtime when values are provided`,
231
+ )
232
+ }
233
+
234
+ if (condition.comparison === 'matches') {
235
+ for (const [index, value] of condition.values.entries()) {
236
+ checkRegex(value, [...path, 'values', index], report)
237
+ }
238
+ }
239
+ }
240
+
241
+ /** `Models/Input.cs::Validate`. */
242
+ function checkInput(input: MinifiedInput, path: Path, report: ReportRule): void {
243
+ if (input.variable && !INPUT_VARIABLE_PATTERN.test(input.variable)) {
244
+ report(
245
+ 'invalid-variable-name',
246
+ [...path, 'variable'],
247
+ `'${input.variable}' is rejected by the runtime: letters, numbers and dots only`,
248
+ )
249
+ }
250
+
251
+ if (input.validation) {
252
+ const { rule, regex, type, error } = input.validation
253
+
254
+ if (rule === 'regex' && !regex) {
255
+ report('invalid-input-validation', [...path, 'validation', 'regex'], "The 'regex' rule needs a regex")
256
+ }
257
+
258
+ if (rule === 'type' && !type) {
259
+ report('invalid-input-validation', [...path, 'validation', 'type'], "The 'type' rule needs a media type")
260
+ }
261
+
262
+ // Required for every rule, not just regex.
263
+ if (!error.trim()) {
264
+ report(
265
+ 'invalid-input-validation',
266
+ [...path, 'validation', 'error'],
267
+ 'The validation needs the message to send when the answer does not pass',
268
+ )
269
+ }
270
+
271
+ if (regex) {
272
+ checkRegex(regex, [...path, 'validation', 'regex'], report)
273
+ }
274
+ }
275
+
276
+ for (const [index, condition] of (input.conditions ?? []).entries()) {
277
+ checkCondition(condition, [...path, 'conditions', index], report)
278
+ }
279
+ }
280
+
281
+ /** What each action needs before the runtime will run it. */
282
+ function checkAction(action: MinifiedAction, path: Path, report: ReportRule): void {
283
+ for (const [index, condition] of (action.conditions ?? []).entries()) {
284
+ checkCondition(condition, [...path, 'conditions', index], report)
285
+ }
286
+
287
+ if (action.type !== 'SendMessage' && action.type !== 'SendRawMessage') {
288
+ return
289
+ }
290
+
291
+ const { type } = action.settings
292
+
293
+ if (!type) {
294
+ report('missing-media-type', [...path, 'settings', 'type'], `A ${action.type} action requires a settings.type`)
295
+ return
296
+ }
297
+
298
+ if (action.type === 'SendRawMessage') {
299
+ if (!MEDIA_TYPE_PATTERN.test(type)) {
300
+ report('missing-media-type', [...path, 'settings', 'type'], `'${type}' is not a valid media type`)
301
+ }
302
+ return
303
+ }
304
+
305
+ // `SendMessageAction.cs` deserializes a `+json` content into a dictionary,
306
+ // which throws on a string. The plain branch stringifies whatever it gets, so
307
+ // only the document types are worth checking.
308
+ if (type !== 'text/plain' && typeof action.settings.content !== 'object') {
309
+ report(
310
+ 'content-type-mismatch',
311
+ [...path, 'settings', 'content'],
312
+ `A '${type}' message needs an object as its content`,
313
+ )
314
+ }
315
+ }
316
+
317
+ /**
318
+ * A state that can be reached again without the user ever answering.
319
+ *
320
+ * `Flow.cs` walks this transitively and refuses to load the flow when the state
321
+ * has no input element at all; a state whose only way out is itself burns the ten
322
+ * transitions an input is allowed and throws mid-turn. A bypassed state that has
323
+ * another way out is left alone: paging through a shrinking variable is a real
324
+ * pattern, and it terminates.
325
+ */
326
+ function checkLoops(
327
+ stateId: string,
328
+ state: MinifiedState,
329
+ flow: Record<string, MinifiedState>,
330
+ report: ReportRule,
331
+ ): void {
332
+ const input = inputOf(state)
333
+
334
+ if (input && !input.bypass) {
335
+ return
336
+ }
337
+
338
+ if (outputsOf(state).every(([output]) => output.stateId === stateId)) {
339
+ report(
340
+ 'transition-loop',
341
+ [stateId],
342
+ 'Every output leads back to this state and it does not wait for an input, so the runtime loops until it hits the transition limit',
343
+ )
344
+ return
345
+ }
346
+
347
+ if (input) {
348
+ return
349
+ }
350
+
351
+ const seen = new Set([stateId])
352
+ const pending = [stateId]
353
+
354
+ while (pending.length > 0) {
355
+ for (const [output] of outputsOf(flow[pending.pop()!])) {
356
+ if (output.stateId === stateId) {
357
+ report(
358
+ 'input-less-loop',
359
+ [stateId],
360
+ 'This state has no input and can be reached again without the user ever answering, which the runtime refuses to load',
361
+ )
362
+ return
363
+ }
364
+
365
+ const next = flow[output.stateId]
366
+
367
+ if (!next || seen.has(output.stateId)) {
368
+ continue
369
+ }
370
+
371
+ // A state that waits for an answer breaks the chain.
372
+ const nextInput = inputOf(next)
373
+
374
+ if (!nextInput || nextInput.bypass) {
375
+ seen.add(output.stateId)
376
+ pending.push(output.stateId)
377
+ }
378
+ }
379
+ }
380
+ }
381
+
382
+ /**
383
+ * Every `{{reference}}` a state carries, deduped, with script sources masked out:
384
+ * a script's braces are a doc comment or a nested object literal, not a read.
385
+ */
386
+ export function placeholderReadsOf(state: MinifiedState): Array<string> {
387
+ const readable = JSON.stringify(state, (_key, value) =>
388
+ value?.type === 'ExecuteScript' || value?.type === 'ExecuteScriptV2'
389
+ ? { ...value, settings: { ...value.settings, source: '' } }
390
+ : value,
391
+ )
392
+
393
+ return [...new Set([...readable.matchAll(PLACEHOLDER_PATTERN)].map((match) => match[1]))]
394
+ }
395
+
396
+ /**
397
+ * A `{{...}}` the replacer will not substitute reaches the user with its braces
398
+ * showing, and one it substitutes but `VariableName.Parse` throws on aborts the
399
+ * turn instead of resolving to an empty string.
400
+ */
401
+ function checkVariableReads(stateId: string, state: MinifiedState, report: ReportRule): void {
402
+ for (const reference of placeholderReadsOf(state)) {
403
+ if (!VARIABLE_NAME.test(reference)) {
404
+ report(
405
+ 'malformed-placeholder',
406
+ [stateId],
407
+ `'{{${reference}}}' is not a name the runtime substitutes${
408
+ reference !== reference.trim() ? ' (spaces are not allowed inside the braces)' : ''
409
+ }, so it is sent as written`,
410
+ )
411
+ continue
412
+ }
413
+
414
+ const name = reference.split('@')[0]
415
+ const namespace = name.split('.')[0]
416
+
417
+ if (PROVIDER_NAMESPACES.has(namespace.toLowerCase())) {
418
+ continue
419
+ }
420
+
421
+ if (!READABLE_NAME_PATTERN.test(name)) {
422
+ report(
423
+ 'unreadable-variable',
424
+ [stateId],
425
+ `'{{${name}}}' cannot be parsed by the runtime — a hyphen is the usual cause — and reading it aborts the turn`,
426
+ )
427
+ } else if (name.includes('.')) {
428
+ report(
429
+ 'unreadable-variable',
430
+ [stateId],
431
+ `'{{${name}}}' looks like a provider read, but '${namespace}' is not one, so reading it aborts the turn. A context variable cannot contain a dot`,
432
+ )
433
+ }
434
+ }
435
+ }
436
+
437
+ function checkRegex(pattern: string, path: Path, report: ReportRule): void {
438
+ try {
439
+ new RegExp(pattern)
440
+ } catch {
441
+ report('invalid-regex', path, `'${pattern}' is not a valid regular expression`)
442
+ }
443
+ }
444
+
445
+ function outputsOf(state: MinifiedState): Array<[{ stateId: string }, Path]> {
446
+ return [
447
+ [state.$defaultOutput, ['$defaultOutput']],
448
+ ...state.$conditionOutputs.map((output, index): [{ stateId: string }, Path] => [
449
+ output,
450
+ ['$conditionOutputs', index],
451
+ ]),
452
+ ]
453
+ }