diff --git a/README.md b/README.md index a74d0083..d4ad0576 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ post-robot will serialize and deserialize the following data types in messages: - Promises - Note: deserialized promises will be instances of [`ZalgoPromise`](https://github.com/krakenjs/zalgo-promise) - Error objects +- Regex objects ## Simple listener and sender diff --git a/src/conf/constants.js b/src/conf/constants.js index 5e3d2a5d..3f8fd051 100644 --- a/src/conf/constants.js +++ b/src/conf/constants.js @@ -33,7 +33,8 @@ export let CONSTANTS = { METHOD: 'postrobot_method', ERROR: 'postrobot_error', PROMISE: 'postrobot_promise', - ZALGO_PROMISE: 'postrobot_zalgo_promise' + ZALGO_PROMISE: 'postrobot_zalgo_promise', + REGEX: 'regex' }, SEND_STRATEGIES: { diff --git a/src/lib/serialize.js b/src/lib/serialize.js index 0d52979e..38e3acfe 100644 --- a/src/lib/serialize.js +++ b/src/lib/serialize.js @@ -5,7 +5,7 @@ import { matchDomain } from 'cross-domain-utils/src'; import { ZalgoPromise } from 'zalgo-promise/src'; import { CONSTANTS } from '../conf'; -import { once, uniqueID, replaceObject, stringifyError } from './util'; +import { once, uniqueID, replaceObject, stringifyError, isRegex } from './util'; import { on, send } from '../interface'; import { log } from './log'; import { global } from '../global'; @@ -108,6 +108,18 @@ function serializeZalgoPromise(destination : any, domain : string, promise : Zal }; } +type SerializedRegex = { + __type__ : string, + __source__ : string +}; + +function serializeRegex(regex : RegExp) : SerializedRegex { + return { + __type__: CONSTANTS.SERIALIZATION_TYPES.REGEX, + __source__: regex.source + }; +} + export function serializeMethods(destination : any, domain : string, obj : Object) : Object { return replaceObject({ obj }, (item, key) => { @@ -127,6 +139,11 @@ export function serializeMethods(destination : any, domain : string, obj : Objec // $FlowFixMe return serializeZalgoPromise(destination, domain, item, key.toString()); } + + if (isRegex(item)) { + // $FlowFixMe + return serializeRegex(item); + } }).obj; } @@ -175,6 +192,10 @@ export function deserializePromise(source : any, origin : string, prom : Object) return new window.Promise((resolve, reject) => deserializeMethod(source, origin, prom.__then__)(resolve, reject)); } +export function deserializeRegex(source : any, origin : string, item : Object) : RegExp { + return new RegExp(item.__source__); +} + export function deserializeMethods(source : any, origin : string, obj : Object) : Object { return replaceObject({ obj }, (item, key) => { @@ -198,5 +219,9 @@ export function deserializeMethods(source : any, origin : string, obj : Object) return deserializeZalgoPromise(source, origin, item); } + if (isSerialized(item, CONSTANTS.SERIALIZATION_TYPES.REGEX)) { + return deserializeRegex(source, origin, item); + } + }).obj; }