/*----------------------------------------------------------------------------*/ /* */ /* Copyright (c) 2026 Rexx Language Association. All rights reserved. */ /* */ /* This program and the accompanying materials are made available under */ /* the terms of the Common Public License v1.0 which accompanies this */ /* distribution. A copy is also available at the following address: */ /* https://www.oorexx.org/license.html */ /* */ /*----------------------------------------------------------------------------*/ /* * fetch.cls: ADDRESS FETCH, HTTP from classic Rexx (ooRexx/WASM, browser and * Node). Written in Rexx on top of three pieces: the interpreter's * .CommandHandler (a command environment written in Rexx), js.cls (JavaScript's fetch()) and json.cls * (ooRexx's JSON reader and writer); commands are split by commandwords.cls, * shared with dom.cls. * * ::requires "fetch.cls" * address fetch * "HEADER Accept application/json" * "GET https://api.example.com/items" * if rc \= 0 then say "HTTP status" rc * "JSON INTO data" -- the body as ooRexx objects * do item over data["items"]; say item["name"]; end * "JSON items.1.name INTO first" -- or one value, by its path * * Commands: words separated by blanks, case does not matter; a word in * quotes ("..." or '...', the quote doubled inside) may hold blanks. Where * a value is expected, FROM name takes it from the variable name. A value * a command gives goes to the variable named by INTO name, anywhere after * the command's name (a stem, INTO name., gets lines as EXECIO does: name.0 * and name.1 ...); without INTO it is written to WITH OUTPUT, or to the * console. * * GET url, HEAD url, DELETE url a request; the response body (text) * [INTO var] to var, or to WITH OUTPUT as lines; * never to the console: unasked, a * body would flood it (it is kept, for * JSON, anyway) * POST url, PUT url, PATCH url the same, sending a body: the value * [[JSON] value] [INTO var] given (a word, or FROM var), or else * the WITH INPUT lines; JSON FROM var * sends var's objects as JSON text * (json.cls; Content-Type * application/json unless a HEADER * set one) * SAVE url file GET, the body (bytes) to a file * HEADER name value a request header for every request * from now on; HEADER name drops it; * HEADER RESET drops them all * TIMEOUT seconds give up on requests after this long * (0: never, the default) * STATUS [INTO var] the last response's status * HEADERS [INTO var] the last response's headers: a * StringTable (or "name: value" lines * for a stem and WITH OUTPUT) * HEADERS name [INTO var] one of them ("" when it is not there) * JSON [path] [INTO var] the last response body, read as JSON * by json.cls: a Directory for an * object, an Array for an array, a * string for a string or a number, * .JsonBoolean, .nil for null; a path * (names and 1-based indexes separated * by dots, results.1.name) picks one * value of it. Without INTO: strings * as they are, the rest as JSON text * * Redirection is part of the ADDRESS instruction, so a command that uses it * names the environment: address fetch "POST" url with input stem body. * (a bare '"POST" url with input stem body.' would be a concatenation). * * RC: 0 when all went well. Positive, and the ERROR condition, when the * command was right but the answer is not the expected one: the HTTP status * of a request that did not get a 2xx; 1 a JSON path that is not in the * body; 2 no body to read as JSON, or one that is not JSON, or no response * yet (HEADERS). Negative, and the FAILURE condition: -1 a network error * (no answer, CORS refusal, timeout; the reason on WITH ERROR or the * console); -3 an unknown command or wrong arguments; -4 SAVE cannot write * its file. SIGNAL ON ERROR / CALL ON FAILURE work as for any command. * * In the browser, requests are made by the Web Worker that runs ooRexx (the * page must grant it: js: {worker: true}); the page's origin rules (CORS) * apply, and its cookies go with requests to its own site. */ .CommandHandler~register("FETCH", .FetchHandler~new) ::requires "commandwords.cls" ::requires "js.cls" ::requires "json.cls" ::class FetchHandler public subclass CommandHandler ::method init expose headers timeout response text json headers = .stringTable~new timeout = 0 response = .nil; text = .nil; json = .nil ::method command use strict arg command, context words = .CommandWords~new(command) if words~error \== .nil then return self~bad(context, words~error) verb = words~take if verb == .nil then return self~bad(context, "a command is needed") verb = verb~upper into = words~takeInto select case verb when "GET", "HEAD", "DELETE", "POST", "PUT", "PATCH" then return self~request(verb, words, into, context) when "SAVE" then return self~save(words, into, context) when "HEADER" then return self~header(words, into, context) when "TIMEOUT" then return self~setTimeout(words, into, context) when "STATUS" then return self~status(words, into, context) when "HEADERS" then return self~responseHeaders(words, into, context) when "JSON" then return self~jsonValue(words, into, context) otherwise return self~bad(context, "unknown command" verb) end -- wrong command: the reason to the error output, FAILURE -3 ::method bad private use strict arg context, why .CommandIO~error(context, "FETCH:" why) return context~raiseFailure(-3) -- a value for INTO var, or to the output ::method give private use strict arg context, into, value if into == .nil then do if value~isA(.String) then .CommandIO~output(context, value) else if value~isA(.StringTable) then do -- headers lines = .array~new do name over value~allIndexes~sortWith(.caselessComparator~new) lines~append(name": "value[name]) end .CommandIO~output(context, lines) end else .CommandIO~output(context, .json~toJSON(value)) return 0 end if into~right(1) == "." then do -- a stem: lines, as EXECIO if value~isA(.String) then lines = value~makeArray("0a"x) else if value~isA(.StringTable) then do lines = .array~new do name over value~allIndexes~sortWith(.caselessComparator~new) lines~append(name": "value[name]) end end else lines = value~makeArray context~dropVar(into) do i = 1 to lines~items context~setVar(into || i, lines[i]) end context~setVar(into || "0", lines~items) return 0 end context~setVar(into, value) return 0 -- one request ::method request private expose response text json headers use strict arg method, words, into, context url = words~take if url == .nil then return self~bad(context, method": a URL is needed") body = .nil; type = .nil if wordPos(method, "POST PUT PATCH") > 0 then do if words~isKeyword(1, "JSON") then do words~take if words~items = 0 then return self~bad(context, method "JSON: a value is needed (FROM var)") data = words~takeValue(context) body = .json~toJSON(data) type = "application/json" end else if words~items > 0 then do body = words~takeValue(context) if body == .nil then return self~bad(context, method": the variable has no value") end else if context~isRedirected("Input") then body = .CommandIO~lines(context)~makeString("L", "0a"x) end if words~items > 0 then return self~bad(context, method": unexpected" words~rest~makeString("L", " ")) if \self~send(method, url, body, type, context) then return context~raiseFailure(-1) text = .nil; json = .nil if method \== "HEAD" then do text = response~text~await lines = text~makeArray("0a"x) do i = 1 to lines~items -- CRLF bodies: drop the CRs if lines[i]~right(1) == "0d"x then lines[i] = lines[i]~left(lines[i]~length - 1) end if into \== .nil then do if into~right(1) == "." then self~give(context, into, lines) else self~give(context, into, text) end -- only to WITH OUTPUT: unasked, a body would flood the console else if lines~items > 0 & context~isRedirected("Output") then .CommandIO~output(context, lines) end else if into \== .nil then return self~bad(context, "HEAD: no body for INTO") return self~result(context) -- GET to a file, as bytes ::method save private expose response text json use strict arg words, into, context url = words~take; file = words~take if url == .nil | file == .nil | words~items > 0 | into \== .nil then return self~bad(context, "SAVE: a URL and a file name are needed") if \self~send("GET", url, .nil, .nil, context) then return context~raiseFailure(-1) text = .nil; json = .nil bytes = response~arrayBuffer~await~js.byteString s = .stream~new(file) if s~open("write replace") \== "READY:" then do .CommandIO~error(context, "FETCH SAVE: cannot write" file) return context~raiseFailure(-4) end do s~charout(bytes) finally s~close end return self~result(context) -- fetch(); .false (and the reason to the error output) on a network error ::method send private expose headers timeout response use strict arg method, url, body, type, context init = .directory~new init["method"] = method -- JavaScript names: exact case h = .js~newObject(.directory~new) hasType = .false do name over headers h[name] = headers[name] if name~caselessEquals("Content-Type") then hasType = .true end if type \== .nil & \hasType then h["Content-Type"] = type init["headers"] = h if body \== .nil then init["body"] = body if timeout > 0 then init["signal"] = .js~AbortSignal~timeout(.js~num(timeout * 1000)) do response = .js~fetch(url, .js~newObject(init))~await return .true catch e = syntax response = .nil reason = e~message parse var reason "JavaScript error: " js if js \== "" then reason = js .CommandIO~error(context, "FETCH" method url":" reason) return .false end -- RC for the last response: 0 for 2xx, else the status (and ERROR) ::method result private expose response use strict arg context status = response~status if status >= 200 & status <= 299 then return 0 return context~raiseError(status) ::method header private expose headers use strict arg words, into, context name = words~take if name == .nil | into \== .nil then return self~bad(context, "HEADER: a header name is needed") if words~items = 0 then do if name~upper == "RESET" & \words~quoted(1) then headers~empty else headers~remove(name) return 0 end value = words~takeValue(context) if value == .nil then return self~bad(context, "HEADER" name": the variable has no value") if words~items > 0 then return self~bad(context, "HEADER" name": one value (in quotes if it has blanks)") headers[name] = value return 0 ::method setTimeout private expose timeout use strict arg words, into, context seconds = words~take if seconds == .nil | words~items > 0 | into \== .nil then signal wrong if \seconds~dataType("N") then signal wrong if seconds < 0 then signal wrong timeout = seconds return 0 wrong: return self~bad(context, "TIMEOUT: seconds expected") ::method status private expose response use strict arg words, into, context if words~items > 0 then return self~bad(context, "STATUS takes no arguments") if response == .nil then return self~give(context, into, 0) return self~give(context, into, response~status) ::method responseHeaders private expose response use strict arg words, into, context name = words~take if words~items > 0 then return self~bad(context, "HEADERS [name]") if response == .nil then do .CommandIO~error(context, "FETCH HEADERS: no response yet") return context~raiseError(2) end if name \== .nil then do value = response~headers~get(name) if value == .nil then value = "" return self~give(context, into, value) end all = .stringTable~new do pair over response~headers -- [name, value] pairs, as for...of all[pair[1]] = pair[2] end return self~give(context, into, all) -- the last body as JSON (json.cls), or one value of it by its path ::method jsonValue private expose text json use strict arg words, into, context path = words~take if words~items > 0 then return self~bad(context, "JSON [path] [INTO var]") if json == .nil then do if text == .nil then do .CommandIO~error(context, "FETCH JSON: no response body") return context~raiseError(2) end do json = .array~of(.json~new~fromJSON(text)) -- in an Array: null is .nil catch syntax .CommandIO~error(context, "FETCH JSON: the response body is not JSON") return context~raiseError(2) end end value = json[1] where = "" if path \== .nil then do step over path~makeArray(".") if step == "" then iterate where = where"."step if value~isA(.Array) then do if \step~dataType("W") then signal missing if step < 1 | step > value~items then signal missing value = value[step] end else if value~isA(.Directory) then do if \value~hasIndex(step) then signal missing value = value[step] end else signal missing end if into == .nil then do if value == .nil then value = "null" else if value~isA(.JsonBoolean) then value = value~makeJSON else if \value~isA(.String) then value = .json~toJSON(value) end return self~give(context, into, value) missing: .CommandIO~error(context, "FETCH JSON: no" where~substr(2) "in the response") return context~raiseError(1)