yahoo / serialize-javascript

Serialize JavaScript to a superset of JSON that includes regular expressions and functions.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

feat: option to inject code verbatim

AndersDJohnson opened this issue · comments

It would be handy for a use case I have for this package to support a feature that could inject code verbatim if it appears in a JavaScript object.

To implement, we could use (A) a special object constructor, (B) a special property on a string, or (C) a tagged template literal returning some special value, which would allow us to detect such cases in the serialization code.

A:

const object = {
  customCode: serialize.verbatim('window.navigator.userAgent')
};

B:

const customCode = 'window.navigator.userAgent';
customCode.verbatim = true;
const object = {
  customCode
};

C:

const customCode = serialize.verbatim`window.navigator.userAgent`;
const object = {
  customCode
};

I tried a hack similar to #32 (comment) using a function as a value and overriding its toString method, but it didn't work since I can't include ( in the code without it being rewritten as part of the function serialization.