diff --git a/docs/guides/sources-and-loading.md b/docs/guides/sources-and-loading.md index 8bf7d3a..ad34b0c 100644 --- a/docs/guides/sources-and-loading.md +++ b/docs/guides/sources-and-loading.md @@ -47,7 +47,11 @@ the document. A source must be a `require()` asset number or an object with `uri`, `filePath` or `base64`. Anything else — a raw URL string (e.g. `'https://...'`), an empty object `{}`, property types that do not match (such as `{ uri: 42 }`), or list -items that are not objects (such as `[null]`) — is malformed: +items that are not objects (such as `[null]`) — is malformed. So is a URI +source with an option of the wrong type: `headers` that is not an object of +strings (a header whose value is `undefined` included), `cache` other than +`'session'` or `'persistent'`, `maxAgeMs` that is not a finite number of at +least 0, or `cacheKey` that is not a string. `null` options count as absent. - In `PdfView`: it never throws during render. Nothing is sent to native, and `onError` is called once with `code: 'invalid-source'` and an explanatory diff --git a/package/src/PdfCache.test.ts b/package/src/PdfCache.test.ts index 79b33f6..7575c6d 100644 --- a/package/src/PdfCache.test.ts +++ b/package/src/PdfCache.test.ts @@ -241,4 +241,21 @@ describe('PdfCache', () => { await expect(removePromise!).rejects.toThrow(); } }); + + test('download, getEntry and remove reject options of the wrong type before native code', async () => { + const source = { uri: 'https://x.test/a.pdf', cacheKey: 42 } as never; + const error = await PdfCache.download(source).catch((e: unknown) => e); + expect(error).toBeInstanceOf(PdfDownloadError); + expect(error).toMatchObject({ + code: 'invalid-source', + message: 'source.cacheKey must be a string; got 42', + }); + await expect(PdfCache.getEntry(source)).rejects.toThrow( + 'source.cacheKey must be a string; got 42', + ); + await expect(PdfCache.remove(source)).rejects.toThrow( + 'source.cacheKey must be a string; got 42', + ); + expect(downloads).toEqual([]); + }); }); diff --git a/package/src/PdfDocument.test.ts b/package/src/PdfDocument.test.ts index 33286e0..9d03983 100644 --- a/package/src/PdfDocument.test.ts +++ b/package/src/PdfDocument.test.ts @@ -172,6 +172,19 @@ describe('PdfDocument.open', () => { } }); + test('rejects options of the wrong type before creating the native object', async () => { + const error = await PdfDocument.open({ + uri: 'https://x.test/a.pdf', + cacheKey: 42, + } as never).catch((e: unknown) => e); + expect(error).toBeInstanceOf(PdfOpenError); + expect(error).toMatchObject({ + code: 'invalid-source', + message: 'source.cacheKey must be a string; got 42', + }); + expect(natives).toEqual([]); + }); + test("a source's own password takes precedence over the option", async () => { void PdfDocument.open( { uri: '/docs/a.pdf', password: 'own' }, diff --git a/package/src/PdfView.test.tsx b/package/src/PdfView.test.tsx index 3829b10..6be26f5 100644 --- a/package/src/PdfView.test.tsx +++ b/package/src/PdfView.test.tsx @@ -1162,6 +1162,27 @@ describe('PdfView', () => { ]); }); + test('source options of the wrong type call onError once and send nothing to native', () => { + const errors: unknown[] = []; + render( + errors.push(err)} + />, + ); + expect(hostRenders.length).toBe(0); + expect(errors).toEqual([ + { + code: 'invalid-source', + message: 'source.headers["X-User"] must be a string; got 7', + sourceIndex: 1, + }, + ]); + }); + test('promise methods reject with coded PdfMethodErrors', async () => { const ref = createRef(); render(); diff --git a/package/src/source.test.ts b/package/src/source.test.ts index e0a90ae..e74a7ca 100644 --- a/package/src/source.test.ts +++ b/package/src/source.test.ts @@ -87,6 +87,105 @@ describe('validateSourceItem', () => { test('unresolvable assets become an empty uri, which native reports as invalid-source', () => { expect(validatedSource(99)).toEqual({ uri: '' }); }); + + test('null options are absent', () => { + expect( + validatedSource({ + uri: 'https://x.test/a.pdf', + headers: null, + cache: null, + maxAgeMs: null, + cacheKey: null, + }), + ).toEqual({ uri: 'https://x.test/a.pdf' }); + }); + + test('reports options of the wrong type, naming the option', () => { + const uri = 'https://x.test/a.pdf'; + const cases: [Record, string][] = [ + [{ uri, cacheKey: 42 }, 'source.cacheKey must be a string; got 42'], + [ + { uri, headers: 'Authorization: x' }, + 'source.headers must be an object of strings; got a string', + ], + [ + { uri, headers: ['x'] }, + 'source.headers must be an object of strings; got an array', + ], + [ + { uri, headers: new Map([['Authorization', 'x']]) }, + 'source.headers must be an object of strings; got a Map', + ], + [ + { uri, headers: { 'X-User': 7 } }, + 'source.headers["X-User"] must be a string; got 7', + ], + [ + { uri, headers: { Authorization: undefined } }, + 'source.headers["Authorization"] must be a string; got undefined', + ], + [ + { uri, headers: { Authorization: null } }, + 'source.headers["Authorization"] must be a string; got null', + ], + [ + { uri, cache: 'Persistent' }, + "source.cache must be 'session' or 'persistent'; got a string", + ], + [ + { uri, cache: true }, + "source.cache must be 'session' or 'persistent'; got true", + ], + [ + { uri, maxAgeMs: '0' }, + 'source.maxAgeMs must be a finite number of at least 0; got a string', + ], + [ + { uri, maxAgeMs: -1 }, + 'source.maxAgeMs must be a finite number of at least 0; got -1', + ], + [ + { uri, maxAgeMs: Number.NaN }, + 'source.maxAgeMs must be a finite number of at least 0; got NaN', + ], + [ + { uri, maxAgeMs: Number.POSITIVE_INFINITY }, + 'source.maxAgeMs must be a finite number of at least 0; got Infinity', + ], + ]; + for (const [source, error] of cases) { + expect(validateSourceItem(source, resolveAsset)).toEqual({ + ok: false, + error, + }); + expect(() => normalizeUriSource(source as never)).toThrow(error); + } + }); + + test('reads each option once, so a getter cannot change it after the check', () => { + let reads = 0; + const headers = { + get Authorization() { + reads += 1; + return reads === 1 ? 'Bearer 1' : (7 as never); + }, + }; + let headersReads = 0; + const source = { + uri: 'https://x.test/a.pdf', + get headers() { + headersReads += 1; + return headersReads === 1 ? headers : (7 as never); + }, + }; + expect(validateSourceItem(source, resolveAsset)).toEqual({ + ok: true, + source: { + uri: 'https://x.test/a.pdf', + headers: { Authorization: 'Bearer 1' }, + }, + }); + }); }); describe('sourceKey', () => { diff --git a/package/src/source.ts b/package/src/source.ts index 6843cc5..6c3d728 100644 --- a/package/src/source.ts +++ b/package/src/source.ts @@ -120,14 +120,21 @@ function describeValue(value: unknown): string { return 'a string'; case 'number': return Number.isNaN(value) ? 'NaN' : String(value); + case 'boolean': + return String(value); case 'bigint': return `${value}n`; case 'symbol': return value.toString(); case 'function': return 'a function'; - case 'object': - return Array.isArray(value) ? 'an array' : 'an object'; + case 'object': { + if (Array.isArray(value)) return 'an array'; + const name = Object.getPrototypeOf(value)?.constructor?.name; + return typeof name === 'string' && name !== 'Object' + ? `a ${name}` + : 'an object'; + } default: return typeof value; } @@ -204,9 +211,8 @@ export function validateSourceItem( }; } if ('uri' in obj) { - if (typeof obj.uri === 'string') { - return { ok: true, source: normalizeUriSource(source as PdfUriSource) }; - } + const { uri } = obj; + if (typeof uri === 'string') return uriSourceResult(uri, obj); return { ok: false, error: `source must be a require() result or an object with uri, filePath or base64; got ${describeSourceType(source)}`, @@ -219,28 +225,90 @@ export function validateSourceItem( } /** - * The native shape of a URI source. Copies `headers` so later mutation of - * the caller's object cannot leak into native code, and leaves absent - * options absent. + * The native shape of a URI source, or why its options are invalid: Nitro's + * converters throw on a value of the wrong type. Reads each option once and + * copies `headers`, so neither a getter nor later mutation of the caller's + * object can change what was checked. `null` options are absent. */ +function uriSourceResult( + uri: string, + source: Record, +): + | { ok: true; source: Omit } + | { ok: false; error: string } { + const { headers, cache, maxAgeMs, cacheKey } = source; + const normalized: Omit = { uri }; + if (headers != null) { + const prototype = + typeof headers === 'object' ? Object.getPrototypeOf(headers) : undefined; + if (prototype !== Object.prototype && prototype !== null) { + return { + ok: false, + error: `source.headers must be an object of strings; got ${describeValue(headers)}`, + }; + } + const copy: Record = {}; + for (const [name, value] of Object.entries(headers as object)) { + if (typeof value !== 'string') { + return { + ok: false, + error: `source.headers[${JSON.stringify(name)}] must be a string; got ${describeValue(value)}`, + }; + } + copy[name] = value; + } + normalized.headers = copy; + } + if (cache != null) { + if (cache !== 'session' && cache !== 'persistent') { + return { + ok: false, + error: `source.cache must be 'session' or 'persistent'; got ${describeValue(cache)}`, + }; + } + normalized.cache = cache; + } + if (maxAgeMs != null) { + if ( + typeof maxAgeMs !== 'number' || + !Number.isFinite(maxAgeMs) || + maxAgeMs < 0 + ) { + return { + ok: false, + error: `source.maxAgeMs must be a finite number of at least 0; got ${describeValue(maxAgeMs)}`, + }; + } + normalized.maxAgeMs = maxAgeMs; + } + if (cacheKey != null) { + if (typeof cacheKey !== 'string') { + return { + ok: false, + error: `source.cacheKey must be a string; got ${describeValue(cacheKey)}`, + }; + } + normalized.cacheKey = cacheKey; + } + return { ok: true, source: normalized }; +} + +/** The native shape of a URI source; throws when it is invalid. */ export function normalizeUriSource( source: PdfUriSource, ): Omit { - if ( - source == null || - typeof source !== 'object' || - typeof (source as { uri?: unknown }).uri !== 'string' - ) { + const uri = (source as { uri?: unknown } | null | undefined)?.uri; + if (source == null || typeof source !== 'object' || typeof uri !== 'string') { throw new Error( `source must be an object with uri; got ${describeSourceType(source, true)}`, ); } - const normalized: Omit = { uri: source.uri }; - if (source.headers != null) normalized.headers = { ...source.headers }; - if (source.cache != null) normalized.cache = source.cache; - if (source.maxAgeMs != null) normalized.maxAgeMs = source.maxAgeMs; - if (source.cacheKey != null) normalized.cacheKey = source.cacheKey; - return normalized; + const result = uriSourceResult( + uri, + source as unknown as Record, + ); + if (!result.ok) throw new Error(result.error); + return result.source; } /** The source's own password, if it has one (bundled assets cannot). */