// Stripe's request encoding: `application/x-www-form-urlencoded` with nesting in brackets (`a[b][0]=c`). A `json` value's // keys can't be listed in Weft, so this walks its JSON text, which keeps the fields in the order they were written. import { parse, stringify } from "std/json" fn isUnreserved(c: int): boolean { return (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 45 || c == 95 || c == 46 || c == 126 } /// `text` percent-encoded as UTF-8, keeping only RFC 3986's unreserved characters. export fn encodeComponent(text: string): string { let mut out: string[] = [] for b of Bytes.fromUtf8(text).toList() { if isUnreserved(b) { out.push(String.fromCharCode(b)) } else { out.push("%" + str(b, { radix: 16 }).toUpperCase().padStart(2, "0")) } } return out.join("") } fn stringEnd(text: string, from: int): int { let mut i = from + 1 while i < text.length { let c = text.codeUnitAt(i) ?? 34 if c == 92 { i += 2 } else if c == 34 { return i + 1 } else { i += 1 } } return i } fn pair(key: string, value: string): string { let name = encodeComponent(key).replaceAll("%5B", "[").replaceAll("%5D", "]") return `${name}=${encodeComponent(value)}` } fn child(key: string, name: string): string { return key == "" ? name : `${key}[${name}]` } /// Writes the JSON value at `at` under `key`, and gives the position after it. fn walk(text: string, at: int, key: string, mut out: string[]): int { let c = text.codeUnitAt(at) ?? 0 if c == 123 { let mut i = at + 1 while text.codeUnitAt(i) != 125 { let end = stringEnd(text, i) let name = try parse(text.slice(i, end)) else "" let label = name is string ? name : "" // `extra` holds fields this package doesn't model: they belong to the object it is written in. i = walk(text, end + 1, label == "extra" ? key : child(key, label), &out) if text.codeUnitAt(i) == 44 { i += 1 } } return i + 1 } if c == 91 { let mut i = at + 1 let mut index = 0 while text.codeUnitAt(i) != 93 { i = walk(text, i, `${key}[${index}]`, &out) index += 1 if text.codeUnitAt(i) == 44 { i += 1 } } return i + 1 } if c == 34 { let end = stringEnd(text, at) let value = try parse(text.slice(at, end)) else "" out.push(pair(key, value is string ? value : "")) return end } let mut end = at while end < text.length { let u = text.codeUnitAt(end) ?? 44 if u == 44 || u == 125 || u == 93 { break } end += 1 } let literal = text.slice(at, end) // A field left out is `null`: Stripe is sent nothing for it. To clear a field, send an empty string. if literal != "null" { out.push(pair(key, literal)) } return end } /// `params` in Stripe's form encoding. `null` fields are left out. export fn encodeForm(params: json): string { let mut out: string[] = [] if params != null { walk(stringify(params), 0, "", &out) } return out.join("&") }