123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isSerializableProps = isSerializableProps;
- var _isPlainObject = require("../shared/lib/is-plain-object");
- const regexpPlainIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
- class SerializableError extends Error {
- constructor(page, method, path, message){
- super(path ? `Error serializing \`${path}\` returned from \`${method}\` in "${page}".\nReason: ${message}` : `Error serializing props returned from \`${method}\` in "${page}".\nReason: ${message}`);
- }
- }
- exports.SerializableError = SerializableError;
- function isSerializableProps(page, method, input) {
- if (!(0, _isPlainObject).isPlainObject(input)) {
- throw new SerializableError(page, method, "", `Props must be returned as a plain object from ${method}: \`{ props: { ... } }\` (received: \`${(0, _isPlainObject).getObjectClassLabel(input)}\`).`);
- }
- function visit(visited, value, path) {
- if (visited.has(value)) {
- throw new SerializableError(page, method, path, `Circular references cannot be expressed in JSON (references: \`${visited.get(value) || "(self)"}\`).`);
- }
- visited.set(value, path);
- }
- function isSerializable(refs, value, path) {
- const type = typeof value;
- if (
- value === null ||
-
-
-
-
- type === "boolean" || type === "number" || type === "string") {
- return true;
- }
- if (type === "undefined") {
- throw new SerializableError(page, method, path, "`undefined` cannot be serialized as JSON. Please use `null` or omit this value.");
- }
- if ((0, _isPlainObject).isPlainObject(value)) {
- visit(refs, value, path);
- if (Object.entries(value).every(([key, nestedValue])=>{
- const nextPath = regexpPlainIdentifier.test(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`;
- const newRefs = new Map(refs);
- return isSerializable(newRefs, key, nextPath) && isSerializable(newRefs, nestedValue, nextPath);
- })) {
- return true;
- }
- throw new SerializableError(page, method, path, `invariant: Unknown error encountered in Object.`);
- }
- if (Array.isArray(value)) {
- visit(refs, value, path);
- if (value.every((nestedValue, index)=>{
- const newRefs = new Map(refs);
- return isSerializable(newRefs, nestedValue, `${path}[${index}]`);
- })) {
- return true;
- }
- throw new SerializableError(page, method, path, `invariant: Unknown error encountered in Array.`);
- }
-
-
- throw new SerializableError(page, method, path, "`" + type + "`" + (type === "object" ? ` ("${Object.prototype.toString.call(value)}")` : "") + " cannot be serialized as JSON. Please only return JSON serializable data types.");
- }
- return isSerializable(new Map(), input, "");
- }
|