@cratis/fundamentals 7.22.3 → 7.22.5
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.
- package/DateOnly.ts +28 -1
- package/JsonSerializer.ts +36 -14
- package/TimeOnly.ts +51 -11
- package/TimeSpan.ts +26 -1
- package/dist/DateOnly.d.ts +1 -0
- package/dist/DateOnly.d.ts.map +1 -1
- package/dist/DateOnly.js +21 -1
- package/dist/DateOnly.js.map +1 -1
- package/dist/JsonSerializer.d.ts.map +1 -1
- package/dist/JsonSerializer.js +29 -9
- package/dist/JsonSerializer.js.map +1 -1
- package/dist/TimeOnly.d.ts +2 -1
- package/dist/TimeOnly.d.ts.map +1 -1
- package/dist/TimeOnly.js +30 -4
- package/dist/TimeOnly.js.map +1 -1
- package/dist/TimeSpan.d.ts.map +1 -1
- package/dist/TimeSpan.js +17 -0
- package/dist/TimeSpan.js.map +1 -1
- package/dist/cjs/DateOnly.d.ts +1 -0
- package/dist/cjs/DateOnly.d.ts.map +1 -1
- package/dist/cjs/DateOnly.js +21 -1
- package/dist/cjs/DateOnly.js.map +1 -1
- package/dist/cjs/JsonSerializer.d.ts.map +1 -1
- package/dist/cjs/JsonSerializer.js +28 -8
- package/dist/cjs/JsonSerializer.js.map +1 -1
- package/dist/cjs/TimeOnly.d.ts +2 -1
- package/dist/cjs/TimeOnly.d.ts.map +1 -1
- package/dist/cjs/TimeOnly.js +30 -4
- package/dist/cjs/TimeOnly.js.map +1 -1
- package/dist/cjs/TimeSpan.d.ts.map +1 -1
- package/dist/cjs/TimeSpan.js +17 -0
- package/dist/cjs/TimeSpan.js.map +1 -1
- package/dist/cjs/index.js +3 -0
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/typeKey.d.ts +3 -0
- package/dist/cjs/typeKey.d.ts.map +1 -1
- package/dist/cjs/typeKey.js +6 -0
- package/dist/cjs/typeKey.js.map +1 -1
- package/dist/esm/DateOnly.d.ts +1 -0
- package/dist/esm/DateOnly.d.ts.map +1 -1
- package/dist/esm/DateOnly.js +21 -1
- package/dist/esm/DateOnly.js.map +1 -1
- package/dist/esm/JsonSerializer.d.ts.map +1 -1
- package/dist/esm/JsonSerializer.js +29 -9
- package/dist/esm/JsonSerializer.js.map +1 -1
- package/dist/esm/TimeOnly.d.ts +2 -1
- package/dist/esm/TimeOnly.d.ts.map +1 -1
- package/dist/esm/TimeOnly.js +30 -4
- package/dist/esm/TimeOnly.js.map +1 -1
- package/dist/esm/TimeSpan.d.ts.map +1 -1
- package/dist/esm/TimeSpan.js +17 -0
- package/dist/esm/TimeSpan.js.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/typeKey.d.ts +3 -0
- package/dist/esm/typeKey.d.ts.map +1 -1
- package/dist/esm/typeKey.js +4 -1
- package/dist/esm/typeKey.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/typeKey.d.ts +3 -0
- package/dist/typeKey.d.ts.map +1 -1
- package/dist/typeKey.js +3 -0
- package/dist/typeKey.js.map +1 -1
- package/for_DateOnly/when_parsing_an_out_of_range_calendar_date.ts +13 -0
- package/for_DateOnly/when_parsing_february_in_leap_and_common_years.ts +11 -0
- package/for_JsonSerializer/when_deserializing_a_value_map_with_c_sharp_written_negative_time_span_keys.ts +19 -0
- package/for_JsonSerializer/when_deserializing_a_value_map_with_c_sharp_written_time_only_keys.ts +19 -0
- package/for_JsonSerializer/when_deserializing_a_value_map_with_c_sharp_written_whole_second_time_span_keys.ts +19 -0
- package/for_JsonSerializer/when_deserializing_a_value_map_with_legacy_quoted_date_only_keys.ts +19 -0
- package/for_JsonSerializer/when_deserializing_a_value_map_with_legacy_quoted_time_only_keys.ts +19 -0
- package/for_JsonSerializer/when_deserializing_a_value_map_with_legacy_quoted_time_span_keys.ts +19 -0
- package/for_JsonSerializer/when_deserializing_a_value_map_with_malformed_date_only_keys.ts +20 -0
- package/for_JsonSerializer/when_deserializing_a_value_map_with_malformed_time_only_keys.ts +20 -0
- package/for_JsonSerializer/when_deserializing_a_value_map_with_malformed_time_span_keys.ts +20 -0
- package/for_JsonSerializer/when_deserializing_a_value_map_with_out_of_range_temporal_keys.ts +19 -0
- package/for_JsonSerializer/when_deserializing_out_of_range_temporal_values.ts +20 -0
- package/for_JsonSerializer/when_round_tripping_a_value_map_with_date_only_keys.ts +26 -0
- package/for_JsonSerializer/when_round_tripping_a_value_map_with_time_only_keys.ts +26 -0
- package/for_JsonSerializer/when_round_tripping_a_value_map_with_time_only_keys_differing_below_a_millisecond.ts +20 -0
- package/for_JsonSerializer/when_round_tripping_a_value_map_with_time_span_keys.ts +26 -0
- package/for_TimeOnly/when_creating_with_out_of_range_sub_millisecond_ticks.ts +11 -0
- package/for_TimeOnly/when_parsing_an_out_of_range_time_of_day.ts +11 -0
- package/for_TimeOnly/when_parsing_the_last_moment_of_the_day.ts +10 -0
- package/for_TimeOnly/when_parsing_the_shapes_the_server_sends.ts +6 -6
- package/for_TimeOnly/when_parsing_times_that_differ_below_a_millisecond.ts +14 -0
- package/for_TimeOnly/when_rendering_a_fraction.ts +11 -0
- package/for_TimeSpan/when_parsing_out_of_range_time.ts +11 -0
- package/for_TimeSpan/when_parsing_the_largest_in_range_time_span.ts +10 -0
- package/for_TimeSpan/when_parsing_time_beyond_what_a_time_span_can_hold.ts +11 -0
- package/package.json +1 -1
- package/typeKey.ts +9 -0
package/dist/cjs/typeKey.js
CHANGED
|
@@ -6,10 +6,16 @@ const typeKeyOf = (type) => type ? type[typeKey] : undefined;
|
|
|
6
6
|
const conceptAsTypeKey = 'ConceptAs';
|
|
7
7
|
const valueMapTypeKey = 'ValueMap';
|
|
8
8
|
const guidTypeKey = 'Guid';
|
|
9
|
+
const dateOnlyTypeKey = 'DateOnly';
|
|
10
|
+
const timeOnlyTypeKey = 'TimeOnly';
|
|
11
|
+
const timeSpanTypeKey = 'TimeSpan';
|
|
9
12
|
|
|
10
13
|
exports.conceptAsTypeKey = conceptAsTypeKey;
|
|
14
|
+
exports.dateOnlyTypeKey = dateOnlyTypeKey;
|
|
11
15
|
exports.declaredTypeKey = declaredTypeKey;
|
|
12
16
|
exports.guidTypeKey = guidTypeKey;
|
|
17
|
+
exports.timeOnlyTypeKey = timeOnlyTypeKey;
|
|
18
|
+
exports.timeSpanTypeKey = timeSpanTypeKey;
|
|
13
19
|
exports.typeKey = typeKey;
|
|
14
20
|
exports.typeKeyOf = typeKeyOf;
|
|
15
21
|
exports.valueMapTypeKey = valueMapTypeKey;
|
package/dist/cjs/typeKey.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typeKey.js","sources":["../../typeKey.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Constructor } from './Constructor';\n\n/**\n * Identifies a type this package converts, by name rather than by the class object itself.\n *\n * `JsonSerializer` recognized a type by comparing constructors, which holds until a second copy of this\n * package is loaded into the same realm - a nested install, or one install reached as both ESM and\n * CommonJS. Each copy then had its own `Guid`, `ConceptAs` and `ValueMap` class objects and neither\n * recognized the other's, so a `Guid` crossing that boundary was written as an object rather than a\n * string, and a concept as `{\"value\": ...}` rather than its underlying value. Both silently.\n *\n * A name survives the boundary where a class object does not: the key is a registered symbol, so every\n * copy resolves the same one, and the values are plain strings.\n *\n * The key is deliberately a symbol rather than a plain static: a string static would appear in\n * `Object.keys(Guid)` and could be shadowed by an unrelated member of the same name.\n */\nexport const typeKey: unique symbol = Symbol.for('@cratis/fundamentals.typeKey');\n\n/** A type carrying the key. Only this package's own convertible types declare one. */\ntype KeyedType = Constructor & { readonly [typeKey]?: string };\n\n/**\n * Gets the key a type declares itself, ignoring any inherited from a base type.\n *\n * Converter lookup uses this, because a key is inherited: a consumer's `class CustomerId extends\n * ConceptAs<string>` reports `ConceptAs`, and registering a converter under that would take the place\n * of concept handling for every concept in the application.\n * @param {Constructor} type The type to read the key from.\n * @returns {string | undefined} The declared key, or undefined when the type declares none.\n */\nexport const declaredTypeKey = (type: Constructor | undefined): string | undefined =>\n type && Object.prototype.hasOwnProperty.call(type, typeKey) ? (type as KeyedType)[typeKey] : undefined;\n\n/**\n * Gets the key a type carries, whether it declares the key or inherits it from a base type.\n *\n * This is what makes a concept recognizable across copies: the key is a static, and a static is\n * inherited through the constructor's prototype chain, so every type deriving from `ConceptAs` reports\n * `ConceptAs` without anything having to compare class objects.\n * @param {Constructor} type The type to read the key from.\n * @returns {string | undefined} The key carried, or undefined when the type carries none.\n */\nexport const typeKeyOf = (type: Constructor | undefined): string | undefined =>\n type ? (type as KeyedType)[typeKey] : undefined;\n\n/** The key every type deriving from `ConceptAs` carries. */\nexport const conceptAsTypeKey = 'ConceptAs';\n\n/** The key `ValueMap` declares. */\nexport const valueMapTypeKey = 'ValueMap';\n\n/** The key `Guid` declares. */\nexport const guidTypeKey = 'Guid';\n"],"names":[],"mappings":";;AAoBO,MAAM,OAAO,GAAkB,MAAM,CAAC,GAAG,CAAC,8BAA8B;AAcxE,MAAM,eAAe,GAAG,CAAC,IAA6B,KACzD,IAAI,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,GAAI,IAAkB,CAAC,OAAO,CAAC,GAAG;MAWpF,SAAS,GAAG,CAAC,IAA6B,KACnD,IAAI,GAAI,IAAkB,CAAC,OAAO,CAAC,GAAG;AAGnC,MAAM,gBAAgB,GAAG;AAGzB,MAAM,eAAe,GAAG;AAGxB,MAAM,WAAW,GAAG
|
|
1
|
+
{"version":3,"file":"typeKey.js","sources":["../../typeKey.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Constructor } from './Constructor';\n\n/**\n * Identifies a type this package converts, by name rather than by the class object itself.\n *\n * `JsonSerializer` recognized a type by comparing constructors, which holds until a second copy of this\n * package is loaded into the same realm - a nested install, or one install reached as both ESM and\n * CommonJS. Each copy then had its own `Guid`, `ConceptAs` and `ValueMap` class objects and neither\n * recognized the other's, so a `Guid` crossing that boundary was written as an object rather than a\n * string, and a concept as `{\"value\": ...}` rather than its underlying value. Both silently.\n *\n * A name survives the boundary where a class object does not: the key is a registered symbol, so every\n * copy resolves the same one, and the values are plain strings.\n *\n * The key is deliberately a symbol rather than a plain static: a string static would appear in\n * `Object.keys(Guid)` and could be shadowed by an unrelated member of the same name.\n */\nexport const typeKey: unique symbol = Symbol.for('@cratis/fundamentals.typeKey');\n\n/** A type carrying the key. Only this package's own convertible types declare one. */\ntype KeyedType = Constructor & { readonly [typeKey]?: string };\n\n/**\n * Gets the key a type declares itself, ignoring any inherited from a base type.\n *\n * Converter lookup uses this, because a key is inherited: a consumer's `class CustomerId extends\n * ConceptAs<string>` reports `ConceptAs`, and registering a converter under that would take the place\n * of concept handling for every concept in the application.\n * @param {Constructor} type The type to read the key from.\n * @returns {string | undefined} The declared key, or undefined when the type declares none.\n */\nexport const declaredTypeKey = (type: Constructor | undefined): string | undefined =>\n type && Object.prototype.hasOwnProperty.call(type, typeKey) ? (type as KeyedType)[typeKey] : undefined;\n\n/**\n * Gets the key a type carries, whether it declares the key or inherits it from a base type.\n *\n * This is what makes a concept recognizable across copies: the key is a static, and a static is\n * inherited through the constructor's prototype chain, so every type deriving from `ConceptAs` reports\n * `ConceptAs` without anything having to compare class objects.\n * @param {Constructor} type The type to read the key from.\n * @returns {string | undefined} The key carried, or undefined when the type carries none.\n */\nexport const typeKeyOf = (type: Constructor | undefined): string | undefined =>\n type ? (type as KeyedType)[typeKey] : undefined;\n\n/** The key every type deriving from `ConceptAs` carries. */\nexport const conceptAsTypeKey = 'ConceptAs';\n\n/** The key `ValueMap` declares. */\nexport const valueMapTypeKey = 'ValueMap';\n\n/** The key `Guid` declares. */\nexport const guidTypeKey = 'Guid';\n\n/** The key `DateOnly` declares. */\nexport const dateOnlyTypeKey = 'DateOnly';\n\n/** The key `TimeOnly` declares. */\nexport const timeOnlyTypeKey = 'TimeOnly';\n\n/** The key `TimeSpan` declares. */\nexport const timeSpanTypeKey = 'TimeSpan';\n"],"names":[],"mappings":";;AAoBO,MAAM,OAAO,GAAkB,MAAM,CAAC,GAAG,CAAC,8BAA8B;AAcxE,MAAM,eAAe,GAAG,CAAC,IAA6B,KACzD,IAAI,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,GAAI,IAAkB,CAAC,OAAO,CAAC,GAAG;MAWpF,SAAS,GAAG,CAAC,IAA6B,KACnD,IAAI,GAAI,IAAkB,CAAC,OAAO,CAAC,GAAG;AAGnC,MAAM,gBAAgB,GAAG;AAGzB,MAAM,eAAe,GAAG;AAGxB,MAAM,WAAW,GAAG;AAGpB,MAAM,eAAe,GAAG;AAGxB,MAAM,eAAe,GAAG;AAGxB,MAAM,eAAe,GAAG;;;;;;;;;;"}
|
package/dist/esm/DateOnly.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ export declare class DateOnly {
|
|
|
6
6
|
day: number;
|
|
7
7
|
static from(year: number, month: number, day: number): DateOnly;
|
|
8
8
|
static parse(value: string): DateOnly;
|
|
9
|
+
private static daysInMonth;
|
|
9
10
|
static fromDate(date: Date): DateOnly;
|
|
10
11
|
toDate(): Date;
|
|
11
12
|
toString(): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DateOnly.d.ts","sourceRoot":"","sources":["../../DateOnly.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAgBpC,qBAAa,QAAQ;IACjB,MAAM,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,cAAc;IAMvC,IAAI,EAAG,MAAM,CAAC;IAMd,KAAK,EAAG,MAAM,CAAC;IAMf,GAAG,EAAG,MAAM,CAAC;IASb,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,QAAQ;
|
|
1
|
+
{"version":3,"file":"DateOnly.d.ts","sourceRoot":"","sources":["../../DateOnly.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAgBpC,qBAAa,QAAQ;IACjB,MAAM,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,cAAc;IAMvC,IAAI,EAAG,MAAM,CAAC;IAMd,KAAK,EAAG,MAAM,CAAC;IAMf,GAAG,EAAG,MAAM,CAAC;IASb,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,QAAQ;IAc/D,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,QAAQ;IA0BrC,OAAO,CAAC,MAAM,CAAC,WAAW;IAiB1B,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,QAAQ;IAWrC,MAAM,IAAI,IAAI;IAQd,QAAQ,IAAI,MAAM;IAalB,MAAM,IAAI,MAAM;IAShB,MAAM,CAAC,KAAK,EAAE,QAAQ,GAAG,SAAS,GAAG,IAAI,GAAG,OAAO;CAGtD"}
|
package/dist/esm/DateOnly.js
CHANGED
|
@@ -20,7 +20,27 @@ class DateOnly {
|
|
|
20
20
|
if (match === null) {
|
|
21
21
|
throw new Error(`Invalid DateOnly format: ${value}`);
|
|
22
22
|
}
|
|
23
|
-
|
|
23
|
+
const year = parseInt(match[1], 10);
|
|
24
|
+
const month = parseInt(match[2], 10);
|
|
25
|
+
const day = parseInt(match[3], 10);
|
|
26
|
+
if (year < 1) {
|
|
27
|
+
throw new Error(`Invalid DateOnly: year ${year} is out of range 1-9999 in '${value}'`);
|
|
28
|
+
}
|
|
29
|
+
if (month < 1 || month > 12) {
|
|
30
|
+
throw new Error(`Invalid DateOnly: month ${month} is out of range 1-12 in '${value}'`);
|
|
31
|
+
}
|
|
32
|
+
const daysInMonth = DateOnly.daysInMonth(year, month);
|
|
33
|
+
if (day < 1 || day > daysInMonth) {
|
|
34
|
+
throw new Error(`Invalid DateOnly: day ${day} is out of range 1-${daysInMonth} for ${match[1]}-${match[2]} in '${value}'`);
|
|
35
|
+
}
|
|
36
|
+
return DateOnly.from(year, month, day);
|
|
37
|
+
}
|
|
38
|
+
static daysInMonth(year, month) {
|
|
39
|
+
if (month === 2) {
|
|
40
|
+
const isLeapYear = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
|
41
|
+
return isLeapYear ? 29 : 28;
|
|
42
|
+
}
|
|
43
|
+
return [4, 6, 9, 11].includes(month) ? 30 : 31;
|
|
24
44
|
}
|
|
25
45
|
static fromDate(date) {
|
|
26
46
|
return DateOnly.from(date.getFullYear(), date.getMonth() + 1, date.getDate());
|
package/dist/esm/DateOnly.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DateOnly.js","sources":["../../DateOnly.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { field } from './fieldDecorator';\nimport { typeKey } from './typeKey';\n\nconst dateOnlyRegex = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/**\n * Represents a date with no time and no time zone - a day on a calendar.\n * @remarks\n * Deliberately not a JavaScript `Date`. A `Date` is an instant, and a calendar date is not one: turning\n * `2026-05-12` into a `Date` produces UTC midnight, which every browser-local getter west of UTC reads back as\n * the 11th. That is a wrong answer that looks right, and it is only wrong for users in some time zones - which is\n * how it survives development in others.\n *\n * Holding the three parts the server sent means there is no instant to convert and nothing to shift. Where a\n * `Date` is genuinely wanted - to feed a date picker, or to do arithmetic - {@link toDate} constructs one in the\n * local time zone, and the choice is then visible at the call site making it.\n */\nexport class DateOnly {\n static readonly [typeKey] = 'DateOnly';\n\n /**\n * The year.\n */\n @field(Number)\n year!: number;\n\n /**\n * The month, 1 through 12.\n */\n @field(Number)\n month!: number;\n\n /**\n * The day of the month, 1 through 31.\n */\n @field(Number)\n day!: number;\n\n /**\n * Creates a {@link DateOnly} from its parts.\n * @param year The year.\n * @param month The month, 1 through 12.\n * @param day The day of the month.\n * @returns The {@link DateOnly}.\n */\n static from(year: number, month: number, day: number): DateOnly {\n const dateOnly = new DateOnly();\n dateOnly.year = year;\n dateOnly.month = month;\n dateOnly.day = day;\n return dateOnly;\n }\n\n /**\n * Parses the ISO-8601 calendar date the server sends, `yyyy-MM-dd`.\n * @param value The value to parse.\n * @returns The {@link DateOnly}.\n */\n static parse(value: string): DateOnly {\n const match = dateOnlyRegex.exec(value);\n if (match === null) {\n throw new Error(`Invalid DateOnly format: ${value}`);\n }\n\n
|
|
1
|
+
{"version":3,"file":"DateOnly.js","sources":["../../DateOnly.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { field } from './fieldDecorator';\nimport { typeKey } from './typeKey';\n\nconst dateOnlyRegex = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/**\n * Represents a date with no time and no time zone - a day on a calendar.\n * @remarks\n * Deliberately not a JavaScript `Date`. A `Date` is an instant, and a calendar date is not one: turning\n * `2026-05-12` into a `Date` produces UTC midnight, which every browser-local getter west of UTC reads back as\n * the 11th. That is a wrong answer that looks right, and it is only wrong for users in some time zones - which is\n * how it survives development in others.\n *\n * Holding the three parts the server sent means there is no instant to convert and nothing to shift. Where a\n * `Date` is genuinely wanted - to feed a date picker, or to do arithmetic - {@link toDate} constructs one in the\n * local time zone, and the choice is then visible at the call site making it.\n */\nexport class DateOnly {\n static readonly [typeKey] = 'DateOnly';\n\n /**\n * The year.\n */\n @field(Number)\n year!: number;\n\n /**\n * The month, 1 through 12.\n */\n @field(Number)\n month!: number;\n\n /**\n * The day of the month, 1 through 31.\n */\n @field(Number)\n day!: number;\n\n /**\n * Creates a {@link DateOnly} from its parts.\n * @param year The year.\n * @param month The month, 1 through 12.\n * @param day The day of the month.\n * @returns The {@link DateOnly}.\n */\n static from(year: number, month: number, day: number): DateOnly {\n const dateOnly = new DateOnly();\n dateOnly.year = year;\n dateOnly.month = month;\n dateOnly.day = day;\n return dateOnly;\n }\n\n /**\n * Parses the ISO-8601 calendar date the server sends, `yyyy-MM-dd`.\n * @param value The value to parse.\n * @returns The {@link DateOnly}.\n * @throws {Error} If the format is invalid or a component is out of range, as C# rejects it.\n */\n static parse(value: string): DateOnly {\n const match = dateOnlyRegex.exec(value);\n if (match === null) {\n throw new Error(`Invalid DateOnly format: ${value}`);\n }\n\n const year = parseInt(match[1], 10);\n const month = parseInt(match[2], 10);\n const day = parseInt(match[3], 10);\n\n if (year < 1) {\n throw new Error(`Invalid DateOnly: year ${year} is out of range 1-9999 in '${value}'`);\n }\n\n if (month < 1 || month > 12) {\n throw new Error(`Invalid DateOnly: month ${month} is out of range 1-12 in '${value}'`);\n }\n\n const daysInMonth = DateOnly.daysInMonth(year, month);\n if (day < 1 || day > daysInMonth) {\n throw new Error(`Invalid DateOnly: day ${day} is out of range 1-${daysInMonth} for ${match[1]}-${match[2]} in '${value}'`);\n }\n\n return DateOnly.from(year, month, day);\n }\n\n private static daysInMonth(year: number, month: number): number {\n if (month === 2) {\n const isLeapYear = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n return isLeapYear ? 29 : 28;\n }\n\n return [4, 6, 9, 11].includes(month) ? 30 : 31;\n }\n\n /**\n * Creates a {@link DateOnly} for the calendar date a {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date | Date} falls on in the local time zone.\n * @param date The date to take the calendar date of.\n * @returns The {@link DateOnly}.\n * @remarks\n * Reads the local parts rather than the UTC ones, because the calendar date a moment falls on is a question\n * only a time zone can answer, and the local one is the one the person looking at the screen is in.\n */\n static fromDate(date: Date): DateOnly {\n return DateOnly.from(date.getFullYear(), date.getMonth() + 1, date.getDate());\n }\n\n /**\n * Converts to a {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date | Date} at midnight in the local time zone.\n * @returns The {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date | Date}.\n * @remarks\n * Local rather than UTC, so the date a caller reads back with `getDate()` is the one they started with. This\n * invents a time that was never sent, which is why it is a method to call rather than what the value is.\n */\n toDate(): Date {\n return new Date(this.year, this.month - 1, this.day);\n }\n\n /**\n * Gets the ISO-8601 representation, `yyyy-MM-dd` - the same form the server sent.\n * @returns The string.\n */\n toString(): string {\n const month = this.month.toString().padStart(2, '0');\n const day = this.day.toString().padStart(2, '0');\n return `${this.year.toString().padStart(4, '0')}-${month}-${day}`;\n }\n\n /**\n * Gets the ISO-8601 representation used when this is serialized as JSON.\n *\n * Without this, `JSON.stringify` falls back to enumerating `year`, `month` and `day`, so a\n * request body carries a component object where the server expects the scalar string.\n * @returns The string.\n */\n toJSON(): string {\n return this.toString();\n }\n\n /**\n * Determines whether this is the same calendar date as another.\n * @param other The other date.\n * @returns True when they are the same date.\n */\n equals(other: DateOnly | undefined | null): boolean {\n return !!other && this.year === other.year && this.month === other.month && this.day === other.day;\n }\n}\n"],"names":[],"mappings":";;;;AAMA,MAAM,aAAa,GAAG,2BAA2B;MAcpC,QAAQ,CAAA;AACjB,IAAA,QAAiB,OAAO,IAAI,UAAU;AAMtC,IAAA,IAAI;AAMJ,IAAA,KAAK;AAML,IAAA,GAAG;AASH,IAAA,OAAO,IAAI,CAAC,IAAY,EAAE,KAAa,EAAE,GAAW,EAAA;AAChD,QAAA,MAAM,QAAQ,GAAG,IAAI,QAAQ,EAAE;AAC/B,QAAA,QAAQ,CAAC,IAAI,GAAG,IAAI;AACpB,QAAA,QAAQ,CAAC,KAAK,GAAG,KAAK;AACtB,QAAA,QAAQ,CAAC,GAAG,GAAG,GAAG;AAClB,QAAA,OAAO,QAAQ;IACnB;IAQA,OAAO,KAAK,CAAC,KAAa,EAAA;QACtB,MAAM,KAAK,GAAG,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC;AACvC,QAAA,IAAI,KAAK,K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AI,CAAC,GAAG,KAAK,KAAK,CAAC,GAAG;IACtG;;AAzHA,UAAA,CAAA;IADC,KAAK,CAAC,MAAM,CAAC;;AACA,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,MAAA,EAAA,MAAA,CAAA;AAMd,UAAA,CAAA;IADC,KAAK,CAAC,MAAM,CAAC;;AACC,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,OAAA,EAAA,MAAA,CAAA;AAMf,UAAA,CAAA;IADC,KAAK,CAAC,MAAM,CAAC;;AACD,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,KAAA,EAAA,MAAA,CAAA;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonSerializer.d.ts","sourceRoot":"","sources":["../../JsonSerializer.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"JsonSerializer.d.ts","sourceRoot":"","sources":["../../JsonSerializer.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAW5C,OAAO,EACH,aAAa,EAUhB,MAAM,QAAQ,CAAC;AA6UhB,qBAAa,cAAc;IACvB,MAAM,CAAC,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAoB;IAsBjE,MAAM,CAAC,iBAAiB,CAAC,SAAS,EAAE,aAAa,GAAG,IAAI;IASxD,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,GAAG,MAAM;IAWpC,MAAM,CAAC,WAAW,CAAC,OAAO,SAAS,MAAM,EAAE,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO;IAWnG,MAAM,CAAC,gBAAgB,CAAC,OAAO,SAAS,MAAM,EAAE,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,EAAE;IAW1G,MAAM,CAAC,uBAAuB,CAAC,OAAO,SAAS,MAAM,EAAE,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,QAAQ,EAAE,GAAG,GAAG,OAAO;IAiEhH,MAAM,CAAC,4BAA4B,CAAC,OAAO,SAAS,MAAM,EAAE,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,GAAG,GAAG,OAAO,EAAE;CAS3H"}
|
|
@@ -3,7 +3,10 @@ import { registerModuleInstance } from './duplicateInstanceGuard.js';
|
|
|
3
3
|
import { Field } from './Field.js';
|
|
4
4
|
import { Fields } from './Fields.js';
|
|
5
5
|
import { Guid } from './Guid.js';
|
|
6
|
-
import {
|
|
6
|
+
import { DateOnly } from './DateOnly.js';
|
|
7
|
+
import { TimeOnly } from './TimeOnly.js';
|
|
8
|
+
import { TimeSpan } from './TimeSpan.js';
|
|
9
|
+
import { guidTypeKey, dateOnlyTypeKey, timeOnlyTypeKey, timeSpanTypeKey, declaredTypeKey, typeKeyOf, conceptAsTypeKey, valueMapTypeKey } from './typeKey.js';
|
|
7
10
|
import { ValueMap } from './ValueMap.js';
|
|
8
11
|
import { DateJsonConverter } from './json/DateJsonConverter.js';
|
|
9
12
|
import { DateOnlyJsonConverter } from './json/DateOnlyJsonConverter.js';
|
|
@@ -121,17 +124,33 @@ const serializeMapKey = (key) => {
|
|
|
121
124
|
if (key instanceof Date) {
|
|
122
125
|
return key.toISOString();
|
|
123
126
|
}
|
|
124
|
-
if (declaredTypeKey(key.constructor)
|
|
127
|
+
if (plainStringMapKeyTypes.has(declaredTypeKey(key.constructor) ?? '')) {
|
|
125
128
|
return key.toString();
|
|
126
129
|
}
|
|
127
130
|
return JsonSerializer.serialize(key);
|
|
128
131
|
};
|
|
129
|
-
const
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
132
|
+
const plainStringMapKeyTypes = new Map([
|
|
133
|
+
[guidTypeKey, {
|
|
134
|
+
name: 'Guid',
|
|
135
|
+
parse: text => {
|
|
136
|
+
if (!Guid.isGuid(text)) {
|
|
137
|
+
throw new Error('Not a Guid.');
|
|
138
|
+
}
|
|
139
|
+
return Guid.parse(text);
|
|
140
|
+
}
|
|
141
|
+
}],
|
|
142
|
+
[dateOnlyTypeKey, { name: 'DateOnly', parse: DateOnly.parse }],
|
|
143
|
+
[timeOnlyTypeKey, { name: 'TimeOnly', parse: TimeOnly.parse }],
|
|
144
|
+
[timeSpanTypeKey, { name: 'TimeSpan', parse: TimeSpan.parse }]
|
|
145
|
+
]);
|
|
146
|
+
const unquoteLegacyMapKey = (key) => key.length >= 2 && key.startsWith('"') && key.endsWith('"') ? key.slice(1, -1) : key;
|
|
147
|
+
const readPlainStringMapKey = (name, parse, key) => {
|
|
148
|
+
try {
|
|
149
|
+
return parse(unquoteLegacyMapKey(key));
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
throw new Error(`The map key '${key}' is not a valid ${name}.`);
|
|
133
153
|
}
|
|
134
|
-
return Guid.parse(text);
|
|
135
154
|
};
|
|
136
155
|
const deserializeMapKey = (keyType, key) => {
|
|
137
156
|
if (keyType === String) {
|
|
@@ -143,8 +162,9 @@ const deserializeMapKey = (keyType, key) => {
|
|
|
143
162
|
if (keyType === Boolean) {
|
|
144
163
|
return key.toLowerCase() === 'true';
|
|
145
164
|
}
|
|
146
|
-
|
|
147
|
-
|
|
165
|
+
const plainKeyType = plainStringMapKeyTypes.get(declaredTypeKey(keyType) ?? '');
|
|
166
|
+
if (plainKeyType) {
|
|
167
|
+
return readPlainStringMapKey(plainKeyType.name, plainKeyType.parse, key);
|
|
148
168
|
}
|
|
149
169
|
const converter = converterFor(keyType);
|
|
150
170
|
if (converter) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonSerializer.js","sources":["../../JsonSerializer.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Constructor } from './Constructor';\nimport { DerivedType } from './DerivedType';\nimport { registerModuleInstance } from './duplicateInstanceGuard';\nimport { Field } from './Field';\nimport { Fields } from './Fields';\nimport { Guid } from './Guid';\nimport { conceptAsTypeKey, declaredTypeKey, guidTypeKey, typeKeyOf, valueMapTypeKey } from './typeKey';\nimport { ValueMap } from './ValueMap';\nimport { \n JsonConverter, \n DateJsonConverter, \n DateOnlyJsonConverter,\n GuidJsonConverter, \n TimeOnlyJsonConverter,\n TimeSpanJsonConverter, \n PointJsonConverter,\n LineStringJsonConverter,\n PolygonJsonConverter,\n ValueMapJsonConverter\n} from './json';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\ntype typeSerializer = (value: any) => any;\n\n// A second copy of this package in the same realm builds its own registry here, and brings its own\n// class objects. Convertible values still cross between the copies, because a type is recognized by\n// the key it declares - but a converter registered on one copy reaches only that one, and a version\n// pinned at the top level never reaches a nested copy. Announce it where the state that cannot be\n// shared is built.\nregisterModuleInstance();\n\n// Initialize converters\nconst converters: JsonConverter[] = [\n new DateJsonConverter(),\n new DateOnlyJsonConverter(),\n new GuidJsonConverter(),\n new TimeOnlyJsonConverter(),\n new TimeSpanJsonConverter(),\n new PointJsonConverter(),\n new LineStringJsonConverter(),\n new PolygonJsonConverter(),\n new ValueMapJsonConverter()\n];\n\n// Converters are found by the key a type declares, and only by the constructor when it declares none.\n// Keying on the constructor alone is what made a second copy of this package silently fatal: each copy\n// brings its own Guid, ConceptAs and ValueMap class objects, so neither recognized the other's. A key\n// crosses that boundary; a class object does not. A consumer's own type has no key and is found by\n// constructor, which is exact and needs nothing to cross.\nconst keyedConverters: Map<string, JsonConverter> = new Map<string, JsonConverter>();\nconst typeConverters: Map<Constructor, JsonConverter> = new Map<Constructor, JsonConverter>();\n\nconst registerConverterFor = (converter: JsonConverter) => {\n const key = declaredTypeKey(converter.type);\n if (key !== undefined) {\n keyedConverters.set(key, converter);\n }\n\n typeConverters.set(converter.type, converter);\n};\n\nconverters.forEach(registerConverterFor);\n\n/**\n * Finds the converter registered for a type, if any.\n * @param {Constructor} type The type to convert.\n * @returns {JsonConverter | undefined} The converter, or undefined when the type has none.\n */\nconst converterFor = (type: Constructor | undefined): JsonConverter | undefined => {\n if (!type) return undefined;\n\n const key = declaredTypeKey(type);\n const keyed = key === undefined ? undefined : keyedConverters.get(key);\n return keyed ?? typeConverters.get(type);\n};\n\n/**\n * Checks whether a type is a ValueMap, including one from another copy of this package.\n * @param {Constructor} type The type to check.\n * @returns {boolean} True when the type is a ValueMap.\n */\nconst isValueMap = (type: Constructor | undefined): boolean => declaredTypeKey(type) === valueMapTypeKey;\n\n// Add primitive type converters that don't need a full JsonConverter class\nconst primitiveConverters: Map<Constructor, typeSerializer> = new Map<Constructor, typeSerializer>([\n [Number, (value: number) => value],\n [String, (value: string) => value],\n [Boolean, (value: boolean) => value]\n]);\n\nconst primitiveSerializers: Map<Constructor, typeSerializer> = new Map<Constructor, typeSerializer>([\n [Number, (value: any) => value],\n [String, (value: any) => value],\n [Boolean, (value: any) => value]\n]);\n\n/**\n * Checks if a constructor is a ConceptAs type.\n * @param {Constructor} type The constructor to check.\n * @returns {boolean} True if the type extends ConceptAs.\n * @remarks\n * Reads the key rather than walking the prototype chain looking for this copy's ConceptAs. The key is a\n * static and a static is inherited, so every type deriving from ConceptAs carries it - including one\n * deriving from another copy's ConceptAs, which a prototype walk could never recognize.\n */\nconst isConceptAs = (type: Constructor): boolean => typeKeyOf(type) === conceptAsTypeKey;\n\nconst serializeValueForType = (type: Constructor, value: any) => {\n if (!value) return value;\n\n // If it's a ConceptAs instance, unwrap it and serialize the inner value recursively\n // This follows the C# pattern: recognize as concept, unwrap, then call serializer\n if (isConceptAs(value.constructor)) {\n const innerValue = value.value;\n // Recursively serialize the inner value to handle complex types\n // Use .constructor directly which works reliably for both primitives and objects\n return serializeValueForType(innerValue.constructor, innerValue);\n }\n\n // Check if there's a registered converter\n const converter = converterFor(type);\n if (converter) {\n return converter.write(value);\n }\n \n // Check primitive converters\n if (primitiveConverters.has(type)) {\n return primitiveConverters.get(type)!(value);\n }\n \n return convertTypesOnInstance(value);\n};\n\nconst deserializeValueFromType = (type: Constructor, value: any) => {\n // If it's a ConceptAs type, instantiate it with the value\n if (isConceptAs(type)) {\n const valueType = (type as Constructor & { valueType?: Constructor }).valueType;\n return new type(valueType ? deserializeValueFromType(valueType, value) : value);\n }\n \n // Check if there's a registered converter\n const converter = converterFor(type);\n if (converter) {\n return converter.read(value);\n }\n \n // Check primitive serializers\n if (primitiveSerializers.has(type)) {\n return primitiveSerializers.get(type)!(value);\n }\n \n return JsonSerializer.deserialize(type, JSON.stringify(value));\n};\n\nconst deserializeValueFromField = (field: Field, value: any) => {\n if (isValueMap(field.type)) {\n return deserializeValueMapFromField(field, value);\n }\n\n // If it's a ConceptAs type, instantiate it with the value\n if (isConceptAs(field.type)) {\n return deserializeValueFromType(field.type, value);\n }\n\n // Check if there's a registered converter\n const converter = converterFor(field.type);\n if (converter) {\n return converter.read(value);\n }\n \n // Check primitive serializers\n if (primitiveSerializers.has(field.type)) {\n return primitiveSerializers.get(field.type)!(value);\n }\n \n let type = field.type;\n if (value[JsonSerializer.DerivedTypeIdProperty]) {\n const derivedTypeId = value[JsonSerializer.DerivedTypeIdProperty];\n const candidates = [...field.derivatives, ...DerivedType.getDerivedTypesFor(field.type)];\n type = candidates.find(_ => DerivedType.get(_) == derivedTypeId) || type;\n }\n\n return JsonSerializer.deserialize(type, JSON.stringify(value));\n};\n\nconst serializeMapKey = (key: any): string => {\n if (key === undefined || key === null) {\n return '';\n }\n\n if (typeof key === 'string') {\n return key;\n }\n\n if (typeof key === 'number' || typeof key === 'boolean' || typeof key === 'bigint') {\n return key.toString();\n }\n\n if (key instanceof Date) {\n return key.toISOString();\n }\n\n // A Guid key is its plain canonical string, which is what a C# dictionary writes. Serializing it\n // like any other object would wrap it in JSON quotes and no other reader accepts that.\n if (declaredTypeKey(key.constructor) === guidTypeKey) {\n return key.toString();\n }\n\n return JsonSerializer.serialize(key);\n};\n\nconst readGuidMapKey = (key: string): Guid => {\n // Keys written before the plain form was adopted carry the JSON quotes of an embedded string.\n const text = key.length >= 2 && key.startsWith('\"') && key.endsWith('\"') ? key.slice(1, -1) : key;\n if (!Guid.isGuid(text)) {\n throw new Error(`The map key '${key}' is not a valid Guid.`);\n }\n\n return Guid.parse(text);\n};\n\nconst deserializeMapKey = (keyType: Constructor, key: string): any => {\n if (keyType === String) {\n return key;\n }\n\n if (keyType === Number) {\n return Number(key);\n }\n\n if (keyType === Boolean) {\n return key.toLowerCase() === 'true';\n }\n\n if (declaredTypeKey(keyType) === guidTypeKey) {\n return readGuidMapKey(key);\n }\n\n // Check if there's a converter for this type\n const converter = converterFor(keyType);\n if (converter) {\n return converter.read(key);\n }\n\n return JsonSerializer.deserialize(keyType, key);\n};\n\nconst deserializeMapValue = (valueType: Constructor | undefined, value: any): any => {\n if (!valueType) {\n return value;\n }\n\n // A map value is an ordinary value of its declared type, so read it the way any other value of that\n // type is read. Resolving it here instead left out the concept and primitive cases, and the\n // primitive one lost data without a sound: a string value went through JsonSerializer.deserialize,\n // which built an empty String object because a primitive has no fields to populate.\n return deserializeValueFromType(valueType, value);\n};\n\nconst deserializeValueMapFromField = (field: Field, value: any): ValueMap<any, any> => {\n const valueMap = new ValueMap<any, any>();\n const keyType = field.genericArguments[0];\n const valueType = field.genericArguments[1];\n\n if (!value || !keyType) {\n return valueMap;\n }\n\n for (const key of Object.keys(value)) {\n const deserializedKey = deserializeMapKey(keyType, key);\n const deserializedValue = deserializeMapValue(valueType, value[key]);\n valueMap.set(deserializedKey, deserializedValue);\n }\n\n return valueMap;\n};\n\nconst convertTypesOnInstance = (instance: any) => {\n // A concept unwraps to its underlying value wherever it is reached, not only when it is reached\n // through a declared field. An array element and a map value arrive here rather than at\n // serializeValueForType, and without this they were written as the object a concept happens to be -\n // {\"value\": ...} where the receiver declared the underlying type.\n if (isConceptAs(instance.constructor)) {\n return serializeValueForType(instance.constructor as Constructor, instance);\n }\n\n // Check if there's a converter for this type\n if (converterFor(instance.constructor)) {\n return serializeValueForType(instance.constructor, instance);\n }\n \n // Check primitive converters\n if (primitiveConverters.has(instance.constructor)) {\n return primitiveConverters.get(instance.constructor)!(instance);\n }\n\n const properties = Object.getOwnPropertyNames(instance);\n const converted: any = {};\n\n // Emit the polymorphic type discriminator, preferring the registered type for the instance's\n // constructor and falling back to a discriminator preserved on the instance itself (e.g. a value\n // that was deserialized before its concrete type could be resolved). This keeps '_derivedTypeId'\n // flowing through serialization transparently — the caller never has to manage it — and is the\n // mirror of preserving it on deserialization.\n const derivedTypeId = DerivedType.get(instance.constructor) ?? instance[JsonSerializer.DerivedTypeIdProperty];\n if (derivedTypeId) {\n converted[JsonSerializer.DerivedTypeIdProperty] = derivedTypeId;\n }\n properties.forEach(property => {\n // The discriminator is handled above as a meta-property; never treat it as a data field.\n if (property === JsonSerializer.DerivedTypeIdProperty) return;\n let value = instance[property];\n if (value !== undefined) {\n if (Array.isArray(value)) {\n value = value.map(_ => convertTypesOnInstance(_));\n } else {\n value = serializeValueForType(value.__proto__.constructor, value);\n }\n }\n\n converted[property] = value;\n });\n\n return converted;\n};\n\n// Initialize ValueMapJsonConverter with helper functions to avoid circular dependencies\n// Must be done after serializeMapKey and convertTypesOnInstance are defined\nValueMapJsonConverter.setHelpers(serializeMapKey, convertTypesOnInstance);\n\n/**\n * Represents a serializer for JSON.\n */\nexport class JsonSerializer {\n static readonly DerivedTypeIdProperty: string = \"_derivedTypeId\";\n\n /**\n * Register a converter for the type it declares through its `type` property.\n * @param {JsonConverter} converter The converter to register.\n * @remarks\n * The converter is used for both directions - `read` on the way in, `write` on the way out - and\n * takes the place of any converter already registered for the same type, including the built-in\n * ones. Replacing a built-in changes the payloads the application produces and consumes, which is\n * the caller's to decide; nothing here second-guesses it.\n *\n * Two shapes resolve ahead of the converters, so a converter registered for them is not reached:\n *\n * - A type deriving from `ConceptAs` is unwrapped to its underlying value in both directions, and\n * converted as that value's type. Register for the underlying type to reach a concept.\n * - A `ValueMap` is read back from the declaring field's generic arguments rather than through a\n * converter. Note the asymmetry: writing a `ValueMap` *does* go through the registered converter,\n * so replacing that one changes only the outbound half.\n * - A `Guid` used as a `ValueMap` key always uses the plain canonical string form and bypasses any\n * registered `Guid` converter, so that keys stay compatible with C# dictionaries.\n */\n static registerConverter(converter: JsonConverter): void {\n registerConverterFor(converter);\n }\n\n /**\n * Serialize with strong type information.\n * @param {*} value The value to serialize.\n * @returns A JSON string.\n */\n static serialize(value: any): string {\n const converted = convertTypesOnInstance(value);\n return JSON.stringify(converted);\n }\n\n /**\n * Deserialize a JSON string to the specific type.\n * @param {Constructor} targetType Type to deserialize to.\n * @param {string} json Actual JSON to deserialize.\n * @returns An instance of the target type.\n */\n static deserialize<TResult extends object>(targetType: Constructor<TResult>, json: string): TResult {\n const parsed = JSON.parse(json);\n return this.deserializeFromInstance<TResult>(targetType, parsed);\n }\n\n /**\n * Deserialize a array JSON string to an array of the specific instance type.\n * @param {Constructor} targetType Type to deserialize to.\n * @param {string} json Actual JSON to deserialize.\n * @returns An array of instances of the target type.\n */\n static deserializeArray<TResult extends object>(targetType: Constructor<TResult>, json: string): TResult[] {\n const parsed = JSON.parse(json);\n return this.deserializeArrayFromInstance(targetType, parsed);\n }\n\n /**\n * Deserialize an any instance to a specific instance type.\n * @param {Constructor} targetType Type to deserialize to.\n * @param {*} instance Actual instance to deserialize.\n * @returns An instance of the target type.\n */\n static deserializeFromInstance<TResult extends object>(targetType: Constructor<TResult>, instance: any): TResult {\n const fields = Fields.getFieldsForType(targetType as Constructor);\n\n if (converterFor(targetType) || isConceptAs(targetType)) {\n return deserializeValueFromType(targetType, instance);\n }\n\n const deserialized = new targetType();\n for (const field of fields) {\n let value = instance[field.name];\n if (value !== undefined && value !== null) {\n if (field.type === Array) {\n const elementType = field.genericArguments[0];\n if (elementType) {\n const elementField = new Field(field.name, elementType, false, field.derivatives, []);\n value = value.map(_ => deserializeValueFromField(elementField, _));\n }\n } else if (field.enumerable) {\n value = value.map(_ => deserializeValueFromField(field, _));\n } else {\n value = deserializeValueFromField(field, value);\n }\n } else if ((field.enumerable || field.type === Array) && value === undefined) {\n // A collection that is absent from the payload deserializes to an empty one rather than to\n // undefined. The declared type says the field is an array, and a producer that leaves an\n // empty collection out - which the Chronicle sink does deliberately, so that a parallel\n // replay cannot overwrite children a sibling event already wrote - would otherwise hand back\n // a value contradicting its own type, putting a null guard on every reader of every\n // collection. An explicit null is left alone: that is the producer saying \"no collection\"\n // rather than \"an empty one\".\n value = [];\n }\n\n deserialized[field.name] = value;\n }\n\n // Preserve the polymorphic type discriminator so it is never lost across (de)serialization\n // layers. '_derivedTypeId' is not a declared field, so it is otherwise dropped here — and a\n // derived value whose concrete type could not be resolved (e.g. its type was not yet\n // registered) would then have no discriminator left to re-resolve or round-trip with, and\n // would serialize back with no type information at all.\n const derivedTypeId = instance[JsonSerializer.DerivedTypeIdProperty];\n if (derivedTypeId !== undefined && derivedTypeId !== null) {\n (deserialized as Record<string, unknown>)[JsonSerializer.DerivedTypeIdProperty] = derivedTypeId;\n }\n\n if ((targetType as Constructor) == Object) {\n const objectFields = Object.keys(instance).filter((value) => {\n return !fields.some(_ => _.name == value);\n });\n\n for (const field of objectFields) {\n deserialized[field] = instance[field];\n }\n }\n\n return deserialized;\n }\n\n /**\n * Deserialize an array of any instances to an array of specific instance types.\n * @param {Constructor} targetType Type to deserialize to.\n * @param {instances} instances Actual instances to deserialize.\n * @returns An array of instances of the target type.\n */\n static deserializeArrayFromInstance<TResult extends object>(targetType: Constructor<TResult>, instances: any): TResult[] {\n const deserialized: TResult[] = [];\n\n for (const instance of instances) {\n deserialized.push(this.deserializeFromInstance<TResult>(targetType, instance));\n }\n\n return deserialized;\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAiCA,sBAAsB,EAAE;AAGxB,MAAM,UAAU,GAAoB;AAChC,IAAA,IAAI,iBAAiB,EAAE;AACvB,IAAA,IAAI,qBAAqB,EAAE;AAC3B,IAAA,IAAI,iBAAiB,EAAE;AACvB,IAAA,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,KAAK,SAAS,EAAE;gBAQ1E,KAAK,GAAG,EAAE;YACd;AAEA,YAAA,YAAY,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,KAAK;QACpC;QAOA,MAAM,aAAa,GAAG,QAAQ,CAAC,cAAc,CAAC,qBAAqB,CAAC;QACpE,IAAI,aAAa,KAAK,SAAS,IAAI,aAAa,KAAK,IAAI,EAAE;AACtD,YAAA,YAAwC,CAAC,cAAc,CAAC,qBAAqB,CAAC,GAAG,aAAa;QACnG;AAEA,QAAA,IAAK,UAA0B,IAAI,MAAM,EAAE;AACvC,YAAA,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,KAAI;AACxD,gBAAA,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC;AAC7C,YAAA,CAAC,CAAC;AAEF,YAAA,KAAK,MAAM,KAAK,IAAI,YAAY,EAAE;gBAC9B,YAAY,CAAC,KAAK,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC;YACzC;QACJ;AAEA,QAAA,OAAO,YAAY;IACvB;AAQA,IAAA,OAAO,4BAA4B,CAAyB,UAAgC,EAAE,SAAc,EAAA;QACxG,MAAM,YAAY,GAAc,EAAE;AAElC,QAAA,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE;AAC9B,YAAA,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,uBAAuB,CAAU,UAAU,EAAE,QAAQ,CAAC,CAAC;QAClF;AAEA,QAAA,OAAO,YAAY;IACvB;;;"}
|
|
1
|
+
{"version":3,"file":"JsonSerializer.js","sources":["../../JsonSerializer.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Constructor } from './Constructor';\nimport { DerivedType } from './DerivedType';\nimport { registerModuleInstance } from './duplicateInstanceGuard';\nimport { Field } from './Field';\nimport { Fields } from './Fields';\nimport { Guid } from './Guid';\nimport { DateOnly } from './DateOnly';\nimport { TimeOnly } from './TimeOnly';\nimport { TimeSpan } from './TimeSpan';\nimport { conceptAsTypeKey, dateOnlyTypeKey, declaredTypeKey, guidTypeKey, timeOnlyTypeKey, timeSpanTypeKey, typeKeyOf, valueMapTypeKey } from './typeKey';\nimport { ValueMap } from './ValueMap';\nimport { \n JsonConverter, \n DateJsonConverter, \n DateOnlyJsonConverter,\n GuidJsonConverter, \n TimeOnlyJsonConverter,\n TimeSpanJsonConverter, \n PointJsonConverter,\n LineStringJsonConverter,\n PolygonJsonConverter,\n ValueMapJsonConverter\n} from './json';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\ntype typeSerializer = (value: any) => any;\n\n// A second copy of this package in the same realm builds its own registry here, and brings its own\n// class objects. Convertible values still cross between the copies, because a type is recognized by\n// the key it declares - but a converter registered on one copy reaches only that one, and a version\n// pinned at the top level never reaches a nested copy. Announce it where the state that cannot be\n// shared is built.\nregisterModuleInstance();\n\n// Initialize converters\nconst converters: JsonConverter[] = [\n new DateJsonConverter(),\n new DateOnlyJsonConverter(),\n new GuidJsonConverter(),\n new TimeOnlyJsonConverter(),\n new TimeSpanJsonConverter(),\n new PointJsonConverter(),\n new LineStringJsonConverter(),\n new PolygonJsonConverter(),\n new ValueMapJsonConverter()\n];\n\n// Converters are found by the key a type declares, and only by the constructor when it declares none.\n// Keying on the constructor alone is what made a second copy of this package silently fatal: each copy\n// brings its own Guid, ConceptAs and ValueMap class objects, so neither recognized the other's. A key\n// crosses that boundary; a class object does not. A consumer's own type has no key and is found by\n// constructor, which is exact and needs nothing to cross.\nconst keyedConverters: Map<string, JsonConverter> = new Map<string, JsonConverter>();\nconst typeConverters: Map<Constructor, JsonConverter> = new Map<Constructor, JsonConverter>();\n\nconst registerConverterFor = (converter: JsonConverter) => {\n const key = declaredTypeKey(converter.type);\n if (key !== undefined) {\n keyedConverters.set(key, converter);\n }\n\n typeConverters.set(converter.type, converter);\n};\n\nconverters.forEach(registerConverterFor);\n\n/**\n * Finds the converter registered for a type, if any.\n * @param {Constructor} type The type to convert.\n * @returns {JsonConverter | undefined} The converter, or undefined when the type has none.\n */\nconst converterFor = (type: Constructor | undefined): JsonConverter | undefined => {\n if (!type) return undefined;\n\n const key = declaredTypeKey(type);\n const keyed = key === undefined ? undefined : keyedConverters.get(key);\n return keyed ?? typeConverters.get(type);\n};\n\n/**\n * Checks whether a type is a ValueMap, including one from another copy of this package.\n * @param {Constructor} type The type to check.\n * @returns {boolean} True when the type is a ValueMap.\n */\nconst isValueMap = (type: Constructor | undefined): boolean => declaredTypeKey(type) === valueMapTypeKey;\n\n// Add primitive type converters that don't need a full JsonConverter class\nconst primitiveConverters: Map<Constructor, typeSerializer> = new Map<Constructor, typeSerializer>([\n [Number, (value: number) => value],\n [String, (value: string) => value],\n [Boolean, (value: boolean) => value]\n]);\n\nconst primitiveSerializers: Map<Constructor, typeSerializer> = new Map<Constructor, typeSerializer>([\n [Number, (value: any) => value],\n [String, (value: any) => value],\n [Boolean, (value: any) => value]\n]);\n\n/**\n * Checks if a constructor is a ConceptAs type.\n * @param {Constructor} type The constructor to check.\n * @returns {boolean} True if the type extends ConceptAs.\n * @remarks\n * Reads the key rather than walking the prototype chain looking for this copy's ConceptAs. The key is a\n * static and a static is inherited, so every type deriving from ConceptAs carries it - including one\n * deriving from another copy's ConceptAs, which a prototype walk could never recognize.\n */\nconst isConceptAs = (type: Constructor): boolean => typeKeyOf(type) === conceptAsTypeKey;\n\nconst serializeValueForType = (type: Constructor, value: any) => {\n if (!value) return value;\n\n // If it's a ConceptAs instance, unwrap it and serialize the inner value recursively\n // This follows the C# pattern: recognize as concept, unwrap, then call serializer\n if (isConceptAs(value.constructor)) {\n const innerValue = value.value;\n // Recursively serialize the inner value to handle complex types\n // Use .constructor directly which works reliably for both primitives and objects\n return serializeValueForType(innerValue.constructor, innerValue);\n }\n\n // Check if there's a registered converter\n const converter = converterFor(type);\n if (converter) {\n return converter.write(value);\n }\n \n // Check primitive converters\n if (primitiveConverters.has(type)) {\n return primitiveConverters.get(type)!(value);\n }\n \n return convertTypesOnInstance(value);\n};\n\nconst deserializeValueFromType = (type: Constructor, value: any) => {\n // If it's a ConceptAs type, instantiate it with the value\n if (isConceptAs(type)) {\n const valueType = (type as Constructor & { valueType?: Constructor }).valueType;\n return new type(valueType ? deserializeValueFromType(valueType, value) : value);\n }\n \n // Check if there's a registered converter\n const converter = converterFor(type);\n if (converter) {\n return converter.read(value);\n }\n \n // Check primitive serializers\n if (primitiveSerializers.has(type)) {\n return primitiveSerializers.get(type)!(value);\n }\n \n return JsonSerializer.deserialize(type, JSON.stringify(value));\n};\n\nconst deserializeValueFromField = (field: Field, value: any) => {\n if (isValueMap(field.type)) {\n return deserializeValueMapFromField(field, value);\n }\n\n // If it's a ConceptAs type, instantiate it with the value\n if (isConceptAs(field.type)) {\n return deserializeValueFromType(field.type, value);\n }\n\n // Check if there's a registered converter\n const converter = converterFor(field.type);\n if (converter) {\n return converter.read(value);\n }\n \n // Check primitive serializers\n if (primitiveSerializers.has(field.type)) {\n return primitiveSerializers.get(field.type)!(value);\n }\n \n let type = field.type;\n if (value[JsonSerializer.DerivedTypeIdProperty]) {\n const derivedTypeId = value[JsonSerializer.DerivedTypeIdProperty];\n const candidates = [...field.derivatives, ...DerivedType.getDerivedTypesFor(field.type)];\n type = candidates.find(_ => DerivedType.get(_) == derivedTypeId) || type;\n }\n\n return JsonSerializer.deserialize(type, JSON.stringify(value));\n};\n\nconst serializeMapKey = (key: any): string => {\n if (key === undefined || key === null) {\n return '';\n }\n\n if (typeof key === 'string') {\n return key;\n }\n\n if (typeof key === 'number' || typeof key === 'boolean' || typeof key === 'bigint') {\n return key.toString();\n }\n\n if (key instanceof Date) {\n return key.toISOString();\n }\n\n // Guid, DateOnly, TimeOnly and TimeSpan keys are their plain canonical strings, as a C# dictionary\n // writes them, rather than the quoted JSON string the generic path would produce.\n if (plainStringMapKeyTypes.has(declaredTypeKey(key.constructor) ?? '')) {\n return key.toString();\n }\n\n return JsonSerializer.serialize(key);\n};\n\nconst plainStringMapKeyTypes = new Map<string, { name: string; parse: (text: string) => any }>([\n [guidTypeKey, {\n name: 'Guid',\n parse: text => {\n if (!Guid.isGuid(text)) {\n throw new Error('Not a Guid.');\n }\n return Guid.parse(text);\n }\n }],\n [dateOnlyTypeKey, { name: 'DateOnly', parse: DateOnly.parse }],\n [timeOnlyTypeKey, { name: 'TimeOnly', parse: TimeOnly.parse }],\n [timeSpanTypeKey, { name: 'TimeSpan', parse: TimeSpan.parse }]\n]);\n\nconst unquoteLegacyMapKey = (key: string): string =>\n // Keys written before the plain form was adopted carry the JSON quotes of an embedded string.\n key.length >= 2 && key.startsWith('\"') && key.endsWith('\"') ? key.slice(1, -1) : key;\n\nconst readPlainStringMapKey = (name: string, parse: (text: string) => any, key: string): any => {\n try {\n return parse(unquoteLegacyMapKey(key));\n } catch {\n throw new Error(`The map key '${key}' is not a valid ${name}.`);\n }\n};\n\nconst deserializeMapKey = (keyType: Constructor, key: string): any => {\n if (keyType === String) {\n return key;\n }\n\n if (keyType === Number) {\n return Number(key);\n }\n\n if (keyType === Boolean) {\n return key.toLowerCase() === 'true';\n }\n\n const plainKeyType = plainStringMapKeyTypes.get(declaredTypeKey(keyType) ?? '');\n if (plainKeyType) {\n return readPlainStringMapKey(plainKeyType.name, plainKeyType.parse, key);\n }\n\n // Check if there's a converter for this type\n const converter = converterFor(keyType);\n if (converter) {\n return converter.read(key);\n }\n\n return JsonSerializer.deserialize(keyType, key);\n};\n\nconst deserializeMapValue = (valueType: Constructor | undefined, value: any): any => {\n if (!valueType) {\n return value;\n }\n\n // A map value is an ordinary value of its declared type, so read it the way any other value of that\n // type is read. Resolving it here instead left out the concept and primitive cases, and the\n // primitive one lost data without a sound: a string value went through JsonSerializer.deserialize,\n // which built an empty String object because a primitive has no fields to populate.\n return deserializeValueFromType(valueType, value);\n};\n\nconst deserializeValueMapFromField = (field: Field, value: any): ValueMap<any, any> => {\n const valueMap = new ValueMap<any, any>();\n const keyType = field.genericArguments[0];\n const valueType = field.genericArguments[1];\n\n if (!value || !keyType) {\n return valueMap;\n }\n\n for (const key of Object.keys(value)) {\n const deserializedKey = deserializeMapKey(keyType, key);\n const deserializedValue = deserializeMapValue(valueType, value[key]);\n valueMap.set(deserializedKey, deserializedValue);\n }\n\n return valueMap;\n};\n\nconst convertTypesOnInstance = (instance: any) => {\n // A concept unwraps to its underlying value wherever it is reached, not only when it is reached\n // through a declared field. An array element and a map value arrive here rather than at\n // serializeValueForType, and without this they were written as the object a concept happens to be -\n // {\"value\": ...} where the receiver declared the underlying type.\n if (isConceptAs(instance.constructor)) {\n return serializeValueForType(instance.constructor as Constructor, instance);\n }\n\n // Check if there's a converter for this type\n if (converterFor(instance.constructor)) {\n return serializeValueForType(instance.constructor, instance);\n }\n \n // Check primitive converters\n if (primitiveConverters.has(instance.constructor)) {\n return primitiveConverters.get(instance.constructor)!(instance);\n }\n\n const properties = Object.getOwnPropertyNames(instance);\n const converted: any = {};\n\n // Emit the polymorphic type discriminator, preferring the registered type for the instance's\n // constructor and falling back to a discriminator preserved on the instance itself (e.g. a value\n // that was deserialized before its concrete type could be resolved). This keeps '_derivedTypeId'\n // flowing through serialization transparently — the caller never has to manage it — and is the\n // mirror of preserving it on deserialization.\n const derivedTypeId = DerivedType.get(instance.constructor) ?? instance[JsonSerializer.DerivedTypeIdProperty];\n if (derivedTypeId) {\n converted[JsonSerializer.DerivedTypeIdProperty] = derivedTypeId;\n }\n properties.forEach(property => {\n // The discriminator is handled above as a meta-property; never treat it as a data field.\n if (property === JsonSerializer.DerivedTypeIdProperty) return;\n let value = instance[property];\n if (value !== undefined) {\n if (Array.isArray(value)) {\n value = value.map(_ => convertTypesOnInstance(_));\n } else {\n value = serializeValueForType(value.__proto__.constructor, value);\n }\n }\n\n converted[property] = value;\n });\n\n return converted;\n};\n\n// Initialize ValueMapJsonConverter with helper functions to avoid circular dependencies\n// Must be done after serializeMapKey and convertTypesOnInstance are defined\nValueMapJsonConverter.setHelpers(serializeMapKey, convertTypesOnInstance);\n\n/**\n * Represents a serializer for JSON.\n */\nexport class JsonSerializer {\n static readonly DerivedTypeIdProperty: string = \"_derivedTypeId\";\n\n /**\n * Register a converter for the type it declares through its `type` property.\n * @param {JsonConverter} converter The converter to register.\n * @remarks\n * The converter is used for both directions - `read` on the way in, `write` on the way out - and\n * takes the place of any converter already registered for the same type, including the built-in\n * ones. Replacing a built-in changes the payloads the application produces and consumes, which is\n * the caller's to decide; nothing here second-guesses it.\n *\n * Two shapes resolve ahead of the converters, so a converter registered for them is not reached:\n *\n * - A type deriving from `ConceptAs` is unwrapped to its underlying value in both directions, and\n * converted as that value's type. Register for the underlying type to reach a concept.\n * - A `ValueMap` is read back from the declaring field's generic arguments rather than through a\n * converter. Note the asymmetry: writing a `ValueMap` *does* go through the registered converter,\n * so replacing that one changes only the outbound half.\n * - A `Guid`, `DateOnly`, `TimeOnly` or `TimeSpan` used as a `ValueMap` key always uses the plain\n * canonical string form and bypasses any registered converter for that type, so that keys stay\n * compatible with C# dictionaries.\n */\n static registerConverter(converter: JsonConverter): void {\n registerConverterFor(converter);\n }\n\n /**\n * Serialize with strong type information.\n * @param {*} value The value to serialize.\n * @returns A JSON string.\n */\n static serialize(value: any): string {\n const converted = convertTypesOnInstance(value);\n return JSON.stringify(converted);\n }\n\n /**\n * Deserialize a JSON string to the specific type.\n * @param {Constructor} targetType Type to deserialize to.\n * @param {string} json Actual JSON to deserialize.\n * @returns An instance of the target type.\n */\n static deserialize<TResult extends object>(targetType: Constructor<TResult>, json: string): TResult {\n const parsed = JSON.parse(json);\n return this.deserializeFromInstance<TResult>(targetType, parsed);\n }\n\n /**\n * Deserialize a array JSON string to an array of the specific instance type.\n * @param {Constructor} targetType Type to deserialize to.\n * @param {string} json Actual JSON to deserialize.\n * @returns An array of instances of the target type.\n */\n static deserializeArray<TResult extends object>(targetType: Constructor<TResult>, json: string): TResult[] {\n const parsed = JSON.parse(json);\n return this.deserializeArrayFromInstance(targetType, parsed);\n }\n\n /**\n * Deserialize an any instance to a specific instance type.\n * @param {Constructor} targetType Type to deserialize to.\n * @param {*} instance Actual instance to deserialize.\n * @returns An instance of the target type.\n */\n static deserializeFromInstance<TResult extends object>(targetType: Constructor<TResult>, instance: any): TResult {\n const fields = Fields.getFieldsForType(targetType as Constructor);\n\n if (converterFor(targetType) || isConceptAs(targetType)) {\n return deserializeValueFromType(targetType, instance);\n }\n\n const deserialized = new targetType();\n for (const field of fields) {\n let value = instance[field.name];\n if (value !== undefined && value !== null) {\n if (field.type === Array) {\n const elementType = field.genericArguments[0];\n if (elementType) {\n const elementField = new Field(field.name, elementType, false, field.derivatives, []);\n value = value.map(_ => deserializeValueFromField(elementField, _));\n }\n } else if (field.enumerable) {\n value = value.map(_ => deserializeValueFromField(field, _));\n } else {\n value = deserializeValueFromField(field, value);\n }\n } else if ((field.enumerable || field.type === Array) && value === undefined) {\n // A collection that is absent from the payload deserializes to an empty one rather than to\n // undefined. The declared type says the field is an array, and a producer that leaves an\n // empty collection out - which the Chronicle sink does deliberately, so that a parallel\n // replay cannot overwrite children a sibling event already wrote - would otherwise hand back\n // a value contradicting its own type, putting a null guard on every reader of every\n // collection. An explicit null is left alone: that is the producer saying \"no collection\"\n // rather than \"an empty one\".\n value = [];\n }\n\n deserialized[field.name] = value;\n }\n\n // Preserve the polymorphic type discriminator so it is never lost across (de)serialization\n // layers. '_derivedTypeId' is not a declared field, so it is otherwise dropped here — and a\n // derived value whose concrete type could not be resolved (e.g. its type was not yet\n // registered) would then have no discriminator left to re-resolve or round-trip with, and\n // would serialize back with no type information at all.\n const derivedTypeId = instance[JsonSerializer.DerivedTypeIdProperty];\n if (derivedTypeId !== undefined && derivedTypeId !== null) {\n (deserialized as Record<string, unknown>)[JsonSerializer.DerivedTypeIdProperty] = derivedTypeId;\n }\n\n if ((targetType as Constructor) == Object) {\n const objectFields = Object.keys(instance).filter((value) => {\n return !fields.some(_ => _.name == value);\n });\n\n for (const field of objectFields) {\n deserialized[field] = instance[field];\n }\n }\n\n return deserialized;\n }\n\n /**\n * Deserialize an array of any instances to an array of specific instance types.\n * @param {Constructor} targetType Type to deserialize to.\n * @param {instances} instances Actual instances to deserialize.\n * @returns An array of instances of the target type.\n */\n static deserializeArrayFromInstance<TResult extends object>(targetType: Constructor<TResult>, instances: any): TResult[] {\n const deserialized: TResult[] = [];\n\n for (const instance of instances) {\n deserialized.push(this.deserializeFromInstance<TResult>(targetType, instance));\n }\n\n return deserialized;\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAoCA,sBAAsB,EAAE;AAGxB,MAAM,UAAU,GAAoB;AAChC,IAAA,IAAI,iBAAiB,EAAE;AACvB,IAAA,IAAI,qBAAqB,EAAE;AAC3B,IAAA,IAAI,iBAAiB,EAAE;AACvB,IAAA,IAAI,qBAAqB,EAAE;AAC3B,IAAA,IAAI,qBAAqB,EAAE;AAC3B,IAAA,IAAI,kBAAkB,EAAE;AACxB,IAAA,IAAI,uBAAuB,EAAE;AAC7B,IAAA,IAAI,oBAAoB,EAAE;AAC1B,IAAA,IAAI,qBAAqB;CAC5B;AAOD,MAAM,eAAe,GAA+B,IAAI,GAAG,EAAyB;AACpF,MAAM,cAAc,GAAoC,IAAI,GAAG,EAA8B;AAE7F,MAAM,oBAAoB,GAAG,CAAC,SAAwB,KAAI;IACtD,MAAM,GAAG,GAAG,eAAe,CAAC,SAAS,CAAC,IAAI,CAAC;AAC3C,IAAA,IAAI,GAAG,KAAK,SAAS,EAAE;AACnB,QAAA,eAAe,CAAC,GAAG,CAAC,GAAG,EAAE,SAAS,CAAC;IACvC;IAEA,cAAc,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,SAAS,CAAC;AACjD,CAAC;AAED,UAAU,CAAC,OAAO,CAAC,oBAAoB,CAAC;AAOxC,MAAM,YAAY,GAAG,CAAC,IAA6B,KAA+B;AAC9E,IAAA,IAAI,CAAC,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,8 @@ export declare class TimeOnly {
|
|
|
5
5
|
minute: number;
|
|
6
6
|
second: number;
|
|
7
7
|
millisecond: number;
|
|
8
|
-
|
|
8
|
+
subMillisecondTicks: number;
|
|
9
|
+
static from(hour: number, minute: number, second?: number, millisecond?: number, subMillisecondTicks?: number): TimeOnly;
|
|
9
10
|
static parse(value: string): TimeOnly;
|
|
10
11
|
toString(): string;
|
|
11
12
|
toJSON(): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TimeOnly.d.ts","sourceRoot":"","sources":["../../TimeOnly.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAWpC,qBAAa,QAAQ;IACjB,MAAM,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,cAAc;IAMvC,IAAI,EAAG,MAAM,CAAC;IAMd,MAAM,EAAG,MAAM,CAAC;IAMhB,MAAM,EAAG,MAAM,CAAC;IAMhB,WAAW,EAAG,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"TimeOnly.d.ts","sourceRoot":"","sources":["../../TimeOnly.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAWpC,qBAAa,QAAQ;IACjB,MAAM,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,cAAc;IAMvC,IAAI,EAAG,MAAM,CAAC;IAMd,MAAM,EAAG,MAAM,CAAC;IAMhB,MAAM,EAAG,MAAM,CAAC;IAMhB,WAAW,EAAG,MAAM,CAAC;IAOrB,mBAAmB,EAAG,MAAM,CAAC;IAY7B,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAE,MAAU,EAAE,WAAW,GAAE,MAAU,EAAE,mBAAmB,GAAE,MAAU,GAAG,QAAQ;IAwBjI,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,QAAQ;IAsCrC,QAAQ,IAAI,MAAM;IAqBlB,MAAM,IAAI,MAAM;IAShB,MAAM,CAAC,KAAK,EAAE,QAAQ,GAAG,SAAS,GAAG,IAAI,GAAG,OAAO;CAQtD"}
|
package/dist/esm/TimeOnly.js
CHANGED
|
@@ -9,12 +9,17 @@ class TimeOnly {
|
|
|
9
9
|
minute;
|
|
10
10
|
second;
|
|
11
11
|
millisecond;
|
|
12
|
-
|
|
12
|
+
subMillisecondTicks;
|
|
13
|
+
static from(hour, minute, second = 0, millisecond = 0, subMillisecondTicks = 0) {
|
|
14
|
+
if (!Number.isInteger(subMillisecondTicks) || subMillisecondTicks < 0 || subMillisecondTicks > 9999) {
|
|
15
|
+
throw new Error(`Invalid TimeOnly: subMillisecondTicks ${subMillisecondTicks} is out of range 0-9999`);
|
|
16
|
+
}
|
|
13
17
|
const timeOnly = new TimeOnly();
|
|
14
18
|
timeOnly.hour = hour;
|
|
15
19
|
timeOnly.minute = minute;
|
|
16
20
|
timeOnly.second = second;
|
|
17
21
|
timeOnly.millisecond = millisecond;
|
|
22
|
+
timeOnly.subMillisecondTicks = subMillisecondTicks;
|
|
18
23
|
return timeOnly;
|
|
19
24
|
}
|
|
20
25
|
static parse(value) {
|
|
@@ -22,14 +27,30 @@ class TimeOnly {
|
|
|
22
27
|
if (match === null) {
|
|
23
28
|
throw new Error(`Invalid TimeOnly format: ${value}`);
|
|
24
29
|
}
|
|
25
|
-
const
|
|
26
|
-
|
|
30
|
+
const hour = parseInt(match[1], 10);
|
|
31
|
+
const minute = parseInt(match[2], 10);
|
|
32
|
+
const second = match[3] ? parseInt(match[3], 10) : 0;
|
|
33
|
+
if (hour > 23) {
|
|
34
|
+
throw new Error(`Invalid TimeOnly: hour ${hour} is out of range 0-23 in '${value}'`);
|
|
35
|
+
}
|
|
36
|
+
if (minute > 59) {
|
|
37
|
+
throw new Error(`Invalid TimeOnly: minute ${minute} is out of range 0-59 in '${value}'`);
|
|
38
|
+
}
|
|
39
|
+
if (second > 59) {
|
|
40
|
+
throw new Error(`Invalid TimeOnly: second ${second} is out of range 0-59 in '${value}'`);
|
|
41
|
+
}
|
|
42
|
+
const fraction = (match[4] ?? '').padEnd(7, '0');
|
|
43
|
+
return TimeOnly.from(hour, minute, second, parseInt(fraction.substring(0, 3), 10), parseInt(fraction.substring(3), 10));
|
|
27
44
|
}
|
|
28
45
|
toString() {
|
|
29
46
|
const hour = this.hour.toString().padStart(2, '0');
|
|
30
47
|
const minute = this.minute.toString().padStart(2, '0');
|
|
31
48
|
const second = this.second.toString().padStart(2, '0');
|
|
32
49
|
const time = `${hour}:${minute}:${second}`;
|
|
50
|
+
const subMillisecondTicks = this.subMillisecondTicks ?? 0;
|
|
51
|
+
if (subMillisecondTicks > 0) {
|
|
52
|
+
return `${time}.${this.millisecond.toString().padStart(3, '0')}${subMillisecondTicks.toString().padStart(4, '0')}`;
|
|
53
|
+
}
|
|
33
54
|
return this.millisecond > 0 ? `${time}.${this.millisecond.toString().padStart(3, '0')}` : time;
|
|
34
55
|
}
|
|
35
56
|
toJSON() {
|
|
@@ -40,7 +61,8 @@ class TimeOnly {
|
|
|
40
61
|
this.hour === other.hour &&
|
|
41
62
|
this.minute === other.minute &&
|
|
42
63
|
this.second === other.second &&
|
|
43
|
-
this.millisecond === other.millisecond
|
|
64
|
+
this.millisecond === other.millisecond &&
|
|
65
|
+
(this.subMillisecondTicks ?? 0) === (other.subMillisecondTicks ?? 0);
|
|
44
66
|
}
|
|
45
67
|
}
|
|
46
68
|
__decorate([
|
|
@@ -59,6 +81,10 @@ __decorate([
|
|
|
59
81
|
field(Number),
|
|
60
82
|
__metadata("design:type", Number)
|
|
61
83
|
], TimeOnly.prototype, "millisecond", void 0);
|
|
84
|
+
__decorate([
|
|
85
|
+
field(Number),
|
|
86
|
+
__metadata("design:type", Number)
|
|
87
|
+
], TimeOnly.prototype, "subMillisecondTicks", void 0);
|
|
62
88
|
|
|
63
89
|
export { TimeOnly };
|
|
64
90
|
//# sourceMappingURL=TimeOnly.js.map
|
package/dist/esm/TimeOnly.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TimeOnly.js","sources":["../../TimeOnly.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { field } from './fieldDecorator';\nimport { typeKey } from './typeKey';\n\nconst timeOnlyRegex = /^(\\d{2}):(\\d{2})(?::(\\d{2}))?(?:\\.(\\d{1,7}))?$/;\n\n/**\n * Represents a time of day with no date and no time zone.\n * @remarks\n * Deliberately not a JavaScript `Date`. A `Date` needs a date, and a time of day has none: `new Date('14:30:45')`\n * is not an instant pinned to some default day, it is `Invalid Date`. The value is destroyed outright rather than\n * merely shifted, which makes this the starker of the two temporal cases.\n */\nexport class TimeOnly {\n static readonly [typeKey] = 'TimeOnly';\n\n /**\n * The hour, 0 through 23.\n */\n @field(Number)\n hour!: number;\n\n /**\n * The minute, 0 through 59.\n */\n @field(Number)\n minute!: number;\n\n /**\n * The second, 0 through 59.\n */\n @field(Number)\n second!: number;\n\n /**\n * The millisecond, 0 through 999.\n */\n @field(Number)\n millisecond!: number;\n\n /**\n * Creates a {@link TimeOnly} from its parts.\n * @param hour The hour.\n * @param minute The minute.\n * @param second The second.\n * @param millisecond The millisecond.\n * @returns The {@link TimeOnly}.\n */\n static from(hour: number, minute: number, second: number = 0, millisecond: number = 0): TimeOnly {\n const timeOnly = new TimeOnly();\n timeOnly.hour = hour;\n timeOnly.minute = minute;\n timeOnly.second = second;\n timeOnly.millisecond = millisecond;\n return timeOnly;\n }\n\n /**\n * Parses the ISO-8601 time of day the server sends, `HH:mm`, `HH:mm:ss` or `HH:mm:ss.fffffff`.\n * @param value The value to parse.\n * @returns The {@link TimeOnly}.\n * @remarks\n * The seconds and the fraction are both optional because the server omits them when they are zero
|
|
1
|
+
{"version":3,"file":"TimeOnly.js","sources":["../../TimeOnly.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { field } from './fieldDecorator';\nimport { typeKey } from './typeKey';\n\nconst timeOnlyRegex = /^(\\d{2}):(\\d{2})(?::(\\d{2}))?(?:\\.(\\d{1,7}))?$/;\n\n/**\n * Represents a time of day with no date and no time zone.\n * @remarks\n * Deliberately not a JavaScript `Date`. A `Date` needs a date, and a time of day has none: `new Date('14:30:45')`\n * is not an instant pinned to some default day, it is `Invalid Date`. The value is destroyed outright rather than\n * merely shifted, which makes this the starker of the two temporal cases.\n */\nexport class TimeOnly {\n static readonly [typeKey] = 'TimeOnly';\n\n /**\n * The hour, 0 through 23.\n */\n @field(Number)\n hour!: number;\n\n /**\n * The minute, 0 through 59.\n */\n @field(Number)\n minute!: number;\n\n /**\n * The second, 0 through 59.\n */\n @field(Number)\n second!: number;\n\n /**\n * The millisecond, 0 through 999.\n */\n @field(Number)\n millisecond!: number;\n\n /**\n * The remaining 100 nanosecond ticks below the millisecond, 0 through 9999. Carries the last four digits of\n * the seven-digit fraction a C# `TimeOnly` holds, so two times that differ below a millisecond stay different.\n */\n @field(Number)\n subMillisecondTicks!: number;\n\n /**\n * Creates a {@link TimeOnly} from its parts.\n * @param hour The hour.\n * @param minute The minute.\n * @param second The second.\n * @param millisecond The millisecond.\n * @param subMillisecondTicks The 100 nanosecond ticks below the millisecond, 0 through 9999.\n * @returns The {@link TimeOnly}.\n * @throws {Error} If `subMillisecondTicks` is not a whole number from 0 through 9999.\n */\n static from(hour: number, minute: number, second: number = 0, millisecond: number = 0, subMillisecondTicks: number = 0): TimeOnly {\n if (!Number.isInteger(subMillisecondTicks) || subMillisecondTicks < 0 || subMillisecondTicks > 9999) {\n throw new Error(`Invalid TimeOnly: subMillisecondTicks ${subMillisecondTicks} is out of range 0-9999`);\n }\n\n const timeOnly = new TimeOnly();\n timeOnly.hour = hour;\n timeOnly.minute = minute;\n timeOnly.second = second;\n timeOnly.millisecond = millisecond;\n timeOnly.subMillisecondTicks = subMillisecondTicks;\n return timeOnly;\n }\n\n /**\n * Parses the ISO-8601 time of day the server sends, `HH:mm`, `HH:mm:ss` or `HH:mm:ss.fffffff`.\n * @param value The value to parse.\n * @returns The {@link TimeOnly}.\n * @remarks\n * The seconds and the fraction are both optional because the server omits them when they are zero. The\n * fraction carries up to seven digits, all of which are kept, so C# times that differ below a millisecond\n * stay distinct. Components outside the ranges C# accepts are rejected.\n * @throws {Error} If the format is invalid or a component is out of range.\n */\n static parse(value: string): TimeOnly {\n const match = timeOnlyRegex.exec(value);\n if (match === null) {\n throw new Error(`Invalid TimeOnly format: ${value}`);\n }\n\n const hour = parseInt(match[1], 10);\n const minute = parseInt(match[2], 10);\n const second = match[3] ? parseInt(match[3], 10) : 0;\n\n if (hour > 23) {\n throw new Error(`Invalid TimeOnly: hour ${hour} is out of range 0-23 in '${value}'`);\n }\n\n if (minute > 59) {\n throw new Error(`Invalid TimeOnly: minute ${minute} is out of range 0-59 in '${value}'`);\n }\n\n if (second > 59) {\n throw new Error(`Invalid TimeOnly: second ${second} is out of range 0-59 in '${value}'`);\n }\n\n const fraction = (match[4] ?? '').padEnd(7, '0');\n\n return TimeOnly.from(\n hour,\n minute,\n second,\n parseInt(fraction.substring(0, 3), 10),\n parseInt(fraction.substring(3), 10));\n }\n\n /**\n * Gets the ISO-8601 representation: `HH:mm:ss`, or `HH:mm:ss.fff` when there is a millisecond part, or the\n * full seven-digit `HH:mm:ss.fffffff` when there is a non-zero part below the millisecond. The seven-digit form\n * is padded, never trimmed, so the two fractional forms are the only ones produced; the parser accepts 1-7 digits.\n * @returns The string.\n */\n toString(): string {\n const hour = this.hour.toString().padStart(2, '0');\n const minute = this.minute.toString().padStart(2, '0');\n const second = this.second.toString().padStart(2, '0');\n const time = `${hour}:${minute}:${second}`;\n const subMillisecondTicks = this.subMillisecondTicks ?? 0;\n if (subMillisecondTicks > 0) {\n return `${time}.${this.millisecond.toString().padStart(3, '0')}${subMillisecondTicks.toString().padStart(4, '0')}`;\n }\n\n return this.millisecond > 0 ? `${time}.${this.millisecond.toString().padStart(3, '0')}` : time;\n }\n\n /**\n * Gets the ISO-8601 representation used when this is serialized as JSON.\n *\n * Without this, `JSON.stringify` falls back to enumerating `hour`, `minute`, `second` and\n * `millisecond`, so a request body carries a component object where the server expects the\n * scalar string.\n * @returns The string.\n */\n toJSON(): string {\n return this.toString();\n }\n\n /**\n * Determines whether this is the same time of day as another.\n * @param other The other time.\n * @returns True when they are the same time.\n */\n equals(other: TimeOnly | undefined | null): boolean {\n return !!other &&\n this.hour === other.hour &&\n this.minute === other.minute &&\n this.second === other.second &&\n this.millisecond === other.millisecond &&\n (this.subMillisecondTicks ?? 0) === (other.subMillisecondTicks ?? 0);\n }\n}\n"],"names":[],"mappings":";;;;AAMA,MAAM,aAAa,GAAG,gDAAgD;MASzD,QAAQ,CAAA;AACjB,IAAA,QAAiB,OAAO,IAAI,UAAU;AAMtC,IAAA,IAAI;AAMJ,IAAA,MAAM;AAMN,IAAA,MAAM;AAMN,IAAA,WAAW;AAOX,IAAA,mBAAmB;AAYnB,IAAA,OAAO,IAAI,CAAC,IAAY,EAAE,MAAc,EAAE,MAAA,GAAiB,CAAC,EAAE,WAAA,GAAsB,CAAC,EAAE,sBAA8B,CAAC,EAAA;AAClH,QAAA,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,mBAAmB,CAAC,IAAI,mBAAmB,GAAG,CAAC,IAAI,mBAAmB,GAAG,IAAI,EAAE;AACjG,YAAA,MAAM,IAAI,KAAK,CAAC,yCAAyC,mBAAmB,CAAA,uBAAA,CAAyB,CAAC;QAC1G;AAEA,QAAA,MAAM,QAAQ,GAAG,IAAI,QAAQ,EAAE;AAC/B,QAAA,QAAQ,CAAC,IAAI,GAAG,IAAI;AACpB,QAAA,QAAQ,CAAC,MAAM,GAAG,MAAM;AACxB,QAAA,QAAQ,CAAC,MAAM,GAAG,MAAM;AACxB,QAAA,QAAQ,CAAC,WAAW,GAAG,WAAW;AAClC,QAAA,QAAQ,CAAC,mBAAmB,GAAG,mBAAmB;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AGnB"}
|
package/dist/esm/TimeSpan.js
CHANGED
|
@@ -30,11 +30,28 @@ class TimeSpan {
|
|
|
30
30
|
const hours = parseInt(match[3], 10);
|
|
31
31
|
const minutes = parseInt(match[4], 10);
|
|
32
32
|
const seconds = parseInt(match[5], 10);
|
|
33
|
+
if (hours > 23) {
|
|
34
|
+
throw new Error(`Invalid TimeSpan: hours ${hours} is out of range 0-23 in '${value}'`);
|
|
35
|
+
}
|
|
36
|
+
if (minutes > 59) {
|
|
37
|
+
throw new Error(`Invalid TimeSpan: minutes ${minutes} is out of range 0-59 in '${value}'`);
|
|
38
|
+
}
|
|
39
|
+
if (seconds > 59) {
|
|
40
|
+
throw new Error(`Invalid TimeSpan: seconds ${seconds} is out of range 0-59 in '${value}'`);
|
|
41
|
+
}
|
|
42
|
+
const maxDays = 10675199;
|
|
43
|
+
if (days > maxDays) {
|
|
44
|
+
throw new Error(`Invalid TimeSpan: days ${days} is out of range 0-${maxDays} in '${value}'`);
|
|
45
|
+
}
|
|
33
46
|
const fractionalSeconds = match[6] ? match[6].padEnd(7, '0') : '0000000';
|
|
34
47
|
const ticksPerDay = 864000000000;
|
|
35
48
|
const ticksPerHour = 36000000000;
|
|
36
49
|
const ticksPerMinute = 600000000;
|
|
37
50
|
const ticksPerSecond = 10000000;
|
|
51
|
+
const remainderTicks = hours * ticksPerHour + minutes * ticksPerMinute + seconds * ticksPerSecond + parseInt(fractionalSeconds, 10);
|
|
52
|
+
if (days === maxDays && remainderTicks > (isNegative ? 100854775808 : 100854775807)) {
|
|
53
|
+
throw new Error(`Invalid TimeSpan: '${value}' is outside the range a TimeSpan can hold`);
|
|
54
|
+
}
|
|
38
55
|
const ticks = days * ticksPerDay +
|
|
39
56
|
hours * ticksPerHour +
|
|
40
57
|
minutes * ticksPerMinute +
|
package/dist/esm/TimeSpan.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TimeSpan.js","sources":["../../TimeSpan.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { typeKey } from './typeKey';\n\nimport { field } from './fieldDecorator';\n\nconst timeSpanRegex = /^(-)?(?:(\\d+)\\.)?(\\d{1,2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,7}))?$/;\n\n/**\n * Represents a time interval.\n */\nexport class TimeSpan {\n static readonly [typeKey] = 'TimeSpan';\n\n \n @field(Number)\n ticks!: number;\n\n @field(Number)\n days!: number;\n\n @field(Number)\n hours!: number;\n\n @field(Number)\n milliseconds!: number;\n\n @field(Number)\n microseconds!: number;\n\n @field(Number)\n nanoseconds!: number;\n\n @field(Number)\n minutes!: number;\n\n @field(Number)\n seconds!: number;\n\n @field(Number)\n totalDays!: number;\n\n @field(Number)\n totalHours!: number;\n\n @field(Number)\n totalMilliseconds!: number;\n\n @field(Number)\n totalMicroseconds!: number;\n\n @field(Number)\n totalNanoseconds!: number;\n\n @field(Number)\n totalMinutes!: number;\n\n @field(Number)\n totalSeconds!: number;\n\n /**\n * Parses a C# compatible TimeSpan string and returns a TimeSpan instance.\n * The string format should match: [-][d.]hh:mm:ss[.fffffff]\n * @param {string} value String representation of TimeSpan.\n * @returns {TimeSpan} A TimeSpan instance with all properties populated.\n * @throws {Error} If the string format is invalid.\n */\n static parse(value: string): TimeSpan {\n const match = timeSpanRegex.exec(value);\n if (match === null) {\n throw new Error(`Invalid TimeSpan format: ${value}`);\n }\n\n const isNegative = match[1] === '-';\n const days = match[2] ? parseInt(match[2], 10) : 0;\n const hours = parseInt(match[3], 10);\n const minutes = parseInt(match[4], 10);\n const seconds = parseInt(match[5], 10);\n const fractionalSeconds = match[6] ? match[6].padEnd(7, '0') : '0000000';\n\n const ticksPerDay = 864000000000;\n const ticksPerHour = 36000000000;\n const ticksPerMinute = 600000000;\n const ticksPerSecond = 10000000;\n\n const ticks =\n days * ticksPerDay +\n hours * ticksPerHour +\n minutes * ticksPerMinute +\n seconds * ticksPerSecond +\n parseInt(fractionalSeconds, 10);\n\n const finalTicks = isNegative ? -ticks : ticks;\n\n const timeSpan = new TimeSpan();\n timeSpan.ticks = finalTicks;\n timeSpan.days = Math.floor(Math.abs(finalTicks) / ticksPerDay) * (isNegative ? -1 : 1);\n timeSpan.hours = Math.floor((Math.abs(finalTicks) / ticksPerHour) % 24);\n timeSpan.minutes = Math.floor((Math.abs(finalTicks) / ticksPerMinute) % 60);\n timeSpan.seconds = Math.floor((Math.abs(finalTicks) / ticksPerSecond) % 60);\n timeSpan.milliseconds = Math.floor((Math.abs(finalTicks) / 10000) % 1000);\n timeSpan.microseconds = Math.floor((Math.abs(finalTicks) / 10) % 1000);\n timeSpan.nanoseconds = Math.floor((Math.abs(finalTicks) % 10) * 100);\n timeSpan.totalDays = finalTicks / ticksPerDay;\n timeSpan.totalHours = finalTicks / ticksPerHour;\n timeSpan.totalMinutes = finalTicks / ticksPerMinute;\n timeSpan.totalSeconds = finalTicks / ticksPerSecond;\n timeSpan.totalMilliseconds = finalTicks / 10000;\n timeSpan.totalMicroseconds = finalTicks / 10;\n timeSpan.totalNanoseconds = finalTicks * 100;\n\n return timeSpan;\n }\n\n /**\n * Converts the TimeSpan to a C# compatible string format.\n * Returns the TimeSpan in format: [-][d.]hh:mm:ss[.fffffff]\n * @returns {string} C# compatible TimeSpan string representation.\n */\n toString(): string {\n const isNegative = this.ticks < 0;\n const absTicks = Math.abs(this.ticks);\n\n const ticksPerDay = 864000000000;\n const ticksPerHour = 36000000000;\n const ticksPerMinute = 600000000;\n const ticksPerSecond = 10000000;\n\n const days = Math.floor(absTicks / ticksPerDay);\n const hours = Math.floor((absTicks / ticksPerHour) % 24);\n const minutes = Math.floor((absTicks / ticksPerMinute) % 60);\n const seconds = Math.floor((absTicks / ticksPerSecond) % 60);\n const fractionalTicks = absTicks % ticksPerSecond;\n\n const parts: string[] = [];\n\n if (isNegative) {\n parts.push('-');\n }\n\n if (days > 0) {\n parts.push(`${days}.`);\n }\n\n parts.push(`${hours.toString().padStart(2, '0')}:`);\n parts.push(`${minutes.toString().padStart(2, '0')}:`);\n parts.push(`${seconds.toString().padStart(2, '0')}`);\n\n if (fractionalTicks > 0) {\n const fractionalStr = fractionalTicks.toString().padStart(7, '0').replace(/0+$/, '');\n parts.push(`.${fractionalStr}`);\n }\n\n return parts.join('');\n }\n\n /**\n * Converts the TimeSpan to a JSON string that works in JSON serialization.\n * Returns the TimeSpan in C# compatible format: [-][d.]hh:mm:ss[.fffffff]\n * @returns {string} C# compatible TimeSpan string representation.\n */\n toJSON(): string {\n return this.toString();\n }\n}\n"],"names":[],"mappings":";;;;AAOA,MAAM,aAAa,GAAG,6DAA6D;MAKtE,QAAQ,CAAA;AACjB,IAAA,QAAiB,OAAO,IAAI,UAAU;AAItC,IAAA,KAAK;AAGL,IAAA,IAAI;AAGJ,IAAA,KAAK;AAGL,IAAA,YAAY;AAGZ,IAAA,YAAY;AAGZ,IAAA,WAAW;AAGX,IAAA,OAAO;AAGP,IAAA,OAAO;AAGP,IAAA,SAAS;AAGT,IAAA,UAAU;AAGV,IAAA,iBAAiB;AAGjB,IAAA,iBAAiB;AAGjB,IAAA,gBAAgB;AAGhB,IAAA,YAAY;AAGZ,IAAA,YAAY;IASZ,OAAO,KAAK,CAAC,KAAa,EAAA;QACtB,MAAM,KAAK,GAAG,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC;AACvC,QAAA,IAAI,KAAK,KAAK,IAAI,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,4BAA4B,KAAK,CAAA,CAAE,CAAC;QACxD;QAEA,MAAM,UAAU,GAAG,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG;QACnC,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC;QAClD,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;QACpC,M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EAAA,QAAA,CAAA,SAAA,EAAA,YAAA,EAAA,MAAA,CAAA;AAGpB,UAAA,CAAA;IADC,KAAK,CAAC,MAAM,CAAC;;AACa,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,mBAAA,EAAA,MAAA,CAAA;AAG3B,UAAA,CAAA;IADC,KAAK,CAAC,MAAM,CAAC;;AACa,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,mBAAA,EAAA,MAAA,CAAA;AAG3B,UAAA,CAAA;IADC,KAAK,CAAC,MAAM,CAAC;;AACY,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,kBAAA,EAAA,MAAA,CAAA;AAG1B,UAAA,CAAA;IADC,KAAK,CAAC,MAAM,CAAC;;AACQ,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,cAAA,EAAA,MAAA,CAAA;AAGtB,UAAA,CAAA;IADC,KAAK,CAAC,MAAM,CAAC;;AACQ,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,cAAA,EAAA,MAAA,CAAA;;"}
|
|
1
|
+
{"version":3,"file":"TimeSpan.js","sources":["../../TimeSpan.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { typeKey } from './typeKey';\n\nimport { field } from './fieldDecorator';\n\nconst timeSpanRegex = /^(-)?(?:(\\d+)\\.)?(\\d{1,2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,7}))?$/;\n\n/**\n * Represents a time interval.\n */\nexport class TimeSpan {\n static readonly [typeKey] = 'TimeSpan';\n\n \n @field(Number)\n ticks!: number;\n\n @field(Number)\n days!: number;\n\n @field(Number)\n hours!: number;\n\n @field(Number)\n milliseconds!: number;\n\n @field(Number)\n microseconds!: number;\n\n @field(Number)\n nanoseconds!: number;\n\n @field(Number)\n minutes!: number;\n\n @field(Number)\n seconds!: number;\n\n @field(Number)\n totalDays!: number;\n\n @field(Number)\n totalHours!: number;\n\n @field(Number)\n totalMilliseconds!: number;\n\n @field(Number)\n totalMicroseconds!: number;\n\n @field(Number)\n totalNanoseconds!: number;\n\n @field(Number)\n totalMinutes!: number;\n\n @field(Number)\n totalSeconds!: number;\n\n /**\n * Parses a C# compatible TimeSpan string and returns a TimeSpan instance.\n * The string format should match: [-][d.]hh:mm:ss[.fffffff]\n * @param {string} value String representation of TimeSpan.\n * @returns {TimeSpan} A TimeSpan instance with all properties populated.\n * @throws {Error} If the string format is invalid or hours, minutes or seconds are out of range, as C# rejects it.\n */\n static parse(value: string): TimeSpan {\n const match = timeSpanRegex.exec(value);\n if (match === null) {\n throw new Error(`Invalid TimeSpan format: ${value}`);\n }\n\n const isNegative = match[1] === '-';\n const days = match[2] ? parseInt(match[2], 10) : 0;\n const hours = parseInt(match[3], 10);\n const minutes = parseInt(match[4], 10);\n const seconds = parseInt(match[5], 10);\n\n if (hours > 23) {\n throw new Error(`Invalid TimeSpan: hours ${hours} is out of range 0-23 in '${value}'`);\n }\n\n if (minutes > 59) {\n throw new Error(`Invalid TimeSpan: minutes ${minutes} is out of range 0-59 in '${value}'`);\n }\n\n if (seconds > 59) {\n throw new Error(`Invalid TimeSpan: seconds ${seconds} is out of range 0-59 in '${value}'`);\n }\n\n const maxDays = 10675199;\n if (days > maxDays) {\n throw new Error(`Invalid TimeSpan: days ${days} is out of range 0-${maxDays} in '${value}'`);\n }\n\n const fractionalSeconds = match[6] ? match[6].padEnd(7, '0') : '0000000';\n\n const ticksPerDay = 864000000000;\n const ticksPerHour = 36000000000;\n const ticksPerMinute = 600000000;\n const ticksPerSecond = 10000000;\n\n // TimeSpan.MaxValue is 10675199.02:48:05.4775807 and MinValue one tick further on the negative side.\n const remainderTicks =\n hours * ticksPerHour + minutes * ticksPerMinute + seconds * ticksPerSecond + parseInt(fractionalSeconds, 10);\n if (days === maxDays && remainderTicks > (isNegative ? 100854775808 : 100854775807)) {\n throw new Error(`Invalid TimeSpan: '${value}' is outside the range a TimeSpan can hold`);\n }\n\n const ticks =\n days * ticksPerDay +\n hours * ticksPerHour +\n minutes * ticksPerMinute +\n seconds * ticksPerSecond +\n parseInt(fractionalSeconds, 10);\n\n const finalTicks = isNegative ? -ticks : ticks;\n\n const timeSpan = new TimeSpan();\n timeSpan.ticks = finalTicks;\n timeSpan.days = Math.floor(Math.abs(finalTicks) / ticksPerDay) * (isNegative ? -1 : 1);\n timeSpan.hours = Math.floor((Math.abs(finalTicks) / ticksPerHour) % 24);\n timeSpan.minutes = Math.floor((Math.abs(finalTicks) / ticksPerMinute) % 60);\n timeSpan.seconds = Math.floor((Math.abs(finalTicks) / ticksPerSecond) % 60);\n timeSpan.milliseconds = Math.floor((Math.abs(finalTicks) / 10000) % 1000);\n timeSpan.microseconds = Math.floor((Math.abs(finalTicks) / 10) % 1000);\n timeSpan.nanoseconds = Math.floor((Math.abs(finalTicks) % 10) * 100);\n timeSpan.totalDays = finalTicks / ticksPerDay;\n timeSpan.totalHours = finalTicks / ticksPerHour;\n timeSpan.totalMinutes = finalTicks / ticksPerMinute;\n timeSpan.totalSeconds = finalTicks / ticksPerSecond;\n timeSpan.totalMilliseconds = finalTicks / 10000;\n timeSpan.totalMicroseconds = finalTicks / 10;\n timeSpan.totalNanoseconds = finalTicks * 100;\n\n return timeSpan;\n }\n\n /**\n * Converts the TimeSpan to a C# compatible string format.\n * Returns the TimeSpan in format: [-][d.]hh:mm:ss[.fffffff]\n * @returns {string} C# compatible TimeSpan string representation.\n */\n toString(): string {\n const isNegative = this.ticks < 0;\n const absTicks = Math.abs(this.ticks);\n\n const ticksPerDay = 864000000000;\n const ticksPerHour = 36000000000;\n const ticksPerMinute = 600000000;\n const ticksPerSecond = 10000000;\n\n const days = Math.floor(absTicks / ticksPerDay);\n const hours = Math.floor((absTicks / ticksPerHour) % 24);\n const minutes = Math.floor((absTicks / ticksPerMinute) % 60);\n const seconds = Math.floor((absTicks / ticksPerSecond) % 60);\n const fractionalTicks = absTicks % ticksPerSecond;\n\n const parts: string[] = [];\n\n if (isNegative) {\n parts.push('-');\n }\n\n if (days > 0) {\n parts.push(`${days}.`);\n }\n\n parts.push(`${hours.toString().padStart(2, '0')}:`);\n parts.push(`${minutes.toString().padStart(2, '0')}:`);\n parts.push(`${seconds.toString().padStart(2, '0')}`);\n\n if (fractionalTicks > 0) {\n const fractionalStr = fractionalTicks.toString().padStart(7, '0').replace(/0+$/, '');\n parts.push(`.${fractionalStr}`);\n }\n\n return parts.join('');\n }\n\n /**\n * Converts the TimeSpan to a JSON string that works in JSON serialization.\n * Returns the TimeSpan in C# compatible format: [-][d.]hh:mm:ss[.fffffff]\n * @returns {string} C# compatible TimeSpan string representation.\n */\n toJSON(): string {\n return this.toString();\n }\n}\n"],"names":[],"mappings":";;;;AAOA,MAAM,aAAa,GAAG,6DAA6D;MAKtE,QAAQ,CAAA;AACjB,IAAA,QAAiB,OAAO,IAAI,UAAU;AAItC,IAAA,KAAK;AAGL,IAAA,IAAI;AAGJ,IAAA,KAAK;AAGL,IAAA,YAAY;AAGZ,IAAA,YAAY;AAGZ,IAAA,WAAW;AAGX,IAAA,OAAO;AAGP,IAAA,OAAO;AAGP,IAAA,SAAS;AAGT,IAAA,UAAU;AAGV,IAAA,iBAAiB;AAGjB,IAAA,iBAAiB;AAGjB,IAAA,gBAAgB;AAGhB,IAAA,YAAY;AAGZ,IAAA,YAAY;IASZ,OAAO,KAAK,CAAC,KAAa,EAAA;QACtB,MAAM,KAAK,GAAG,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC;AACvC,QAAA,IAAI,KAAK,KAAK,IAAI,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,4BAA4B,KAAK,CAAA,CAAE,CAAC;QACxD;QAEA,MAAM,UAAU,GAAG,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG;QACnC,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC;QAClD,MAAM,KAAK,GAAG,QAA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UAAA,CAAA;IADC,KAAK,CAAC,MAAM,CAAC;;AACa,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,mBAAA,EAAA,MAAA,CAAA;AAG3B,UAAA,CAAA;IADC,KAAK,CAAC,MAAM,CAAC;;AACY,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,kBAAA,EAAA,MAAA,CAAA;AAG1B,UAAA,CAAA;IADC,KAAK,CAAC,MAAM,CAAC;;AACQ,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,cAAA,EAAA,MAAA,CAAA;AAGtB,UAAA,CAAA;IADC,KAAK,CAAC,MAAM,CAAC;;AACQ,CAAA,EAAA,QAAA,CAAA,SAAA,EAAA,cAAA,EAAA,MAAA,CAAA;;"}
|
package/dist/esm/index.js
CHANGED
|
@@ -22,7 +22,7 @@ export { PropertyPathResolverProxyHandler } from './PropertyPathResolverProxyHan
|
|
|
22
22
|
export { TimeOnly } from './TimeOnly.js';
|
|
23
23
|
export { TimeSpan } from './TimeSpan.js';
|
|
24
24
|
export { ValueMap } from './ValueMap.js';
|
|
25
|
-
export { conceptAsTypeKey, declaredTypeKey, guidTypeKey, typeKey, typeKeyOf, valueMapTypeKey } from './typeKey.js';
|
|
25
|
+
export { conceptAsTypeKey, dateOnlyTypeKey, declaredTypeKey, guidTypeKey, timeOnlyTypeKey, timeSpanTypeKey, typeKey, typeKeyOf, valueMapTypeKey } from './typeKey.js';
|
|
26
26
|
export { field } from './fieldDecorator.js';
|
|
27
27
|
export { derivedType } from './derivedTypeDecorator.js';
|
|
28
28
|
export { JsonSerializer } from './JsonSerializer.js';
|
package/dist/esm/typeKey.d.ts
CHANGED
|
@@ -5,4 +5,7 @@ export declare const typeKeyOf: (type: Constructor | undefined) => string | unde
|
|
|
5
5
|
export declare const conceptAsTypeKey = "ConceptAs";
|
|
6
6
|
export declare const valueMapTypeKey = "ValueMap";
|
|
7
7
|
export declare const guidTypeKey = "Guid";
|
|
8
|
+
export declare const dateOnlyTypeKey = "DateOnly";
|
|
9
|
+
export declare const timeOnlyTypeKey = "TimeOnly";
|
|
10
|
+
export declare const timeSpanTypeKey = "TimeSpan";
|
|
8
11
|
//# sourceMappingURL=typeKey.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typeKey.d.ts","sourceRoot":"","sources":["../../typeKey.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAiB5C,eAAO,MAAM,OAAO,EAAE,OAAO,MAAmD,CAAC;AAcjF,eAAO,MAAM,eAAe,GAAI,MAAM,WAAW,GAAG,SAAS,KAAG,MAAM,GAAG,SACiC,CAAC;AAW3G,eAAO,MAAM,SAAS,GAAI,MAAM,WAAW,GAAG,SAAS,KAAG,MAAM,GAAG,SAChB,CAAC;AAGpD,eAAO,MAAM,gBAAgB,cAAc,CAAC;AAG5C,eAAO,MAAM,eAAe,aAAa,CAAC;AAG1C,eAAO,MAAM,WAAW,SAAS,CAAC"}
|
|
1
|
+
{"version":3,"file":"typeKey.d.ts","sourceRoot":"","sources":["../../typeKey.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAiB5C,eAAO,MAAM,OAAO,EAAE,OAAO,MAAmD,CAAC;AAcjF,eAAO,MAAM,eAAe,GAAI,MAAM,WAAW,GAAG,SAAS,KAAG,MAAM,GAAG,SACiC,CAAC;AAW3G,eAAO,MAAM,SAAS,GAAI,MAAM,WAAW,GAAG,SAAS,KAAG,MAAM,GAAG,SAChB,CAAC;AAGpD,eAAO,MAAM,gBAAgB,cAAc,CAAC;AAG5C,eAAO,MAAM,eAAe,aAAa,CAAC;AAG1C,eAAO,MAAM,WAAW,SAAS,CAAC;AAGlC,eAAO,MAAM,eAAe,aAAa,CAAC;AAG1C,eAAO,MAAM,eAAe,aAAa,CAAC;AAG1C,eAAO,MAAM,eAAe,aAAa,CAAC"}
|