@es-joy/jsoe 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/.eslintrc.cjs +2 -1
  2. package/CHANGES.md +13 -0
  3. package/README.md +4 -4
  4. package/demo/index.html +1 -0
  5. package/demo/index.js +147 -14
  6. package/index.html +10 -0
  7. package/package.json +9 -9
  8. package/src/formatAndTypeChoices.js +245 -0
  9. package/src/formats/indexedDBKey.js +5 -4
  10. package/src/formats/json.js +1 -1
  11. package/src/formats/schemaAndArbitrary.js +1 -1
  12. package/src/formats/schemaOnly.js +1 -1
  13. package/src/formats/structuredCloning.js +4 -22
  14. package/src/formats.js +17 -206
  15. package/src/fundamentalTypes/BooleanObjectType.js +1 -1
  16. package/src/fundamentalTypes/NumberObjectType.js +1 -1
  17. package/src/fundamentalTypes/StringObjectType.js +1 -1
  18. package/src/fundamentalTypes/arrayReferenceType.js +1 -1
  19. package/src/fundamentalTypes/arrayType.js +3 -3
  20. package/src/fundamentalTypes/bigintType.js +1 -1
  21. package/src/fundamentalTypes/dateType.js +1 -1
  22. package/src/fundamentalTypes/nullType.js +1 -1
  23. package/src/fundamentalTypes/numberType.js +1 -1
  24. package/src/fundamentalTypes/objectReferenceType.js +1 -1
  25. package/src/fundamentalTypes/objectType.js +1 -1
  26. package/src/fundamentalTypes/regexpType.js +1 -1
  27. package/src/fundamentalTypes/sparseUndefinedType.js +1 -1
  28. package/src/fundamentalTypes/stringType.js +1 -1
  29. package/src/fundamentalTypes/undefinedType.js +1 -1
  30. package/src/index.js +7 -2
  31. package/src/jsoe.css +58 -0
  32. package/src/subTypes/falseType.js +1 -1
  33. package/src/subTypes/trueType.js +1 -1
  34. package/src/superTypes/SpecialNumberSuperType.js +17 -10
  35. package/src/superTypes/SpecialRealNumberSuperType.js +56 -0
  36. package/src/typeChoices.js +229 -117
  37. package/src/types.js +56 -37
  38. package/vendor/typeson-registry/dist/index.js +19 -3
  39. package/src/superTypes/InfinitiesSuperType.js +0 -49
@@ -1,137 +1,249 @@
1
+ import Formats, {getControlsForFormatAndValue} from './formats.js';
2
+ import Types from './types.js';
1
3
  import {jml} from '../vendor/jamilih/dist/jml-es.js';
2
- import Formats from './formats.js';
4
+
3
5
  import {$e, DOM} from './utils/templateUtils.js';
6
+ import dialogs from './utils/dialogs.js';
4
7
 
5
8
  /**
6
- * Defaults to structured cloning.
7
- * @todo Compose from format metadata, so can make user customizable.
8
- * @param {object} cfg
9
- * @param {string} [cfg.schema] (NOT IN USE)
10
- * @param {boolean} [cfg.hasKeyPath] Whether or not a key path is expected; if
11
- * true, an indexedDB key is not allowed here as a key does not support
12
- * the object type which is needed for a key path.
13
- * @returns {DocumentFragment}
9
+ * An arbitrary Structured Clone, JSON, etc. value.
10
+ * @typedef {any} StructuredCloneValue
14
11
  */
15
- export const getFormatAndSchemaChoices = ({schema, hasKeyPath} = {}) => {
16
- const hasSchema = typeof schema === 'string';
17
- return [
18
- ['JSON only', {value: 'json'}],
19
- ...(hasKeyPath
20
- ? []
21
- : [['IndexedDB key', {value: 'indexedDBKey'}]]),
22
- ['Structured Clone (via Typeson JSON)', {
23
- value: 'structuredCloning', selected: !hasSchema
24
- }]
25
- /* schema:
26
- ...(hasSchema
27
- ? [
28
- [`Schema + arbitrary: ${schema}`, {
29
- value: 'schemaAndArbitrary',
30
- dataset: {schema}
31
- }],
32
- [`Schema only: ${schema}`, {
33
- value: 'schemaOnly',
34
- dataset: {schema},
35
- selected: hasSchema
36
- }]
37
- ]
38
- : []
39
- )
40
- */
41
- /*
42
- // This can be supported for editing only
43
- ['Arbitrary (Non-Typeson-serializable will be read-only)', {
44
- value: 'arbitrary',
45
- title: 'Any value that the typeson-registry supports ' +
46
- 'for structured cloning'
47
- }]
48
- */
49
- ].map(([optText, optAtts]) => {
50
- return jml('option', optAtts, [optText]);
51
- }).reduce((frag, option) => {
52
- frag.append(option);
53
- return frag;
54
- }, document.createDocumentFragment());
55
- };
56
12
 
57
13
  /**
58
- * Builds a selector and container for types.
14
+ * @callback BuildTypeChoices
59
15
  * @param {object} cfg
60
- * @param {string} [cfg.schema] The schema name (NOT IN USE)
61
- * @param {object} [cfg.schemaContent] The schema content (NOT IN USE)
62
- * @param {boolean} [cfg.hasValue] Set to `true` if you are supplying
63
- * your own value. If `false` and `hasKeyPath` is `true`,
64
- * will initialize with an object.
65
- * @param {boolean} [cfg.singleValue] (NOT IN USE)
66
- * @param {boolean} [cfg.hasKeyPath] If this is set (because there is a keyPath
67
- * to be found within the object) and `hasValue` is true, an object type
68
- * will be set and required at the root level. This option will also
69
- * prevent selection of indexedDB key at root (since a key cannot be a
70
- * plain object).
71
- * @param {string} [cfg.typeNamespace] Used to prevent conflicts with other
72
- * instances of typeChoices on the page
73
- * @returns {[
74
- * mainTypeChoices: HTMLSelectElement,
75
- * typesHolder: HTMLDivElement
76
- * ]} The selector for types and the container for them. Both should be
77
- * added to the page.
16
+ * @param {string} cfg.format
17
+ * @param {string} cfg.typeNamespace
18
+ * @param {StructuredCloneValue} cfg.value
19
+ * @param {boolean} [cfg.setValue=false]
20
+ * @param {string} cfg.state
21
+ * @param {string} cfg.keySelectClass
22
+ * @param {boolean} cfg.requireObject
23
+ * @param {boolean} cfg.objectHasValue
24
+ * @param {RootElement} cfg.topRoot Always a `div` element?
25
+ * @param {string} cfg.schema Schema name
26
+ * @param {string} cfg.schemaContent Schema contents
27
+ * @returns {[select: Element, typeContainer: Element]}
28
+ */
29
+
30
+ /**
31
+ * @type {BuildTypeChoices}
78
32
  */
79
- function typeChoices ({
33
+ export const buildTypeChoices = ({
34
+ format,
35
+ typeNamespace,
36
+ value,
37
+ setValue = false,
38
+ state,
39
+ // itemIndex = 0,
40
+ keySelectClass,
41
+ requireObject,
42
+ objectHasValue,
43
+ topRoot,
80
44
  schema,
81
- schemaContent,
82
- hasValue,
83
- singleValue,
84
- hasKeyPath,
85
- typeNamespace
86
- }) {
87
- const mainTypeChoices = jml('select', {
88
- class: 'mainTypeChoices',
89
- hidden: singleValue,
90
- // is: 'main-type-choices',
45
+ schemaContent
46
+ }) => {
47
+ // console.log('format', format, 'state', state, 'path', typeNamespace);
48
+ const typeOptions = requireObject
49
+ ? [Types.getOptionForType('object')]
50
+ : Types.getTypeOptionsForFormatAndState(format, state);
51
+
52
+ let editUI;
53
+ const sel = jml('select', {
54
+ hidden: requireObject,
55
+ class: `typeChoices-${typeNamespace}${keySelectClass
56
+ ? ' ' + keySelectClass
57
+ : ''
58
+ }`,
59
+ // is: 'type-choices',
91
60
  $custom: {
92
- $setFormat (valueFormat) {
93
- this.value = valueFormat;
94
- this.$buildTypeChoices();
61
+ $setType ({type, baseValue, bringIntoFocus}) {
62
+ this.value = type;
63
+ this.$setStyles();
64
+ this.$addAndValidateEditUI({baseValue, bringIntoFocus});
65
+ },
66
+ $setTypeNoEditUI ({type}) {
67
+ this.value = type;
68
+ this.$setStyles();
69
+ },
70
+ $setStyles () {
71
+ const {value: type} = this;
72
+ this.dataset.type = type; // Used for styling
73
+ const parEl = this.parentElement;
74
+ if (parEl.nodeName.toLowerCase() === 'fieldset') {
75
+ parEl.dataset.type = type;
76
+ DOM.filterChildElements(parEl, 'legend').forEach((legend) => {
77
+ legend.dataset.type = type;
78
+ });
79
+ }
80
+ },
81
+ $getTypeRoot () {
82
+ const container = this.$getContainer();
83
+ /* istanbul ignore if -- How to replicate? */
84
+ if (!container) {
85
+ return false;
86
+ }
87
+ return $e(container, 'div[data-type]');
95
88
  },
96
- $buildTypeChoices () {
97
- DOM.removeChildren(typesHolder);
98
- jml({'#': Formats.buildTypeChoices({
99
- topRoot: $e(typesHolder, 'div[data-type]'),
100
- resultType: 'both',
101
- format: this.value,
89
+ $addAndValidateEditUI ({baseValue, bringIntoFocus} = {}) {
90
+ const {value: type} = this;
91
+
92
+ if (!type) { return; }
93
+ let topRoot = this.$getTopRoot();
94
+
95
+ // Todo (low): Try to avoid need for `baseValue`
96
+ // (needed by arrayNonindexKeys for setting an array
97
+ // length and avoiding errors); could set all
98
+ // values through here?
99
+ editUI = Types.getUIForModeAndType({
100
+ readonly: false,
102
101
  typeNamespace,
103
- requireObject: hasKeyPath,
104
- objectHasValue: hasValue,
105
- schema,
106
- schemaContent
107
- })}, typesHolder);
102
+ type,
103
+ bringIntoFocus,
104
+ hasValue: type === 'arrayNonindexKeys' && baseValue,
105
+ value: baseValue,
106
+ buildTypeChoices,
107
+ format,
108
+ topRoot
109
+ });
110
+ this.$addEditUI({editUI});
111
+ this.$validate();
112
+ topRoot = this.$getTopRoot(); // May be existing now
113
+ // Needed; Array/object ref somewhere could now be valid or invalid
114
+ Types.validateAllReferences({topRoot});
115
+ },
116
+ $addTypeAndEditUI ({type, editUI}) {
117
+ this.$setTypeNoEditUI({type});
118
+ this.$addEditUI({editUI});
119
+ },
120
+ $addEditUI ({editUI}) {
121
+ const container = this.$getContainer();
122
+ DOM.removeChildren(container);
123
+ jml(editUI, container);
124
+ },
125
+ $getContainer () {
126
+ return this.nextElementSibling;
127
+ },
128
+ $getTopRoot () {
129
+ return topRoot || this.$getTypeRoot();
130
+ },
131
+ $validate () {
132
+ const {value: type} = this;
133
+ const container = this.$getContainer();
134
+ if (!container.firstElementChild) {
135
+ return false;
136
+ }
137
+ const editUI = container.firstElementChild;
138
+ return Types.validate({
139
+ type, root: editUI, topRoot: this.$getTopRoot()
140
+ });
108
141
  }
109
142
  },
110
- $on: {change () {
111
- this.$buildTypeChoices();
143
+ $on: {change (e) {
144
+ // We don't want form `onchange` to run `$checkForKeyDuplicates`
145
+ // again (through `addAndValidateEditUI`->`validateAllReferences`)
146
+ e.stopPropagation();
147
+ this.$addAndValidateEditUI();
148
+ this.$setStyles();
112
149
  }}
113
- }, [getFormatAndSchemaChoices({schema, hasKeyPath})]);
114
- const typesHolder = jml('div', {class: 'typesHolder', $custom: {
115
- $getTypeRoot () {
116
- return $e(this, 'div[data-type]');
150
+ }, [
151
+ ['option', {value: ''}, [
152
+ '(Choose a type)'
153
+ ]],
154
+ ...typeOptions.map(
155
+ ([optText, optAtts]) => [
156
+ 'option',
157
+ optAtts ||
158
+ /* istanbul ignore next -- Should always have atts */
159
+ {},
160
+ [optText]
161
+ ]
162
+ )
163
+ ]);
164
+ if (setValue || (requireObject && !objectHasValue)) {
165
+ setTimeout(async () => {
166
+ if (!setValue) { // if (requireObject && !objectHasValue) {
167
+ // Todo (low): We could auto-populate keypath if has
168
+ // keypath (and we probably also only want if
169
+ // not autoincrement)
170
+ value = {};
171
+ }
172
+ try {
173
+ const rootEditUI = await Formats.availableFormats[format].iterate(
174
+ value,
175
+ {
176
+ readonly: false,
177
+ typeNamespace,
178
+ schema,
179
+ schemaContent
180
+ }
181
+ );
182
+ const type = Types.getTypeForRoot(rootEditUI);
183
+ sel.$addTypeAndEditUI({type, editUI: rootEditUI});
184
+ } catch (err) {
185
+ /* istanbul ignore next -- At least some errors handled earlier */
186
+ dialogs.alert({
187
+ message: 'The object to be added had types not supported ' +
188
+ 'by the current format.'
189
+ });
190
+ /* istanbul ignore next -- How to trigger? */
191
+ console.log('err', err);
192
+ }
193
+ });
194
+ }
195
+
196
+ const typeContainer = jml('div', {class: 'typeContainer'});
197
+
198
+ return {
199
+ domArray: [
200
+ sel,
201
+ typeContainer
202
+ ],
203
+
204
+ /**
205
+ * @param {import('./types.js').StateObject} [stateObj] Will
206
+ * auto-set `typeNamespace` and `format`
207
+ * @param {string} [currentPath]
208
+ * @returns {StructuredCloneValue}
209
+ */
210
+ getValue (stateObj, currentPath) {
211
+ const root = $e(typeContainer, 'div[data-type]');
212
+ return Types.getValueForRoot(root, {
213
+ typeNamespace,
214
+ format,
215
+ ...stateObj
216
+ }, currentPath);
117
217
  },
118
- $getTypeSelect () {
119
- return $e(this, `.typeChoices-${typeNamespace}`);
120
- }
121
- }});
122
218
 
123
- jml({'#': Formats.buildTypeChoices({
124
- resultType: 'both',
125
- topRoot: $e(typesHolder, 'div[data-type]'),
126
- format: 'structuredCloning',
127
- typeNamespace,
128
- requireObject: hasKeyPath,
129
- objectHasValue: hasValue,
130
- schema,
131
- schemaContent
132
- })}, typesHolder);
219
+ /**
220
+ * @returns {string|undefined}
221
+ */
222
+ getType () {
223
+ const root = $e(typeContainer, 'div[data-type]');
224
+ return Types.getTypeForRoot(root);
225
+ },
133
226
 
134
- return [mainTypeChoices, typesHolder];
135
- }
227
+ /**
228
+ * @returns {boolean}
229
+ */
230
+ validValuesSet () {
231
+ const root = $e(typeContainer, 'div[data-type]');
232
+ const form = root.closest('form');
233
+ return Types.validValuesSet({form, typeNamespace});
234
+ },
136
235
 
137
- export default typeChoices;
236
+ /**
237
+ * @param {StructuredCloneValue} value
238
+ * @param {import('./types.js').StateObject} stateObj
239
+ * @returns {Promise<void>}
240
+ */
241
+ async setValue (value, stateObj) {
242
+ const rootEditUI = await getControlsForFormatAndValue(
243
+ format, value, stateObj
244
+ );
245
+ const type = Types.getTypeForRoot(rootEditUI);
246
+ sel.$addTypeAndEditUI({type, editUI: rootEditUI});
247
+ }
248
+ };
249
+ };
package/src/types.js CHANGED
@@ -25,10 +25,12 @@ import BooleanObjectType from './fundamentalTypes/BooleanObjectType.js';
25
25
  import NumberObjectType from './fundamentalTypes/NumberObjectType.js';
26
26
  import StringObjectType from './fundamentalTypes/StringObjectType.js';
27
27
  import sparseUndefinedType from './fundamentalTypes/sparseUndefinedType.js';
28
- import InfinitiesSuperType from './superTypes/InfinitiesSuperType.js';
28
+ import SpecialRealNumberSuperType from
29
+ './superTypes/SpecialRealNumberSuperType.js';
29
30
  import SpecialNumberSuperType from './superTypes/SpecialNumberSuperType.js';
30
31
 
31
32
  /**
33
+ * Utility to retrieve the property value given a legend element.
32
34
  * @param {HTMLLegendElement} legend
33
35
  * @returns {string}
34
36
  */
@@ -54,42 +56,34 @@ const Types = {};
54
56
  * present, use `stringRegex`
55
57
  * @property {RegExp} [stringRegexEnd] Used for string parsing. If not
56
58
  * present, use `stringRegex`
57
- * @property {
58
- * (ArbitraryValue) => boolean
59
- * } [valueMatch] Function to check whether this subtype matches
59
+ * @property {(ArbitraryValue) => boolean} [valueMatch] Function to
60
+ * check whether this subtype matches
60
61
  * @property {string} [superType] The greater fundamental type to which
61
62
  * the type belongs
62
63
  * @property {(s: string) => ArbitraryValue} toValue Converts from
63
64
  * string to value. May use `stringRegex` to find components.
64
- * @property {
65
- * (info: {root?: HTMLDivElement}) => ArbitraryValue
65
+ * @property {(info: {root?: HTMLDivElement}) =>
66
+ * ArbitraryValue
66
67
  * } getValue Gets the value for the type
67
- * @property {
68
- * (info: {root?: HTMLDivElement}) => void
69
- * } [setValue] Should set the value of the form's `getInput` element
70
- * @property {
71
- * (info: {
72
- * value?: ArbitraryValue,
73
- * typeNamespace?: string,
74
- * type?: string,
75
- * topRoot?: HTMLDivElement,
76
- * resultType?: "keys"|"values"|"both",
77
- * format?: string
78
- * }) => JamilihArray
79
- * } viewUI
80
- * @property {
81
- * (info: {
82
- * value?: ArbitraryValue,
83
- * typeNamespace?: string,
84
- * }) => JamilihArray
85
- * } editUI
86
- * @property {
87
- * (info: {root: HTMLDivElement}) =>
88
- * HTMLInputElement|HTMLTextareaElement|HTMLSelectElement
89
- * } getInput Gets the form control (with `value`)
90
- * @property {
91
- * (path: string, value: ArbitraryValue) => ArbitraryValue
92
- * } [resolveReference] Gets the reference. For array and object
68
+ * @property {(info: {root?: HTMLDivElement}) => void} [setValue] Should set
69
+ * the value of the form's `getInput` element
70
+ * @property {(info: {
71
+ * value?: ArbitraryValue,
72
+ * typeNamespace?: string,
73
+ * type?: string,
74
+ * topRoot?: HTMLDivElement,
75
+ * resultType?: "keys"|"values"|"both",
76
+ * format?: string
77
+ * }) => JamilihArray} viewUI
78
+ * @property {(info: {
79
+ * value?: ArbitraryValue,
80
+ * typeNamespace?: string,
81
+ * }) => JamilihArray} editUI
82
+ * @property {(info: {root: HTMLDivElement}) =>
83
+ * HTMLInputElement|HTMLTextareaElement|HTMLSelectElement} getInput Gets the
84
+ * form control (with `value`)
85
+ * @property {(path: string, value: ArbitraryValue) =>
86
+ * ArbitraryValue} [resolveReference] Gets the reference. For array and object
93
87
  * references types only
94
88
  * @property {(info: {root: HTMLDivElement, topRoot?: HTMLDivElement}) => {
95
89
  * message: string,
@@ -128,7 +122,7 @@ Types.availableTypes = {
128
122
  // passed in:
129
123
  userObject: ['User objects'],
130
124
  undef: undefinedType,
131
- Infinities: InfinitiesSuperType,
125
+ SpecialRealNumber: SpecialRealNumberSuperType,
132
126
  SpecialNumber: SpecialNumberSuperType,
133
127
 
134
128
  regexp: regexpType,
@@ -240,28 +234,52 @@ copyTypeObjs([
240
234
  ]);
241
235
 
242
236
  /**
237
+ * Utility to retrieve the type out of a type root element.
243
238
  * @public
244
- * @param {RootElement} root
245
- * @returns {string|boolean} Why would it not exist?
239
+ * @param {?RootElement} root
240
+ * @returns {string|undefined} Why would it not exist?
246
241
  */
247
242
  Types.getTypeForRoot = (root) => {
248
243
  return root && root.dataset.type;
249
244
  };
250
245
 
251
246
  /**
247
+ * @typedef {{
248
+ * typeNamespace: string,
249
+ * "readonly": boolean,
250
+ * format: string,
251
+ * error: Error,
252
+ * rootUI: Element,
253
+ * schemaContent: string,
254
+ * getPossibleSchemasForPathAndType: (
255
+ * keypath: string,
256
+ * parentPath: string,
257
+ * arrayOrObjectPropertyName: string,
258
+ * valueType: string
259
+ * ) => StateObject
260
+ * }} StateObject
261
+ */
262
+
263
+ /**
264
+ * Utility to get the value out of a type root element with a given
265
+ * state and path.
252
266
  * @public
253
267
  * @param {RootElement} root
254
268
  * @param {StateObject} stateObj
255
- * @param {string} currentPath
269
+ * @param {string} [currentPath]
256
270
  * @returns {StructuredCloneValue}
257
271
  */
258
272
  Types.getValueForRoot = (root, stateObj, currentPath) => {
259
- return Types.availableTypes[Types.getTypeForRoot(root)].getValue({
273
+ const typeObject = /** @type {TypeObject} */ (
274
+ Types.availableTypes[Types.getTypeForRoot(root)]
275
+ );
276
+ return typeObject.getValue({
260
277
  root, stateObj, currentPath
261
278
  });
262
279
  };
263
280
 
264
281
  /**
282
+ * Utility to get the form control (e.g., input element) for a root.
265
283
  * @public
266
284
  * @param {RootElement} root
267
285
  * @returns {null|HTMLInputElement}
@@ -276,6 +294,7 @@ Types.getFormControlForRoot = (root) => {
276
294
  };
277
295
 
278
296
  /**
297
+ * Utility to get the value for a root using its ancestor and state.
279
298
  * @public
280
299
  * @param {string|Element} selOrEl
281
300
  * @param {StateObject} stateObj
@@ -1,4 +1,4 @@
1
- function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n);}return r}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t]);})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t));}));}return e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,_toPropertyKey(n.key),n);}}function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function _defineProperty(e,t,r){return (t=_toPropertyKey(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _slicedToArray(e,t){return function _arrayWithHoles(e){if(Array.isArray(e))return e}(e)||function _iterableToArrayLimit(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,a,i,c=[],s=!0,u=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1;}else for(;!(s=(n=a.call(r)).done)&&(c.push(n.value),c.length!==t);s=!0);}catch(e){u=!0,o=e;}finally{try{if(!s&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(u)throw o}}return c}}(e,t)||_unsupportedIterableToArray(e,t)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}(e)||function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||_unsupportedIterableToArray(e)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return "Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function _toPropertyKey(e){var t=function _toPrimitive(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return ("string"===t?String:Number)(e)}(e,"string");return "symbol"==typeof t?t:String(t)}var e=_createClass((function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e);}));e.__typeson__type__="TypesonPromise","undefined"!=typeof Symbol&&(e.prototype[Symbol.toStringTag]="TypesonPromise"),e.prototype.then=function(t,r){var n=this;return new e((function(e,o){n.p.then((function(r){e(t?t(r):r);})).catch((function(e){return r?r(e):Promise.reject(e)})).then(e,o);}))},e.prototype.catch=function(e){return this.then(null,e)},e.resolve=function(t){return new e((function(e){e(t);}))},e.reject=function(t){return new e((function(e,r){r(t);}))},["all","race","allSettled"].forEach((function(t){e[t]=function(r){return new e((function(e,n){Promise[t](r.map((function(e){return e&&e.constructor&&"TypesonPromise"===e.constructor.__typeson__type__?e.p:e}))).then(e,n);}))};}));var t={}.toString,r={}.hasOwnProperty,n=Object.getPrototypeOf,o=r.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return t.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return !1;var a=n(e);if(!a)return null===t;var i=r.call(a,"constructor")&&a.constructor;return "function"!=typeof i?null===t:t===i||(null!==t&&o.call(i)===o.call(t)||"function"==typeof t&&"string"==typeof i.__typeson__type__&&i.__typeson__type__===t.__typeson__type__)}function isPlainObject(e){return !(!e||"Object"!==toStringTag(e))&&(!n(e)||hasConstructorOf(e,Object))}function isUserObject(e){if(!e||"Object"!==toStringTag(e))return !1;var t=n(e);return !t||(hasConstructorOf(e,Object)||isUserObject(t))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/''/g,"''''").replace(/^$/,"''").replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~").replace(/^''$/,"").replace(/''''/g,"''")}function getByKeyPath(e,t){if(""===t)return e;var r=t.indexOf(".");if(r>-1){var n=e[unescapeKeyPathComponent(t.slice(0,r))];return void 0===n?void 0:getByKeyPath(n,t.slice(r+1))}return e[unescapeKeyPathComponent(t)]}function setAtKeyPath(e,t,r){if(""===t)return r;var n=t.indexOf(".");return n>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,n))],t.slice(n+1),r):(e[unescapeKeyPathComponent(t)]=r,e)}function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)}function _await(e,t,r){return r?t?t(e):e:(e&&e.then||(e=Promise.resolve(e)),t?e.then(t):e)}var a=Object.keys,i$1=Array.isArray,c={}.hasOwnProperty,s=["type","replaced","iterateIn","iterateUnsetNumeric"];function _async(e){return function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];try{return Promise.resolve(e.apply(this,t))}catch(e){return Promise.reject(e)}}}function nestedPathsFirst(e,t){if(""===e.keypath)return -1;var r=e.keypath.match(/\./g)||0,n=t.keypath.match(/\./g)||0;return r&&(r=r.length),n&&(n=n.length),r>n?-1:r<n?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var u=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={};}return _createClass(Typeson,[{key:"stringify",value:function stringify(e,t,r,n){n=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),n),{},{stringification:!0});var o=this.encapsulate(e,null,n);return i$1(o)?JSON.stringify(o[0],t,r):o.then((function(e){return JSON.stringify(e,t,r)}))}},{key:"stringifySync",value:function stringifySync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!1}))}},{key:"parse",value:function parse(e,t,r){return r=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),r),{},{parse:!0}),this.revive(JSON.parse(e,t),r)}},{key:"parseSync",value:function parseSync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.returnTypeNames=!0,this.encapsulate(e,t,r)}},{key:"rootTypeName",value:function rootTypeName(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.iterateNone=!0,this.encapsulate(e,t,r)}},{key:"encapsulate",value:function encapsulate(t,r,n){var o=_async((function(t,r){return _await(Promise.all(r.map((function(e){return e[1].p}))),(function(n){return _await(Promise.all(n.map(_async((function(n){var a=!1,i=[],c=_slicedToArray(r.splice(0,1),1),s=_slicedToArray(c[0],7),u=s[0],p=s[2],l=s[3],y=s[4],f=s[5],h=s[6],v=_encapsulate(u,n,p,l,i,!0,h),b=hasConstructorOf(v,e);return function _invoke(e,t){var r=e();return r&&r.then?r.then(t):t(r)}((function(){if(u&&b)return _await(v.p,(function(e){y[f]=e;var r=o(t,i);return a=!0,r}))}),(function(e){return a?e:(u?y[f]=v:t=b?v.p:v,o(t,i))}))})))),(function(){return t}))}))})),u=(n=_objectSpread2(_objectSpread2({sync:!0},this.options),n)).sync,p=this,l={},y=[],f=[],h=[],v=!("cyclic"in n)||n.cyclic,b=n.encapsulateObserver,d=_encapsulate("",t,v,r||{},h);function finish(e){var t=Object.values(l);if(n.iterateNone)return t.length?t[0]:getJSONType(e);if(t.length){if(n.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!c.call(e,"$types")?e.$types=l:e={$:e,$types:{$:l}};}else isObject(e)&&c.call(e,"$types")&&(e={$:e,$types:!0});return !n.returnTypeNames&&e}function _adaptBuiltinStateObjectProperties(e,t,r){Object.assign(e,t);var n=s.map((function(t){var r=e[t];return delete e[t],r}));r(),s.forEach((function(t,r){e[t]=n[r];}));}function _encapsulate(t,r,o,s,u,h,v){var d,_={},O=_typeof(r),j=b?function(n){var a=v||s.type||getJSONType(r);b(Object.assign(n||_,{keypath:t,value:r,cyclic:o,stateObj:s,promisesData:u,resolvingTypesonPromise:h,awaitingTypesonPromise:hasConstructorOf(r,e)},{type:a}));}:null;if(["string","boolean","number","undefined"].includes(O))return void 0===r||Number.isNaN(r)||r===Number.NEGATIVE_INFINITY||r===Number.POSITIVE_INFINITY?(d=s.replaced?r:replace(t,r,s,u,!1,h,j))!==r&&(_={replaced:d}):d=r,j&&j(),d;if(null===r)return j&&j(),r;if(o&&!s.iterateIn&&!s.iterateUnsetNumeric&&r&&"object"===_typeof(r)){var m=y.indexOf(r);if(!(m<0))return l[t]="#",j&&j({cyclicKeypath:f[m]}),"#"+f[m];!0===o&&(y.push(r),f.push(t));}var g,S=isPlainObject(r),P=i$1(r),T=(S||P)&&(!p.plainObjectReplacers.length||s.replaced)||s.iterateIn?r:replace(t,r,s,u,S||P,null,j);if(T!==r?(d=T,_={replaced:T}):""===t&&hasConstructorOf(r,e)?(u.push([t,r,o,s,void 0,void 0,s.type]),d=r):P&&"object"!==s.iterateIn||"array"===s.iterateIn?(g=new Array(r.length),_={clone:g}):(["function","symbol"].includes(_typeof(r))||"toJSON"in r||hasConstructorOf(r,e)||hasConstructorOf(r,Promise)||hasConstructorOf(r,ArrayBuffer))&&!S&&"object"!==s.iterateIn?d=r:(g={},s.addLength&&(g.length=r.length),_={clone:g}),j&&j(),n.iterateNone)return g||d;if(!g)return d;if(s.iterateIn){var w=function _loop(n){var a={ownKeys:c.call(r,n)};_adaptBuiltinStateObjectProperties(s,a,(function(){var a=t+(t?".":"")+escapeKeyPathComponent(n),i=_encapsulate(a,r[n],Boolean(o),s,u,h);hasConstructorOf(i,e)?u.push([a,i,Boolean(o),s,g,n,s.type]):void 0!==i&&(g[n]=i);}));};for(var A in r)w(A);j&&j({endIterateIn:!0,end:!0});}else a(r).forEach((function(n){var a=t+(t?".":"")+escapeKeyPathComponent(n);_adaptBuiltinStateObjectProperties(s,{ownKeys:!0},(function(){var t=_encapsulate(a,r[n],Boolean(o),s,u,h);hasConstructorOf(t,e)?u.push([a,t,Boolean(o),s,g,n,s.type]):void 0!==t&&(g[n]=t);}));})),j&&j({endIterateOwn:!0,end:!0});if(s.iterateUnsetNumeric){for(var C=r.length,k=function _loop2(n){if(!(n in r)){var a=t+(t?".":"")+n;_adaptBuiltinStateObjectProperties(s,{ownKeys:!1},(function(){var t=_encapsulate(a,void 0,Boolean(o),s,u,h);hasConstructorOf(t,e)?u.push([a,t,Boolean(o),s,g,n,s.type]):void 0!==t&&(g[n]=t);}));}},N=0;N<C;N++)k(N);j&&j({endIterateUnsetNumeric:!0,end:!0});}return g}function replace(e,t,r,n,o,a,i){for(var c=o?p.plainObjectReplacers:p.nonplainObjectReplacers,s=c.length;s--;){var y=c[s];if(y.test(t,r)){var f=y.type;if(p.revivers[f]){var h=l[e];l[e]=h?[f].concat(h):f;}return Object.assign(r,{type:f,replaced:!0}),!u&&y.replaceAsync||y.replace?(i&&i({replacing:!0}),_encapsulate(e,y[u||!y.replaceAsync?"replace":"replaceAsync"](t,r),v&&"readonly",r,n,a,f)):(i&&i({typeDetected:!0}),_encapsulate(e,t,v&&"readonly",r,n,a,f))}}return t}return h.length?u&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(o(d,h)).then(finish):!u&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():n.stringification&&u?[finish(d)]:u?finish(d):Promise.resolve(finish(d))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,r){return this.encapsulate(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,r){return this.encapsulate(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!1}))}},{key:"revive",value:function revive(t,r){var n=t&&t.$types;if(!n)return t;if(!0===n)return t.$;var o=(r=_objectSpread2(_objectSpread2({sync:!0},this.options),r)).sync,c=[],s={},u=!0;n.$&&isPlainObject(n.$)&&(t=t.$,n=n.$,u=!1);var l=this;function executeReviver(e,t){var r=_slicedToArray(l.revivers[e]||[],1)[0];if(!r)throw new Error("Unregistered type: "+e);return o&&!("revive"in r)?t:r[o&&r.revive?"revive":!o&&r.reviveAsync?"reviveAsync":"revive"](t,s)}var y=[];function checkUndefined(e){return hasConstructorOf(e,p)?void 0:e}var f,h=function revivePlainObjects(){var r=[];if(Object.entries(n).forEach((function(e){var t=_slicedToArray(e,2),o=t[0],a=t[1];"#"!==a&&[].concat(a).forEach((function(e){_slicedToArray(l.revivers[e]||[null,{}],2)[1].plain&&(r.push({keypath:o,type:e}),delete n[o]);}));})),r.length)return r.sort(nestedPathsFirst).reduce((function reducer(r,n){var o=n.keypath,a=n.type;if(isThenable(r))return r.then((function(e){return reducer(e,{keypath:o,type:a})}));var i=getByKeyPath(t,o);if(hasConstructorOf(i=executeReviver(a,i),e))return i.then((function(e){var r=setAtKeyPath(t,o,e);r===e&&(t=r);}));var c=setAtKeyPath(t,o,i);c===i&&(t=c);}),void 0)}();return hasConstructorOf(h,e)?f=h.then((function(){return t})):(f=function _revive(t,r,o,s,l){if(!u||"$types"!==t){var f=n[t],h=i$1(r);if(h||isPlainObject(r)){var v=h?new Array(r.length):{};for(a(r).forEach((function(n){var a=_revive(t+(t?".":"")+escapeKeyPathComponent(n),r[n],o||v,v,n),i=function set(e){return hasConstructorOf(e,p)?v[n]=void 0:void 0!==e&&(v[n]=e),e};hasConstructorOf(a,e)?y.push(a.then((function(e){return i(e)}))):i(a);})),r=v;c.length;){var b=_slicedToArray(c[0],4),d=b[0],_=b[1],O=b[2],j=b[3],m=getByKeyPath(d,_);if(void 0===m)break;O[j]=m,c.splice(0,1);}}if(!f)return r;if("#"===f){var g=getByKeyPath(o,r.slice(1));return void 0===g&&c.push([o,r.slice(1),s,l]),g}return [].concat(f).reduce((function reducer(t,r){return hasConstructorOf(t,e)?t.then((function(e){return reducer(e,r)})):executeReviver(r,t)}),r)}}("",t,null),y.length&&(f=e.resolve(f).then((function(t){return e.all([t].concat(y))})).then((function(e){return _slicedToArray(e,1)[0]})))),isThenable(f)?o&&r.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(f,e)?f.p.then(checkUndefined):f:!o&&r.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():o?checkUndefined(f):Promise.resolve(checkUndefined(f))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},t),{},{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},t),{},{sync:!1}))}},{key:"register",value:function register(e,t){var r=this;t=t||{};var n=function R(e){i$1(e)?e.forEach((function(e){return R(e)})):e&&a(e).forEach((function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(l.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var o=e[n],a=o&&o.testPlainObjects?r.plainObjectReplacers:r.nonplainObjectReplacers,c=a.filter((function(e){return e.type===n}));if(c.length&&(a.splice(a.indexOf(c[0]),1),delete r.revivers[n],delete r.types[n]),"function"==typeof o){var s=o;o={test:function test(e){return e&&e.constructor===s},replace:function replace(e){return _objectSpread2({},e)},revive:function revive(e){return Object.assign(Object.create(s.prototype),e)}};}else if(i$1(o)){var u=_slicedToArray(o,3);o={test:u[0],replace:u[1],revive:u[2]};}if(o&&o.test){var p={type:n,test:o.test.bind(o)};o.replace&&(p.replace=o.replace.bind(o)),o.replaceAsync&&(p.replaceAsync=o.replaceAsync.bind(o));var y="number"==typeof t.fallback?t.fallback:t.fallback?0:Number.POSITIVE_INFINITY;if(o.testPlainObjects?r.plainObjectReplacers.splice(y,0,p):r.nonplainObjectReplacers.splice(y,0,p),o.revive||o.reviveAsync){var f={};o.revive&&(f.revive=o.revive.bind(o)),o.reviveAsync&&(f.reviveAsync=o.reviveAsync.bind(o)),r.revivers[n]=[f,{plain:o.testPlainObjects}];}r.types[n]=o;}}));};return [].concat(e).forEach((function(e){return n(e)})),this}}]),Typeson}(),p=_createClass((function Undefined(){_classCallCheck(this,Undefined);}));p.__typeson__type__="TypesonUndefined";var l=["null","boolean","number","string","array","object"];
1
+ function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n);}return r}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t]);})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t));}));}return e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,_toPropertyKey(n.key),n);}}function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function _defineProperty(e,t,r){return (t=_toPropertyKey(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _slicedToArray(e,t){return function _arrayWithHoles(e){if(Array.isArray(e))return e}(e)||function _iterableToArrayLimit(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,a,i,c=[],s=!0,u=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1;}else for(;!(s=(n=a.call(r)).done)&&(c.push(n.value),c.length!==t);s=!0);}catch(e){u=!0,o=e;}finally{try{if(!s&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(u)throw o}}return c}}(e,t)||_unsupportedIterableToArray(e,t)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _toConsumableArray(e){return function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}(e)||function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||_unsupportedIterableToArray(e)||function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return "Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function _toPropertyKey(e){var t=function _toPrimitive(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return ("string"===t?String:Number)(e)}(e,"string");return "symbol"==typeof t?t:String(t)}var e=_createClass((function TypesonPromise(e){_classCallCheck(this,TypesonPromise),this.p=new Promise(e);}));e.__typeson__type__="TypesonPromise","undefined"!=typeof Symbol&&(e.prototype[Symbol.toStringTag]="TypesonPromise"),e.prototype.then=function(t,r){var n=this;return new e((function(e,o){n.p.then((function(r){e(t?t(r):r);})).catch((function(e){return r?r(e):Promise.reject(e)})).then(e,o);}))},e.prototype.catch=function(e){return this.then(null,e)},e.resolve=function(t){return new e((function(e){e(t);}))},e.reject=function(t){return new e((function(e,r){r(t);}))},["all","race","allSettled"].forEach((function(t){e[t]=function(r){return new e((function(e,n){Promise[t](r.map((function(e){return e&&e.constructor&&"TypesonPromise"===e.constructor.__typeson__type__?e.p:e}))).then(e,n);}))};}));var t={}.toString,r={}.hasOwnProperty,n=Object.getPrototypeOf,o=r.toString;function isThenable(e,t){return isObject(e)&&"function"==typeof e.then&&(!t||"function"==typeof e.catch)}function toStringTag(e){return t.call(e).slice(8,-1)}function hasConstructorOf(e,t){if(!e||"object"!==_typeof(e))return !1;var a=n(e);if(!a)return null===t;var i=r.call(a,"constructor")&&a.constructor;return "function"!=typeof i?null===t:t===i||(null!==t&&o.call(i)===o.call(t)||"function"==typeof t&&"string"==typeof i.__typeson__type__&&i.__typeson__type__===t.__typeson__type__)}function isPlainObject(e){return !(!e||"Object"!==toStringTag(e))&&(!n(e)||hasConstructorOf(e,Object))}function isUserObject(e){if(!e||"Object"!==toStringTag(e))return !1;var t=n(e);return !t||(hasConstructorOf(e,Object)||isUserObject(t))}function isObject(e){return e&&"object"===_typeof(e)}function escapeKeyPathComponent(e){return e.replace(/''/g,"''''").replace(/^$/,"''").replace(/~/g,"~0").replace(/\./g,"~1")}function unescapeKeyPathComponent(e){return e.replace(/~1/g,".").replace(/~0/g,"~").replace(/^''$/,"").replace(/''''/g,"''")}function getByKeyPath(e,t){if(""===t)return e;var r=t.indexOf(".");if(r>-1){var n=e[unescapeKeyPathComponent(t.slice(0,r))];return void 0===n?void 0:getByKeyPath(n,t.slice(r+1))}return e[unescapeKeyPathComponent(t)]}function setAtKeyPath(e,t,r){if(""===t)return r;var n=t.indexOf(".");return n>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,n))],t.slice(n+1),r):(e[unescapeKeyPathComponent(t)]=r,e)}function getJSONType(e){return null===e?"null":Array.isArray(e)?"array":_typeof(e)}function _await(e,t,r){return r?t?t(e):e:(e&&e.then||(e=Promise.resolve(e)),t?e.then(t):e)}var a=Object.keys,i$1=Array.isArray,c={}.hasOwnProperty,s=["type","replaced","iterateIn","iterateUnsetNumeric"];function _async(e){return function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];try{return Promise.resolve(e.apply(this,t))}catch(e){return Promise.reject(e)}}}function nestedPathsFirst(e,t){if(""===e.keypath)return -1;var r=e.keypath.match(/\./g)||0,n=t.keypath.match(/\./g)||0;return r&&(r=r.length),n&&(n=n.length),r>n?-1:r<n?1:e.keypath<t.keypath?-1:e.keypath>t.keypath}var u=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={};}return _createClass(Typeson,[{key:"stringify",value:function stringify(e,t,r,n){n=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),n),{},{stringification:!0});var o=this.encapsulate(e,null,n);return i$1(o)?JSON.stringify(o[0],t,r):o.then((function(e){return JSON.stringify(e,t,r)}))}},{key:"stringifySync",value:function stringifySync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!1}))}},{key:"parse",value:function parse(e,t,r){return r=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),r),{},{parse:!0}),this.revive(JSON.parse(e,t),r)}},{key:"parseSync",value:function parseSync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.returnTypeNames=!0,this.encapsulate(e,t,r)}},{key:"rootTypeName",value:function rootTypeName(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.iterateNone=!0,this.encapsulate(e,t,r)}},{key:"encapsulate",value:function encapsulate(t,r,n){var o=_async((function(t,r){return _await(Promise.all(r.map((function(e){return e[1].p}))),(function(n){return _await(Promise.all(n.map(_async((function(n){var a=!1,i=[],c=_slicedToArray(r.splice(0,1),1),s=_slicedToArray(c[0],7),u=s[0],p=s[2],l=s[3],y=s[4],f=s[5],h=s[6],v=_encapsulate(u,n,p,l,i,!0,h),b=hasConstructorOf(v,e);return function _invoke(e,t){var r=e();return r&&r.then?r.then(t):t(r)}((function(){if(u&&b)return _await(v.p,(function(e){y[f]=e;var r=o(t,i);return a=!0,r}))}),(function(e){return a?e:(u?y[f]=v:t=b?v.p:v,o(t,i))}))})))),(function(){return t}))}))})),u=(n=_objectSpread2(_objectSpread2({sync:!0},this.options),n)).sync,p=this,l={},y=[],f=[],h=[],v=!("cyclic"in n)||n.cyclic,b=n.encapsulateObserver,d=_encapsulate("",t,v,r||{},h);function finish(e){var t=Object.values(l);if(n.iterateNone)return t.length?t[0]:getJSONType(e);if(t.length){if(n.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!c.call(e,"$types")?e.$types=l:e={$:e,$types:{$:l}};}else isObject(e)&&c.call(e,"$types")&&(e={$:e,$types:!0});return !n.returnTypeNames&&e}function _adaptBuiltinStateObjectProperties(e,t,r){Object.assign(e,t);var n=s.map((function(t){var r=e[t];return delete e[t],r}));r(),s.forEach((function(t,r){e[t]=n[r];}));}function _encapsulate(t,r,o,s,u,h,v){var d,_={},O=_typeof(r),j=b?function(n){var a=v||s.type||getJSONType(r);b(Object.assign(n||_,{keypath:t,value:r,cyclic:o,stateObj:s,promisesData:u,resolvingTypesonPromise:h,awaitingTypesonPromise:hasConstructorOf(r,e)},{type:a}));}:null;if(["string","boolean","number","undefined"].includes(O))return void 0===r||Number.isNaN(r)||r===Number.NEGATIVE_INFINITY||r===Number.POSITIVE_INFINITY||0===r?(d=s.replaced?r:replace(t,r,s,u,!1,h,j))!==r&&(_={replaced:d}):d=r,j&&j(),d;if(null===r)return j&&j(),r;if(o&&!s.iterateIn&&!s.iterateUnsetNumeric&&r&&"object"===_typeof(r)){var m=y.indexOf(r);if(!(m<0))return l[t]="#",j&&j({cyclicKeypath:f[m]}),"#"+f[m];!0===o&&(y.push(r),f.push(t));}var g,S=isPlainObject(r),P=i$1(r),T=(S||P)&&(!p.plainObjectReplacers.length||s.replaced)||s.iterateIn?r:replace(t,r,s,u,S||P,null,j);if(T!==r?(d=T,_={replaced:T}):""===t&&hasConstructorOf(r,e)?(u.push([t,r,o,s,void 0,void 0,s.type]),d=r):P&&"object"!==s.iterateIn||"array"===s.iterateIn?(g=new Array(r.length),_={clone:g}):(["function","symbol"].includes(_typeof(r))||"toJSON"in r||hasConstructorOf(r,e)||hasConstructorOf(r,Promise)||hasConstructorOf(r,ArrayBuffer))&&!S&&"object"!==s.iterateIn?d=r:(g={},s.addLength&&(g.length=r.length),_={clone:g}),j&&j(),n.iterateNone)return g||d;if(!g)return d;if(s.iterateIn){var w=function _loop(n){var a={ownKeys:c.call(r,n)};_adaptBuiltinStateObjectProperties(s,a,(function(){var a=t+(t?".":"")+escapeKeyPathComponent(n),i=_encapsulate(a,r[n],Boolean(o),s,u,h);hasConstructorOf(i,e)?u.push([a,i,Boolean(o),s,g,n,s.type]):void 0!==i&&(g[n]=i);}));};for(var A in r)w(A);j&&j({endIterateIn:!0,end:!0});}else a(r).forEach((function(n){var a=t+(t?".":"")+escapeKeyPathComponent(n);_adaptBuiltinStateObjectProperties(s,{ownKeys:!0},(function(){var t=_encapsulate(a,r[n],Boolean(o),s,u,h);hasConstructorOf(t,e)?u.push([a,t,Boolean(o),s,g,n,s.type]):void 0!==t&&(g[n]=t);}));})),j&&j({endIterateOwn:!0,end:!0});if(s.iterateUnsetNumeric){for(var C=r.length,k=function _loop2(n){if(!(n in r)){var a=t+(t?".":"")+n;_adaptBuiltinStateObjectProperties(s,{ownKeys:!1},(function(){var t=_encapsulate(a,void 0,Boolean(o),s,u,h);hasConstructorOf(t,e)?u.push([a,t,Boolean(o),s,g,n,s.type]):void 0!==t&&(g[n]=t);}));}},N=0;N<C;N++)k(N);j&&j({endIterateUnsetNumeric:!0,end:!0});}return g}function replace(e,t,r,n,o,a,i){for(var c=o?p.plainObjectReplacers:p.nonplainObjectReplacers,s=c.length;s--;){var y=c[s];if(y.test(t,r)){var f=y.type;if(p.revivers[f]){var h=l[e];l[e]=h?[f].concat(h):f;}return Object.assign(r,{type:f,replaced:!0}),!u&&y.replaceAsync||y.replace?(i&&i({replacing:!0}),_encapsulate(e,y[u||!y.replaceAsync?"replace":"replaceAsync"](t,r),v&&"readonly",r,n,a,f)):(i&&i({typeDetected:!0}),_encapsulate(e,t,v&&"readonly",r,n,a,f))}}return t}return h.length?u&&n.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():Promise.resolve(o(d,h)).then(finish):!u&&n.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():n.stringification&&u?[finish(d)]:u?finish(d):Promise.resolve(finish(d))}},{key:"encapsulateSync",value:function encapsulateSync(e,t,r){return this.encapsulate(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!0}))}},{key:"encapsulateAsync",value:function encapsulateAsync(e,t,r){return this.encapsulate(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!1}))}},{key:"revive",value:function revive(t,r){var n=t&&t.$types;if(!n)return t;if(!0===n)return t.$;var o=(r=_objectSpread2(_objectSpread2({sync:!0},this.options),r)).sync,c=[],s={},u=!0;n.$&&isPlainObject(n.$)&&(t=t.$,n=n.$,u=!1);var l=this;function executeReviver(e,t){var r=_slicedToArray(l.revivers[e]||[],1)[0];if(!r)throw new Error("Unregistered type: "+e);return o&&!("revive"in r)?t:r[o&&r.revive?"revive":!o&&r.reviveAsync?"reviveAsync":"revive"](t,s)}var y=[];function checkUndefined(e){return hasConstructorOf(e,p)?void 0:e}var f,h=function revivePlainObjects(){var r=[];if(Object.entries(n).forEach((function(e){var t=_slicedToArray(e,2),o=t[0],a=t[1];"#"!==a&&[].concat(a).forEach((function(e){_slicedToArray(l.revivers[e]||[null,{}],2)[1].plain&&(r.push({keypath:o,type:e}),delete n[o]);}));})),r.length)return r.sort(nestedPathsFirst).reduce((function reducer(r,n){var o=n.keypath,a=n.type;if(isThenable(r))return r.then((function(e){return reducer(e,{keypath:o,type:a})}));var i=getByKeyPath(t,o);if(hasConstructorOf(i=executeReviver(a,i),e))return i.then((function(e){var r=setAtKeyPath(t,o,e);r===e&&(t=r);}));var c=setAtKeyPath(t,o,i);c===i&&(t=c);}),void 0)}();return hasConstructorOf(h,e)?f=h.then((function(){return t})):(f=function _revive(t,r,o,s,l){if(!u||"$types"!==t){var f=n[t],h=i$1(r);if(h||isPlainObject(r)){var v=h?new Array(r.length):{};for(a(r).forEach((function(n){var a=_revive(t+(t?".":"")+escapeKeyPathComponent(n),r[n],o||v,v,n),i=function set(e){return hasConstructorOf(e,p)?v[n]=void 0:void 0!==e&&(v[n]=e),e};hasConstructorOf(a,e)?y.push(a.then((function(e){return i(e)}))):i(a);})),r=v;c.length;){var b=_slicedToArray(c[0],4),d=b[0],_=b[1],O=b[2],j=b[3],m=getByKeyPath(d,_);if(void 0===m)break;O[j]=m,c.splice(0,1);}}if(!f)return r;if("#"===f){var g=getByKeyPath(o,r.slice(1));return void 0===g&&c.push([o,r.slice(1),s,l]),g}return [].concat(f).reduce((function reducer(t,r){return hasConstructorOf(t,e)?t.then((function(e){return reducer(e,r)})):executeReviver(r,t)}),r)}}("",t,null),y.length&&(f=e.resolve(f).then((function(t){return e.all([t].concat(y))})).then((function(e){return _slicedToArray(e,1)[0]})))),isThenable(f)?o&&r.throwOnBadSyncType?function(){throw new TypeError("Sync method requested but async result obtained")}():hasConstructorOf(f,e)?f.p.then(checkUndefined):f:!o&&r.throwOnBadSyncType?function(){throw new TypeError("Async method requested but sync result obtained")}():o?checkUndefined(f):Promise.resolve(checkUndefined(f))}},{key:"reviveSync",value:function reviveSync(e,t){return this.revive(e,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},t),{},{sync:!0}))}},{key:"reviveAsync",value:function reviveAsync(e,t){return this.revive(e,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},t),{},{sync:!1}))}},{key:"register",value:function register(e,t){var r=this;t=t||{};var n=function R(e){i$1(e)?e.forEach((function(e){return R(e)})):e&&a(e).forEach((function(n){if("#"===n)throw new TypeError("# cannot be used as a type name as it is reserved for cyclic objects");if(l.includes(n))throw new TypeError("Plain JSON object types are reserved as type names");var o=e[n],a=o&&o.testPlainObjects?r.plainObjectReplacers:r.nonplainObjectReplacers,c=a.filter((function(e){return e.type===n}));if(c.length&&(a.splice(a.indexOf(c[0]),1),delete r.revivers[n],delete r.types[n]),"function"==typeof o){var s=o;o={test:function test(e){return e&&e.constructor===s},replace:function replace(e){return _objectSpread2({},e)},revive:function revive(e){return Object.assign(Object.create(s.prototype),e)}};}else if(i$1(o)){var u=_slicedToArray(o,3);o={test:u[0],replace:u[1],revive:u[2]};}if(o&&o.test){var p={type:n,test:o.test.bind(o)};o.replace&&(p.replace=o.replace.bind(o)),o.replaceAsync&&(p.replaceAsync=o.replaceAsync.bind(o));var y="number"==typeof t.fallback?t.fallback:t.fallback?0:Number.POSITIVE_INFINITY;if(o.testPlainObjects?r.plainObjectReplacers.splice(y,0,p):r.nonplainObjectReplacers.splice(y,0,p),o.revive||o.reviveAsync){var f={};o.revive&&(f.revive=o.revive.bind(o)),o.reviveAsync&&(f.reviveAsync=o.reviveAsync.bind(o)),r.revivers[n]=[f,{plain:o.testPlainObjects}];}r.types[n]=o;}}));};return [].concat(e).forEach((function(e){return n(e)})),this}}]),Typeson}(),p=_createClass((function Undefined(){_classCallCheck(this,Undefined);}));p.__typeson__type__="TypesonUndefined";var l=["null","boolean","number","string","array","object"];
2
2
 
3
3
  /*
4
4
  * base64-arraybuffer
@@ -715,6 +715,21 @@ const negativeInfinity = {
715
715
  }
716
716
  };
717
717
 
718
+ const negativeZero = {
719
+ negativeZero: {
720
+ test (x) {
721
+ return Object.is(x, -0);
722
+ },
723
+ replace (n) {
724
+ // Just adding 0 here for minimized space; will still revive as -0
725
+ return 0;
726
+ },
727
+ revive (s) {
728
+ return -0;
729
+ }
730
+ }
731
+ };
732
+
718
733
  const nonbuiltinIgnore = {
719
734
  nonbuiltinIgnore: {
720
735
  test (x) {
@@ -1036,7 +1051,8 @@ const arrayNonindexKeys = [
1036
1051
  const specialNumbers = [
1037
1052
  nan,
1038
1053
  infinity,
1039
- negativeInfinity
1054
+ negativeInfinity,
1055
+ negativeZero
1040
1056
  ];
1041
1057
 
1042
1058
  /* This preset includes types that are built-in into the JavaScript
@@ -1258,5 +1274,5 @@ const universal = [
1258
1274
  // built-in into ecmasript standard.
1259
1275
  ];
1260
1276
 
1261
- export { l as JSON_TYPES, u as Typeson, e as TypesonPromise, p as Undefined, arrayNonindexKeys, arraybuffer, bigint, bigintObject, blob, expObj$1 as builtin, cloneable, cryptokey, dataview, date, error, errors, escapeKeyPathComponent, file, filelist, getByKeyPath, getJSONType, hasConstructorOf, imagebitmap, imagedata, infinity, intlTypes, isObject, isPlainObject, isThenable, isUserObject, map, nan, negativeInfinity, nonbuiltinIgnore, postmessage, primitiveObjects, regexp, resurrectable, set, setAtKeyPath, socketio, sparseUndefined, specialNumbers, expObj as structuredCloning, structuredCloningThrowing, toStringTag, typedArrays, typedArraysSocketIO as typedArraysSocketio, undef$1 as undef, undef as undefPreset, unescapeKeyPathComponent, universal, userObject };
1277
+ export { l as JSON_TYPES, u as Typeson, e as TypesonPromise, p as Undefined, arrayNonindexKeys, arraybuffer, bigint, bigintObject, blob, expObj$1 as builtin, cloneable, cryptokey, dataview, date, error, errors, escapeKeyPathComponent, file, filelist, getByKeyPath, getJSONType, hasConstructorOf, imagebitmap, imagedata, infinity, intlTypes, isObject, isPlainObject, isThenable, isUserObject, map, nan, negativeInfinity, negativeZero, nonbuiltinIgnore, postmessage, primitiveObjects, regexp, resurrectable, set, setAtKeyPath, socketio, sparseUndefined, specialNumbers, expObj as structuredCloning, structuredCloningThrowing, toStringTag, typedArrays, typedArraysSocketIO as typedArraysSocketio, undef$1 as undef, undef as undefPreset, unescapeKeyPathComponent, universal, userObject };
1262
1278
  //# sourceMappingURL=index.js.map