{
  "version": 14,
  "name": "21_server_sent_events",
  "description": "Example: server-sent events (request sse). Covers the four ways a stream ends: the server closes it, after a number of events, after a time (not an error), and at a stop event; Events checks with JSON paths over the list ($.length, $[0].data..., $[*].event); the raw text in the body; and an event stream read with http() in code.\nAPIs: httpbingo.org/sse (a short stream that ends by itself), stream.wikimedia.org (live recent changes, endless; needs a User-Agent) and echo.websocket.org/.sse (a server event, an echo of the request, then the time every second).",
  "tags": [
    "example",
    "sse"
  ],
  "globals": [
    {
      "name": "$changes",
      "value": "https://stream.wikimedia.org/v2/stream/recentchange"
    },
    {
      "name": "$userAgent",
      "value": "CLEM-example/1.0 (https://clemflows.com)"
    },
    {
      "name": "$firstWiki",
      "value": ""
    },
    {
      "name": "$echoSse",
      "value": "https://echo.websocket.org/.sse"
    },
    {
      "name": "$finiteSse",
      "value": "https://httpbingo.org/sse"
    }
  ],
  "globalFunctions": "// Assertion helpers, built on check(label, pass, details).\n// Each records a pass / fail line in the log and the report.\n// A failed one fails its step when the step is done;\n// the code keeps running. Change them or add your own.\n// r defaults to the last response.\n\nfunction assertTrue(value, label = \"is true\") {\n  return check(label, Boolean(value), { actual: value, expected: true });\n}\n\nfunction assertEqual(actual, expected, label = \"equals \" + JSON.stringify(expected)) {\n  return check(label, isEqual(actual, expected), { actual, expected });\n}\n\nfunction assertNotEqual(actual, unexpected, label = \"does not equal \" + JSON.stringify(unexpected)) {\n  return check(label, !isEqual(actual, unexpected), { actual, expected: \"not \" + JSON.stringify(unexpected) });\n}\n\n// text contains a part, or a list contains an item\nfunction assertContains(haystack, needle, label = \"contains \" + JSON.stringify(needle)) {\n  const pass = Array.isArray(haystack) ? haystack.some((x) => isEqual(x, needle)) : String(haystack).includes(needle);\n  return check(label, pass, { actual: haystack, expected: needle });\n}\n\nfunction assertMatch(text, regex, label = \"matches \" + regex) {\n  return check(label, new RegExp(regex).test(String(text)), { actual: text, expected: String(regex) });\n}\n\nfunction assertLessThan(actual, limit, label = \"< \" + limit) {\n  return check(label, Number(actual) < Number(limit), { actual, expected: \"< \" + limit });\n}\n\nfunction assertGreaterThan(actual, limit, label = \"> \" + limit) {\n  return check(label, Number(actual) > Number(limit), { actual, expected: \"> \" + limit });\n}\n\n// expected: 200, \"2xx\", or a list such as [200, 201]\nfunction assertStatus(expected, r = response) {\n  const list = [].concat(expected).map(String);\n  const status = String(r && r.status);\n  const pass = list.some((e) => e === status || (/^[1-5]xx$/i.test(e) && e[0] === status[0]));\n  return check(\"status is \" + list.join(\" or \"), pass, { actual: r && r.status, expected });\n}\n\nfunction assertTimeBelow(ms, r = response) {\n  return check(\"time < \" + ms + \" ms\", Boolean(r) && r.timeMs < ms, { actual: r && r.timeMs, expected: \"< \" + ms });\n}\n\n// without expected, the header only has to exist\nfunction assertHeader(name, expected, r = response) {\n  const value = r ? r.headers[String(name).toLowerCase()] : undefined;\n  if (expected === undefined) return check(\"header \" + name + \" exists\", value !== undefined, { actual: value });\n  return check(\"header \" + name + \" equals \" + expected, String(value) === String(expected), { actual: value, expected });\n}\n\n// e.g. assertJsonPath(\"$.items[0].id\", 42); without expected, the value only has to exist\nfunction assertJsonPath(path, expected, r = response) {\n  const value = jsonPath(path, r);\n  if (expected === undefined) return check(path + \" exists\", value !== undefined, { actual: value });\n  return check(path + \" equals \" + JSON.stringify(expected), isEqual(value, expected), { actual: value, expected });\n}\n\n// schema: a JSON Schema object\nfunction assertSchema(schema, r = response) {\n  const result = validateSchema(r, schema);\n  return check(\"matches the JSON Schema\", result.valid, { error: result.errors || undefined });\n}\n",
  "libraries": [],
  "activeEnvironment": "",
  "auth": {
    "type": "none"
  },
  "settings": {},
  "data": {
    "file": ""
  },
  "cookies": [],
  "steps": [
    {
      "id": "closed",
      "type": "request",
      "name": "Read until the server closes",
      "conditional": "true",
      "method": "GET",
      "url": "$finiteSse",
      "params": [
        {
          "name": "count",
          "value": "3"
        },
        {
          "name": "duration",
          "value": "1s"
        }
      ],
      "headers": [],
      "bodyMode": "raw",
      "body": "",
      "multipart": [],
      "bodyFile": {
        "path": "",
        "contentType": ""
      },
      "followRedirects": true,
      "httpVersion": "inherit",
      "auth": {
        "type": "inherit"
      },
      "extract": [],
      "checks": [
        {
          "enabled": true,
          "target": "status",
          "path": "",
          "op": "equals",
          "value": "200"
        },
        {
          "enabled": true,
          "target": "events",
          "path": "$.length",
          "op": "equals",
          "value": "3"
        },
        {
          "enabled": true,
          "target": "events",
          "path": "$[*].event",
          "op": "contains",
          "value": "ping"
        },
        {
          "enabled": true,
          "target": "events",
          "path": "$[0].data.id",
          "op": "equals",
          "value": "0"
        },
        {
          "enabled": true,
          "target": "events",
          "path": "$[-1].data.id",
          "op": "equals",
          "value": "2"
        }
      ],
      "loop": {
        "enabled": false,
        "count": 5,
        "untilStatus": 200,
        "intervalMs": 1000
      },
      "saveResponse": {
        "enabled": false,
        "path": "",
        "onlyOk": true
      },
      "sse": {
        "enabled": true,
        "maxEvents": 0,
        "until": "",
        "waitMs": 10000
      }
    },
    {
      "id": "count",
      "type": "request",
      "name": "Stop after 5 events",
      "conditional": "true",
      "method": "GET",
      "url": "$changes",
      "params": [],
      "headers": [
        {
          "name": "User-Agent",
          "value": "$userAgent"
        }
      ],
      "bodyMode": "raw",
      "body": "",
      "multipart": [],
      "bodyFile": {
        "path": "",
        "contentType": ""
      },
      "followRedirects": true,
      "httpVersion": "inherit",
      "auth": {
        "type": "inherit"
      },
      "extract": [],
      "checks": [
        {
          "enabled": true,
          "target": "events",
          "path": "$.length",
          "op": "equals",
          "value": "5"
        },
        {
          "enabled": true,
          "target": "events",
          "path": "$[*].event",
          "op": "contains",
          "value": "message"
        },
        {
          "enabled": true,
          "target": "events",
          "path": "$[0].data.meta.stream",
          "op": "equals",
          "value": "mediawiki.recentchange"
        },
        {
          "enabled": true,
          "target": "events",
          "path": "$[-1].data.title",
          "op": "type",
          "value": "string"
        },
        {
          "enabled": true,
          "target": "body",
          "path": "",
          "op": "contains",
          "value": "data: {"
        }
      ],
      "loop": {
        "enabled": false,
        "count": 5,
        "untilStatus": 200,
        "intervalMs": 1000
      },
      "saveResponse": {
        "enabled": false,
        "path": "",
        "onlyOk": true
      },
      "sse": {
        "enabled": true,
        "maxEvents": 5,
        "until": "",
        "waitMs": 20000
      }
    },
    {
      "id": "time",
      "type": "request",
      "name": "Listen for 2 seconds",
      "conditional": "true",
      "method": "GET",
      "url": "$changes",
      "params": [],
      "headers": [
        {
          "name": "User-Agent",
          "value": "$userAgent"
        }
      ],
      "bodyMode": "raw",
      "body": "",
      "multipart": [],
      "bodyFile": {
        "path": "",
        "contentType": ""
      },
      "followRedirects": true,
      "httpVersion": "inherit",
      "auth": {
        "type": "inherit"
      },
      "extract": [],
      "checks": [
        {
          "enabled": true,
          "target": "status",
          "path": "",
          "op": "equals",
          "value": "200"
        },
        {
          "enabled": true,
          "target": "events",
          "path": "$.length",
          "op": "gte",
          "value": "1"
        }
      ],
      "loop": {
        "enabled": false,
        "count": 5,
        "untilStatus": 200,
        "intervalMs": 1000
      },
      "saveResponse": {
        "enabled": false,
        "path": "",
        "onlyOk": true
      },
      "sse": {
        "enabled": true,
        "maxEvents": 0,
        "until": "",
        "waitMs": 2000
      }
    },
    {
      "id": "until",
      "type": "request",
      "name": "Stop at the first time event",
      "conditional": "true",
      "method": "GET",
      "url": "$echoSse",
      "params": [],
      "headers": [],
      "bodyMode": "raw",
      "body": "",
      "multipart": [],
      "bodyFile": {
        "path": "",
        "contentType": ""
      },
      "followRedirects": true,
      "httpVersion": "inherit",
      "auth": {
        "type": "inherit"
      },
      "extract": [],
      "checks": [
        {
          "enabled": true,
          "target": "events",
          "path": "$[0].event",
          "op": "equals",
          "value": "server"
        },
        {
          "enabled": true,
          "target": "events",
          "path": "$[1].event",
          "op": "equals",
          "value": "request"
        },
        {
          "enabled": true,
          "target": "events",
          "path": "$[1].data",
          "op": "contains",
          "value": "Accept: text/event-stream"
        },
        {
          "enabled": true,
          "target": "events",
          "path": "$[-1].event",
          "op": "equals",
          "value": "time"
        },
        {
          "enabled": true,
          "target": "events",
          "path": "$.length",
          "op": "equals",
          "value": "3"
        }
      ],
      "loop": {
        "enabled": false,
        "count": 5,
        "untilStatus": 200,
        "intervalMs": 1000
      },
      "saveResponse": {
        "enabled": false,
        "path": "",
        "onlyOk": true
      },
      "sse": {
        "enabled": true,
        "maxEvents": 0,
        "until": "time",
        "waitMs": 10000
      }
    },
    {
      "id": "code",
      "type": "code",
      "name": "An event stream from code",
      "conditional": "true",
      "code": "const r = await http({\n  url: $echoSse,\n  sse: { enabled: true, maxEvents: 4, waitMs: 10000 },\n});\nconst times = r.events.filter((e) => e.event === \"time\").map((e) => e.data);\nlog(`${r.events.length} events; times: ${times.join(\", \")}`);\nassertEqual(r.stream.endedBy, \"count\", \"stopped after 4 events\");\nassertEqual(times.length, 2, \"two time events\");",
      "requests": []
    }
  ]
}
