# **Context:** Flow API spec: Used to create a ServiceNow Flow (`sys_hub_flow`) — a workflow-as-code automation that reacts to triggers and executes actions. Flows are defined in TypeScript using the Fluent `Flow()` function from `@servicenow/sdk/automation`

```typescript
// Creates a Flow (`sys_hub_flow`)
// Import from @servicenow/sdk/automation, NOT @servicenow/sdk/core
import { Flow, FlowStage, wfa, trigger, action } from '@servicenow/sdk/automation'

Flow(
    // 1. Flow definition config
    {
        $id: Now.ID['my_flow'], // string | Now.ID key, mandatory — unique identifier
        name: '',               // string, mandatory — display name of the flow
        description: '',        // string, optional — purpose description
        runAs: 'system',        // 'system' | 'user', optional — execution context (default: 'system' since SDK v4.5.0, was 'user' before)
        runWithRoles: [],       // (string | Role)[], optional — roles to run flow with
        flowPriority: 'LOW',    // 'LOW' | 'MEDIUM' | 'HIGH', optional — execution priority
        protection: 'read',     // 'read' | '', optional — 'read' makes flow read-protected
        flowVariables: {},      // Record<string, FlowValueType>, optional — typed flow-level variables accessible throughout the flow body
        stages: {               // Record<string, FlowStage>, optional (SDK v4.7.0+) — named stages for progress tracking (`sys_hub_flow_stage`)
            // <key>: FlowStage({ label, value, duration?, alwaysShow?, states? }) — value must match the property key; activate in body via wfa.stage(params.stages.<key>)
        },
    },
    // 2. Trigger instance — created via wfa.trigger()
    wfa.trigger(
        trigger.record.created,              // TriggerDefinition — the built-in trigger type (see below)
        { $id: Now.ID['my_trigger'] },       // { $id: string }, mandatory — unique id for this trigger instance
        { table: 'incident', condition: '' } // TriggerInputTypes — inputs required by the trigger
    ),
    // 3. Flow body — callback receiving params.trigger (trigger outputs) and params.flowVariables
    (params) => {
        // Use wfa.action(), wfa.flowLogic.*, wfa.dataPill() inside here
    }
)

// ─── BUILT-IN TRIGGERS (import { trigger } from '@servicenow/sdk/automation') ───

// Record triggers
trigger.record.created          // fires when a record is inserted
trigger.record.updated          // fires when a record is updated
trigger.record.createdOrUpdated // fires on insert or update

// Scheduled triggers
trigger.scheduled.daily         // runs once per day
trigger.scheduled.weekly        // runs once per week
trigger.scheduled.monthly       // runs once per month
trigger.scheduled.repeat        // repeats on a defined interval
trigger.scheduled.runOnce       // runs exactly once at a specified time

// Application triggers
trigger.application.inboundEmail        // fires on inbound email events
trigger.application.remoteTableQuery    // fires for remote table query events
trigger.application.knowledgeManagement // fires for knowledge management events
trigger.application.slaTask             // fires for SLA task events

// Service Catalog trigger (SDK 4.4.0)
trigger.application.serviceCatalog // fires when a catalog item request item is created

// ─── TRIGGER INPUTS (vary by trigger type) ───
// Shape for record triggers:
const _recordTriggerInputs = {
    table: '',          // string (TableName), mandatory — the table to watch
    condition: '',      // string, optional — encoded query condition to filter which records fire the trigger
    run_flow_in: 'background', // 'any' | 'background' | 'foreground', optional
}

// Shape for scheduled.daily:
const _dailyTriggerInputs = {
    time: '00:00:00',   // string, optional — time of day to run (HH:MM:SS)
}

// Shape for scheduled.repeat:
const _repeatTriggerInputs = {
    repeat: Duration({ hours: 1 }), // Duration, mandatory — repeat interval
}

// Shape for scheduled.runOnce:
const _runOnceTriggerInputs = {
    run_in: '', // string, mandatory — datetime string (YYYY-MM-DD HH:mm:ss)
}

// ─── FLOW ACTIONS (wfa.action) ───
// Syntax: wfa.action(action.core.<actionName>, { $id: Now.ID['step_id'] }, { ...inputs })

// Record operations
wfa.action(action.core.createRecord,  { $id: Now.ID['step'] }, { table_name: '', values: {} })
wfa.action(action.core.updateRecord,  { $id: Now.ID['step'] }, { table_name: '', record: dataPill, values: {} })
wfa.action(action.core.deleteRecord,  { $id: Now.ID['step'] }, { table_name: '', record: dataPill })
wfa.action(action.core.lookUpRecord,  { $id: Now.ID['step'] }, { table: '', conditions: '' })
wfa.action(action.core.lookUpRecords, { $id: Now.ID['step'] }, { table: '', conditions: '' })

// Communication
wfa.action(action.core.sendNotification, { $id: Now.ID['step'] }, { table_name: '', record: dataPill, notification: '' })
wfa.action(action.core.sendEmail,        { $id: Now.ID['step'] }, { ah_to: '', ah_subject: '', ah_body: '' })
wfa.action(action.core.sendSms,          { $id: Now.ID['step'] }, { recipients: [], message: '' })
wfa.action(action.core.askForApproval,   { $id: Now.ID['step'] }, { table: '', record: dataPill, approval_conditions: '' })

// Logging and utilities
wfa.action(action.core.log,        { $id: Now.ID['step'] }, { log_level: 'info', log_message: '' })
// For inline script logic in v4.6.0, define a Custom Action via Action() and invoke it
// from the flow with wfa.action(<yourCustomAction>, ...) — see the custom-action spec.

// Service Catalog actions (SDK 4.4.0)
wfa.action(action.core.getCatalogVariables,      { $id: Now.ID['step'] }, { requested_item: dataPill, template_catalog_item: '' })
wfa.action(action.core.createCatalogTask,        { $id: Now.ID['step'] }, { ah_requested_item: dataPill })
wfa.action(action.core.submitCatalogItemRequest, { $id: Now.ID['step'] }, { catalog_item: '' })

// ─── SUBFLOW INVOCATION (wfa.subflow) — SDK 4.5.0+ ───
// Invoke a defined Subflow from inside a Flow. As of SDK 4.6.0, also callable from inside another Subflow (subflow-of-subflow).
// In real code, import the exported subflow constant; example shape:
//   import { mySubflow } from '../subflows/my-subflow.now'
declare const mySubflow: any  // doc placeholder — replace with the imported subflow constant
wfa.subflow(mySubflow, { $id: Now.ID['call_subflow'] }, { inputKey: dataPill })

// ─── CUSTOM ACTION STEPS (wfa.action with a custom Action) — SDK 4.6.0+ ───
// Invoke a Custom Action (created via Action() in @servicenow/sdk/automation) as a flow step.
// See the custom-action spec/snippets for how to define one.
//   import { escalateIncident } from '../actions/escalate-incident.now'
declare const escalateIncident: any  // doc placeholder — replace with the imported custom action
wfa.action(escalateIncident, { $id: Now.ID['call_action'] }, { incident: dataPill, reason: 'Auto-escalate' })

// Cross-scope: when invoking a Subflow or Custom Action defined in another scope, declare it as
// an SDK dependency in now.config.json so the type definitions are available at build time.

// ─── FLOW LOGIC ───
wfa.flowLogic.if(
    { $id: Now.ID['check_cond'], condition: '' }, // condition: encoded query string or data pill expression
    () => { /* actions when true */ }
)
wfa.flowLogic.elseIf(
    { $id: Now.ID['check_cond2'], condition: '' },
    () => { /* actions */ }
)
wfa.flowLogic.else(
    { $id: Now.ID['else_branch'] },
    () => { /* actions */ }
)
wfa.flowLogic.forEach(
    dataPill,                      // array data pill to iterate over
    { $id: Now.ID['loop_id'] },
    () => { /* loop body actions */ }
)
wfa.flowLogic.waitForADuration({
    $id: Now.ID['wait_id'],
    durationType: 'explicit_duration',
    duration: Duration({ minutes: 30 }),
})
wfa.flowLogic.exitLoop({ $id: Now.ID['exit_id'] })
wfa.flowLogic.endFlow({ $id: Now.ID['end_id'] }) // must sit inside an if/elseIf/else, forEach, doTheFollowing, doInParallel or (SDK v4.13.0+) tryCatch block —
    // a top-level endFlow is a build error (TS213 "End Flow must be used within a Do In Parallel, Do The Following, For Each, Try/Catch, or If block")
wfa.flowLogic.skipIteration({ $id: Now.ID['skip_id'] })

// ─── DO-WHILE RETRY LOOP — SDK v4.11.0+ (NEW construct, not a rename of anything) ───
// Repeats the body until an exit condition is met, with DO-WHILE semantics: the body ALWAYS runs at
// least once, and the condition is evaluated only AFTER each run — so it can reference outputs of
// actions declared inside the same body.
// NOTE the authored names are `doTheFollowing` + `until`. There is no `doTheFollowingUntil` function;
// that string appears only as a doc tag keyword.
wfa.flowLogic.doTheFollowing(
    { $id: Now.ID['do_until_id'], label: '', annotation: '' }, // { $id, label?: string, annotation?: string }
    () => {
        // loop body actions...
        // The condition MUST be the body's LAST statement, and must be CALLED, not returned:
        // omitting it, or using `return wfa.flowLogic.until(...)`, fails build-time validation.
        wfa.flowLogic.until('') // string condition; may embed wfa.dataPill(...) references
    }
)
// `doTheFollowing` counts as a loop construct, so exitLoop / skipIteration work inside its body
// exactly as inside forEach. endFlow inside the body still terminates the WHOLE flow, not the loop.
// Guard against infinite loops: because the condition is checked after the body, include a bounded
// signal (retry counter, timeout field, max-attempts flag). When polling, put a waitForADuration
// inside the body to avoid tight polling.

// ─── ERROR HANDLING & PARALLELISM — SDK v4.7.0+ (output hoisting SDK v4.13.0+) ───
// tryCatch: run a try block, run the catch block only if the try block errors. Blocks can be nested.
// Side-effect-only arms (no return, zero-arg catch) remain valid exactly as before.
wfa.flowLogic.tryCatch(
    { $id: Now.ID['tc_id'], annotation: '' }, // { $id: string, annotation?: string }
    {
        try: () => { /* actions to attempt */ },
        catch: () => { /* actions when the try block fails */ },
    }
)
// doInParallel: run two or more blocks in parallel. Cannot be nested inside another doInParallel.
wfa.flowLogic.doInParallel(
    { $id: Now.ID['parallel_id'], annotation: '' }, // { $id: string, annotation?: string }
    () => { /* block 1 */ },
    () => { /* block 2 */ } // ...one or more blocks; each may return void or an object of outputs
)

// ─── OUTPUT HOISTING out of tryCatch / doInParallel — SDK v4.13.0+ ───
// WARNING — CHANGED GUIDANCE: before SDK v4.13.0, action outputs inside a tryCatch/doInParallel block were NOT
// reachable outside it (the workaround was setFlowVariables). That limitation is RETIRED: a block can now RETURN
// the actions it wants to expose, and code after the block dot-walks them from the call's return value.
//   - doInParallel returns { output_0, output_1, … } — branch N's returned object, by POSITION (side-effect branch → {}).
//   - tryCatch returns the MERGED outputs of both arms directly (no output_N). The catch arm receives the try arm's
//     outputs as its single parameter (`tryOutputs`); never reference the outer const from inside an arm.
//   - Hoisting exists ONLY for these two: an action nested in if/elseIf/else/forEach/doTheFollowing is not exposed,
//     and only actions declared DIRECTLY in an arm/branch body can be returned.
// Build-verified rules (the SDK docs/JSDoc examples break the first two):
//   1. Write explicit property assignments: return { lookup: lookup }. The doc shorthand "return { lookup }" is a
//      build error (TS304 — shorthand properties are not allowed in Fluent files).
//   2. Give each exposed action an explicit string-literal `uuid` in its instance config. Without it, a catch-arm
//      reference (tryOutputs.lookup.X) fails with TS211 "Invalid pill reference", and outer references build but
//      emit a pill on the tryCatch/doInParallel CONTAINER instead of on the action.
//   3. An unused catch parameter fails the build (TS6133): omit it, or name it `_tryOutputs`.
//   4. endFlow may be used inside EITHER tryCatch arm (SDK v4.13.0+); see the endFlow note above.
const guarded = wfa.flowLogic.tryCatch(
    { $id: Now.ID['tc_hoist'] },
    {
        try: () => {
            const lookup = wfa.action(
                action.core.lookUpRecord,
                { $id: Now.ID['tc_hoist_lookup'], uuid: '00000000-0000-4000-8000-000000000001' }, // literal uuid: required to hoist
                { table: 'sys_user', conditions: 'active=true' }
            )
            return { lookup: lookup } // NOT the shorthand { lookup }
        },
        catch: (tryOutputs) => {
            wfa.action(action.core.log, { $id: Now.ID['tc_hoist_log'] }, {
                log_level: 'error',
                log_message: `${wfa.dataPill(tryOutputs.lookup.__action_status__.message, 'string')}`,
            })
            wfa.flowLogic.endFlow({ $id: Now.ID['tc_hoist_end'] }) // allowed inside a tryCatch arm
        },
    }
)
const parallel = wfa.flowLogic.doInParallel(
    { $id: Now.ID['dip_hoist'] },
    () => {
        const groupLookup = wfa.action(
            action.core.lookUpRecord,
            { $id: Now.ID['dip_hoist_lookup'], uuid: '00000000-0000-4000-8000-000000000002' },
            { table: 'sys_user_group', conditions: 'active=true' }
        )
        return { groupLookup: groupLookup } // branch 0 → parallel.output_0.groupLookup
    },
    () => { /* side-effect-only branch: exposes nothing */ }
)
// After the blocks: guarded.lookup.Record, guarded.lookup.__action_status__.message, parallel.output_0.groupLookup.Record
wfa.action(action.core.log, { $id: Now.ID['hoist_consumer'] }, {
    log_level: 'info',
    log_message: `${wfa.dataPill(guarded.lookup.Record, 'reference')} ${wfa.dataPill(parallel.output_0.groupLookup.Record, 'reference')}`,
})
// (Use real random UUIDs per action, e.g. from `uuidgen`; the zero-padded values above are placeholders.)
// appendToFlowVariables: append element(s) to an Array.Object flow variable
// (declared via FlowArray({ elementType: FlowObject(...) })). Pass params.flowVariables as the schema.
wfa.flowLogic.appendToFlowVariables(
    { $id: Now.ID['append_id'], annotation: '' },
    params.flowVariables,                 // the flow variables schema
    { collectedItems: { name: '', id: 0 } } // single element, array of elements, data pill, or template string
)

// ─── STAGE ACTIVATION (wfa.stage) — SDK v4.7.0+ ───
// Marks the start of a declared stage; all subsequent actions belong to it until the next wfa.stage() call.
wfa.stage(params.stages.triage) // params.stages.<key> must match a stage declared in the config `stages` object
// Signature: setFlowVariables(_definition, _variables, _values)
//   _definition — { $id: Now.ID['…'] }
//   _variables  — the FlowSchemaType returned by FlowVariables() in the parent flow config
//   _values     — partial record of variable assignments
wfa.flowLogic.setFlowVariables({ $id: Now.ID['set_vars'] }, flowVarSchema, { varName: '' })

// ─── DATA PILLS (wfa.dataPill) ───
// References output fields from previous steps, with type-safe dot-walking
wfa.dataPill(params.trigger.current.sys_id, 'reference')  // reference type data pill
wfa.dataPill(params.trigger.current.short_description, 'string')  // string type data pill
wfa.dataPill(params.trigger.current.additional_assignee_list, 'array.string') // array type

// ─── FLOW VARIABLES ───
// Declare typed variables in the config object; access them in body via params.flowVariables
import { StringColumn, IntegerColumn } from '@servicenow/sdk/core'
Flow(
    {
        $id: Now.ID['my_flow'],
        name: 'My Flow',
        flowVariables: {
            counter: IntegerColumn({ label: 'Counter' }),
            status: StringColumn({ label: 'Status' }),
        },
    },
    wfa.trigger(trigger.record.created, { $id: Now.ID['trigger'] }, { table: 'incident' }),
    (params) => {
        // params.flowVariables.counter, params.flowVariables.status are typed
    }
)
```
