@voxgig/sdkgen 4.39.1 → 4.40.0

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 (86) hide show
  1. package/bin/voxgig-sdkgen +1 -1
  2. package/dist/helpers/testPolicy.d.ts +8 -2
  3. package/dist/helpers/testPolicy.js +18 -0
  4. package/dist/helpers/testPolicy.js.map +1 -1
  5. package/dist/sdkgen.d.ts +4 -4
  6. package/dist/sdkgen.js +4 -3
  7. package/dist/sdkgen.js.map +1 -1
  8. package/dist/tsconfig.tsbuildinfo +1 -1
  9. package/package.json +1 -1
  10. package/project/.sdk/model/target/rust.aontu +1 -0
  11. package/project/.sdk/src/cmp/c/fragment/Main.fragment.c +15 -0
  12. package/project/.sdk/src/cmp/cpp/TestDirect_cpp.ts +2 -0
  13. package/project/.sdk/src/cmp/csharp/TestDirect_csharp.ts +20 -3
  14. package/project/.sdk/src/cmp/csharp/TestEntity_csharp.ts +43 -15
  15. package/project/.sdk/src/cmp/csharp/fragment/Main.fragment.cs +17 -0
  16. package/project/.sdk/src/cmp/elixir/fragment/Main.fragment.ex +10 -0
  17. package/project/.sdk/src/cmp/go/TestDirect_go.ts +23 -4
  18. package/project/.sdk/src/cmp/go/TestEntity_go.ts +37 -12
  19. package/project/.sdk/src/cmp/go/fragment/Main.fragment.go +14 -0
  20. package/project/.sdk/src/cmp/java/TestDirect_java.ts +18 -3
  21. package/project/.sdk/src/cmp/java/TestEntity_java.ts +39 -14
  22. package/project/.sdk/src/cmp/js/TestDirect_js.ts +7 -1
  23. package/project/.sdk/src/cmp/js/fragment/Main.fragment.js +7 -0
  24. package/project/.sdk/src/cmp/kotlin/TestDirect_kotlin.ts +18 -3
  25. package/project/.sdk/src/cmp/kotlin/TestEntity_kotlin.ts +37 -14
  26. package/project/.sdk/src/cmp/lua/TestDirect_lua.ts +13 -3
  27. package/project/.sdk/src/cmp/lua/TestEntity_lua.ts +36 -10
  28. package/project/.sdk/src/cmp/lua/fragment/Main.fragment.lua +14 -0
  29. package/project/.sdk/src/cmp/ocaml/TestDirect_ocaml.ts +3 -1
  30. package/project/.sdk/src/cmp/perl/TestDirect_perl.ts +9 -3
  31. package/project/.sdk/src/cmp/perl/TestEntity_perl.ts +22 -8
  32. package/project/.sdk/src/cmp/perl/fragment/Main.fragment.pm +6 -0
  33. package/project/.sdk/src/cmp/php/TestDirect_php.ts +13 -3
  34. package/project/.sdk/src/cmp/php/TestEntity_php.ts +31 -9
  35. package/project/.sdk/src/cmp/php/fragment/Main.fragment.php +14 -0
  36. package/project/.sdk/src/cmp/py/TestDirect_py.ts +11 -3
  37. package/project/.sdk/src/cmp/py/TestEntity_py.ts +30 -9
  38. package/project/.sdk/src/cmp/py/fragment/Main.fragment.py +6 -0
  39. package/project/.sdk/src/cmp/rb/TestDirect_rb.ts +9 -3
  40. package/project/.sdk/src/cmp/rb/TestEntity_rb.ts +25 -10
  41. package/project/.sdk/src/cmp/rb/fragment/Main.fragment.rb +7 -0
  42. package/project/.sdk/src/cmp/rust/TestDirect_rust.ts +13 -3
  43. package/project/.sdk/src/cmp/rust/TestEntity_rust.ts +48 -27
  44. package/project/.sdk/src/cmp/rust/fragment/Main.fragment.rs +15 -0
  45. package/project/.sdk/src/cmp/swift/fragment/Main.fragment.swift +7 -0
  46. package/project/.sdk/src/cmp/ts/TestDirect_ts.ts +7 -1
  47. package/project/.sdk/src/cmp/ts/TestEntity_ts.ts +8 -2
  48. package/project/.sdk/src/cmp/ts/fragment/Main.fragment.ts +7 -0
  49. package/project/.sdk/src/cmp/zig/TestDirect_zig.ts +1 -0
  50. package/project/.sdk/src/cmp/zig/fragment/Main.fragment.zig +16 -0
  51. package/project/.sdk/tm/c/utility/http.c +256 -0
  52. package/project/.sdk/tm/clojure/src/sdk/client.clj +7 -0
  53. package/project/.sdk/tm/clojure/src/sdk/core.clj +24 -1
  54. package/project/.sdk/tm/cpp/core/types.hpp +14 -0
  55. package/project/.sdk/tm/csharp/test/Runner.cs +49 -3
  56. package/project/.sdk/tm/csharp/utility/Fetcher.cs +5 -1
  57. package/project/.sdk/tm/elixir/lib/projectname/utility.ex +54 -19
  58. package/project/.sdk/tm/go/test/testsupport_test.go +44 -3
  59. package/project/.sdk/tm/go/utility/fetcher.go +40 -0
  60. package/project/.sdk/tm/java/core/SdkClient.java +7 -0
  61. package/project/.sdk/tm/java/test/RunnerSupport.java +45 -2
  62. package/project/.sdk/tm/java/utility/Fetcher.java +67 -1
  63. package/project/.sdk/tm/js/src/utility/MakeResultUtility.js +3 -1
  64. package/project/.sdk/tm/js/test/live-entity.js +7 -3
  65. package/project/.sdk/tm/kotlin/core/SdkClient.kt +7 -0
  66. package/project/.sdk/tm/kotlin/test/RunnerSupport.kt +40 -3
  67. package/project/.sdk/tm/kotlin/utility/Fetcher.kt +52 -1
  68. package/project/.sdk/tm/lua/test/runner.lua +49 -2
  69. package/project/.sdk/tm/lua/utility/fetcher.lua +228 -0
  70. package/project/.sdk/tm/ocaml/sdk_features.ml +8 -0
  71. package/project/.sdk/tm/perl/t/runner.pm +18 -3
  72. package/project/.sdk/tm/perl/utility/fetcher.pm +42 -3
  73. package/project/.sdk/tm/php/test/Runner.php +43 -5
  74. package/project/.sdk/tm/php/utility/Fetcher.php +36 -0
  75. package/project/.sdk/tm/php/utility/MakeResult.php +3 -1
  76. package/project/.sdk/tm/py/test/runner.py +32 -3
  77. package/project/.sdk/tm/rb/test/runner.rb +24 -1
  78. package/project/.sdk/tm/rust/tests/common/mod.rs +53 -5
  79. package/project/.sdk/tm/rust/utility/fetcher.rs +43 -3
  80. package/project/.sdk/tm/scala/core/SdkClient.scala +7 -0
  81. package/project/.sdk/tm/scala/utility/Fetcher.scala +48 -1
  82. package/project/.sdk/tm/ts/src/utility/MakeResultUtility.ts +3 -1
  83. package/project/.sdk/tm/ts/test/live-entity.ts +8 -3
  84. package/project/sdkgen-package.json +1 -1
  85. package/src/helpers/testPolicy.ts +23 -2
  86. package/src/sdkgen.ts +4 -2
@@ -29,6 +29,223 @@ local function getonly_refusal(fullurl, method)
29
29
  "[GET-ONLY GUARD] blocked " .. method .. " " .. path)
30
30
  end
31
31
 
32
+ -- Inflate, in Lua: luasocket decodes no Content-Encoding, and a server may
33
+ -- compress its answer unasked. Canonical Huffman decoding a bit at a time, as
34
+ -- zlib's puff.c does, so no C library is needed.
35
+ local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
36
+ 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }
37
+ local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
38
+ 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }
39
+ local DBASE = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
40
+ 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 }
41
+ local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
42
+ 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }
43
+ local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }
44
+
45
+ -- The canonical code for code lengths lens[0..n-1].
46
+ local function huffman(lens, n)
47
+ local count, offs, symbol = {}, {}, {}
48
+ for len = 0, 15 do count[len] = 0 end
49
+ for sym = 0, n - 1 do count[lens[sym]] = count[lens[sym]] + 1 end
50
+ offs[1] = 0
51
+ for len = 1, 14 do offs[len + 1] = offs[len] + count[len] end
52
+ for sym = 0, n - 1 do
53
+ local len = lens[sym]
54
+ if len ~= 0 then
55
+ symbol[offs[len]] = sym
56
+ offs[len] = offs[len] + 1
57
+ end
58
+ end
59
+ return { count = count, symbol = symbol }
60
+ end
61
+
62
+ local FIXED_LEN, FIXED_DIST
63
+ do
64
+ local lens = {}
65
+ for sym = 0, 287 do
66
+ lens[sym] = sym < 144 and 8 or sym < 256 and 9 or sym < 280 and 7 or 8
67
+ end
68
+ FIXED_LEN = huffman(lens, 288)
69
+ local dists = {}
70
+ for sym = 0, 29 do dists[sym] = 5 end
71
+ FIXED_DIST = huffman(dists, 30)
72
+ end
73
+
74
+ local function inflate_raw(data, pos)
75
+ local size = #data
76
+ local bitbuf, bitcnt = 0, 0
77
+ local out, n = {}, 0
78
+
79
+ local function bits(need)
80
+ while bitcnt < need do
81
+ if pos > size then error("inflate: the data ends early", 0) end
82
+ bitbuf = bitbuf | (string.byte(data, pos) << bitcnt)
83
+ pos = pos + 1
84
+ bitcnt = bitcnt + 8
85
+ end
86
+ local val = bitbuf & ((1 << need) - 1)
87
+ bitbuf = bitbuf >> need
88
+ bitcnt = bitcnt - need
89
+ return val
90
+ end
91
+
92
+ local function decode(h)
93
+ local code, first, index = 0, 0, 0
94
+ for len = 1, 15 do
95
+ code = code | bits(1)
96
+ local count = h.count[len]
97
+ if code - count < first then
98
+ return h.symbol[index + (code - first)]
99
+ end
100
+ index = index + count
101
+ first = (first + count) << 1
102
+ code = code << 1
103
+ end
104
+ error("inflate: an invalid code", 0)
105
+ end
106
+
107
+ local function codes(lencode, distcode)
108
+ while true do
109
+ local sym = decode(lencode)
110
+ if sym < 256 then
111
+ n = n + 1
112
+ out[n] = sym
113
+ elseif sym == 256 then
114
+ return
115
+ else
116
+ sym = sym - 257
117
+ if sym >= 29 then error("inflate: an invalid length", 0) end
118
+ local len = LBASE[sym + 1] + bits(LEXT[sym + 1])
119
+ local dsym = decode(distcode)
120
+ if dsym >= 30 then error("inflate: an invalid distance", 0) end
121
+ local dist = DBASE[dsym + 1] + bits(DEXT[dsym + 1])
122
+ if dist > n then error("inflate: a distance too far back", 0) end
123
+ for _ = 1, len do
124
+ n = n + 1
125
+ out[n] = out[n - dist]
126
+ end
127
+ end
128
+ end
129
+ end
130
+
131
+ repeat
132
+ local last = bits(1)
133
+ local kind = bits(2)
134
+ if kind == 0 then
135
+ -- A stored block starts on a byte boundary: what is left of this byte goes.
136
+ bitbuf, bitcnt = 0, 0
137
+ if pos + 3 > size then error("inflate: the data ends early", 0) end
138
+ local a, b, c, d = string.byte(data, pos, pos + 3)
139
+ local len = a | (b << 8)
140
+ if len ~= (~(c | (d << 8)) & 0xffff) then
141
+ error("inflate: a stored block length is corrupt", 0)
142
+ end
143
+ pos = pos + 4
144
+ if pos + len - 1 > size then error("inflate: the data ends early", 0) end
145
+ for i = pos, pos + len - 1 do
146
+ n = n + 1
147
+ out[n] = string.byte(data, i)
148
+ end
149
+ pos = pos + len
150
+ elseif kind == 1 then
151
+ codes(FIXED_LEN, FIXED_DIST)
152
+ elseif kind == 2 then
153
+ local nlen = bits(5) + 257
154
+ local ndist = bits(5) + 1
155
+ local ncode = bits(4) + 4
156
+ if nlen > 286 or ndist > 30 then error("inflate: too many codes", 0) end
157
+ local lens = {}
158
+ for i = 0, 18 do lens[i] = 0 end
159
+ for i = 1, ncode do lens[CLORDER[i]] = bits(3) end
160
+ local lencode = huffman(lens, 19)
161
+ local all = {}
162
+ local index = 0
163
+ while index < nlen + ndist do
164
+ local sym = decode(lencode)
165
+ if sym < 16 then
166
+ all[index] = sym
167
+ index = index + 1
168
+ else
169
+ local len, rep = 0, 0
170
+ if sym == 16 then
171
+ if index == 0 then error("inflate: a repeat with nothing before it", 0) end
172
+ len = all[index - 1]
173
+ rep = 3 + bits(2)
174
+ elseif sym == 17 then
175
+ rep = 3 + bits(3)
176
+ else
177
+ rep = 11 + bits(7)
178
+ end
179
+ if index + rep > nlen + ndist then error("inflate: too many lengths", 0) end
180
+ for _ = 1, rep do
181
+ all[index] = len
182
+ index = index + 1
183
+ end
184
+ end
185
+ end
186
+ if all[256] == 0 then error("inflate: no end-of-block code", 0) end
187
+ local litlens, distlens = {}, {}
188
+ for i = 0, nlen - 1 do litlens[i] = all[i] end
189
+ for i = 0, ndist - 1 do distlens[i] = all[nlen + i] end
190
+ codes(huffman(litlens, nlen), huffman(distlens, ndist))
191
+ else
192
+ error("inflate: an invalid block type", 0)
193
+ end
194
+ until last == 1
195
+
196
+ local parts = {}
197
+ for i = 1, n, 4096 do
198
+ parts[#parts + 1] = string.char(table.unpack(out, i, math.min(i + 4095, n)))
199
+ end
200
+ return table.concat(parts)
201
+ end
202
+
203
+ -- A gzip or deflate body decoded; deflate is zlib-wrapped, or raw as some
204
+ -- servers send it.
205
+ local function decode_body(body, encoding)
206
+ if encoding == "gzip" or encoding == "x-gzip" then
207
+ local a, b, method, flags = string.byte(body, 1, 4)
208
+ if a ~= 0x1f or b ~= 0x8b or method ~= 8 then
209
+ error("not gzip data", 0)
210
+ end
211
+ local pos = 11
212
+ if flags & 4 ~= 0 then
213
+ local lo, hi = string.byte(body, pos, pos + 1)
214
+ pos = pos + 2 + (lo | ((hi or 0) << 8))
215
+ end
216
+ if flags & 8 ~= 0 then pos = (string.find(body, "\0", pos, true) or #body) + 1 end
217
+ if flags & 16 ~= 0 then pos = (string.find(body, "\0", pos, true) or #body) + 1 end
218
+ if flags & 2 ~= 0 then pos = pos + 2 end
219
+ return inflate_raw(body, pos)
220
+ end
221
+ local cmf, flg = string.byte(body, 1, 2)
222
+ if cmf ~= nil and flg ~= nil and cmf & 0x0f == 8 and ((cmf << 8) | flg) % 31 == 0 then
223
+ return inflate_raw(body, 3)
224
+ end
225
+ return inflate_raw(body, 1)
226
+ end
227
+
228
+ -- OpenSSL reports a TLS close without close_notify as "unexpected eof while
229
+ -- reading", where every other target reads it as the end of the body. The
230
+ -- other options are luasec's defaults, which an options list replaces.
231
+ local TLS_OPTIONS = { "all", "no_sslv2", "no_sslv3", "no_tlsv1", "ignore_unexpected_eof" }
232
+
233
+ local function tls_options()
234
+ local ssl_ok, ssl = pcall(require, "ssl")
235
+ local known = ssl_ok and type(ssl) == "table" and type(ssl.config) == "table"
236
+ and ssl.config.options or nil
237
+ if type(known) ~= "table" or not known.ignore_unexpected_eof then
238
+ return nil
239
+ end
240
+ local options = {}
241
+ for _, name in ipairs(TLS_OPTIONS) do
242
+ if known[name] then
243
+ table.insert(options, name)
244
+ end
245
+ end
246
+ return options
247
+ end
248
+
32
249
  local function send_once(fullurl, fetchdef)
33
250
  -- Use LuaSocket or similar for real HTTP requests.
34
251
  -- This is the default live implementation.
@@ -72,6 +289,7 @@ local function send_once(fullurl, fetchdef)
72
289
  source = body_str and ltn12.source.string(body_str) or nil,
73
290
  sink = ltn12.sink.table(response_body),
74
291
  redirect = false,
292
+ options = string.find(string.lower(fullurl), "^https:") and tls_options() or nil,
75
293
  })
76
294
 
77
295
  if not res then
@@ -86,6 +304,16 @@ local function send_once(fullurl, fetchdef)
86
304
  end
87
305
  end
88
306
 
307
+ local encoding = string.lower(tostring(resp_headers["content-encoding"] or ""))
308
+ encoding = string.match(encoding, "^%s*(.-)%s*$")
309
+ if body ~= "" and (encoding == "gzip" or encoding == "x-gzip" or encoding == "deflate") then
310
+ local decoded_ok, decoded = pcall(decode_body, body, encoding)
311
+ if not decoded_ok then
312
+ return nil, "response body is not valid " .. encoding .. " data: " .. tostring(decoded)
313
+ end
314
+ body = decoded
315
+ end
316
+
89
317
  local json_body = nil
90
318
  local unreadable = false
91
319
  if string.find(body, "%S") then
@@ -1737,6 +1737,14 @@ let prepare (client : sdk_client) (fetchargs : value) : value =
1737
1737
  ("step", Str "start")]) in
1738
1738
  ctx.c_spec <- Some sp;
1739
1739
  (match getp fetchargs "headers" with Map _ as uh -> List.iter (fun k -> setp sp.sp_headers k (getp uh k)) (keysof uh) | _ -> ());
1740
+ (* A raw request has no point to declare its response type, so it asks for
1741
+ * the JSON it reads: an API that negotiates on Accept otherwise answers in
1742
+ * its own default format. A caller's own accept wins. *)
1743
+ (match sp.sp_headers with
1744
+ | Map _ as hm ->
1745
+ if not (List.exists (fun k -> String.lowercase_ascii k = "accept") (keysof hm)) then
1746
+ setp hm "accept" (Str "application/json")
1747
+ | _ -> ());
1740
1748
  (match u.u_prepare_auth ctx with (_, Some err) -> raise (Sdk_error_exc err) | _ -> ());
1741
1749
  (match u.u_make_fetch_def ctx with (_, Some err) -> raise (Sdk_error_exc err) | (fd, None) -> fd)
1742
1750
 
@@ -223,10 +223,10 @@ sub live_describe {
223
223
  }
224
224
 
225
225
  # The record a create-less flow reads live: the first its list returns, put
226
- # where the flow reads the fixture's existing records. False once the test
227
- # is settled and its block ends.
226
+ # where the flow reads the fixture's existing records, a record with no
227
+ # identity taking the fallback. False once the test is settled.
228
228
  sub live_existing {
229
- my ($setup, $strict, $label, $name, $list) = @_;
229
+ my ($setup, $strict, $label, $name, $list, $field, $fallback) = @_;
230
230
  my $found = eval { $list->() };
231
231
  if (my $err = $@) {
232
232
  live_miss($strict, $label, "Live list discovery failed: $err");
@@ -243,10 +243,25 @@ sub live_existing {
243
243
  my $first = $found->[0];
244
244
  my $record = (Scalar::Util::blessed($first) && $first->can('data_get'))
245
245
  ? $first->data_get : $first;
246
+ if (ref $record ne 'HASH' || !defined $record->{$field}) {
247
+ if (!defined $fallback) {
248
+ live_miss($strict, $label, "Live entity test blocked: the listed $name record has no $field, "
249
+ . "and neither *_ENTID nor the load route's example gives one");
250
+ return 0;
251
+ }
252
+ $record = { (ref $record eq 'HASH' ? %$record : ()), $field => $fallback };
253
+ }
246
254
  $setup->{data}{existing}{$name} = { 'live01' => $record };
247
255
  return 1;
248
256
  }
249
257
 
258
+ # Sleeps test.live.delayMs before a live request.
259
+ sub live_pace {
260
+ my $ms = live_delay_ms();
261
+ select(undef, undef, undef, $ms / 1000) if $ms > 0;
262
+ return;
263
+ }
264
+
250
265
  # In a lenient live run a step that dies skips, observing the live API.
251
266
  sub live_observe {
252
267
  my ($err, $setup, $strict, $label) = @_;
@@ -175,10 +175,19 @@ sub _send_once {
175
175
  $resp_headers->{lc "$k"} = $v;
176
176
  }
177
177
 
178
+ my $content = $res->{content};
179
+ my $encoding = lc(defined $resp_headers->{'content-encoding'} ? $resp_headers->{'content-encoding'} : '');
180
+ $encoding =~ s/\A\s+|\s+\z//g;
181
+ if (defined $content && length $content && $encoding =~ /\A(?:gzip|x-gzip|deflate)\z/) {
182
+ my ($decoded, $derr) = _decode_body($content, $encoding);
183
+ return (undef, $derr) if defined $derr;
184
+ $content = $decoded;
185
+ }
186
+
178
187
  my $json_body;
179
188
  my $unreadable = 0;
180
- if (defined $res->{content} && $res->{content} =~ /\S/) {
181
- my $parsed = eval { $json_body = Voxgig::Struct::parse_json($res->{content}); 1 };
189
+ if (defined $content && $content =~ /\S/) {
190
+ my $parsed = eval { $json_body = Voxgig::Struct::parse_json($content); 1 };
182
191
  $unreadable = 1 unless $parsed;
183
192
  }
184
193
  my $captured = $json_body;
@@ -188,11 +197,41 @@ sub _send_once {
188
197
  'statusText' => (defined $res->{reason} ? "$res->{reason}" : ''),
189
198
  'headers' => $resp_headers,
190
199
  'json' => sub { $captured },
191
- 'body' => $res->{content},
200
+ 'body' => $content,
192
201
  'unreadable' => $unreadable,
193
202
  }, undef);
194
203
  }
195
204
 
205
+ # HTTP::Tiny decodes no Content-Encoding, and a server may compress its answer
206
+ # whatever the request asked for. Deflate is zlib-wrapped, or
207
+ # raw as some servers send it.
208
+ sub _decode_body {
209
+ no warnings 'once';
210
+ my ($content, $encoding) = @_;
211
+ my $out;
212
+ my $ok = eval {
213
+ if ('deflate' eq $encoding) {
214
+ require IO::Uncompress::Inflate;
215
+ require IO::Uncompress::RawInflate;
216
+ IO::Uncompress::Inflate::inflate(\$content => \$out, Transparent => 0)
217
+ or IO::Uncompress::RawInflate::rawinflate(\$content => \$out, Transparent => 0)
218
+ or die "$IO::Uncompress::RawInflate::RawInflateError\n";
219
+ }
220
+ else {
221
+ require IO::Uncompress::Gunzip;
222
+ IO::Uncompress::Gunzip::gunzip(\$content => \$out, Transparent => 0)
223
+ or die "$IO::Uncompress::Gunzip::GunzipError\n";
224
+ }
225
+ 1;
226
+ };
227
+ if (!$ok) {
228
+ my $e = "$@";
229
+ $e =~ s/\s+\z//;
230
+ return (undef, "response body is not valid $encoding data: $e");
231
+ }
232
+ return ($out, undef);
233
+ }
234
+
196
235
  $REGISTRY{fetcher} = sub {
197
236
  my ($ctx, $fullurl, $fetchdef) = @_;
198
237
 
@@ -240,9 +240,11 @@ class ProjectNameTestRunner
240
240
 
241
241
  /**
242
242
  * The record a create-less flow reads live: the first its list returns,
243
- * put where the flow reads the fixture's existing records.
243
+ * put where the flow reads the fixture's existing records. A record with
244
+ * no value in the identity field takes the fallback identity.
244
245
  */
245
- public static function live_existing(array &$setup, bool $strict, string $name, callable $list): void
246
+ public static function live_existing(array &$setup, bool $strict, string $name, callable $list,
247
+ string $field, $fallback): void
246
248
  {
247
249
  $found = null;
248
250
  try {
@@ -257,9 +259,45 @@ class ProjectNameTestRunner
257
259
  self::live_empty("The account has no $name record to load");
258
260
  }
259
261
  $first = $found[0];
260
- $setup["data"]["existing"][$name] = [
261
- "live01" => (is_object($first) && method_exists($first, 'data_get')) ? $first->data_get() : $first,
262
- ];
262
+ $record = (is_object($first) && method_exists($first, 'data_get')) ? $first->data_get() : $first;
263
+ if (!is_array($record) || null === ($record[$field] ?? null)) {
264
+ if (null === $fallback) {
265
+ self::live_miss($strict, "Live entity test blocked: the listed $name record has no $field, "
266
+ . "and neither *_ENTID nor the load route's example gives one");
267
+ }
268
+ $record = is_array($record) ? $record : [];
269
+ $record[$field] = $fallback;
270
+ }
271
+ $setup["data"]["existing"][$name] = ["live01" => $record];
272
+ }
273
+
274
+ /**
275
+ * Identities compared by their string forms: a route parameter's
276
+ * value is a string where the record may hold a number.
277
+ */
278
+ public static function live_same_id($a, $b): bool
279
+ {
280
+ if (null === $a || null === $b) {
281
+ return null === $a && null === $b;
282
+ }
283
+ return self::live_id_str($a) === self::live_id_str($b);
284
+ }
285
+
286
+ private static function live_id_str($v): string
287
+ {
288
+ if (is_bool($v)) {
289
+ return $v ? 'true' : 'false';
290
+ }
291
+ if (is_float($v) && is_finite($v) && floor($v) == $v && abs($v) < PHP_INT_MAX) {
292
+ return (string)(int)$v;
293
+ }
294
+ return is_scalar($v) ? (string)$v : json_encode($v);
295
+ }
296
+
297
+ /** Sleeps test.live.delayMs before a live request. */
298
+ public static function live_pace(): void
299
+ {
300
+ usleep(self::live_delay_ms() * 1000);
263
301
  }
264
302
 
265
303
  /** In a lenient live run a failing check skips, observing the live API. */
@@ -206,6 +206,13 @@ class ProjectNameFetcher
206
206
  }
207
207
  }
208
208
 
209
+ // The stream wrapper does not decode a compressed body, which a
210
+ // server may send whatever the request asked for.
211
+ [$response_body, $decode_err] = self::decodeBody($response_body, $resp_headers['content-encoding'] ?? '');
212
+ if (null !== $decode_err) {
213
+ return [null, $decode_err];
214
+ }
215
+
209
216
  $json_body = null;
210
217
  $unreadable = false;
211
218
  if (trim($response_body) !== '') {
@@ -230,6 +237,32 @@ class ProjectNameFetcher
230
237
  ];
231
238
  }
232
239
 
240
+ // A gzip or deflate body decoded, as cURL does with CURLOPT_ENCODING; a
241
+ // deflate body is zlib-wrapped, or raw as some servers
242
+ // send it. Any other encoding is left as it came.
243
+ public static function decodeBody(string $body, string $encoding): array
244
+ {
245
+ $encoding = strtolower(trim($encoding));
246
+ if ('' === $body || !in_array($encoding, ['gzip', 'x-gzip', 'deflate'], true)) {
247
+ return [$body, null];
248
+ }
249
+ if (!function_exists('gzdecode')) {
250
+ return [null, "response body is {$encoding} encoded, and this PHP has no zlib to decode it"];
251
+ }
252
+ if ('deflate' === $encoding) {
253
+ $decoded = @gzuncompress($body);
254
+ if (false === $decoded) {
255
+ $decoded = @gzinflate($body);
256
+ }
257
+ } else {
258
+ $decoded = @gzdecode($body);
259
+ }
260
+ if (!is_string($decoded)) {
261
+ return [null, "response body is not valid {$encoding} data"];
262
+ }
263
+ return [$decoded, null];
264
+ }
265
+
233
266
  private static function curlFetch(string $fullurl, string $method, $body_str, array $header_lines): array
234
267
  {
235
268
  $ch = self::curlHandle($fullurl);
@@ -239,6 +272,9 @@ class ProjectNameFetcher
239
272
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);
240
273
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
241
274
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
275
+ // '' offers every encoding this cURL decodes, and decodes it: a
276
+ // server may compress its answer whatever the request asked for.
277
+ curl_setopt($ch, CURLOPT_ENCODING, '');
242
278
  if (!empty($header_lines)) {
243
279
  curl_setopt($ch, CURLOPT_HTTPHEADER, $header_lines);
244
280
  }
@@ -29,7 +29,9 @@ class ProjectNameMakeResult
29
29
  if ($op->name === 'list') {
30
30
  $resdata = $result->resdata;
31
31
  $result->resdata = [];
32
- if (is_array($resdata) && !empty($resdata) && $entity) {
32
+ // A decoded JSON object is a PHP array too: only a list holds
33
+ // records, as ts reads `resdata.length`, which an object lacks.
34
+ if (is_array($resdata) && !empty($resdata) && array_is_list($resdata) && $entity) {
33
35
  $entities = [];
34
36
  foreach ($resdata as $entry) {
35
37
  $ent = $entity->make();
@@ -238,9 +238,10 @@ def live_describe(result):
238
238
  (" " + str(ctype).split(";")[0].strip() if ctype else "")
239
239
 
240
240
 
241
- def live_existing(setup, strict, name, list_call):
241
+ def live_existing(setup, strict, name, list_call, field, fallback):
242
242
  """Finds the record a create-less flow reads live: the first its list
243
- returns, put where the flow reads the fixture's existing records."""
243
+ returns, put where the flow reads the fixture's existing records. A
244
+ record with no value in the identity field takes the fallback identity."""
244
245
  try:
245
246
  found = list_call()
246
247
  except Exception as err:
@@ -249,8 +250,36 @@ def live_existing(setup, strict, name, list_call):
249
250
  live_miss(strict, "Live list discovery returned no list")
250
251
  if 0 == len(found):
251
252
  live_empty(f"The account has no {name} record to load")
253
+ record = entity_data(found[0])
254
+ if not isinstance(record, dict) or record.get(field) is None:
255
+ if fallback is None:
256
+ live_miss(strict, f"Live entity test blocked: the listed {name} record has no {field}, "
257
+ "and neither *_ENTID nor the load route's example gives one")
258
+ record = {**(record if isinstance(record, dict) else {}), field: fallback}
252
259
  existing = setup["data"].setdefault("existing", {})
253
- existing[name] = {"live01": entity_data(found[0])}
260
+ existing[name] = {"live01": record}
261
+
262
+
263
+ def live_same_id(a, b):
264
+ """Identities compared by their string forms: a route parameter's
265
+ value is a string where the record may hold a number."""
266
+ if a is None or b is None:
267
+ return a is None and b is None
268
+ return _live_id_str(a) == _live_id_str(b)
269
+
270
+
271
+ def _live_id_str(v):
272
+ if isinstance(v, bool):
273
+ return "true" if v else "false"
274
+ if isinstance(v, float) and v.is_integer():
275
+ return str(int(v))
276
+ return str(v)
277
+
278
+
279
+ def live_pace():
280
+ """Sleeps test.live.delayMs before a live request."""
281
+ import time
282
+ time.sleep(live_delay_ms() / 1000.0)
254
283
 
255
284
 
256
285
  def live_observe(live_env, strict):
@@ -167,7 +167,7 @@ module ProjectNameTestRunner
167
167
 
168
168
  # The record a create-less flow reads live: the first its list returns,
169
169
  # put where the flow reads the fixture's existing records.
170
- def self.live_existing(setup, strict, name)
170
+ def self.live_existing(setup, strict, name, field, fallback)
171
171
  found = begin
172
172
  yield
173
173
  rescue StandardError => e
@@ -177,9 +177,32 @@ module ProjectNameTestRunner
177
177
  live_empty("The account has no #{name} record to load") if found.empty?
178
178
  first = found[0]
179
179
  record = first.respond_to?(:data_get) ? first.data_get : first
180
+ if !record.is_a?(Hash) || record[field].nil?
181
+ if fallback.nil?
182
+ live_miss(strict, "Live entity test blocked: the listed #{name} record has no #{field}, " \
183
+ "and neither *_ENTID nor the load route's example gives one")
184
+ end
185
+ record = (record.is_a?(Hash) ? record : {}).merge(field => fallback)
186
+ end
180
187
  (setup[:data]["existing"] ||= {})[name] = { "live01" => record }
181
188
  end
182
189
 
190
+ # Identities compared by their string forms: a route parameter's
191
+ # value is a string where the record may hold a number.
192
+ def self.live_same_id(a, b)
193
+ return a.nil? && b.nil? if a.nil? || b.nil?
194
+ live_id_str(a) == live_id_str(b)
195
+ end
196
+
197
+ def self.live_id_str(v)
198
+ v.is_a?(Float) && v.finite? && v == v.floor ? v.to_i.to_s : v.to_s
199
+ end
200
+
201
+ # Sleeps test.live.delayMs before a live request.
202
+ def self.live_pace
203
+ sleep(live_delay_ms / 1000.0)
204
+ end
205
+
183
206
  # In a lenient live run a failing check skips, observing the live API.
184
207
  def self.live_observe(error, setup, strict)
185
208
  raise error if strict || !setup.is_a?(Hash) || !setup[:live] || error.is_a?(Minitest::Skip)
@@ -246,12 +246,14 @@ pub fn live_describe(result: &Value) -> String {
246
246
  }
247
247
 
248
248
  // The record a create-less flow reads live: the first its list returns, put
249
- // where the flow reads the fixture's existing records. False once the test
250
- // is settled and has to return.
249
+ // where the flow reads the fixture's existing records, a record with no
250
+ // identity taking the fallback. False once the test is settled.
251
251
  pub fn live_existing(
252
252
  data: &Value,
253
253
  strict: bool,
254
254
  name: &str,
255
+ field: &str,
256
+ fallback: Value,
255
257
  list: impl FnOnce() -> Result<Value, ProjectNameError>,
256
258
  ) -> bool {
257
259
  let found = match list() {
@@ -265,20 +267,66 @@ pub fn live_existing(
265
267
  live_miss(strict, "Live list discovery returned no list");
266
268
  return false;
267
269
  }
268
- let first = vs::get_elem(&found, &Value::Num(0.0), Value::Noval);
269
- if first.is_noval() {
270
+ let mut record = vs::get_elem(&found, &Value::Num(0.0), Value::Noval);
271
+ if record.is_noval() {
270
272
  live_empty(&format!("The account has no {} record to load", name));
271
273
  return false;
272
274
  }
275
+ let is_map = matches!(record, Value::Map(_));
276
+ let held = if is_map { getp(&record, field) } else { Value::Noval };
277
+ if held.is_noval() || held.is_null() {
278
+ if fallback.is_noval() || fallback.is_null() {
279
+ live_miss(strict, &format!(
280
+ "Live entity test blocked: the listed {} record has no {}, \
281
+ and neither *_ENTID nor the load route's example gives one",
282
+ name, field
283
+ ));
284
+ return false;
285
+ }
286
+ let filled = Value::empty_map();
287
+ if is_map {
288
+ for key in vs::keysof_vec(&record) {
289
+ setp(&filled, &key, getp(&record, &key));
290
+ }
291
+ }
292
+ setp(&filled, field, fallback);
293
+ record = filled;
294
+ }
273
295
  let mut existing = getp(data, "existing");
274
296
  if !matches!(existing, Value::Map(_)) {
275
297
  existing = Value::empty_map();
276
298
  setp(data, "existing", existing.clone());
277
299
  }
278
- setp(&existing, name, jo(vec![("live01", first)]));
300
+ setp(&existing, name, jo(vec![("live01", record)]));
279
301
  true
280
302
  }
281
303
 
304
+ // Identities compared by their string forms: a route parameter's value
305
+ // is a string where the record may hold a number.
306
+ pub fn live_same_id(a: &Value, b: &Value) -> bool {
307
+ let absent = |v: &Value| v.is_noval() || v.is_null();
308
+ if absent(a) || absent(b) {
309
+ return absent(a) && absent(b);
310
+ }
311
+ live_id_str(a) == live_id_str(b)
312
+ }
313
+
314
+ fn live_id_str(v: &Value) -> String {
315
+ match v {
316
+ Value::Str(s) => s.clone(),
317
+ Value::Num(n) if n.is_finite() && 0.0 == n.fract() && n.abs() < 9.0e15 => format!("{}", *n as i64),
318
+ _ => vs::stringify(v, None, false),
319
+ }
320
+ }
321
+
322
+ // Sleeps test.live.delayMs before a live request.
323
+ pub fn live_pace() {
324
+ let ms = live_delay_ms();
325
+ if ms > 0 {
326
+ std::thread::sleep(std::time::Duration::from_millis(ms as u64));
327
+ }
328
+ }
329
+
282
330
  // In a lenient live run a panicking check is reported and the test returns,
283
331
  // observing the live API rather than failing on it.
284
332
  pub fn live_observe(err: Box<dyn std::any::Any + Send>, live: bool, strict: bool) {