@ultimat3/core 31.6.0 → 31.7.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.
@@ -0,0 +1,169 @@
1
+ // Single responsibility: the transform itself, ON THE THREAD THAT CALLS IT — decode, resize,
2
+ // compose, encode. `pipeline.ts`'s `transformImageBytes` runs it inside `raster-worker.ts`; the
3
+ // event loop runs it only where no Worker can start, and there the web role holds it to a budget.
4
+
5
+ import { assert } from '../assert';
6
+ import { composeOnto, type Layout, layOut, type ResizeSpec } from './canvas';
7
+ import { imageFromBunError, imageRasterBudget, imageUnsupported } from './errors';
8
+ import { unshared } from './png-bytes';
9
+ import { decodeImage, encodeImage } from './png-pixels';
10
+ import type { ImageFormat } from './probe';
11
+ import { cropRaster, type ImageRegion, type ImageSize, MAX_IMAGE_PIXELS } from './raster';
12
+
13
+ /**
14
+ * What the pipeline can produce, on every platform, byte for byte. `Bun.Image` also reaches
15
+ * HEIC and AVIF **through an OS codec** — Apple's ImageIO, Windows' WIC — which is a variant
16
+ * that exists on the developer's laptop and not on the Linux node that serves it, under a key
17
+ * that says nothing about which machine minted it. `backend = 'bun'` below refuses that trade,
18
+ * so those two formats are refused HERE rather than silently on one deploy out of two: a caller
19
+ * that needs them routes transforms through a driver (`@ultimat3/seo`'s `ImageTransformDriver`).
20
+ */
21
+ export const ENCODABLE_FORMATS = ['png', 'jpeg', 'webp'] as const;
22
+ /** What the static codecs read. `svg` is markup, and `probeImage` measures it without decoding. */
23
+ export const DECODABLE_FORMATS = ['png', 'jpeg', 'webp', 'gif'] as const;
24
+
25
+ export type DecodableFormat = (typeof DECODABLE_FORMATS)[number];
26
+ export type EncodableFormat = (typeof ENCODABLE_FORMATS)[number];
27
+
28
+ export const canDecode = (format: string): format is DecodableFormat =>
29
+ (DECODABLE_FORMATS as readonly string[]).includes(format);
30
+
31
+ export const canEncode = (format: string): format is EncodableFormat =>
32
+ (ENCODABLE_FORMATS as readonly string[]).includes(format);
33
+
34
+ /** 1-100, lossy formats only. Bun's own default, pinned here so output cannot drift with it. */
35
+ export const DEFAULT_IMAGE_QUALITY = 80;
36
+
37
+ /**
38
+ * The encoder CLAMPS and never refuses, which is why this is a screen and not a comment. Exported
39
+ * because `@ultimat3/storage` mints a variant KEY from the same number without ever reaching this
40
+ * pipeline — two screens that refuse different qualities would mint `q150` keys for bytes this
41
+ * encoder goes on to refuse, which is the dead-on-arrival shape `buildSignedUrl`'s own
42
+ * `finiteCount` screen already exists for — that package held a private `assertFiniteSignedUrlBound`
43
+ * until this sweep collapsed it onto the tier-0 check. Measured
44
+ * on a 3x2 PNG re-encoded as JPEG: quality 80 wrote 663 bytes, and `NaN`, `-5` and `0` each wrote
45
+ * 635 — the worst encoding the codec can make — while `Infinity` and `1e9` each wrote 719. Every
46
+ * one of them silently. `Number(url.searchParams.get('q'))` is `NaN` when the parameter is absent,
47
+ * so the degraded image is the one an unparameterised URL gets.
48
+ */
49
+ export const assertFiniteImageQuality = (quality: number): number => {
50
+ assert(
51
+ Number.isInteger(quality) && quality >= 1 && quality <= 100,
52
+ `image quality is ${String(quality)}, and the encoder clamps rather than refusing: it must be a whole number from 1 to 100`,
53
+ `pass a whole quality from 1 to 100 — transformImageBytes(bytes, { quality: ${String(DEFAULT_IMAGE_QUALITY)} }) — and parse a query value before you pass it`,
54
+ );
55
+ return quality;
56
+ };
57
+
58
+ const encodeFix =
59
+ "request 'png', 'jpeg' or 'webp', or route the transform through an ImageTransformDriver (a " +
60
+ 'CDN or an external encoder) that can produce it';
61
+
62
+ export interface ImageTransformSpec extends ResizeSpec {
63
+ /** Defaults to the source's format when the pipeline can write it, PNG otherwise. */
64
+ readonly format?: ImageFormat | undefined;
65
+ /** 1-100, lossy formats only. */
66
+ readonly quality?: number | undefined;
67
+ }
68
+
69
+ /**
70
+ * `backend = 'bun'` is set on every call, not once at import. It forces the statically-linked
71
+ * codecs and the Highway geometry kernels on every OS, which is what makes the same source and
72
+ * the same spec the same BYTES on a laptop and on the node — and `variantKey` is content-
73
+ * addressed, so a variant that re-encoded differently per platform would be a cache that never
74
+ * hits and a hash that never agrees. Per call rather than at import because the property is
75
+ * process-global and writable: an app that flips it back would otherwise silently win.
76
+ */
77
+ export function bunImage(bytes: Uint8Array): Bun.Image {
78
+ Bun.Image.backend = 'bun';
79
+ // The decompression-bomb ceiling, enforced by the decoder from the header before it allocates
80
+ // — the same number `probeImage` refuses at, so the two answers cannot disagree.
81
+ return new Bun.Image(unshared(bytes), { maxPixels: MAX_IMAGE_PIXELS });
82
+ }
83
+
84
+ function withFormat(image: Bun.Image, format: EncodableFormat, quality: number): Bun.Image {
85
+ if (format === 'png') return image.png();
86
+ if (format === 'jpeg') return image.jpeg({ quality });
87
+ return image.webp({ quality });
88
+ }
89
+
90
+ /** Every rejection from `Bun.Image` becomes one of the three `X_IMAGE_*` codes, never a bare one. */
91
+ export async function run<T>(doing: string, work: () => Promise<T>): Promise<T> {
92
+ try {
93
+ return await work();
94
+ } catch (error) {
95
+ throw imageFromBunError(error, doing);
96
+ }
97
+ }
98
+
99
+ /**
100
+ * `region` of the source as PNG. `Bun.Image` has no crop, so the source is decoded to a raster
101
+ * (within the same `MAX_IMAGE_PIXELS` its header was held to) and the region copied out of it.
102
+ */
103
+ async function croppedPng(bytes: Uint8Array, region: ImageRegion): Promise<Uint8Array> {
104
+ const whole = await run('decoding the image', () => bunImage(bytes).png().bytes());
105
+ return encodeImage(cropRaster(decodeImage(whole), region));
106
+ }
107
+
108
+ /**
109
+ * The whole pipeline in one call: decode, resize, compose, encode. `syncBudget` is the most pixels
110
+ * the two raster hops below — `png-pixels.ts`'s inflate and deflate, which block the thread — may
111
+ * touch; past it the call is `X_IMAGE_RASTER_BUDGET` before either hop runs. Absent, no bound:
112
+ * inside the Worker a long hop blocks nobody.
113
+ */
114
+ export async function transformInline(
115
+ bytes: Uint8Array,
116
+ spec: ImageTransformSpec = {},
117
+ syncBudget?: number,
118
+ ): Promise<Uint8Array> {
119
+ const { format } = spec;
120
+ // The spec alone answers "can this be written?", so answer it here — decoding and resampling
121
+ // 64 megapixels first, only to refuse at the encoder, is work nobody can use.
122
+ if (format !== undefined && !canEncode(format)) {
123
+ throw imageUnsupported(`encoding ${format} is not built in`, encodeFix, { format });
124
+ }
125
+ const quality = assertFiniteImageQuality(spec.quality ?? DEFAULT_IMAGE_QUALITY);
126
+ const source = await run('reading the image header', () => bunImage(bytes).metadata());
127
+ const output: EncodableFormat = format ?? (canEncode(source.format) ? source.format : 'png');
128
+ const layout = layOut(source, spec);
129
+ const { box, drawn, crop } = layout;
130
+ if (syncBudget !== undefined) holdToBudget(source, layout, syncBudget);
131
+ // The cropped region stands in for the source from here on: what is resampled is what shows.
132
+ const input = crop === undefined ? bytes : await croppedPng(bytes, crop);
133
+ const inputSize = crop ?? source;
134
+
135
+ if (!layout.needsCanvas) {
136
+ return run('transforming the image', () => {
137
+ const image = bunImage(input);
138
+ if (box.width !== inputSize.width || box.height !== inputSize.height) {
139
+ image.resize(box.width, box.height, { fit: 'fill' });
140
+ }
141
+ return withFormat(image, output, quality).bytes();
142
+ });
143
+ }
144
+
145
+ // The letterbox / padding / crop path. `Bun.Image` resamples but has no compositor, so the
146
+ // artwork comes back as PNG, is placed on the canvas here, and goes back through Bun to be
147
+ // written. Back through Bun even when the output IS png: `png-pixels.ts` writes filter 0, which
148
+ // is 1.2-1.8x libspng's bytes on a real icon (measured), and one writer for everything this
149
+ // function returns is also what makes "same input, same bytes" rest on the static codecs alone.
150
+ const art = await run('resampling the image', () =>
151
+ bunImage(input).resize(drawn.width, drawn.height, { fit: 'fill' }).png().bytes(),
152
+ );
153
+ const composed = encodeImage(composeOnto(decodeImage(art), layout));
154
+ return run('encoding the image', () => withFormat(bunImage(composed), output, quality).bytes());
155
+ }
156
+
157
+ /**
158
+ * The pixels the synchronous hops would inflate plus those they would deflate: a crop decodes the
159
+ * WHOLE source and encodes the region, a composite decodes the resampled art and encodes the
160
+ * canvas. A plain resize touches none — `Bun.Image` resamples off the event loop (measured: 0-9 ms
161
+ * worst gap on a 4096² source).
162
+ */
163
+ function holdToBudget(source: ImageSize, layout: Layout, budget: number): void {
164
+ const area = (size: ImageSize): number => size.width * size.height;
165
+ const cropped = layout.crop === undefined ? 0 : area(source) + area(layout.crop);
166
+ const composed = layout.needsCanvas ? area(layout.drawn) + area(layout.box) : 0;
167
+ const pixels = cropped + composed;
168
+ if (pixels > budget) throw imageRasterBudget(pixels, budget);
169
+ }
package/src/index.ts CHANGED
@@ -92,6 +92,8 @@ export type {
92
92
  BreakerVerdict,
93
93
  } from './breaker';
94
94
  export { breaker, settleWith } from './breaker';
95
+ export type { RetryBudget } from './breaker-retry-budget';
96
+ export { retryBudgetOf } from './breaker-retry-budget';
95
97
  export { isCompiledBundle } from './bunfs';
96
98
  export type { CacheEvictionOptions } from './cache-eviction';
97
99
  export { evictCacheFiles } from './cache-eviction';
@@ -571,6 +573,7 @@ export {
571
573
  memoryExporter,
572
574
  memoryMetricExporter,
573
575
  metricsText,
576
+ monitorFingerprint,
574
577
  noopErrorReporter,
575
578
  OTLP_RETRY_STATUSES,
576
579
  OtlpEndpointInvalidError,
@@ -724,6 +727,7 @@ export {
724
727
  export type { ImageFit, ResizeSpec } from './image/canvas';
725
728
  export {
726
729
  ImageDecodeFailedError,
730
+ ImageRasterBudgetError,
727
731
  ImageTooLargeError,
728
732
  ImageUnsupportedError,
729
733
  imageDecodeFailed,
@@ -749,6 +753,9 @@ export {
749
753
  hasAlpha,
750
754
  MAX_IMAGE_PIXELS,
751
755
  } from './image/raster';
756
+ export { RASTER_SYNC_PIXELS } from './image/raster-pool';
757
+ export type { RasterWorkerBundle } from './image/raster-worker-bundle';
758
+ export { RASTER_WORKER_DEFINE, rasterWorkerBundle } from './image/raster-worker-bundle';
752
759
  export { impersonate, isImpersonating } from './impersonate';
753
760
  export { withInProcessFetch } from './in-process-fetch';
754
761
  export {
@@ -819,7 +826,9 @@ export type { LocalePathSplit } from './locale-path';
819
826
  export { localeSegment, localizePath, splitLocalePath } from './locale-path';
820
827
  // The process logger's test seam, beside nothing it groups with: where a default-writer line goes.
821
828
  export type { LogSink } from './logger';
822
- export { installLogSink } from './logger';
829
+ export { installLogSink, teeLogLines } from './logger';
830
+ export type { MapBoundedOptions } from './map-bounded';
831
+ export { mapBounded } from './map-bounded';
823
832
  export {
824
833
  isAgentOffered,
825
834
  isMcpExposed,
@@ -0,0 +1,222 @@
1
+ // Single responsibility: what a log line may carry — the one answer to "is this field a
2
+ // credential?" (`isRedactedKey`) and the walk that makes a caller's record safe to serialise and
3
+ // safe to ship (`redactFields`). Split out of `logger.ts`, which writes the line.
4
+
5
+ import { renderCauseValue } from './error-render';
6
+ import { isUltimateError } from './errors';
7
+ import { isSecret, REDACTED } from './secret';
8
+
9
+ /** What a `Date` this file cannot render says instead — the line survives, the value is named. */
10
+ export const INVALID_DATE = 'an invalid Date';
11
+
12
+ /** A caller's field record. Declared here, re-exported by `logger.ts`, so neither imports a cycle. */
13
+ export interface LogFields {
14
+ readonly [key: string]: unknown;
15
+ }
16
+
17
+ /**
18
+ * The exact-key FAST PATH. LOWERCASE, always: `isRedactedKey` lowercases its lookup, so
19
+ * `apiKey`/`accessToken`/`refreshToken` sat here for three releases matching nothing — and those
20
+ * are the exact field names on `@ultimat3/auth`'s `OAuthTokens`. Add through `redactKeys()` (which
21
+ * lowercases) rather than here. A name this set misses still meets `CREDENTIAL_NAME` below.
22
+ */
23
+ const redactedKeys = new Set<string>([
24
+ 'password',
25
+ 'token',
26
+ 'secret',
27
+ 'authorization',
28
+ 'cookie',
29
+ 'set-cookie',
30
+ 'apikey',
31
+ 'api_key',
32
+ 'accesstoken',
33
+ 'access_token',
34
+ 'refreshtoken',
35
+ 'refresh_token',
36
+ 'idtoken',
37
+ 'id_token',
38
+ 'sessiontoken',
39
+ 'session_token',
40
+ 'clientsecret',
41
+ 'client_secret',
42
+ 'privatekey',
43
+ 'private_key',
44
+ // The framework's own columns (`@ultimat3/auth`): a hash is what an offline guess runs against.
45
+ 'passwordhash',
46
+ 'tokenhash',
47
+ 'keyhash',
48
+ ]);
49
+
50
+ /**
51
+ * The second half, for the names no list can enumerate. Exact-key matching alone let every
52
+ * COMPOUND credential through — `currentPassword`, `mfaSecret`, `resetToken`, `recoveryCode` — and
53
+ * `@ultimat3/action`'s audit walk asks this same predicate, so each was persisted in clear.
54
+ *
55
+ * Tested against the key lowercased with `_` and `-` removed, so one pattern covers the camel, the
56
+ * snake and the header spelling. It names what BEARS a credential and nothing wider, because a
57
+ * redacted field is one an operator cannot correlate on:
58
+ *
59
+ * - `password` / `passphrase` anywhere — no ordinary field carries the word.
60
+ * - `secret` as the LAST word (`mfaSecret`, `webhookSecret`, `appSecrets`, `secretAccessKey`), so
61
+ * `clientSecretEnv` and `secretsPath` — a variable name and a path — stay readable.
62
+ * - a `token` is a bearer UNLESS its qualifier says it is not: fail closed, with the exceptions
63
+ * named. `idempotencyToken`, `pageToken`, `continuationToken`, `cursorToken`, `syncToken` are
64
+ * dedupe and paging keys an operator greps for; everything else ending in `token` — `resetToken`,
65
+ * `githubToken`, `NPM_TOKEN` — is redacted without a provider list to keep current. The PLURAL
66
+ * is the reverse: `maxTokens` / `inputTokens` are counts on every `@ultimat3/ai` usage line, so
67
+ * `tokens` is redacted only behind a bearer qualifier (`accessTokens`).
68
+ * - key MATERIAL by its qualifier (`apiKey`, `privateKey`, `signingKey`, `encryptionKey`,
69
+ * `masterKey`, `hmacKey`, `secretsKey`, `accessKey`, `retiredKeys`) and the id half of a key
70
+ * pair (`accessKeyId`). A LOOKUP key — `cacheKey`, `primaryKey`, `idempotencyKey` — and a key's
71
+ * own id (`signingKeyId`) carry no qualifier on this list and stay readable.
72
+ * - a value that EMBEDS a credential: `connectionString`, `dsn`, a registry `authConfig`, and the
73
+ * service URLs that carry `user:password@` (`databaseUrl`, `REDIS_URL`). A bare `url` does not.
74
+ * - the one-time codes by name. Never a `code` suffix: that is the error contract's own field.
75
+ * - a stored hash of any of them: it is what an offline guess runs against.
76
+ * - a bearer by its kind as the LAST word: `credentials`, `jwt`, `bearer`, `cookies`, a session's
77
+ * id or key (`sessionId` IS the session), and key material by encoding (`privateKeyPem`).
78
+ * `credentialId`, `jwtIssuer`, `cookieName`, `privateKeyId` name a credential, not hold one.
79
+ * - card verification codes (`cvv`, `cvc2`) as a suffix, and a `pin` only as the WHOLE word
80
+ * behind an owner qualifier — three letters inside `spinner`, `shipping` or `pinned` are not one.
81
+ *
82
+ * Built from constant alternatives with no nested quantifier, so there is no input it backtracks on.
83
+ */
84
+ /**
85
+ * The verdict per key AS WRITTEN, so a repeat skips the lower-casing too. A line asks it for every
86
+ * key, every time: 249 ns a key through the regex, a handful of distinct keys per process in practice.
87
+ */
88
+ const verdicts = new Map<string, boolean>();
89
+
90
+ /** Exported for its own work-count test only (`logger-redact.test.ts`); never on the barrel. */
91
+ export const CREDENTIAL_NAME = new RegExp(
92
+ [
93
+ 'passw(?:or)?d|passphrase',
94
+ 'secrets?$',
95
+ '(?:api|private|signing|encryption|master|hmac|secrets?|access|retired)keys?$|accesskeyid$',
96
+ '(?:token|key)hash(?:es)?$',
97
+ '(?<!idempotency|page|continuation|cursor|sync)token$',
98
+ '(?:access|refresh|id|session|reset|bearer|auth|api|csrf|xsrf|captcha|card|verification|invite|magic|magiclink|device|push|workload|oauth)tokens$',
99
+ 'authconfig$|connectionstring$|dsn$',
100
+ '(?:database|db|redis|replication|nats|smtp|amqp|mongo)ur[li]s?$',
101
+ '^totp$|totpcode$|otp$|otpcode$',
102
+ '(?:recovery|backup|mfa)codes?(?:hash(?:es)?)?$',
103
+ 'credentials?$|jwts?$|bearer$|cookies?$|session(?:id|key)s?$',
104
+ 'privatekey(?:pem|der|jwk)$',
105
+ 'cv[vc]2?$',
106
+ '^(?:card|atm|security|account|user|wallet)?pin(?:code|number)?(?:hash(?:es)?)?$',
107
+ ].join('|'),
108
+ );
109
+
110
+ /** Mark keys as secret everywhere. `defineEnv()` calls this for every `secret: true` var. */
111
+ export function redactKeys(keys: Iterable<string>): void {
112
+ for (const key of keys) redactedKeys.add(key.toLowerCase());
113
+ // A key memoised as readable before it was declared secret must not stay readable — and neither
114
+ // may a field a logger redacted when it was bound: the generation tells it to redact again.
115
+ verdicts.clear();
116
+ generation += 1;
117
+ }
118
+
119
+ /** Bumped by every `redactKeys` call. A snapshot redacted at an older generation is stale. */
120
+ let generation = 0;
121
+
122
+ /** The current redaction generation: one integer compare is the whole cost of staying current. */
123
+ export function redactionGeneration(): number {
124
+ return generation;
125
+ }
126
+
127
+ /** How many key verdicts are remembered. Past it the oldest is forgotten and asked again. */
128
+ export const REDACTION_MEMO_SIZE = 4096;
129
+
130
+ /**
131
+ * The framework's ONE answer to "is this field a credential?" — the log line, the error monitor's
132
+ * envelope and `@ultimat3/action`'s audit row all ask it, so a value that is `[redacted]` in one
133
+ * cannot be plaintext in another.
134
+ */
135
+ export function isRedactedKey(key: string): boolean {
136
+ const known = verdicts.get(key);
137
+ if (known !== undefined) return known;
138
+ const lower = key.toLowerCase();
139
+ const verdict = redactedKeys.has(lower) || CREDENTIAL_NAME.test(lower.replace(/[_-]/g, ''));
140
+ // Insertion order is age, so the first key is the oldest: FIFO, no bookkeeping per hit. Bounded
141
+ // because a key is caller data — a request body's own keys reach `redactFields`.
142
+ if (verdicts.size >= REDACTION_MEMO_SIZE) verdicts.delete(verdicts.keys().next().value ?? '');
143
+ verdicts.set(key, verdict);
144
+ return verdict;
145
+ }
146
+
147
+ /**
148
+ * TOTAL, on purpose. `lifecycle.ts` logs the value a shutdown hook threw and the value a
149
+ * readiness check threw — both caught, both arbitrary — so a renderer that throws here escapes
150
+ * `runPhase`'s catch, rejects the drain promise, and `installSignalHandlers` never reaches
151
+ * `process.exit(0)`: SIGTERM hangs, and `/readyz` dies with the check it was reporting on. A log
152
+ * line must never replace the event it describes.
153
+ *
154
+ * Degradation is per KEY, the same shape `renderMetaRecord` uses: one hostile getter must not
155
+ * cost a reader the fields beside it.
156
+ */
157
+ function serialiseValue(value: unknown, depth: number): unknown {
158
+ try {
159
+ return serialise(value, depth);
160
+ } catch {
161
+ // `instanceof`, `Object.keys` and `toJSON` are all property reads on a value the framework
162
+ // did not build; `renderCauseValue` is the one renderer that cannot itself throw.
163
+ return renderCauseValue(value);
164
+ }
165
+ }
166
+
167
+ function serialise(value: unknown, depth: number): unknown {
168
+ // `JSON.stringify` raises a `TypeError` on a bigint, so the whole line died for one field.
169
+ if (typeof value === 'bigint') return renderCauseValue(value);
170
+ if (value === null || typeof value !== 'object') return value;
171
+ // Before every other branch: a `Secret` is redacted by VALUE, so it stays redacted under a key
172
+ // nobody listed — `{ dsn: secret(url) }` is the leak key-name redaction cannot see.
173
+ if (isSecret(value)) return REDACTED;
174
+ // `toISOString()` THROWS on an invalid Date, and an invalid Date is exactly the value worth
175
+ // logging when a schedule went wrong.
176
+ if (value instanceof Date) {
177
+ return Number.isNaN(value.getTime()) ? INVALID_DATE : value.toISOString();
178
+ }
179
+ if (isUltimateError(value)) return value.toJSON();
180
+ if (value instanceof Error) return { name: value.name, message: value.message };
181
+ if (depth >= 6) return '[depth-limit]';
182
+ if (Array.isArray(value)) return value.map((item) => serialiseValue(item, depth + 1));
183
+ const source = value as Record<string, unknown>;
184
+ const out: Record<string, unknown> = {};
185
+ for (const key of Object.keys(source)) {
186
+ out[key] = isRedactedKey(key) ? REDACTED : entryValue(source, key, depth);
187
+ }
188
+ return out;
189
+ }
190
+
191
+ /** One field. The `try` covers the property READ — `serialiseValue` above is already total. */
192
+ function entryValue(source: Record<string, unknown>, key: string, depth: number): unknown {
193
+ try {
194
+ return serialiseValue(source[key], depth + 1);
195
+ } catch {
196
+ return 'a value that cannot be read';
197
+ }
198
+ }
199
+
200
+ /**
201
+ * A caller's record made safe to SERIALISE and safe to SHIP: credentials replaced by key and by
202
+ * value, a bigint / cycle / hostile getter degraded per field. Exported for the one other sink
203
+ * that sends a caller's record off the box — `error-reporter-sentry.ts`.
204
+ */
205
+ export function redactFields(fields: LogFields): Record<string, unknown> {
206
+ const out: Record<string, unknown> = {};
207
+ const source = fields as Record<string, unknown>;
208
+ // `Object.keys` before the values, so the read of each value is its own guarded step: a field
209
+ // record is the caller's object, and enumerating it eagerly threw on the first hostile getter.
210
+ for (const key of ownKeys(source)) {
211
+ out[key] = isRedactedKey(key) ? REDACTED : entryValue(source, key, 0);
212
+ }
213
+ return out;
214
+ }
215
+
216
+ function ownKeys(source: Record<string, unknown>): readonly string[] {
217
+ try {
218
+ return Object.keys(source);
219
+ } catch {
220
+ return [];
221
+ }
222
+ }