@yolk-sdk/conformance 0.1.0-canary.96
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.
- package/LICENSE +21 -0
- package/README.md +316 -0
- package/dist/case.d.mts +89 -0
- package/dist/case.d.mts.map +1 -0
- package/dist/case.mjs +101 -0
- package/dist/case.mjs.map +1 -0
- package/dist/fixture.d.mts +432 -0
- package/dist/fixture.d.mts.map +1 -0
- package/dist/fixture.mjs +391 -0
- package/dist/fixture.mjs.map +1 -0
- package/dist/record.d.mts +96 -0
- package/dist/record.d.mts.map +1 -0
- package/dist/record.mjs +212 -0
- package/dist/record.mjs.map +1 -0
- package/dist/replay.d.mts +316 -0
- package/dist/replay.d.mts.map +1 -0
- package/dist/replay.mjs +272 -0
- package/dist/replay.mjs.map +1 -0
- package/dist/runner.d.mts +163 -0
- package/dist/runner.d.mts.map +1 -0
- package/dist/runner.mjs +264 -0
- package/dist/runner.mjs.map +1 -0
- package/dist/wire-internal.d.mts +90 -0
- package/dist/wire-internal.d.mts.map +1 -0
- package/dist/wire-internal.mjs +212 -0
- package/dist/wire-internal.mjs.map +1 -0
- package/package.json +75 -0
- package/src/case.ts +153 -0
- package/src/fixture.ts +625 -0
- package/src/record.ts +377 -0
- package/src/replay.ts +617 -0
- package/src/runner.ts +559 -0
- package/src/wire-internal.ts +382 -0
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { Effect, Encoding, Option, Predicate, Result } from 'effect'
|
|
2
|
+
import * as Schema from 'effect/Schema'
|
|
3
|
+
import type { HttpClientRequest } from 'effect/unstable/http'
|
|
4
|
+
|
|
5
|
+
// Header names that carry credentials or session state. Fixtures must never
|
|
6
|
+
// contain them and replay ledgers redact them.
|
|
7
|
+
const credentialHeaderNames: ReadonlySet<string> = new Set([
|
|
8
|
+
'authorization',
|
|
9
|
+
'proxy-authorization',
|
|
10
|
+
'cookie',
|
|
11
|
+
'set-cookie',
|
|
12
|
+
'x-api-key',
|
|
13
|
+
'api-key',
|
|
14
|
+
'x-goog-api-key',
|
|
15
|
+
'x-auth-token',
|
|
16
|
+
'x-access-token',
|
|
17
|
+
'x-amz-security-token',
|
|
18
|
+
'x-vercel-oidc-token',
|
|
19
|
+
'x-csrf-token'
|
|
20
|
+
])
|
|
21
|
+
|
|
22
|
+
const credentialHeaderPattern = /(api[-_]?key|secret|password|cookie|authorization)/i
|
|
23
|
+
|
|
24
|
+
// A `-`/`_`-separated name segment that is exactly `token`, `key`, or `auth`
|
|
25
|
+
// (`x-auth-token`, `private-token`, `x-figma-token`, `x-*-key`). Plural
|
|
26
|
+
// segments such as `x-ratelimit-remaining-tokens` do not match.
|
|
27
|
+
const credentialHeaderSegmentPattern = /(^|[-_])(token|key|auth)([-_]|$)/i
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* True for header names that carry credentials or session state. Used by the
|
|
31
|
+
* fixture secret scan, recorder drop rules, and ledger redaction.
|
|
32
|
+
*/
|
|
33
|
+
export const isCredentialHeaderName = (name: string): boolean => {
|
|
34
|
+
const lower = name.toLowerCase()
|
|
35
|
+
|
|
36
|
+
return (
|
|
37
|
+
credentialHeaderNames.has(lower) ||
|
|
38
|
+
credentialHeaderPattern.test(lower) ||
|
|
39
|
+
credentialHeaderSegmentPattern.test(lower)
|
|
40
|
+
)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export const redactedHeaderValue = '<redacted>'
|
|
44
|
+
|
|
45
|
+
// Credential text patterns. The fixture secret scan (`scanFixtureForSecrets`) tests them and the
|
|
46
|
+
// runner's report sanitizer redacts with them, so both share this one definition.
|
|
47
|
+
|
|
48
|
+
/** `Bearer <token>` with a token-shaped value. */
|
|
49
|
+
export const bearerPattern = /\bbearer\s+[A-Za-z0-9._~+/=-]{8,}/i
|
|
50
|
+
|
|
51
|
+
/** PEM private key header. */
|
|
52
|
+
const privateKeyPattern = /-----BEGIN [A-Z ]*PRIVATE KEY-----/
|
|
53
|
+
|
|
54
|
+
/** Common API-key prefixes and JSON Web Tokens. */
|
|
55
|
+
const tokenPrefixPatterns: ReadonlyArray<RegExp> = [
|
|
56
|
+
// OpenAI/Anthropic/DeepSeek-style secret keys (sk-..., sk-ant-..., sk-proj-...)
|
|
57
|
+
/\bsk-[A-Za-z0-9_-]{16,}/,
|
|
58
|
+
/\b[sr]k_(live|test)_[A-Za-z0-9]{16,}/,
|
|
59
|
+
/\bxai-[A-Za-z0-9]{20,}/,
|
|
60
|
+
/\bvck_[A-Za-z0-9]{16,}/,
|
|
61
|
+
/\bgh[pousr]_[A-Za-z0-9]{20,}/,
|
|
62
|
+
/\bgithub_pat_[A-Za-z0-9_]{20,}/,
|
|
63
|
+
/\bAKIA[0-9A-Z]{16}\b/,
|
|
64
|
+
/\bAIza[0-9A-Za-z_-]{35}/,
|
|
65
|
+
/\bxox[abprs]-[A-Za-z0-9-]{10,}/,
|
|
66
|
+
// JSON Web Tokens (OIDC/OAuth access tokens)
|
|
67
|
+
/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
/** Common API-key prefixes, JSON Web Tokens, and PEM private keys. */
|
|
71
|
+
export const apiKeyPatterns: ReadonlyArray<RegExp> = [...tokenPrefixPatterns, privateKeyPattern]
|
|
72
|
+
|
|
73
|
+
const credentialParamNames =
|
|
74
|
+
'api[_-]?key|key|token|access[_-]?token|refresh[_-]?token|id[_-]?token|auth|secret|password|client[_-]?secret|x-amz-signature|x-amz-credential|x-amz-security-token'
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Query-string or form-encoded credential parameter, anchored at the start of
|
|
78
|
+
* the text or after `?`/`&` (URLs and `application/x-www-form-urlencoded` bodies).
|
|
79
|
+
*/
|
|
80
|
+
export const credentialParamPattern = new RegExp(`(?:^|[?&])(${credentialParamNames})=[^&#]+`, 'i')
|
|
81
|
+
|
|
82
|
+
// Every `name=` of a credential parameter, found on its own: the pattern stops at `=` and never
|
|
83
|
+
// consumes the value, so a later `?name=` or `&name=` is always found, whatever the value holds.
|
|
84
|
+
const credentialParamNamesAt = new RegExp(`(?:^|[?&])(${credentialParamNames})=`, 'gi')
|
|
85
|
+
|
|
86
|
+
// What ends a raw parameter value: a character that cannot appear raw inside a URL query value
|
|
87
|
+
// (RFC 3986): `&`, `#`, whitespace, `"`, `<`, `>`. `?` and `'` are NOT boundaries (both are legal
|
|
88
|
+
// raw inside a query value), and neither is any percent-encoded delimiter.
|
|
89
|
+
const valueBoundary = /[&#\s"<>]/
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The exact synthetic credential values a `PortFixture` may carry, keyed by lower-case parameter
|
|
93
|
+
* name: SigV4 presigned-URL placeholders for S3-compatible ports (the R2 conformance fixtures sign
|
|
94
|
+
* with them). `scanPortFixtureForSecrets` exempts a credential parameter only when its name is a
|
|
95
|
+
* key here and its whole raw value (up to `&`, `#`, whitespace, `"`, `<`, `>`, or the end),
|
|
96
|
+
* percent-decoded, equals that key's value exactly; anything else inside the value (a raw `?`, an
|
|
97
|
+
* encoded delimiter, any suffix), another parameter name, or another scope is flagged.
|
|
98
|
+
* `scanFixtureForSecrets` exempts nothing. Never build a placeholder by prefixing or suffixing a
|
|
99
|
+
* real value.
|
|
100
|
+
*/
|
|
101
|
+
export const syntheticPortCredentialParams = Object.freeze({
|
|
102
|
+
'x-amz-signature': 'yolk-synthetic-signature',
|
|
103
|
+
'x-amz-credential': 'yolk-synthetic-access-key-id/20260930/auto/s3/aws4_request'
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
const exactPlaceholders = new Map<string, string>(Object.entries(syntheticPortCredentialParams))
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* `text` with `%XX` escapes decoded, repeatedly (at most three layers, then left as it is). The R2
|
|
110
|
+
* guard (`findR2PortFixtureSecrets` in `@yolk-sdk/connectors`) applies at most the same three
|
|
111
|
+
* percent-decoding rounds (plus its escape rounds): keep the percent depth in step.
|
|
112
|
+
*/
|
|
113
|
+
const percentDecodedLayers = (text: string): string => {
|
|
114
|
+
let current = text
|
|
115
|
+
|
|
116
|
+
for (let round = 0; round < 3 && /%[0-9A-Fa-f]{2}/.test(current); round++) {
|
|
117
|
+
current = current.replace(/%([0-9A-Fa-f]{2})/g, (_match, hex: string) =>
|
|
118
|
+
String.fromCharCode(Number.parseInt(hex, 16))
|
|
119
|
+
)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return current
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The raw, undecoded value starting at `start`: up to the first structural boundary. */
|
|
126
|
+
const rawParamValueAt = (text: string, start: number): string => {
|
|
127
|
+
const rest = text.slice(start)
|
|
128
|
+
const end = rest.search(valueBoundary)
|
|
129
|
+
|
|
130
|
+
return end === -1 ? rest : rest.slice(0, end)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* True when `text` carries a credential query or form parameter that is not an exact synthetic
|
|
135
|
+
* placeholder (`syntheticPortCredentialParams`). Every `name=` is found and judged on its own: its
|
|
136
|
+
* raw value runs to the next structural boundary (see `rawParamValueAt`), is percent-decoded
|
|
137
|
+
* (`percentDecodedLayers`), and is exempt only when it equals that name's placeholder exactly. It
|
|
138
|
+
* flags at least whatever `credentialParamPattern` flags (a `name=` followed by any character but
|
|
139
|
+
* `&` or `#`), except the exact placeholders.
|
|
140
|
+
*/
|
|
141
|
+
export const hasLiveCredentialParam = (text: string): boolean =>
|
|
142
|
+
[...text.matchAll(credentialParamNamesAt)].some(match => {
|
|
143
|
+
const name = (match[1] ?? '').toLowerCase()
|
|
144
|
+
const start = match.index + match[0].length
|
|
145
|
+
const value = rawParamValueAt(text, start)
|
|
146
|
+
const next = text.charAt(start)
|
|
147
|
+
const present = value.length > 0 || (next !== '' && next !== '&' && next !== '#')
|
|
148
|
+
|
|
149
|
+
return present && exactPlaceholders.get(name) !== percentDecodedLayers(value)
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
// Singular credential field names (snake, kebab, or camel case), including the AWS-style
|
|
153
|
+
// `accessKeyId` / `secretAccessKey` / `sessionToken` of S3-compatible signing inputs. Plural usage
|
|
154
|
+
// counters such as `max_tokens` or `prompt_tokens` never match.
|
|
155
|
+
const credentialFieldNames =
|
|
156
|
+
'(?:access|refresh|id|auth|api|session|private|bearer|oauth)[_-]?token|token|client[_-]?secret|secret(?:[_-]?key)?|private[_-]?key|password|passwd|api[_-]?key|access[_-]?key[_-]?id|secret[_-]?access[_-]?key|authorization'
|
|
157
|
+
|
|
158
|
+
/** A JSON object key (or similar field name) that holds a credential. */
|
|
159
|
+
export const credentialFieldPattern = new RegExp(`^(${credentialFieldNames})$`, 'i')
|
|
160
|
+
|
|
161
|
+
const globally = (pattern: RegExp): RegExp =>
|
|
162
|
+
new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`)
|
|
163
|
+
|
|
164
|
+
// Redaction forms of the patterns above. They are deliberately broader than the scan (any bearer
|
|
165
|
+
// value, parameters after whitespace or punctuation, `name: value` field pairs) because
|
|
166
|
+
// over-redacting a report message is harmless.
|
|
167
|
+
const bearerRedaction = /\bbearer\s+\S+/gi
|
|
168
|
+
|
|
169
|
+
const apiKeyRedactions: ReadonlyArray<RegExp> = [
|
|
170
|
+
...tokenPrefixPatterns.map(globally),
|
|
171
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g
|
|
172
|
+
]
|
|
173
|
+
|
|
174
|
+
const credentialParamRedaction = new RegExp(
|
|
175
|
+
`(^|[?&\\s;,(])(${credentialParamNames})=[^&#\\s;,)]+`,
|
|
176
|
+
'gi'
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
// `name: value` / `"name": "value"` / `name=value`. An unquoted value may carry an auth scheme
|
|
180
|
+
// (`Authorization: Basic <token>`); a value already redacted as `Bearer <redacted>` is kept.
|
|
181
|
+
const credentialFieldRedaction = new RegExp(
|
|
182
|
+
`(^|[^A-Za-z0-9_-])(["']?)(${credentialFieldNames})\\2(\\s*[:=]\\s*)(?!bearer <redacted>)(?:"(?:[^"\\\\]|\\\\.)*"?|'[^']*'?|(?:(?:basic|bearer|digest|negotiate|token)\\s+)?[^\\s,;&}\\]]+)`,
|
|
183
|
+
'gi'
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
// Candidate unquoted `Name:` header-like names inside one line (colon only). Quoted keys such
|
|
187
|
+
// as `"x-api-key": "..."` are handled by `quotedCredentialHeaderRedaction`; `name=value` pairs
|
|
188
|
+
// are left to the quote-aware field and parameter passes.
|
|
189
|
+
const headerLikeNamePattern = /(?:^|[^A-Za-z0-9_-])([A-Za-z][A-Za-z0-9_-]*)\s*:/g
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Redact the rest of a line after the first header-like `Name:` that `isCredentialHeaderName`
|
|
193
|
+
* accepts (`X-Api-Key: ...`, `Proxy-Authorization: Basic ...`, `Cookie: ...`), so every header the
|
|
194
|
+
* fixture scan flags is also redacted in report text. Runs on the raw text before any other pass,
|
|
195
|
+
* so a partially matched value (for example a key-shaped cookie name) never shields the rest of
|
|
196
|
+
* the line.
|
|
197
|
+
*/
|
|
198
|
+
const redactCredentialHeaderLines = (text: string): string =>
|
|
199
|
+
text
|
|
200
|
+
.split(/(\r\n|\r|\n)/)
|
|
201
|
+
.map(line => {
|
|
202
|
+
headerLikeNamePattern.lastIndex = 0
|
|
203
|
+
|
|
204
|
+
for (let match = headerLikeNamePattern.exec(line); match !== null;) {
|
|
205
|
+
const name = match[1]
|
|
206
|
+
|
|
207
|
+
if (name !== undefined && isCredentialHeaderName(name)) {
|
|
208
|
+
return `${line.slice(0, match.index + match[0].length)} ${redactedHeaderValue}`
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
match = headerLikeNamePattern.exec(line)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return line
|
|
215
|
+
})
|
|
216
|
+
.join('')
|
|
217
|
+
|
|
218
|
+
// A quoted key that `isCredentialHeaderName` accepts (`"x-api-key": "..."`,
|
|
219
|
+
// `'Proxy-Authorization': '...'`): only the value is redacted, so JSON stays balanced.
|
|
220
|
+
const quotedCredentialHeaderRedaction =
|
|
221
|
+
/(["'])([A-Za-z][A-Za-z0-9_-]*)\1(\s*:\s*)("(?:[^"\\]|\\.)*"?|'[^']*'?|[^\s,;&{}[\]]+)/g
|
|
222
|
+
|
|
223
|
+
const redactQuotedCredentialHeaders = (text: string): string =>
|
|
224
|
+
text.replace(
|
|
225
|
+
quotedCredentialHeaderRedaction,
|
|
226
|
+
(match, quote: string, name: string, separator: string) =>
|
|
227
|
+
isCredentialHeaderName(name)
|
|
228
|
+
? `${quote}${name}${quote}${separator}${redactedHeaderValue}`
|
|
229
|
+
: match
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Redact every credential pattern shared with the fixture secret scan: credential header lines
|
|
234
|
+
* (first, to the end of the line), quoted credential header keys (value only), bearer tokens,
|
|
235
|
+
* API-key prefixes, JWTs, private keys, credential field pairs (`"api_key": "..."`,
|
|
236
|
+
* `password="..."`), and credential query/form parameters. Best effort; used on report messages.
|
|
237
|
+
* Known gap: escaped JSON inside a quoted string value (`"body":"{\\"x-api-key\\":...}"`) is not
|
|
238
|
+
* parsed.
|
|
239
|
+
* Quote-aware field redaction runs before parameter redaction so a quoted value with spaces is
|
|
240
|
+
* removed whole.
|
|
241
|
+
*/
|
|
242
|
+
export const redactCredentialText = (text: string): string => {
|
|
243
|
+
let result = redactCredentialHeaderLines(text).replace(
|
|
244
|
+
bearerRedaction,
|
|
245
|
+
`Bearer ${redactedHeaderValue}`
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
for (const pattern of apiKeyRedactions) {
|
|
249
|
+
result = result.replace(pattern, redactedHeaderValue)
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return redactQuotedCredentialHeaders(result)
|
|
253
|
+
.replace(
|
|
254
|
+
credentialFieldRedaction,
|
|
255
|
+
(_match, prefix: string, quote: string, name: string, separator: string) =>
|
|
256
|
+
`${prefix}${quote}${name}${quote}${separator}${redactedHeaderValue}`
|
|
257
|
+
)
|
|
258
|
+
.replace(
|
|
259
|
+
credentialParamRedaction,
|
|
260
|
+
(_match, prefix: string, name: string) => `${prefix}${name}=${redactedHeaderValue}`
|
|
261
|
+
)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export const redactHeaders = (headers: Readonly<Record<string, string>>) => {
|
|
265
|
+
const redacted: Record<string, string> = {}
|
|
266
|
+
|
|
267
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
268
|
+
redacted[name] = isCredentialHeaderName(name) ? redactedHeaderValue : value
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
return redacted
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const compareStrings = (left: string, right: string): number => {
|
|
275
|
+
if (left < right) {
|
|
276
|
+
return -1
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
return left > right ? 1 : 0
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Canonical absolute URL used for matching: hash removed and query parameters
|
|
284
|
+
* sorted by name, then value. Unparseable input is returned unchanged.
|
|
285
|
+
*/
|
|
286
|
+
export const normalizeWireUrl = (input: string): string => {
|
|
287
|
+
if (!URL.canParse(input)) {
|
|
288
|
+
return input
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const url = new URL(input)
|
|
292
|
+
url.hash = ''
|
|
293
|
+
|
|
294
|
+
const params = [...url.searchParams.entries()].sort(
|
|
295
|
+
([leftName, leftValue], [rightName, rightValue]) =>
|
|
296
|
+
leftName === rightName
|
|
297
|
+
? compareStrings(leftValue, rightValue)
|
|
298
|
+
: compareStrings(leftName, rightName)
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
url.search = ''
|
|
302
|
+
|
|
303
|
+
for (const [name, value] of params) {
|
|
304
|
+
url.searchParams.append(name, value)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
return url.toString()
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Match an optional URL filter. A pattern ending in `*` is a prefix match on
|
|
312
|
+
* the normalized URL; otherwise the normalized URLs must be equal.
|
|
313
|
+
*/
|
|
314
|
+
export const urlMatchesPattern = (pattern: string, normalizedUrl: string): boolean =>
|
|
315
|
+
pattern.endsWith('*')
|
|
316
|
+
? normalizedUrl.startsWith(pattern.slice(0, -1))
|
|
317
|
+
: normalizeWireUrl(pattern) === normalizedUrl
|
|
318
|
+
|
|
319
|
+
/** Request body as UTF-8 text when it is an in-memory body; otherwise undefined. */
|
|
320
|
+
export const requestBodyText = (
|
|
321
|
+
request: HttpClientRequest.HttpClientRequest
|
|
322
|
+
): string | undefined => {
|
|
323
|
+
const body = request.body
|
|
324
|
+
|
|
325
|
+
if (Predicate.isTagged(body, 'Uint8Array')) {
|
|
326
|
+
return new TextDecoder().decode(body.body)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
if (Predicate.isTagged(body, 'Raw') && Predicate.isString(body.body)) {
|
|
330
|
+
return body.body
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
return undefined
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** Exact bytes of standard base64 text; `None` when the text is not valid base64. */
|
|
337
|
+
export const decodeBase64Bytes = (text: string): Option.Option<Uint8Array> =>
|
|
338
|
+
Result.getSuccess(Encoding.decodeBase64(text))
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Decode bytes as UTF-8 only when they are valid UTF-8 on their own. A leading
|
|
342
|
+
* byte-order mark is kept so that re-encoding yields the same bytes.
|
|
343
|
+
*/
|
|
344
|
+
export const decodeUtf8Strict = (bytes: Uint8Array): Option.Option<string> =>
|
|
345
|
+
Option.liftThrowable(() =>
|
|
346
|
+
new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes)
|
|
347
|
+
)()
|
|
348
|
+
|
|
349
|
+
/** Lossless recording of bytes: readable text when valid UTF-8, otherwise base64. */
|
|
350
|
+
export const recordBytes = (
|
|
351
|
+
bytes: Uint8Array
|
|
352
|
+
): { readonly text: string } | { readonly base64: string } =>
|
|
353
|
+
Option.match(decodeUtf8Strict(bytes), {
|
|
354
|
+
onNone: () => ({ base64: Encoding.encodeBase64(bytes) }),
|
|
355
|
+
onSome: text => ({ text })
|
|
356
|
+
})
|
|
357
|
+
|
|
358
|
+
const decodeJsonText = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Json))
|
|
359
|
+
|
|
360
|
+
/** Parse text as JSON; `None` when it is not valid JSON. */
|
|
361
|
+
export const parseJsonText = (text: string): Effect.Effect<Option.Option<Schema.Json>> =>
|
|
362
|
+
decodeJsonText(text).pipe(Effect.option)
|
|
363
|
+
|
|
364
|
+
export const headerRecord = (headers: Readonly<Record<string, string | undefined>>) => {
|
|
365
|
+
const record: Record<string, string> = {}
|
|
366
|
+
|
|
367
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
368
|
+
if (value !== undefined) {
|
|
369
|
+
record[name.toLowerCase()] = value
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
return record
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export const mediaType = (contentType: string | undefined): string | undefined =>
|
|
377
|
+
contentType?.split(';', 1)[0]?.trim().toLowerCase()
|
|
378
|
+
|
|
379
|
+
// Web `Response` rejects a body for these statuses.
|
|
380
|
+
const nullBodyStatuses: ReadonlySet<number> = new Set([101, 103, 204, 205, 304])
|
|
381
|
+
|
|
382
|
+
export const isNullBodyStatus = (status: number): boolean => nullBodyStatuses.has(status)
|