diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index b8c10a5..5b8ab0b 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -27,15 +27,6 @@ jobs: run: npm run build - name: Run benchmark - run: node benchmark.js | tee output.txt + run: node benchmark.js env: NODE_ENV: production - - - name: Store benchmark result - uses: rhysd/github-action-benchmark@v1 - with: - tool: 'benchmarkjs' - output-file-path: output.txt - comment-on-alert: true - save-data-file: ${{ github.ref == 'refs/heads/main' }} - github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/benchmark.js b/benchmark.js index 44ccd11..1051b1a 100644 --- a/benchmark.js +++ b/benchmark.js @@ -81,9 +81,14 @@ const instances = { const suite = new Benchmark.Suite('serialize & deserialize'); for (const [key, instance] of Object.entries(instances)) { - suite.add(key, () => { - SuperJSON.deserialize(SuperJSON.serialize(instance)); - }); + suite.add( + key, + async deferred => { + await SuperJSON.deserialize(await SuperJSON.serialize(instance)); + deferred.resolve(); + }, + { defer: true } + ); } suite.on('cycle', event => { diff --git a/package-lock.json b/package-lock.json index 7452961..39a3563 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,11 +1,11 @@ { - "name": "superjson", + "name": "@eridu-tech/superjson", "version": "2.2.5", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "superjson", + "name": "@eridu-tech/superjson", "version": "2.2.5", "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index e621094..b1addd9 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ }, "scripts": { "build": "tsc", + "check": "tsc --noEmit --project ./tsconfig.check.json", "test": "vitest run", "prepack": "npm run build" }, @@ -24,7 +25,7 @@ "singleQuote": true, "trailingComma": "es5" }, - "name": "superjson", + "name": "@eridu-tech/superjson", "author": { "name": "Simon Knott", "email": "info@simonknott.de", diff --git a/src/accessDeep.test.ts b/src/accessDeep.test.ts index 5e64fad..828977c 100644 --- a/src/accessDeep.test.ts +++ b/src/accessDeep.test.ts @@ -2,27 +2,27 @@ import { setDeep } from './accessDeep.js'; import { describe, it, expect } from 'vitest'; -describe('setDeep', () => { - it('correctly sets values in maps', () => { +describe('setDeep', () => { + it('correctly sets values in maps', async () => { const obj = { a: new Map([[new Set(['NaN']), [[1, 'undefined']]]]), }; - setDeep(obj, ['a', 0, 0, 0], Number); - setDeep(obj, ['a', 0, 1], entries => new Map(entries)); - setDeep(obj, ['a', 0, 1, 0, 1], () => undefined); + await setDeep(obj, ['a', 0, 0, 0], async v => Number(v)); + await setDeep(obj, ['a', 0, 1], async entries => new Map(entries)); + await setDeep(obj, ['a', 0, 1, 0, 1], async () => undefined); expect(obj).toEqual({ a: new Map([[new Set([NaN]), new Map([[1, undefined]])]]), }); }); - it('correctly sets values in sets', () => { + it('correctly sets values in sets', async () => { const obj = { a: new Set([10, new Set(['NaN'])]), }; - setDeep(obj, ['a', 1, 0], Number); + await setDeep(obj, ['a', 1, 0], async v => Number(v)); expect(obj).toEqual({ a: new Set([10, new Set([NaN])]), diff --git a/src/accessDeep.ts b/src/accessDeep.ts index ea98613..096cb1e 100644 --- a/src/accessDeep.ts +++ b/src/accessDeep.ts @@ -52,15 +52,15 @@ export const getDeep = (object: object, path: (string | number)[]): object => { return object; }; -export const setDeep = ( +export const setDeep = async ( object: any, path: (string | number)[], - mapper: (v: any) => any -): any => { + mapper: (v: any) => Promise +): Promise => { validatePath(path); if (path.length === 0) { - return mapper(object); + return await mapper(object); } let parent = object; @@ -100,14 +100,14 @@ export const setDeep = ( const lastKey = path[path.length - 1]; if (isArray(parent)) { - parent[+lastKey] = mapper(parent[+lastKey]); + parent[+lastKey] = await mapper(parent[+lastKey]); } else if (isPlainObject(parent)) { - parent[lastKey] = mapper(parent[lastKey]); + parent[lastKey] = await mapper(parent[lastKey]); } if (isSet(parent)) { const oldValue = getNthKey(parent, +lastKey); - const newValue = mapper(oldValue); + const newValue = await mapper(oldValue); if (oldValue !== newValue) { parent.delete(oldValue); parent.add(newValue); @@ -121,7 +121,7 @@ export const setDeep = ( const type = +lastKey === 0 ? 'key' : 'value'; switch (type) { case 'key': { - const newKey = mapper(keyToRow); + const newKey = await mapper(keyToRow); parent.set(newKey, parent.get(keyToRow)); if (newKey !== keyToRow) { @@ -131,7 +131,7 @@ export const setDeep = ( } case 'value': { - parent.set(keyToRow, mapper(parent.get(keyToRow))); + parent.set(keyToRow, await mapper(parent.get(keyToRow))); break; } } diff --git a/src/custom-transformer-registry.ts b/src/custom-transformer-registry.ts index ebd3db6..c6a2f53 100644 --- a/src/custom-transformer-registry.ts +++ b/src/custom-transformer-registry.ts @@ -3,9 +3,9 @@ import { find } from './util.js'; export interface CustomTransfomer { name: string; - isApplicable: (v: any) => v is I; - serialize: (v: I) => O; - deserialize: (v: O) => I; + isApplicable: (v: any) => boolean | Promise; + serialize: (v: I) => O | Promise; + deserialize: (v: O) => I | Promise; } export class CustomTransformerRegistry { @@ -15,13 +15,13 @@ export class CustomTransformerRegistry { this.transfomers[transformer.name] = transformer; } - findApplicable(v: T) { - return find(this.transfomers, transformer => + findApplicable(v: T): Promise | undefined> { + return find(this.transfomers, async transformer => transformer.isApplicable(v) - ) as CustomTransfomer | undefined; + ); } - findByName(name: string) { + findByName(name: string): CustomTransfomer { return this.transfomers[name]; } } diff --git a/src/index.test.ts b/src/index.test.ts index 249bbb0..d9d10f0 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -835,19 +835,19 @@ describe('stringify & parse', () => { let testFunc = test; if (skipOnNode10 && isNode10) { - testFunc = test.skip; + testFunc = test.skip as any; } if (only) { - testFunc = test.only; + testFunc = test as any; } - testFunc(testName, () => { + testFunc(testName, async () => { const inputValue = typeof input === 'function' ? input() : input; // let's make sure SuperJSON doesn't mutate our input! deepFreeze(inputValue); - const { json, meta } = SuperJSON.serialize(inputValue); + const { json, meta } = await SuperJSON.serialize(inputValue); if (typeof expectedOutput === 'function') { expectedOutput(json); @@ -862,7 +862,7 @@ describe('stringify & parse', () => { expect(meta).toEqual(expectedOutputAnnotations); } - const untransformed = SuperJSON.deserialize( + const untransformed = await SuperJSON.deserialize( JSON.parse(JSON.stringify({ json, meta })) ); if (!dontExpectEquality) { @@ -873,7 +873,7 @@ describe('stringify & parse', () => { } describe('when serializing custom class instances', () => { - it('revives them to their original class', () => { + it('revives them to their original class', async () => { class Carriage { constructor(public name: string) {} } @@ -884,7 +884,7 @@ describe('stringify & parse', () => { private topSpeed: number, private color: 'red' | 'blue' | 'yellow', private brand: string, - public carriages: Set, + public carriages: Set ) {} public brag() { @@ -894,30 +894,40 @@ describe('stringify & parse', () => { SuperJSON.registerClass(Train); - const { json, meta } = SuperJSON.serialize({ - s7: new Train(100, 'yellow', 'Bombardier', new Set([new Carriage('front'), new Carriage('back')])) as any, + const { json, meta } = await SuperJSON.serialize({ + s7: new Train( + 100, + 'yellow', + 'Bombardier', + new Set([new Carriage('front'), new Carriage('back')]) + ) as any, }); - + expect(json).toEqual({ s7: { topSpeed: 100, color: 'yellow', brand: 'Bombardier', - carriages: [ - { name: 'front' }, - { name: 'back' }, - ], + carriages: [{ name: 'front' }, { name: 'back' }], }, }); expect(meta).toEqual({ v: 1, values: { - s7: [['class', 'Train'], { carriages: ["set", { 0: [['class', 'Carriage']], 1: [['class', 'Carriage']] }] }], + s7: [ + ['class', 'Train'], + { + carriages: [ + 'set', + { 0: [['class', 'Carriage']], 1: [['class', 'Carriage']] }, + ], + }, + ], }, }); - const deserialized: any = SuperJSON.deserialize( + const deserialized: any = await SuperJSON.deserialize( JSON.parse(JSON.stringify({ json, meta })) ); expect(deserialized.s7).toBeInstanceOf(Train); @@ -928,7 +938,7 @@ describe('stringify & parse', () => { }); describe('with accessor attributes', () => { - it('works', () => { + it('works', async () => { class Currency { constructor(private valueInUsd: number) {} @@ -940,7 +950,7 @@ describe('stringify & parse', () => { SuperJSON.registerClass(Currency); - const { json, meta } = SuperJSON.serialize({ + const { json, meta } = await SuperJSON.serialize({ price: new Currency(100) as any, }); @@ -950,7 +960,9 @@ describe('stringify & parse', () => { }, }); - const result: any = SuperJSON.parse(JSON.stringify({ json, meta })); + const result: any = await SuperJSON.parse( + JSON.stringify({ json, meta }) + ); const price: Currency = result.price; @@ -963,7 +975,7 @@ describe('stringify & parse', () => { it.todo('has undefined behaviour'); }); - test('regression #65: BigInt on Safari v13', () => { + test('regression #65: BigInt on Safari v13', async () => { const oldBigInt = global.BigInt; // @ts-ignore delete global.BigInt; @@ -972,7 +984,7 @@ describe('stringify & parse', () => { a: oldBigInt('1000'), }; - const superJSONed = SuperJSON.serialize(input); + const superJSONed = await SuperJSON.serialize(input); expect(superJSONed).toEqual({ json: { a: '1000', @@ -985,7 +997,7 @@ describe('stringify & parse', () => { }, }); - const deserialised = SuperJSON.deserialize( + const deserialised = await SuperJSON.deserialize( JSON.parse(JSON.stringify(superJSONed)) ); expect(deserialised).toEqual({ @@ -995,7 +1007,7 @@ describe('stringify & parse', () => { global.BigInt = oldBigInt; }); - test('regression #80: Custom error serialisation isnt overriden', () => { + test('regression #80: Custom error serialisation isnt overriden', async () => { class CustomError extends Error { constructor(public readonly customProperty: number) { super("I'm a custom error"); @@ -1008,11 +1020,11 @@ describe('stringify & parse', () => { SuperJSON.registerClass(CustomError); - const { error } = SuperJSON.deserialize( - SuperJSON.serialize({ + const { error } = (await SuperJSON.deserialize( + await SuperJSON.serialize({ error: new CustomError(10), }) - ) as any; + )) as any; expect(error).toBeInstanceOf(CustomError); expect(error.customProperty).toEqual(10); @@ -1020,7 +1032,7 @@ describe('stringify & parse', () => { }); describe('allowErrorProps(...) (#91)', () => { - it('works with simple prop values', () => { + it('works with simple prop values', async () => { const errorWithAdditionalProps: Error & any = new Error( 'I have additional props 😄' ); @@ -1031,8 +1043,8 @@ describe('allowErrorProps(...) (#91)', () => { SuperJSON.allowErrorProps('code'); SuperJSON.allowErrorProps('meta'); - const errorAfterTransition: any = SuperJSON.parse( - SuperJSON.stringify(errorWithAdditionalProps) + const errorAfterTransition: any = await SuperJSON.parse( + await SuperJSON.stringify(errorWithAdditionalProps) ); expect(errorAfterTransition).toBeInstanceOf(Error); @@ -1041,14 +1053,14 @@ describe('allowErrorProps(...) (#91)', () => { expect(errorAfterTransition.meta).toEqual('👾'); }); - it.skip('works with complex prop values', () => { + it.skip('works with complex prop values', async () => { const errorWithAdditionalProps: any = new Error(); errorWithAdditionalProps.map = new Map(); SuperJSON.allowErrorProps('map'); - const errorAfterTransition: any = SuperJSON.parse( - SuperJSON.stringify(errorWithAdditionalProps) + const errorAfterTransition: any = await SuperJSON.parse( + await SuperJSON.stringify(errorWithAdditionalProps) ); expect(errorAfterTransition.map).toEqual(undefined); @@ -1058,43 +1070,47 @@ describe('allowErrorProps(...) (#91)', () => { }); describe('Error without a cause', () => { - it('does not synthesize an own cause property on the round-trip', () => { + it('does not synthesize an own cause property on the round-trip', async () => { const original = new Error('no cause here'); expect(Object.hasOwn(original, 'cause')).toBe(false); - const roundTripped: any = SuperJSON.parse(SuperJSON.stringify(original)); + const roundTripped: any = await SuperJSON.parse( + await SuperJSON.stringify(original) + ); expect(roundTripped).toBeInstanceOf(Error); expect(roundTripped.message).toBe('no cause here'); expect(Object.hasOwn(roundTripped, 'cause')).toBe(false); }); - it('preserves an explicit cause', () => { + it('preserves an explicit cause', async () => { const original = new Error('outer', { cause: 'inner reason' }); expect(Object.hasOwn(original, 'cause')).toBe(true); - const roundTripped: any = SuperJSON.parse(SuperJSON.stringify(original)); + const roundTripped: any = await SuperJSON.parse( + await SuperJSON.stringify(original) + ); expect(Object.hasOwn(roundTripped, 'cause')).toBe(true); expect(roundTripped.cause).toBe('inner reason'); }); }); -test('regression #83: negative zero', () => { +test('regression #83: negative zero', async () => { const input = -0; - const stringified = SuperJSON.stringify(input); + const stringified = await SuperJSON.stringify(input); expect(stringified).toMatchInlineSnapshot( `"{\\"json\\":\\"-0\\",\\"meta\\":{\\"values\\":[\\"number\\"],\\"v\\":1}}"` ); - const parsed: number = SuperJSON.parse(stringified); + const parsed: number = await SuperJSON.parse(stringified); expect(1 / parsed).toBe(-Infinity); }); -test('regression https://github.com/blitz-js/babel-plugin-superjson-next/issues/63: Nested BigInt', () => { - const serialized = SuperJSON.serialize({ +test('regression https://github.com/blitz-js/babel-plugin-superjson-next/issues/63: Nested BigInt', async () => { + const serialized = await SuperJSON.serialize({ topics: [ { post_count: BigInt('22'), @@ -1113,11 +1129,11 @@ test('regression https://github.com/blitz-js/babel-plugin-superjson-next/issues/ ], }); - SuperJSON.deserialize(serialized); + await SuperJSON.deserialize(serialized); expect(typeof (serialized.json as any).topics[0].post_count).toBe('string'); }); -test('performance regression', () => { +test('performance regression', async () => { const data: any[] = []; for (let i = 0; i < 100; i++) { let nested1 = []; @@ -1150,62 +1166,62 @@ test('performance regression', () => { } const t1 = Date.now(); - SuperJSON.serialize(data); + await SuperJSON.serialize(data); const t2 = Date.now(); const duration = t2 - t1; expect(duration).toBeLessThan(700); }); -test('regression #95: no undefined', () => { +test('regression #95: no undefined', async () => { const input: unknown[] = []; - const out = SuperJSON.serialize(input); + const out = await SuperJSON.serialize(input); expect(out).not.toHaveProperty('meta'); - const parsed: number = SuperJSON.deserialize(out); + const parsed: number = await SuperJSON.deserialize(out); expect(parsed).toEqual(input); }); -test('regression #108: Error#stack should not be included by default', () => { +test('regression #108: Error#stack should not be included by default', async () => { const input = new Error("Beep boop, you don't wanna see me. I'm an error!"); expect(input).toHaveProperty('stack'); - const { stack: thatShouldBeUndefined } = SuperJSON.parse( - SuperJSON.stringify(input) - ) as any; + const { stack: thatShouldBeUndefined } = (await SuperJSON.parse( + await SuperJSON.stringify(input) + )) as any; expect(thatShouldBeUndefined).toBeUndefined(); SuperJSON.allowErrorProps('stack'); - const { stack: thatShouldExist } = SuperJSON.parse( - SuperJSON.stringify(input) - ) as any; + const { stack: thatShouldExist } = (await SuperJSON.parse( + await SuperJSON.stringify(input) + )) as any; expect(thatShouldExist).toEqual(input.stack); }); -test('regression: `Object.create(null)` / object without prototype', () => { +test('regression: `Object.create(null)` / object without prototype', async () => { const input: Record = Object.create(null); input.date = new Date(); - const stringified = SuperJSON.stringify(input); - const parsed: any = SuperJSON.parse(stringified); + const stringified = await SuperJSON.stringify(input); + const parsed: any = await SuperJSON.parse(stringified); expect(parsed.date).toBeInstanceOf(Date); }); test.each(['__proto__', 'prototype', 'constructor'])( 'serialize prototype pollution: %s', - forbidden => { - expect(() => { + async forbidden => { + await expect( SuperJSON.serialize({ [forbidden]: 1, - }); - }).toThrowError(/This is a prototype pollution risk/); + }) + ).rejects.toThrowError(/This is a prototype pollution risk/); } ); -test('prototype pollution - __proto__', () => { - expect(() => { +test('prototype pollution - __proto__', async () => { + await expect( SuperJSON.parse( JSON.stringify({ json: { @@ -1217,15 +1233,15 @@ test('prototype pollution - __proto__', () => { }, }, }) - ); - }).toThrowErrorMatchingInlineSnapshot( + ) + ).rejects.toThrowErrorMatchingInlineSnapshot( `"__proto__ is not allowed as a property"` ); expect((Object.prototype as any).x).toBeUndefined(); }); -test('prototype pollution - prototype', () => { - expect(() => { +test('prototype pollution - prototype', async () => { + await expect( SuperJSON.parse( JSON.stringify({ json: { @@ -1237,14 +1253,14 @@ test('prototype pollution - prototype', () => { }, }, }) - ); - }).toThrowErrorMatchingInlineSnapshot( + ) + ).rejects.toThrowErrorMatchingInlineSnapshot( `"prototype is not allowed as a property"` ); }); -test('prototype pollution - constructor', () => { - expect(() => { +test('prototype pollution - constructor', async () => { + await expect( SuperJSON.parse( JSON.stringify({ json: { @@ -1256,15 +1272,15 @@ test('prototype pollution - constructor', () => { }, }, }) - ); - }).toThrowErrorMatchingInlineSnapshot( + ) + ).rejects.toThrowErrorMatchingInlineSnapshot( `"prototype is not allowed as a property"` ); expect((Object.prototype as any).x).toBeUndefined(); }); -test('superjson instances are independent of one another', () => { +test('superjson instances are independent of one another', async () => { class Car {} const s1 = new SuperJSON(); s1.registerClass(Car); @@ -1275,13 +1291,13 @@ test('superjson instances are independent of one another', () => { car: new Car(), }; - const res1 = s1.serialize(value); + const res1 = await s1.serialize(value); expect(res1.meta?.values).toEqual({ car: [['class', 'Car']] }); - const res2 = s2.serialize(value); + const res2 = await s2.serialize(value); expect(res2.json).toEqual(value); }); -test('regression #245: superjson referential equalities only use the top-most parent node', () => { +test('regression #245: superjson referential equalities only use the top-most parent node', async () => { type Node = { children: Node[]; }; @@ -1292,7 +1308,7 @@ test('regression #245: superjson referential equalities only use the top-most pa a: root, b: root, }; - const res = SuperJSON.serialize(input); + const res = await SuperJSON.serialize(input); expect(res.meta?.referentialEqualities).toHaveProperty(['a']); @@ -1309,11 +1325,11 @@ test('regression #245: superjson referential equalities only use the top-most pa } `); - const parsed = SuperJSON.deserialize(res); + const parsed = await SuperJSON.deserialize(res); expect(parsed).toEqual(input); }); -test('dedupe=true', () => { +test('dedupe=true', async () => { const instance = new SuperJSON({ dedupe: true, }); @@ -1328,7 +1344,7 @@ test('dedupe=true', () => { a: root, b: root, }; - const output = instance.serialize(input); + const output = await instance.serialize(input); const json = output.json as any; @@ -1346,14 +1362,14 @@ test('dedupe=true', () => { } `); - expect(instance.deserialize(output)).toEqual(input); + expect(await instance.deserialize(output)).toEqual(input); }); -test('dedupe=true on a large complicated schema', () => { +test('dedupe=true on a large complicated schema', async () => { const content = fs.readFileSync(__dirname + '/non-deduped-cal.json', 'utf-8'); const parsed = JSON.parse(content); - const deserialized = SuperJSON.deserialize(parsed); + const deserialized = await SuperJSON.deserialize(parsed); const nondeduped = new SuperJSON({}); @@ -1361,40 +1377,48 @@ test('dedupe=true on a large complicated schema', () => { dedupe: true, }); - const nondedupedOut = nondeduped.deserialize( - nondeduped.serialize(deserialized) + const nondedupedOut = await nondeduped.deserialize( + await nondeduped.serialize(deserialized) + ); + const dedupedOut = await deduped.deserialize( + await deduped.serialize(deserialized) ); - const dedupedOut = deduped.deserialize(deduped.serialize(deserialized)); expect(nondedupedOut).toEqual(deserialized); expect(dedupedOut).toEqual(deserialized); }); -test('doesnt iterate to keys that dont exist', () => { +test('doesnt iterate to keys that dont exist', async () => { const robbyBubble = { id: 5 }; const highscores = new Map([[robbyBubble, 5000]]); const objectWithReferentialEquality = { highscores, topScorer: robbyBubble }; - const res = SuperJSON.serialize(objectWithReferentialEquality); + const res = await SuperJSON.serialize(objectWithReferentialEquality); - expect(res.meta.referentialEqualities.topScorer).toEqual(['highscores.0.0']); - res.meta.referentialEqualities.topScorer = ['highscores.99999.0']; + expect((res.meta!.referentialEqualities! as any).topScorer).toEqual([ + 'highscores.0.0', + ]); + (res.meta!.referentialEqualities! as any).topScorer = ['highscores.99999.0']; - expect(() => SuperJSON.deserialize(res)).toThrowError('index out of bounds'); + await expect(SuperJSON.deserialize(res)).rejects.toThrowError( + 'index out of bounds' + ); }); // https://github.com/flightcontrolhq/superjson/issues/319 -test('deserialize in place', () => { - const serialized = SuperJSON.serialize({ a: new Date() }); - const deserializedCopy = SuperJSON.deserialize(serialized); - const deserializedInPlace = SuperJSON.deserialize(serialized, { inPlace: true }); +test('deserialize in place', async () => { + const serialized = await SuperJSON.serialize({ a: new Date() }); + const deserializedCopy = await SuperJSON.deserialize(serialized); + const deserializedInPlace = await SuperJSON.deserialize(serialized, { + inPlace: true, + }); expect(deserializedInPlace).toBe(serialized.json); expect(deserializedCopy).not.toBe(serialized.json); expect(deserializedCopy).toEqual(deserializedInPlace); }); -test('#310 fixes backwards compat', () => { +test('#310 fixes backwards compat', async () => { expect( - SuperJSON.deserialize({ + await SuperJSON.deserialize({ json: { 'a\\.1': { b: [1, 2], @@ -1413,7 +1437,7 @@ test('#310 fixes backwards compat', () => { }); expect( - SuperJSON.deserialize({ + await SuperJSON.deserialize({ json: { 'a.1': { b: [1, 2], diff --git a/src/index.ts b/src/index.ts index 9a11ad7..86e1f4b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -30,9 +30,9 @@ export default class SuperJSON { this.dedupe = dedupe; } - serialize(object: SuperJSONValue): SuperJSONResult { + async serialize(object: SuperJSONValue): Promise { const identities = new Map(); - const output = walker(object, identities, this, this.dedupe); + const output = await walker(object, identities, this, this.dedupe); const res: SuperJSONResult = { json: output.transformedValue, }; @@ -60,17 +60,17 @@ export default class SuperJSON { return res; } - deserialize(payload: SuperJSONResult, options?: { inPlace?: boolean }): T { + async deserialize(payload: SuperJSONResult, options?: { inPlace?: boolean }): Promise { const { json, meta } = payload; let result: T = options?.inPlace ? json : copy(json) as any; if (meta?.values) { - result = applyValueAnnotations(result, meta.values, meta.v ?? 0, this); + result = await applyValueAnnotations(result, meta.values, meta.v ?? 0, this); } if (meta?.referentialEqualities) { - result = applyReferentialEqualityAnnotations( + result = await applyReferentialEqualityAnnotations( result, meta.referentialEqualities, meta.v ?? 0 @@ -80,21 +80,21 @@ export default class SuperJSON { return result; } - stringify(object: SuperJSONValue): string { - return JSON.stringify(this.serialize(object)); + async stringify(object: SuperJSONValue): Promise { + return JSON.stringify(await this.serialize(object)); } - parse(string: string): T { + parse(string: string): Promise { return this.deserialize(JSON.parse(string), { inPlace: true }); } readonly classRegistry = new ClassRegistry(); - registerClass(v: Class, options?: RegisterOptions | string) { + registerClass(v: Class, options?: RegisterOptions | string): void { this.classRegistry.register(v, options); } readonly symbolRegistry = new Registry(s => s.description ?? ''); - registerSymbol(v: Symbol, identifier?: string) { + registerSymbol(v: Symbol, identifier?: string): void { this.symbolRegistry.register(v, identifier); } @@ -102,7 +102,7 @@ export default class SuperJSON { registerCustom( transformer: Omit, 'name'>, name: string - ) { + ): void { this.customTransformerRegistry.register({ name, ...transformer, @@ -110,7 +110,7 @@ export default class SuperJSON { } readonly allowedErrorProps: string[] = []; - allowErrorProps(...props: string[]) { + allowErrorProps(...props: string[]): void { this.allowedErrorProps.push(...props); } diff --git a/src/plainer.spec.ts b/src/plainer.spec.ts index 0b63577..ded697a 100644 --- a/src/plainer.spec.ts +++ b/src/plainer.spec.ts @@ -3,9 +3,9 @@ import { walker } from './plainer.js'; import { test, expect } from 'vitest'; -test('walker', () => { +test('walker', async () => { expect( - walker( + await walker( { a: new Map([[NaN, null]]), b: /test/g, diff --git a/src/plainer.ts b/src/plainer.ts index 8e9059f..cde36f8 100644 --- a/src/plainer.ts +++ b/src/plainer.ts @@ -27,19 +27,19 @@ export type MinimisedTree = Tree | Record> | undefined; const enableLegacyPaths = (version: number) => version < 1; -function traverse( +async function traverse( tree: MinimisedTree, - walker: (v: T, path: string[]) => void, + walker: (v: T, path: string[]) => Promise, version: number, origin: string[] = [] -): void { +): Promise { if (!tree) { return; } const legacyPaths = enableLegacyPaths(version); if (!isArray(tree)) { - forEach(tree, (subtree, key) => + await forEach(tree, async (subtree, key) => traverse(subtree, walker, version, [ ...origin, ...parsePath(key, legacyPaths), @@ -50,27 +50,29 @@ function traverse( const [nodeValue, children] = tree; if (children) { - forEach(children, (child, key) => { + await forEach(children, async (child, key) => traverse(child, walker, version, [ ...origin, ...parsePath(key, legacyPaths), - ]); - }); + ]) + ); } - walker(nodeValue, origin); + await walker(nodeValue, origin); } -export function applyValueAnnotations( +export async function applyValueAnnotations( plain: any, annotations: MinimisedTree, version: number, superJson: SuperJSON ) { - traverse( + await traverse( annotations, - (type, path) => { - plain = setDeep(plain, path, v => untransformValue(v, type, superJson)); + async (type, path) => { + plain = await setDeep(plain, path, v => + untransformValue(v, type, superJson) + ); }, version ); @@ -78,37 +80,39 @@ export function applyValueAnnotations( return plain; } -export function applyReferentialEqualityAnnotations( +export async function applyReferentialEqualityAnnotations( plain: any, annotations: ReferentialEqualityAnnotations, version: number ) { const legacyPaths = enableLegacyPaths(version); - function apply(identicalPaths: string[], path: string) { + async function apply(identicalPaths: string[], path: string) { const object = getDeep(plain, parsePath(path, legacyPaths)); - identicalPaths + const promises = identicalPaths .map(path => parsePath(path, legacyPaths)) - .forEach(identicalObjectPath => { - plain = setDeep(plain, identicalObjectPath, () => object); + .map(async identicalObjectPath => { + plain = await setDeep(plain, identicalObjectPath, async () => object); }); + await Promise.all(promises); } if (isArray(annotations)) { const [root, other] = annotations; - root.forEach(identicalPath => { - plain = setDeep( + const promises = root.map(async identicalPath => { + plain = await setDeep( plain, parsePath(identicalPath, legacyPaths), () => plain ); }); + await Promise.all(promises); if (other) { - forEach(other, apply); + await forEach(other, apply); } } else { - forEach(annotations, apply); + await forEach(annotations, apply); } return plain; @@ -185,7 +189,7 @@ export function generateReferentialEqualityAnnotations( } } -export const walker = ( +export const walker = async ( object: any, identities: Map, superJson: SuperJSON, @@ -193,7 +197,7 @@ export const walker = ( path: any[] = [], objectsInThisPath: any[] = [], seenObjects = new Map() -): Result => { +): Promise => { const primitive = isPrimitive(object); if (!primitive) { @@ -211,7 +215,7 @@ export const walker = ( } if (!isDeep(object, superJson)) { - const transformed = transformValue(object, superJson); + const transformed = await transformValue(object, superJson); const result: Result = transformed ? { @@ -234,13 +238,13 @@ export const walker = ( }; } - const transformationResult = transformValue(object, superJson); + const transformationResult = await transformValue(object, superJson); const transformed = transformationResult?.value ?? object; const transformedValue: any = isArray(transformed) ? [] : {}; const innerAnnotations: Record> = {}; - forEach(transformed, (value, index) => { + await forEach(transformed, async (value, index) => { if ( index === '__proto__' || index === 'constructor' || @@ -251,7 +255,7 @@ export const walker = ( ); } - const recursiveResult = walker( + const recursiveResult = await walker( value, identities, superJson, @@ -266,7 +270,7 @@ export const walker = ( if (isArray(recursiveResult.annotations)) { innerAnnotations[escapeKey(index)] = recursiveResult.annotations; } else if (isPlainObject(recursiveResult.annotations)) { - forEach(recursiveResult.annotations, (tree, key) => { + await forEach(recursiveResult.annotations, async (tree, key) => { innerAnnotations[escapeKey(index) + '.' + key] = tree; }); } diff --git a/src/transformer.test.ts b/src/transformer.test.ts index ac8ffdf..a4ae16d 100644 --- a/src/transformer.test.ts +++ b/src/transformer.test.ts @@ -2,7 +2,7 @@ import SuperJSON from './index.js'; import { test, expect } from 'vitest'; -test('throws an descriptive error when transforming', () => { +test('throws an descriptive error when transforming', async () => { const instance = new SuperJSON(); class FunnyNumber { constructor(private number: number) {} @@ -13,16 +13,19 @@ test('throws an descriptive error when transforming', () => { } } instance.registerClass(FunnyNumber); - expect(() => + + const { json } = await instance.serialize({ + number: new FunnyNumber(2137), + }); + + await expect( instance.deserialize({ - json: instance.serialize({ - number: new FunnyNumber(2137), - }).json, + json, meta: { values: [['class', 'NotRegistered']], }, }) - ).toThrowError( + ).rejects.toThrowError( `Trying to deserialize unknown class 'NotRegistered' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564` ); }); diff --git a/src/transformer.ts b/src/transformer.ts index cce7d55..5d87f5b 100644 --- a/src/transformer.ts +++ b/src/transformer.ts @@ -11,12 +11,14 @@ import { isArray, isError, isTypedArray, + TypedArray, TypedArrayConstructor, BigIntTypedArrayConstructor, isURL, } from './is.js'; import { findArr } from './util.js'; import SuperJSON from './index.js'; +import { JSONValue } from './types.js'; export type PrimitiveTypeAnnotation = 'number' | 'undefined' | 'bigint'; @@ -175,10 +177,10 @@ const simpleRules = [ ]; function compositeTransformation( - isApplicable: (v: any, superJson: SuperJSON) => v is I, - annotation: (v: I, superJson: SuperJSON) => A, - transform: (v: I, superJson: SuperJSON) => O, - untransform: (v: O, a: A, superJson: SuperJSON) => I + isApplicable: (v: any, superJson: SuperJSON) => Promise, + annotation: (v: I, superJson: SuperJSON) => Promise, + transform: (v: I, superJson: SuperJSON) => Promise, + untransform: (v: O, a: A, superJson: SuperJSON) => Promise ) { return { isApplicable, @@ -188,20 +190,24 @@ function compositeTransformation( }; } -const symbolRule = compositeTransformation( - (s, superJson): s is Symbol => { +const symbolRule = compositeTransformation< + Symbol, + string | undefined, + ['symbol', string] +>( + async (s, superJson): Promise => { if (isSymbol(s)) { const isRegistered = !!superJson.symbolRegistry.getIdentifier(s); return isRegistered; } return false; }, - (s, superJson) => { + async (s, superJson) => { const identifier = superJson.symbolRegistry.getIdentifier(s); return ['symbol', identifier!]; }, - v => v.description, - (_, a, superJson) => { + async v => v.description, + async (_, a, superJson) => { const value = superJson.symbolRegistry.getValue(a[1]); if (!value) { throw new Error('Trying to deserialize unknown symbol'); @@ -235,10 +241,14 @@ if (typeof BigUint64Array !== 'undefined') { bigIntConstructorToName[BigUint64Array.name] = BigUint64Array; } -const typedArrayRule = compositeTransformation( - isTypedArray, - v => ['typed-array', v.constructor.name], - v => +const typedArrayRule = compositeTransformation< + TypedArray, + (string | number)[], + ['typed-array', string] +>( + async a => isTypedArray(a), + async v => ['typed-array', v.constructor.name], + async v => [...v].map(n => { // bigint values (from BigInt64Array / BigUint64Array) are not valid JSON, // so they're stored as strings. @@ -253,7 +263,7 @@ const typedArrayRule = compositeTransformation( } return n; }), - (v, a) => { + async (v, a) => { const bigIntCtor = bigIntConstructorToName[a[1]]; if (bigIntCtor) { const values = v.map((n: string | number | bigint): bigint => BigInt(n)); @@ -291,13 +301,13 @@ export function isInstanceOfRegisteredClass( return false; } -const classRule = compositeTransformation( - isInstanceOfRegisteredClass, - (clazz, superJson) => { +const classRule = compositeTransformation( + async (value, superJson) => isInstanceOfRegisteredClass(value, superJson), + async (clazz, superJson) => { const identifier = superJson.classRegistry.getIdentifier(clazz.constructor); return ['class', identifier!]; }, - (clazz, superJson) => { + async (clazz, superJson) => { const allowedProps = superJson.classRegistry.getAllowedProps( clazz.constructor ); @@ -311,7 +321,7 @@ const classRule = compositeTransformation( }); return result; }, - (v, a, superJson) => { + async (v, a, superJson) => { const clazz = superJson.classRegistry.getValue(a[1]); if (!clazz) { @@ -324,23 +334,27 @@ const classRule = compositeTransformation( } ); -const customRule = compositeTransformation( - (value, superJson): value is any => { - return !!superJson.customTransformerRegistry.findApplicable(value); +const customRule = compositeTransformation< + any, + JSONValue | Promise, + ['custom', any] +>( + async (value, superJson): Promise => { + return !!(await superJson.customTransformerRegistry.findApplicable(value)); }, - (value, superJson) => { - const transformer = superJson.customTransformerRegistry.findApplicable( + async (value, superJson) => { + const transformer = (await superJson.customTransformerRegistry.findApplicable( value - )!; + ))!; return ['custom', transformer.name]; }, - (value, superJson) => { - const transformer = superJson.customTransformerRegistry.findApplicable( + async (value, superJson) => { + const transformer = (await superJson.customTransformerRegistry.findApplicable( value - )!; + ))!; return transformer.serialize(value); }, - (v, a, superJson) => { + async (v, a, superJson) => { const transformer = superJson.customTransformerRegistry.findByName(a[1]); if (!transformer) { throw new Error('Trying to deserialize unknown custom value'); @@ -351,21 +365,21 @@ const customRule = compositeTransformation( const compositeRules = [classRule, symbolRule, customRule, typedArrayRule]; -export const transformValue = ( +export const transformValue = async ( value: any, superJson: SuperJSON -): { value: any; type: TypeAnnotation } | undefined => { - const applicableCompositeRule = findArr(compositeRules, rule => - rule.isApplicable(value, superJson) +): Promise<{ value: any; type: TypeAnnotation } | undefined> => { + const applicableCompositeRule = await findArr(compositeRules, async rule => + await rule.isApplicable(value, superJson) ); if (applicableCompositeRule) { return { - value: applicableCompositeRule.transform(value as never, superJson), - type: applicableCompositeRule.annotation(value, superJson), + value: await applicableCompositeRule.transform(value as never, superJson), + type: await applicableCompositeRule.annotation(value, superJson), }; } - const applicableSimpleRule = findArr(simpleRules, rule => + const applicableSimpleRule = await findArr(simpleRules, async rule => rule.isApplicable(value, superJson) ); @@ -384,7 +398,7 @@ simpleRules.forEach(rule => { simpleRulesByAnnotation[rule.annotation] = rule; }); -export const untransformValue = ( +export const untransformValue = async ( json: any, type: TypeAnnotation, superJson: SuperJSON diff --git a/src/util.ts b/src/util.ts index 13a5288..4379633 100644 --- a/src/util.ts +++ b/src/util.ts @@ -16,21 +16,16 @@ function valuesOfObj(record: Record): T[] { return values; } -export function find( +export async function find( record: Record, - predicate: (v: T) => boolean -): T | undefined { + predicate: (v: T) => Promise +): Promise { const values = valuesOfObj(record); - if ('find' in values) { - // eslint-disable-next-line es5/no-es6-methods - return values.find(predicate); - } - const valuesNotNever = values as T[]; for (let i = 0; i < valuesNotNever.length; i++) { const value = valuesNotNever[i]; - if (predicate(value)) { + if (await predicate(value)) { return value; } } @@ -38,24 +33,26 @@ export function find( return undefined; } -export function forEach( +export async function forEach( record: Record, - run: (v: T, key: string) => void -) { - Object.entries(record).forEach(([key, value]) => run(value, key)); + run: (v: T, key: string) => Promise +): Promise { + for (const [key, value] of Object.entries(record)) { + await run(value, key) + } } export function includes(arr: T[], value: T) { return arr.indexOf(value) !== -1; } -export function findArr( +export async function findArr( record: T[], - predicate: (v: T) => boolean -): T | undefined { + predicate: (v: T) => Promise +): Promise { for (let i = 0; i < record.length; i++) { const value = record[i]; - if (predicate(value)) { + if (await predicate(value)) { return value; } } diff --git a/tsconfig.base.json b/tsconfig.base.json new file mode 100644 index 0000000..f298d8e --- /dev/null +++ b/tsconfig.base.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "node16", + "moduleResolution": "node16", + "lib": ["esnext", "DOM"], + "importHelpers": false, + "declaration": true, + "rootDir": "./src", + "outDir": "./dist", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "esModuleInterop": true, + "skipLibCheck": true + } +} diff --git a/tsconfig.check.json b/tsconfig.check.json new file mode 100644 index 0000000..71909c0 --- /dev/null +++ b/tsconfig.check.json @@ -0,0 +1,4 @@ +{ + "include": ["src"], + "extends": "./tsconfig.base.json" +} diff --git a/tsconfig.json b/tsconfig.json index b0adc92..37c5bdc 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,22 +1,5 @@ { "include": ["src"], "exclude": ["**/*.spec.ts", "**/*.test.ts"], - "compilerOptions": { - "target": "ES2020", - "module": "node16", - "moduleResolution": "node16", - "lib": ["esnext"], - "importHelpers": false, - "declaration": true, - "rootDir": "./src", - "outDir": "./dist", - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noImplicitReturns": true, - "noFallthroughCasesInSwitch": true, - "esModuleInterop": true, - "downlevelIteration": true, - "skipLibCheck": true - } + "extends": "./tsconfig.base.json" }