@cratis/arc 22.13.1 → 22.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/README.md +5 -4
  2. package/dist/cjs/Globals.js.map +1 -1
  3. package/dist/cjs/UrlHelpers.js.map +1 -1
  4. package/dist/cjs/commands/Command.js.map +1 -1
  5. package/dist/cjs/commands/CommandResult.js.map +1 -1
  6. package/dist/cjs/commands/CommandResults.js.map +1 -1
  7. package/dist/cjs/commands/CommandValidator.js.map +1 -1
  8. package/dist/cjs/commands/index.js.map +1 -1
  9. package/dist/cjs/deepEqual.js.map +1 -1
  10. package/dist/cjs/identity/IIdentityProvider.js.map +1 -1
  11. package/dist/cjs/identity/IdentityProvider.js.map +1 -1
  12. package/dist/cjs/identity/index.js.map +1 -1
  13. package/dist/cjs/joinPaths.js.map +1 -1
  14. package/dist/cjs/messaging/IMessenger.js.map +1 -1
  15. package/dist/cjs/messaging/Message.js.map +1 -1
  16. package/dist/cjs/messaging/Messenger.js.map +1 -1
  17. package/dist/cjs/messaging/index.js.map +1 -1
  18. package/dist/cjs/queries/HubConnectionKeepAlive.js.map +1 -1
  19. package/dist/cjs/queries/IQueryProvider.js.map +1 -1
  20. package/dist/cjs/queries/NullObservableQueryConnection.js.map +1 -1
  21. package/dist/cjs/queries/ObservableQueryConnection.js.map +1 -1
  22. package/dist/cjs/queries/ObservableQueryConnectionFactory.js.map +1 -1
  23. package/dist/cjs/queries/ObservableQueryConnectionPool.js.map +1 -1
  24. package/dist/cjs/queries/ObservableQueryDiagnostics.js.map +1 -1
  25. package/dist/cjs/queries/ObservableQueryFor.js.map +1 -1
  26. package/dist/cjs/queries/ObservableQueryMultiplexer.js.map +1 -1
  27. package/dist/cjs/queries/ObservableQuerySubscription.js.map +1 -1
  28. package/dist/cjs/queries/Paging.js.map +1 -1
  29. package/dist/cjs/queries/PagingInfo.js.map +1 -1
  30. package/dist/cjs/queries/QueryFor.js.map +1 -1
  31. package/dist/cjs/queries/QueryHttpMethod.js.map +1 -1
  32. package/dist/cjs/queries/QueryHttpMethodResolver.js.map +1 -1
  33. package/dist/cjs/queries/QueryHttpRequest.js.map +1 -1
  34. package/dist/cjs/queries/QueryInstanceCache.js.map +1 -1
  35. package/dist/cjs/queries/QueryProvider.js.map +1 -1
  36. package/dist/cjs/queries/QueryResult.js.map +1 -1
  37. package/dist/cjs/queries/QueryResultWithState.js.map +1 -1
  38. package/dist/cjs/queries/QueryTransportMethod.js.map +1 -1
  39. package/dist/cjs/queries/QueryValidator.js.map +1 -1
  40. package/dist/cjs/queries/ReconnectPolicy.js.map +1 -1
  41. package/dist/cjs/queries/ServerSentEventHubConnection.js.map +1 -1
  42. package/dist/cjs/queries/ServerSentEventQueryConnection.js.map +1 -1
  43. package/dist/cjs/queries/SortDirection.js.map +1 -1
  44. package/dist/cjs/queries/Sorting.js.map +1 -1
  45. package/dist/cjs/queries/SortingActions.js.map +1 -1
  46. package/dist/cjs/queries/SortingActionsForObservableQuery.js.map +1 -1
  47. package/dist/cjs/queries/SortingActionsForQuery.js.map +1 -1
  48. package/dist/cjs/queries/ValidateRequestArguments.js.map +1 -1
  49. package/dist/cjs/queries/WebSocketHubConnection.js.map +1 -1
  50. package/dist/cjs/queries/WebSocketMessage.js.map +1 -1
  51. package/dist/cjs/queries/deserializeQueryModel.js.map +1 -1
  52. package/dist/cjs/queries/index.js.map +1 -1
  53. package/dist/cjs/queries/isAbortError.js.map +1 -1
  54. package/dist/cjs/queries/reconcileQueryData.js.map +1 -1
  55. package/dist/cjs/reflection/ParameterDescriptor.js.map +1 -1
  56. package/dist/cjs/reflection/ParametersHelper.js.map +1 -1
  57. package/dist/cjs/reflection/PropertyDescriptor.js.map +1 -1
  58. package/dist/cjs/reflection/index.js.map +1 -1
  59. package/dist/cjs/validation/PropertyRule.js.map +1 -1
  60. package/dist/cjs/validation/PropertyValidator.js.map +1 -1
  61. package/dist/cjs/validation/RuleBuilder.js.map +1 -1
  62. package/dist/cjs/validation/RuleBuilderExtensions.js.map +1 -1
  63. package/dist/cjs/validation/ValidationResult.js.map +1 -1
  64. package/dist/cjs/validation/ValidationResultReason.js.map +1 -1
  65. package/dist/cjs/validation/ValidationResultSeverity.js.map +1 -1
  66. package/dist/cjs/validation/Validator.js.map +1 -1
  67. package/dist/cjs/validation/index.js.map +1 -1
  68. package/dist/cjs/validation/rules/ComparisonRules.js.map +1 -1
  69. package/dist/cjs/validation/rules/EmailRule.js.map +1 -1
  70. package/dist/cjs/validation/rules/LengthRules.js.map +1 -1
  71. package/dist/cjs/validation/rules/NotEmptyRule.js.map +1 -1
  72. package/dist/cjs/validation/rules/PhoneRule.js.map +1 -1
  73. package/dist/cjs/validation/rules/RegexRule.js.map +1 -1
  74. package/dist/cjs/validation/rules/UrlRule.js.map +1 -1
  75. package/dist/esm/Globals.js.map +1 -1
  76. package/dist/esm/UrlHelpers.js.map +1 -1
  77. package/dist/esm/commands/Command.js.map +1 -1
  78. package/dist/esm/commands/CommandResult.js.map +1 -1
  79. package/dist/esm/commands/CommandResults.js.map +1 -1
  80. package/dist/esm/commands/CommandValidator.js.map +1 -1
  81. package/dist/esm/deepEqual.js.map +1 -1
  82. package/dist/esm/identity/IIdentityProvider.js.map +1 -1
  83. package/dist/esm/identity/IdentityProvider.js.map +1 -1
  84. package/dist/esm/joinPaths.js.map +1 -1
  85. package/dist/esm/messaging/IMessenger.js.map +1 -1
  86. package/dist/esm/messaging/Message.js.map +1 -1
  87. package/dist/esm/messaging/Messenger.js.map +1 -1
  88. package/dist/esm/queries/HubConnectionKeepAlive.js.map +1 -1
  89. package/dist/esm/queries/IQueryProvider.js.map +1 -1
  90. package/dist/esm/queries/NullObservableQueryConnection.js.map +1 -1
  91. package/dist/esm/queries/ObservableQueryConnection.js.map +1 -1
  92. package/dist/esm/queries/ObservableQueryConnectionFactory.js.map +1 -1
  93. package/dist/esm/queries/ObservableQueryConnectionPool.js.map +1 -1
  94. package/dist/esm/queries/ObservableQueryDiagnostics.js.map +1 -1
  95. package/dist/esm/queries/ObservableQueryFor.js.map +1 -1
  96. package/dist/esm/queries/ObservableQueryMultiplexer.js.map +1 -1
  97. package/dist/esm/queries/ObservableQuerySubscription.js.map +1 -1
  98. package/dist/esm/queries/Paging.js.map +1 -1
  99. package/dist/esm/queries/PagingInfo.js.map +1 -1
  100. package/dist/esm/queries/QueryFor.js.map +1 -1
  101. package/dist/esm/queries/QueryHttpMethod.js.map +1 -1
  102. package/dist/esm/queries/QueryHttpMethodResolver.js.map +1 -1
  103. package/dist/esm/queries/QueryHttpRequest.js.map +1 -1
  104. package/dist/esm/queries/QueryInstanceCache.js.map +1 -1
  105. package/dist/esm/queries/QueryProvider.js.map +1 -1
  106. package/dist/esm/queries/QueryResult.js.map +1 -1
  107. package/dist/esm/queries/QueryResultWithState.js.map +1 -1
  108. package/dist/esm/queries/QueryTransportMethod.js.map +1 -1
  109. package/dist/esm/queries/QueryValidator.js.map +1 -1
  110. package/dist/esm/queries/ReconnectPolicy.js.map +1 -1
  111. package/dist/esm/queries/ServerSentEventHubConnection.js.map +1 -1
  112. package/dist/esm/queries/ServerSentEventQueryConnection.js.map +1 -1
  113. package/dist/esm/queries/SortDirection.js.map +1 -1
  114. package/dist/esm/queries/Sorting.js.map +1 -1
  115. package/dist/esm/queries/SortingActions.js.map +1 -1
  116. package/dist/esm/queries/SortingActionsForObservableQuery.js.map +1 -1
  117. package/dist/esm/queries/SortingActionsForQuery.js.map +1 -1
  118. package/dist/esm/queries/ValidateRequestArguments.js.map +1 -1
  119. package/dist/esm/queries/WebSocketHubConnection.js.map +1 -1
  120. package/dist/esm/queries/WebSocketMessage.js.map +1 -1
  121. package/dist/esm/queries/deserializeQueryModel.js.map +1 -1
  122. package/dist/esm/queries/isAbortError.js.map +1 -1
  123. package/dist/esm/queries/reconcileQueryData.js.map +1 -1
  124. package/dist/esm/reflection/ParameterDescriptor.js.map +1 -1
  125. package/dist/esm/reflection/ParametersHelper.js.map +1 -1
  126. package/dist/esm/reflection/PropertyDescriptor.js.map +1 -1
  127. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  128. package/dist/esm/validation/PropertyRule.js.map +1 -1
  129. package/dist/esm/validation/PropertyValidator.js.map +1 -1
  130. package/dist/esm/validation/RuleBuilder.js.map +1 -1
  131. package/dist/esm/validation/RuleBuilderExtensions.js.map +1 -1
  132. package/dist/esm/validation/ValidationResult.js.map +1 -1
  133. package/dist/esm/validation/ValidationResultReason.js.map +1 -1
  134. package/dist/esm/validation/ValidationResultSeverity.js.map +1 -1
  135. package/dist/esm/validation/Validator.js.map +1 -1
  136. package/dist/esm/validation/rules/ComparisonRules.js.map +1 -1
  137. package/dist/esm/validation/rules/EmailRule.js.map +1 -1
  138. package/dist/esm/validation/rules/LengthRules.js.map +1 -1
  139. package/dist/esm/validation/rules/NotEmptyRule.js.map +1 -1
  140. package/dist/esm/validation/rules/PhoneRule.js.map +1 -1
  141. package/dist/esm/validation/rules/RegexRule.js.map +1 -1
  142. package/dist/esm/validation/rules/UrlRule.js.map +1 -1
  143. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"LengthRules.js","sources":["../../../../validation/rules/LengthRules.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 { PropertyRule } from '../PropertyRule';\n\n/**\n * Validation rule that checks if a string has a minimum length.\n * @template T The type being validated.\n */\nexport class MinLengthRule<T> extends PropertyRule<T, string> {\n /**\n * Initializes a new instance of the {@link MinLengthRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n * @param minLength The minimum length required.\n */\n constructor(propertyAccessor: (instance: T) => string, private readonly minLength: number) {\n super(propertyAccessor, `'{PropertyName}' must be at least ${minLength} characters.`);\n }\n\n /** @inheritdoc */\n protected isValid(value: string): boolean {\n if (value === null || value === undefined) {\n return true; // Use NotNull/NotEmpty for null checks\n }\n return value.length >= this.minLength;\n }\n}\n\n/**\n * Validation rule that checks if a string has a maximum length.\n * @template T The type being validated.\n */\nexport class MaxLengthRule<T> extends PropertyRule<T, string> {\n /**\n * Initializes a new instance of the {@link MaxLengthRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n * @param maxLength The maximum length allowed.\n */\n constructor(propertyAccessor: (instance: T) => string, private readonly maxLength: number) {\n super(propertyAccessor, `'{PropertyName}' must be at most ${maxLength} characters.`);\n }\n\n /** @inheritdoc */\n protected isValid(value: string): boolean {\n if (value === null || value === undefined) {\n return true; // Use NotNull/NotEmpty for null checks\n }\n return value.length <= this.maxLength;\n }\n}\n\n/**\n * Validation rule that checks if a string has an exact length.\n * @template T The type being validated.\n */\nexport class LengthRule<T> extends PropertyRule<T, string> {\n /**\n * Initializes a new instance of the {@link LengthRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n * @param min The minimum length required.\n * @param max The maximum length allowed.\n */\n constructor(propertyAccessor: (instance: T) => string, private readonly min: number, private readonly max: number) {\n super(propertyAccessor, `'{PropertyName}' must be between ${min} and ${max} characters.`);\n }\n\n /** @inheritdoc */\n protected isValid(value: string): boolean {\n if (value === null || value === undefined) {\n return true; // Use NotNull/NotEmpty for null checks\n }\n return value.length >= this.min && value.length <= this.max;\n }\n}\n"],"names":["MinLengthRule","PropertyRule","propertyAccessor","minLength","isValid","value","undefined","length","MaxLengthRule","maxLength","LengthRule","min","max"],"mappings":";;;;AAAA;AACA;AAIA;;;IAIO,MAAMA,aAAAA,SAAyBC,yBAAAA,CAAAA;;AAClC;;;;AAIC,QACD,WAAA,CAAYC,gBAAyC,EAAmBC,SAAiB,CAAE;QACvF,KAAK,CAACD,kBAAkB,CAAC,kCAAkC,EAAEC,SAAAA,CAAU,YAAY,CAAC,CAAA,EAAA,IAAA,CADhBA,SAAAA,GAAAA,SAAAA;AAExE,IAAA;AAEA,uBACUC,OAAAA,CAAQC,KAAa,EAAW;QACtC,IAAIA,KAAAA,KAAU,IAAA,IAAQA,KAAAA,KAAUC,SAAAA,EAAW;AACvC,YAAA,OA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yright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { PropertyRule } from '../PropertyRule';\n\n/**\n * Validation rule that checks if a string has a minimum length.\n * @template T The type being validated.\n */\nexport class MinLengthRule<T> extends PropertyRule<T, string> {\n /**\n * Initializes a new instance of the {@link MinLengthRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n * @param minLength The minimum length required.\n */\n constructor(propertyAccessor: (instance: T) => string, private readonly minLength: number) {\n super(propertyAccessor, `'{PropertyName}' must be at least ${minLength} characters.`);\n }\n\n /** @inheritdoc */\n protected isValid(value: string): boolean {\n if (value === null || value === undefined) {\n return true; // Use NotNull/NotEmpty for null checks\n }\n return value.length >= this.minLength;\n }\n}\n\n/**\n * Validation rule that checks if a string has a maximum length.\n * @template T The type being validated.\n */\nexport class MaxLengthRule<T> extends PropertyRule<T, string> {\n /**\n * Initializes a new instance of the {@link MaxLengthRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n * @param maxLength The maximum length allowed.\n */\n constructor(propertyAccessor: (instance: T) => string, private readonly maxLength: number) {\n super(propertyAccessor, `'{PropertyName}' must be at most ${maxLength} characters.`);\n }\n\n /** @inheritdoc */\n protected isValid(value: string): boolean {\n if (value === null || value === undefined) {\n return true; // Use NotNull/NotEmpty for null checks\n }\n return value.length <= this.maxLength;\n }\n}\n\n/**\n * Validation rule that checks if a string has an exact length.\n * @template T The type being validated.\n */\nexport class LengthRule<T> extends PropertyRule<T, string> {\n /**\n * Initializes a new instance of the {@link LengthRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n * @param min The minimum length required.\n * @param max The maximum length allowed.\n */\n constructor(propertyAccessor: (instance: T) => string, private readonly min: number, private readonly max: number) {\n super(propertyAccessor, `'{PropertyName}' must be between ${min} and ${max} characters.`);\n }\n\n /** @inheritdoc */\n protected isValid(value: string): boolean {\n if (value === null || value === undefined) {\n return true; // Use NotNull/NotEmpty for null checks\n }\n return value.length >= this.min && value.length <= this.max;\n }\n}\n"],"names":["MinLengthRule","PropertyRule","propertyAccessor","minLength","isValid","value","undefined","length","MaxLengthRule","maxLength","LengthRule","min","max"],"mappings":";;;;AAAA;AACA;AAIA;;;IAIO,MAAMA,aAAAA,SAAyBC,yBAAAA,CAAAA;;AAClC;;;;AAIC,QACD,WAAA,CAAYC,gBAAyC,EAAmBC,SAAiB,CAAE;QACvF,KAAK,CAACD,kBAAkB,CAAC,kCAAkC,EAAEC,SAAAA,CAAU,YAAY,CAAC,CAAA,EAAA,IAAA,CADhBA,SAAAA,GAAAA,SAAAA;AAExE,IAAA;AAEA,uBACUC,OAAAA,CAAQC,KAAa,EAAW;QACtC,IAAIA,KAAAA,KAAU,IAAA,IAAQA,KAAAA,KAAUC,SAAAA,EAAW;AACvC,YAAA,OAAO;AACX,QAAA;AACA,QAAA,OAAOD,KAAAA,CAAME,MAAM,IAAI,IAAI,CAACJ,SAAS;AACzC,IAAA;AACJ;AAEA;;;IAIO,MAAMK,aAAAA,SAAyBP,yBAAAA,CAAAA;;AAClC;;;;AAIC,QACD,WAAA,CAAYC,gBAAyC,EAAmBO,SAAiB,CAAE;QACvF,KAAK,CAACP,kBAAkB,CAAC,iCAAiC,EAAEO,SAAAA,CAAU,YAAY,CAAC,CAAA,EAAA,IAAA,CADfA,SAAAA,GAAAA,SAAAA;AAExE,IAAA;AAEA,uBACUL,OAAAA,CAAQC,KAAa,EAAW;QACtC,IAAIA,KAAAA,KAAU,IAAA,IAAQA,KAAAA,KAAUC,SAAAA,EAAW;AACvC,YAAA,OAAO;AACX,QAAA;AACA,QAAA,OAAOD,KAAAA,CAAME,MAAM,IAAI,IAAI,CAACE,SAAS;AACzC,IAAA;AACJ;AAEA;;;IAIO,MAAMC,UAAAA,SAAsBT,yBAAAA,CAAAA;;;AAC/B;;;;;QAMA,WAAA,CAAYC,gBAAyC,EAAmBS,GAAW,EAAmBC,GAAW,CAAE;AAC/G,QAAA,KAAK,CAACV,gBAAAA,EAAkB,CAAC,iCAAiC,EAAES,GAAAA,CAAI,KAAK,EAAEC,GAAAA,CAAI,YAAY,CAAC,CAAA,EAAA,IAAA,CADpBD,GAAAA,GAAAA,UAA8BC,GAAAA,GAAAA,GAAAA;AAEtG,IAAA;AAEA,uBACUR,OAAAA,CAAQC,KAAa,EAAW;QACtC,IAAIA,KAAAA,KAAU,IAAA,IAAQA,KAAAA,KAAUC,SAAAA,EAAW;AACvC,YAAA,OAAO;AACX,QAAA;AACA,QAAA,OAAOD,KAAAA,CAAME,MAAM,IAAI,IAAI,CAACI,GAAG,IAAIN,KAAAA,CAAME,MAAM,IAAI,IAAI,CAACK,GAAG;AAC/D,IAAA;AACJ;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"NotEmptyRule.js","sources":["../../../../validation/rules/NotEmptyRule.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 { PropertyRule } from '../PropertyRule';\n\n/**\n * Validation rule that checks if a value is not null, undefined, or empty.\n * @template T The type being validated.\n */\nexport class NotEmptyRule<T> extends PropertyRule<T, unknown> {\n /**\n * Initializes a new instance of the {@link NotEmptyRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n */\n constructor(propertyAccessor: (instance: T) => unknown) {\n super(propertyAccessor, \"'{PropertyName}' must not be empty.\");\n }\n\n /** @inheritdoc */\n protected isValid(value: unknown): boolean {\n if (value === null || value === undefined) {\n return false;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return false;\n }\n if (Array.isArray(value) && value.length === 0) {\n return false;\n }\n return true;\n }\n}\n\n/**\n * Validation rule that checks if a value is not null or undefined.\n * @template T The type being validated.\n */\nexport class NotNullRule<T> extends PropertyRule<T, unknown> {\n /**\n * Initializes a new instance of the {@link NotNullRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n */\n constructor(propertyAccessor: (instance: T) => unknown) {\n super(propertyAccessor, \"'{PropertyName}' must not be empty.\");\n }\n\n /** @inheritdoc */\n protected isValid(value: unknown): boolean {\n return value !== null && value !== undefined;\n }\n}\n"],"names":["NotEmptyRule","PropertyRule","propertyAccessor","isValid","value","undefined","trim","Array","isArray","length","NotNullRule"],"mappings":";;;;AAAA;AACA;AAIA;;;IAIO,MAAMA,YAAAA,SAAwBC,yBAAAA,CAAAA;AACjC;;;QAIA,WAAA,CAAYC,gBAA0C,CAAE;AACpD,QAAA,KAAK,CAACA,gBAAAA,EAAkB,qCAAA,CAAA;AAC5B,IAAA;AAEA,uBACUC,OAAAA,CAAQC,KAAc,EAAW;QACvC,IAAIA,KAAAA,KAAU,IAAA,IAAQA,KAAAA,KAAUC,SAAAA,EAAW;YACvC,OAAO,KAAA;AACX,QAAA;AACA,QAAA,IAAI,OAAOD,KAAAA,KAAU,QAAA,IAAYA,KAAAA,CAAME,IAAI,OAAO,EAAA,EAAI;YAClD,OAAO,KAAA;AACX,QAAA;AACA,QAAA,IAAIC,MAAMC,OAAO,CAACJ,UAAUA,KAAAA,CAAMK,MAAM,KAAK,CAAA,EAAG;YAC5C,OAAO,KAAA;AACX,QAAA;QACA,OAAO,IAAA;AACX,IAAA;AACJ;AAEA;;;IAIO,MAAMC,WAAAA,SAAuBT,yBAAAA,CAAAA;AAChC;;;QAIA,WAAA,CAAYC,gBAA0C,CAAE;AACpD,QAAA,KAAK,CAACA,gBAAAA,EAAkB,qCAAA,CAAA;AAC5B,IAAA;AAEA,uBACUC,OAAAA,CAAQC,KAAc,EAAW;QACvC,OAAOA,KAAAA,KAAU,QAAQA,KAAAA,KAAUC,SAAAA;AACvC,IAAA;AACJ;;;;;"}
1
+ {"version":3,"file":"NotEmptyRule.js","sources":["../../../../validation/rules/NotEmptyRule.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 { PropertyRule } from '../PropertyRule';\n\n/**\n * Validation rule that checks if a value is not null, undefined, or empty.\n * @template T The type being validated.\n */\nexport class NotEmptyRule<T> extends PropertyRule<T, unknown> {\n /**\n * Initializes a new instance of the {@link NotEmptyRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n */\n constructor(propertyAccessor: (instance: T) => unknown) {\n super(propertyAccessor, \"'{PropertyName}' must not be empty.\");\n }\n\n /** @inheritdoc */\n protected isValid(value: unknown): boolean {\n if (value === null || value === undefined) {\n return false;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return false;\n }\n if (Array.isArray(value) && value.length === 0) {\n return false;\n }\n return true;\n }\n}\n\n/**\n * Validation rule that checks if a value is not null or undefined.\n * @template T The type being validated.\n */\nexport class NotNullRule<T> extends PropertyRule<T, unknown> {\n /**\n * Initializes a new instance of the {@link NotNullRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n */\n constructor(propertyAccessor: (instance: T) => unknown) {\n super(propertyAccessor, \"'{PropertyName}' must not be empty.\");\n }\n\n /** @inheritdoc */\n protected isValid(value: unknown): boolean {\n return value !== null && value !== undefined;\n }\n}\n"],"names":["NotEmptyRule","PropertyRule","propertyAccessor","isValid","value","undefined","trim","Array","isArray","length","NotNullRule"],"mappings":";;;;AAAA;AACA;AAIA;;;IAIO,MAAMA,YAAAA,SAAwBC,yBAAAA,CAAAA;AACjC;;;QAIA,WAAA,CAAYC,gBAA0C,CAAE;AACpD,QAAA,KAAK,CAACA,gBAAAA,EAAkB,qCAAA,CAAA;AAC5B,IAAA;AAEA,uBACUC,OAAAA,CAAQC,KAAc,EAAW;QACvC,IAAIA,KAAAA,KAAU,IAAA,IAAQA,KAAAA,KAAUC,SAAAA,EAAW;YACvC,OAAO,KAAA;AACX,QAAA;AACA,QAAA,IAAI,OAAOD,KAAAA,KAAU,QAAA,IAAYA,KAAAA,CAAME,IAAI,OAAO,EAAA,EAAI;YAClD,OAAO,KAAA;AACX,QAAA;AACA,QAAA,IAAIC,MAAMC,OAAO,CAACJ,UAAUA,KAAAA,CAAMK,MAAM,KAAK,CAAA,EAAG;YAC5C,OAAO,KAAA;AACX,QAAA;QACA,OAAO,IAAA;AACX,IAAA;AACJ;AAEA;;;IAIO,MAAMC,WAAAA,SAAuBT,yBAAAA,CAAAA;AAChC;;;QAIA,WAAA,CAAYC,gBAA0C,CAAE;AACpD,QAAA,KAAK,CAACA,gBAAAA,EAAkB,qCAAA,CAAA;AAC5B,IAAA;AAEA,uBACUC,OAAAA,CAAQC,KAAc,EAAW;QACvC,OAAOA,KAAAA,KAAU,QAAQA,KAAAA,KAAUC,SAAAA;AACvC,IAAA;AACJ;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"PhoneRule.js","sources":["../../../../validation/rules/PhoneRule.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 { PropertyRule } from '../PropertyRule';\n\n/**\n * Validation rule that checks if a string matches a phone number pattern.\n * @template T The type being validated.\n */\nexport class PhoneRule<T> extends PropertyRule<T, string> {\n private static readonly phoneRegex = /^[\\d\\s()+-]+$/;\n\n /**\n * Initializes a new instance of the {@link PhoneRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n */\n constructor(propertyAccessor: (instance: T) => string) {\n super(propertyAccessor, \"'{PropertyName}' is not a valid phone number.\");\n }\n\n /** @inheritdoc */\n protected isValid(value: string): boolean {\n if (value === null || value === undefined || value === '') {\n return true; // Use NotNull/NotEmpty for null checks\n }\n return PhoneRule.phoneRegex.test(value);\n }\n}\n"],"names":["PhoneRule","PropertyRule","phoneRegex","propertyAccessor","isValid","value","undefined","test"],"mappings":";;;;AAAA;AACA;AAIA;;;IAIO,MAAMA,SAAAA,SAAqBC,yBAAAA,CAAAA;AAC9B,IAAA,OAAwBC,aAAa,eAAA;AAErC;;;QAIA,WAAA,CAAYC,gBAAyC,CAAE;AACnD,QAAA,KAAK,CAACA,gBAAAA,EAAkB,+CAAA,CAAA;AAC5B,IAAA;AAEA,uBACUC,OAAAA,CAAQC,KAAa,EAAW;AACtC,QAAA,IAAIA,KAAAA,KAAU,IAAA,IAAQA,KAAAA,KAAUC,SAAAA,IAAaD,UAAU,EAAA,EAAI;AACvD,YAAA,OAAO;AACX,QAAA;AACA,QAAA,OAAOL,SAAAA,CAAUE,UAAU,CAACK,IAAI,CAACF,KAAAA,CAAAA;AACrC,IAAA;AACJ;;;;"}
1
+ {"version":3,"file":"PhoneRule.js","sources":["../../../../validation/rules/PhoneRule.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 { PropertyRule } from '../PropertyRule';\n\n/**\n * Validation rule that checks if a string matches a phone number pattern.\n * @template T The type being validated.\n */\nexport class PhoneRule<T> extends PropertyRule<T, string> {\n private static readonly phoneRegex = /^[\\d\\s()+-]+$/;\n\n /**\n * Initializes a new instance of the {@link PhoneRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n */\n constructor(propertyAccessor: (instance: T) => string) {\n super(propertyAccessor, \"'{PropertyName}' is not a valid phone number.\");\n }\n\n /** @inheritdoc */\n protected isValid(value: string): boolean {\n if (value === null || value === undefined || value === '') {\n return true; // Use NotNull/NotEmpty for null checks\n }\n return PhoneRule.phoneRegex.test(value);\n }\n}\n"],"names":["PhoneRule","PropertyRule","phoneRegex","propertyAccessor","isValid","value","undefined","test"],"mappings":";;;;AAAA;AACA;AAIA;;;IAIO,MAAMA,SAAAA,SAAqBC,yBAAAA,CAAAA;AAC9B,IAAA,OAAwBC,aAAa,eAAA;AAErC;;;QAIA,WAAA,CAAYC,gBAAyC,CAAE;AACnD,QAAA,KAAK,CAACA,gBAAAA,EAAkB,+CAAA,CAAA;AAC5B,IAAA;AAEA,uBACUC,OAAAA,CAAQC,KAAa,EAAW;AACtC,QAAA,IAAIA,KAAAA,KAAU,IAAA,IAAQA,KAAAA,KAAUC,SAAAA,IAAaD,UAAU,EAAA,EAAI;AACvD,YAAA,OAAO;AACX,QAAA;AACA,QAAA,OAAOL,SAAAA,CAAUE,UAAU,CAACK,IAAI,CAACF,KAAAA,CAAAA;AACrC,IAAA;AACJ;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"RegexRule.js","sources":["../../../../validation/rules/RegexRule.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 { PropertyRule } from '../PropertyRule';\n\n/**\n * Validation rule that checks if a value matches a regular expression.\n * @template T The type being validated.\n */\nexport class RegexRule<T> extends PropertyRule<T, string> {\n /**\n * Initializes a new instance of the {@link RegexRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n * @param pattern The regular expression pattern to match.\n * @param errorMessage Optional error message.\n */\n constructor(propertyAccessor: (instance: T) => string, private readonly pattern: RegExp, errorMessage?: string) {\n super(propertyAccessor, errorMessage || \"'{PropertyName}' is not in the correct format.\");\n }\n\n /** @inheritdoc */\n protected isValid(value: string): boolean {\n if (value === null || value === undefined || value === '') {\n return true; // Use NotNull/NotEmpty for null checks\n }\n return this.pattern.test(value);\n }\n}\n"],"names":["RegexRule","PropertyRule","propertyAccessor","errorMessage","pattern","isValid","value","undefined","test"],"mappings":";;;;AAAA;AACA;AAIA;;;IAIO,MAAMA,SAAAA,SAAqBC,yBAAAA,CAAAA;;AAC9B;;;;;AAKC,QACD,YAAYC,gBAAyC,EAAE,OAAgC,EAAEC,YAAqB,CAAE;AAC5G,QAAA,KAAK,CAACD,gBAAAA,EAAkBC,YAAAA,IAAgB,gDAAA,CAAA,EAAA,IAAA,CAD4BC,OAAAA,GAAAA,OAAAA;AAExE,IAAA;AAEA,uBACUC,OAAAA,CAAQC,KAAa,EAAW;AACtC,QAAA,IAAIA,KAAAA,KAAU,IAAA,IAAQA,KAAAA,KAAUC,SAAAA,IAAaD,UAAU,EAAA,EAAI;AACvD,YAAA,OAAO;AACX,QAAA;AACA,QAAA,OAAO,IAAI,CAACF,OAAO,CAACI,IAAI,CAACF,KAAAA,CAAAA;AAC7B,IAAA;AACJ;;;;"}
1
+ {"version":3,"file":"RegexRule.js","sources":["../../../../validation/rules/RegexRule.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 { PropertyRule } from '../PropertyRule';\n\n/**\n * Validation rule that checks if a value matches a regular expression.\n * @template T The type being validated.\n */\nexport class RegexRule<T> extends PropertyRule<T, string> {\n /**\n * Initializes a new instance of the {@link RegexRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n * @param pattern The regular expression pattern to match.\n * @param errorMessage Optional error message.\n */\n constructor(propertyAccessor: (instance: T) => string, private readonly pattern: RegExp, errorMessage?: string) {\n super(propertyAccessor, errorMessage || \"'{PropertyName}' is not in the correct format.\");\n }\n\n /** @inheritdoc */\n protected isValid(value: string): boolean {\n if (value === null || value === undefined || value === '') {\n return true; // Use NotNull/NotEmpty for null checks\n }\n return this.pattern.test(value);\n }\n}\n"],"names":["RegexRule","PropertyRule","propertyAccessor","errorMessage","pattern","isValid","value","undefined","test"],"mappings":";;;;AAAA;AACA;AAIA;;;IAIO,MAAMA,SAAAA,SAAqBC,yBAAAA,CAAAA;;AAC9B;;;;;AAKC,QACD,YAAYC,gBAAyC,EAAE,OAAgC,EAAEC,YAAqB,CAAE;AAC5G,QAAA,KAAK,CAACD,gBAAAA,EAAkBC,YAAAA,IAAgB,gDAAA,CAAA,EAAA,IAAA,CAD4BC,OAAAA,GAAAA,OAAAA;AAExE,IAAA;AAEA,uBACUC,OAAAA,CAAQC,KAAa,EAAW;AACtC,QAAA,IAAIA,KAAAA,KAAU,IAAA,IAAQA,KAAAA,KAAUC,SAAAA,IAAaD,UAAU,EAAA,EAAI;AACvD,YAAA,OAAO;AACX,QAAA;AACA,QAAA,OAAO,IAAI,CAACF,OAAO,CAACI,IAAI,CAACF,KAAAA,CAAAA;AAC7B,IAAA;AACJ;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"UrlRule.js","sources":["../../../../validation/rules/UrlRule.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 { PropertyRule } from '../PropertyRule';\n\n/**\n * Validation rule that checks if a string is a valid URL.\n * @template T The type being validated.\n */\nexport class UrlRule<T> extends PropertyRule<T, string> {\n private static readonly urlRegex = /^https?:\\/\\/.+/i;\n\n /**\n * Initializes a new instance of the {@link UrlRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n */\n constructor(propertyAccessor: (instance: T) => string) {\n super(propertyAccessor, \"'{PropertyName}' is not a valid URL.\");\n }\n\n /** @inheritdoc */\n protected isValid(value: string): boolean {\n if (value === null || value === undefined || value === '') {\n return true; // Use NotNull/NotEmpty for null checks\n }\n return UrlRule.urlRegex.test(value);\n }\n}\n"],"names":["UrlRule","PropertyRule","urlRegex","propertyAccessor","isValid","value","undefined","test"],"mappings":";;;;AAAA;AACA;AAIA;;;IAIO,MAAMA,OAAAA,SAAmBC,yBAAAA,CAAAA;AAC5B,IAAA,OAAwBC,WAAW,iBAAA;AAEnC;;;QAIA,WAAA,CAAYC,gBAAyC,CAAE;AACnD,QAAA,KAAK,CAACA,gBAAAA,EAAkB,sCAAA,CAAA;AAC5B,IAAA;AAEA,uBACUC,OAAAA,CAAQC,KAAa,EAAW;AACtC,QAAA,IAAIA,KAAAA,KAAU,IAAA,IAAQA,KAAAA,KAAUC,SAAAA,IAAaD,UAAU,EAAA,EAAI;AACvD,YAAA,OAAO;AACX,QAAA;AACA,QAAA,OAAOL,OAAAA,CAAQE,QAAQ,CAACK,IAAI,CAACF,KAAAA,CAAAA;AACjC,IAAA;AACJ;;;;"}
1
+ {"version":3,"file":"UrlRule.js","sources":["../../../../validation/rules/UrlRule.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 { PropertyRule } from '../PropertyRule';\n\n/**\n * Validation rule that checks if a string is a valid URL.\n * @template T The type being validated.\n */\nexport class UrlRule<T> extends PropertyRule<T, string> {\n private static readonly urlRegex = /^https?:\\/\\/.+/i;\n\n /**\n * Initializes a new instance of the {@link UrlRule} class.\n * @param propertyAccessor Function to access the property value from the instance.\n */\n constructor(propertyAccessor: (instance: T) => string) {\n super(propertyAccessor, \"'{PropertyName}' is not a valid URL.\");\n }\n\n /** @inheritdoc */\n protected isValid(value: string): boolean {\n if (value === null || value === undefined || value === '') {\n return true; // Use NotNull/NotEmpty for null checks\n }\n return UrlRule.urlRegex.test(value);\n }\n}\n"],"names":["UrlRule","PropertyRule","urlRegex","propertyAccessor","isValid","value","undefined","test"],"mappings":";;;;AAAA;AACA;AAIA;;;IAIO,MAAMA,OAAAA,SAAmBC,yBAAAA,CAAAA;AAC5B,IAAA,OAAwBC,WAAW,iBAAA;AAEnC;;;QAIA,WAAA,CAAYC,gBAAyC,CAAE;AACnD,QAAA,KAAK,CAACA,gBAAAA,EAAkB,sCAAA,CAAA;AAC5B,IAAA;AAEA,uBACUC,OAAAA,CAAQC,KAAa,EAAW;AACtC,QAAA,IAAIA,KAAAA,KAAU,IAAA,IAAQA,KAAAA,KAAUC,SAAAA,IAAaD,UAAU,EAAA,EAAI;AACvD,YAAA,OAAO;AACX,QAAA;AACA,QAAA,OAAOL,OAAAA,CAAQE,QAAQ,CAACK,IAAI,CAACF,KAAAA,CAAAA;AACjC,IAAA;AACJ;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"Globals.js","sources":["../../Globals.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 { GetHttpHeaders } from './GetHttpHeaders';\nimport { EventSourceFactory } from './EventSourceFactory';\nimport { QueryTransportMethod } from './queries/QueryTransportMethod';\nimport { QueryHttpMethod } from './queries/QueryHttpMethod';\nimport { QueryHttpMethodResolver } from './queries/QueryHttpMethodResolver';\n\n/**\n * Defines the transfer mode used for observable query subscriptions.\n *\n * - {@link ObservableQueryTransferMode.Delta} (default): Only the items that changed since\n * the previous update (added, replaced, removed) are exposed via {@code useChangeStream}.\n * The full collection state is still maintained internally by {@code useObservableQuery}.\n *\n * - {@link ObservableQueryTransferMode.Full}: Every update delivers the complete current\n * collection. The change set returned by {@code useChangeStream} treats the entire new\n * collection as {@code added} and the previous collection as {@code removed}.\n */\nexport enum ObservableQueryTransferMode {\n /** Compute and expose only the items that changed since the previous update (default). */\n Delta = 'delta',\n /** Expose the full collection on every update. */\n Full = 'full',\n}\n\nexport interface IGlobals {\n microservice: string;\n apiBasePath: string;\n origin: string;\n microserviceHttpHeader: string;\n microserviceWSQueryArgument: string;\n queryTransportMethod: QueryTransportMethod;\n /**\n * The HTTP method used to perform non-streaming queries. Defaults to {@link QueryHttpMethod.Get}.\n * Set to {@link QueryHttpMethod.Query} to carry arguments in a JSON request body (RFC 10008)\n * instead of the URL query string. Individual queries can override this via {@code setHttpMethod}.\n */\n queryHttpMethod: QueryHttpMethod;\n /**\n * Optional per-query policy for choosing the query HTTP method from the request (e.g. by URL length).\n * Consulted only when a query has no explicit method set via {@code setHttpMethod}; it takes\n * precedence over {@link queryHttpMethod}. See {@link lengthBasedQueryHttpMethod} for a built-in.\n */\n queryHttpMethodResolver?: QueryHttpMethodResolver;\n /**\n * Number of hub connections maintained for observable queries.\n * When greater than one, queries are distributed across the pool round-robin.\n * Only applies when {@link queryTransportMethod} is a centralized hub transport.\n * Defaults to 1.\n */\n queryConnectionCount: number;\n /**\n * When true, observable queries connect directly to the per-query WebSocket URL\n * instead of routing through the centralized hub endpoint.\n * Defaults to false (use the centralized hub).\n */\n queryDirectMode: boolean;\n /**\n * Controls how observable query updates are transferred and exposed.\n * {@link ObservableQueryTransferMode.Delta} (default) computes per-update deltas;\n * {@link ObservableQueryTransferMode.Full} delivers the whole collection on every update.\n */\n observableQueryTransferMode: ObservableQueryTransferMode;\n /**\n * Callback that returns custom HTTP headers to include in hub transport requests\n * (e.g. SSE subscribe/unsubscribe POST calls).\n */\n httpHeadersCallback: GetHttpHeaders;\n /**\n * Optional factory used to create the {@link EventSource} instances that back SSE\n * observable query connections. Falls back to the global {@link EventSource}\n * constructor when not set — override it to supply a custom SSE client (e.g. a\n * native implementation on React Native, where the global constructor is unavailable).\n */\n eventSourceFactory?: EventSourceFactory;\n /**\n * How long in milliseconds to retain a query cache entry after the last subscriber\n * releases it before evicting the subscription and the cached data.\n *\n * A non-zero value allows a user navigating away and back quickly to see cached\n * data immediately instead of waiting for a fresh server round-trip. The entry is\n * still evicted once the window expires, so memory is eventually reclaimed.\n *\n * Defaults to 30 000 ms (30 seconds). Set to 0 to restore the previous\n * immediate-eviction behaviour.\n */\n queryCacheRetentionMs: number;\n}\n\nexport const Globals: IGlobals = {\n microservice: '',\n apiBasePath: '',\n origin: '',\n microserviceHttpHeader: 'x-cratis-microservice',\n microserviceWSQueryArgument: 'x-cratis-microservice',\n queryTransportMethod: QueryTransportMethod.WebSocket,\n queryHttpMethod: QueryHttpMethod.Get,\n queryConnectionCount: 1,\n queryDirectMode: false,\n observableQueryTransferMode: ObservableQueryTransferMode.Delta,\n httpHeadersCallback: () => ({}),\n queryCacheRetentionMs: 30_000,\n};"],"names":["ObservableQueryTransferMode","Globals","microservice","apiBasePath","origin","microserviceHttpHeader","microserviceWSQueryArgument","queryTransportMethod","QueryTransportMethod","WebSocket","queryHttpMethod","QueryHttpMethod","Get","queryConnectionCount","queryDirectMode","observableQueryTransferMode","httpHeadersCallback","queryCacheRetentionMs"],"mappings":";;;AAAA;AACA;AAQA;;;;;;;;;;IAWO,IAAKA,2BAAAA,iBAAAA,SAAAA,2BAAAA,EAAAA;+FACgF,2BAAA,CAAA,OAAA,CAAA,GAAA,OAAA;uDAExC,2BAAA,CAAA,MAAA,CAAA,GAAA,MAAA;AAHxCA,IAAAA,OAAAA,2BAAAA;AAKX,CAAA,CAAA,EAAA;MAkEYC,OAAAA,GAAoB;IAC7BC,YAAAA,EAAc,EAAA;IACdC,WAAAA,EAAa,EAAA;IACbC,MAAAA,EAAQ,EAAA;IACRC,sBAAAA,EAAwB,uBAAA;IACxBC,2BAAAA,EAA6B,uBAAA;AAC7BC,IAAAA,oBAAAA,EAAsBC,qBAAqBC,SAAS;AACpDC,IAAAA,eAAAA,EAAiBC,gBAAgBC,GAAG;IACpCC,oBAAAA,EAAsB,CAAA;IACtBC,eAAAA,EAAiB,KAAA;IACjBC,2BAA2B,EAAA,OAAA;IAC3BC,mBAAAA,EAAqB,KAAO,EAAC,CAAA;IAC7BC,qBAAAA,EAAuB;AAC3B;;;;"}
1
+ {"version":3,"file":"Globals.js","sources":["../../Globals.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 { GetHttpHeaders } from './GetHttpHeaders';\nimport { EventSourceFactory } from './EventSourceFactory';\nimport { QueryTransportMethod } from './queries/QueryTransportMethod';\nimport { QueryHttpMethod } from './queries/QueryHttpMethod';\nimport { QueryHttpMethodResolver } from './queries/QueryHttpMethodResolver';\n\n/**\n * Defines the transfer mode used for observable query subscriptions.\n *\n * - {@link ObservableQueryTransferMode.Delta} (default): Only the items that changed since\n * the previous update (added, replaced, removed) are exposed via {@code useChangeStream}.\n * The full collection state is still maintained internally by {@code useObservableQuery}.\n *\n * - {@link ObservableQueryTransferMode.Full}: Every update delivers the complete current\n * collection. The change set returned by {@code useChangeStream} treats the entire new\n * collection as {@code added} and the previous collection as {@code removed}.\n */\nexport enum ObservableQueryTransferMode {\n /** Compute and expose only the items that changed since the previous update (default). */\n Delta = 'delta',\n /** Expose the full collection on every update. */\n Full = 'full',\n}\n\nexport interface IGlobals {\n microservice: string;\n apiBasePath: string;\n origin: string;\n microserviceHttpHeader: string;\n microserviceWSQueryArgument: string;\n queryTransportMethod: QueryTransportMethod;\n /**\n * The HTTP method used to perform non-streaming queries. Defaults to {@link QueryHttpMethod.Get}.\n * Set to {@link QueryHttpMethod.Query} to carry arguments in a JSON request body (RFC 10008)\n * instead of the URL query string. Individual queries can override this via {@code setHttpMethod}.\n */\n queryHttpMethod: QueryHttpMethod;\n /**\n * Optional per-query policy for choosing the query HTTP method from the request (e.g. by URL length).\n * Consulted only when a query has no explicit method set via {@code setHttpMethod}; it takes\n * precedence over {@link queryHttpMethod}. See {@link lengthBasedQueryHttpMethod} for a built-in.\n */\n queryHttpMethodResolver?: QueryHttpMethodResolver;\n /**\n * Number of hub connections maintained for observable queries.\n * When greater than one, queries are distributed across the pool round-robin.\n * Only applies when {@link queryTransportMethod} is a centralized hub transport.\n * Defaults to 1.\n */\n queryConnectionCount: number;\n /**\n * When true, observable queries connect directly to the per-query WebSocket URL\n * instead of routing through the centralized hub endpoint.\n * Defaults to false (use the centralized hub).\n */\n queryDirectMode: boolean;\n /**\n * Controls how observable query updates are transferred and exposed.\n * {@link ObservableQueryTransferMode.Delta} (default) computes per-update deltas;\n * {@link ObservableQueryTransferMode.Full} delivers the whole collection on every update.\n */\n observableQueryTransferMode: ObservableQueryTransferMode;\n /**\n * Callback that returns custom HTTP headers to include in hub transport requests\n * (e.g. SSE subscribe/unsubscribe POST calls).\n */\n httpHeadersCallback: GetHttpHeaders;\n /**\n * Optional factory used to create the {@link EventSource} instances that back SSE\n * observable query connections. Falls back to the global {@link EventSource}\n * constructor when not set — override it to supply a custom SSE client (e.g. a\n * native implementation on React Native, where the global constructor is unavailable).\n */\n eventSourceFactory?: EventSourceFactory;\n /**\n * How long in milliseconds to retain a query cache entry after the last subscriber\n * releases it before evicting the subscription and the cached data.\n *\n * A non-zero value allows a user navigating away and back quickly to see cached\n * data immediately instead of waiting for a fresh server round-trip. The entry is\n * still evicted once the window expires, so memory is eventually reclaimed.\n *\n * Defaults to 30 000 ms (30 seconds). Set to 0 to restore the previous\n * immediate-eviction behaviour.\n */\n queryCacheRetentionMs: number;\n}\n\nexport const Globals: IGlobals = {\n microservice: '',\n apiBasePath: '',\n origin: '',\n microserviceHttpHeader: 'x-cratis-microservice',\n microserviceWSQueryArgument: 'x-cratis-microservice',\n queryTransportMethod: QueryTransportMethod.WebSocket,\n queryHttpMethod: QueryHttpMethod.Get,\n queryConnectionCount: 1,\n queryDirectMode: false,\n observableQueryTransferMode: ObservableQueryTransferMode.Delta,\n httpHeadersCallback: () => ({}),\n queryCacheRetentionMs: 30_000,\n};"],"names":["ObservableQueryTransferMode","Globals","microservice","apiBasePath","origin","microserviceHttpHeader","microserviceWSQueryArgument","queryTransportMethod","QueryTransportMethod","WebSocket","queryHttpMethod","QueryHttpMethod","Get","queryConnectionCount","queryDirectMode","observableQueryTransferMode","httpHeadersCallback","queryCacheRetentionMs"],"mappings":";;;AAAA;AACA;AAQA;;;;;;;;;;IAWO,IAAKA,2BAAAA,iBAAAA,SAAAA,2BAAAA,EAAAA;+FACgF,2BAAA,CAAA,OAAA,CAAA,GAAA,OAAA;uDAExC,2BAAA,CAAA,MAAA,CAAA,GAAA,MAAA;AAHxCA,IAAAA,OAAAA,2BAAAA;AAKX,CAAA,CAAA,EAAA;MAkEYC,OAAAA,GAAoB;IAC7BC,YAAAA,EAAc,EAAA;IACdC,WAAAA,EAAa,EAAA;IACbC,MAAAA,EAAQ,EAAA;IACRC,sBAAAA,EAAwB,uBAAA;IACxBC,2BAAAA,EAA6B,uBAAA;AAC7BC,IAAAA,oBAAAA,EAAsBC,qBAAqBC,SAAS;AACpDC,IAAAA,eAAAA,EAAiBC,gBAAgBC,GAAG;IACpCC,oBAAAA,EAAsB,CAAA;IACtBC,eAAAA,EAAiB,KAAA;IACjBC,2BAA2B,EAAA,OAAA;IAC3BC,mBAAAA,EAAqB,KAAO,EAAC,CAAA;IAC7BC,qBAAAA,EAAuB;AAC3B;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"UrlHelpers.js","sources":["../../UrlHelpers.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\n/**\n * Format a single query / route parameter value into a string the .NET TypeConverter\n * infrastructure can round-trip. Date values are emitted as ISO 8601 so DateTimeOffset\n * binding succeeds; everything else falls back to the JS String coercion.\n */\nfunction formatQueryValue(value: unknown): string {\n if (value instanceof Date) {\n return value.toISOString();\n }\n return String(value);\n}\n\nexport class UrlHelpers {\n /**\n * Creates a URL from the given origin, API base path, and route.\n * @param origin The origin of the request. If not provided, it defaults to the current document's origin.\n * @param apiBasePath The base path for the API.\n * @param route The specific route for the request.\n * @returns The constructed URL.\n */\n static createUrlFrom(origin: string, apiBasePath: string, route: string): URL {\n if ((!origin || origin.length === 0) && typeof document !== 'undefined') {\n origin = document.location?.origin ?? '';\n }\n\n return new URL(route, `${origin}${apiBasePath}`);\n }\n\n /**\n * Replaces route parameters in the route template with values from the parameters object.\n * Returns both the updated route and the parameters that were not used in the route.\n * @param route The route template with placeholders like {paramName}.\n * @param parameters The parameters to replace in the route.\n * @returns An object containing the updated route and unused parameters.\n */\n static replaceRouteParameters<T extends object>(route: string, parameters?: T): { route: string; unusedParameters: Partial<T> } {\n if (!parameters) {\n return { route, unusedParameters: {} };\n }\n\n let result = route;\n const unusedParameters: Partial<T> = { ...parameters };\n\n for (const [key, value] of Object.entries(parameters)) {\n // Array values cannot be encoded as a single route segment — leave them as unused so\n // they are serialized as repeated query string parameters (e.g. ?ids=1&ids=2&ids=3).\n if (Array.isArray(value)) {\n continue;\n }\n\n const pattern = new RegExp(`\\\\{${key}\\\\}`, 'gi');\n const newRoute = result.replace(pattern, encodeURIComponent(formatQueryValue(value)));\n\n if (newRoute !== result) {\n delete unusedParameters[key as keyof T];\n result = newRoute;\n }\n }\n\n return { route: result, unusedParameters };\n }\n\n /**\n * Builds URLSearchParams from the given parameters and additional query parameters.\n * Array values are serialized as repeated key=value pairs (e.g. ?ids=1&ids=2&ids=3).\n * @param unusedParameters Parameters that were not used in route replacement.\n * @param additionalParams Additional query parameters to include.\n * @returns URLSearchParams containing all parameters.\n */\n static buildQueryParams(unusedParameters: object, additionalParams?: Record<string, string | number>): URLSearchParams {\n const queryParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(unusedParameters)) {\n if (value !== undefined && value !== null) {\n if (Array.isArray(value)) {\n for (const item of value) {\n queryParams.append(key, formatQueryValue(item));\n }\n } else {\n queryParams.set(key, formatQueryValue(value));\n }\n }\n }\n\n if (additionalParams) {\n for (const [key, value] of Object.entries(additionalParams)) {\n queryParams.set(key, formatQueryValue(value));\n }\n }\n\n return queryParams;\n }\n}\n"],"names":["formatQueryValue","value","Date","toISOString","String","UrlHelpers","createUrlFrom","origin","apiBasePath","route","length","document","location","URL","replaceRouteParameters","parameters","unusedParameters","result","key","Object","entries","Array","isArray","pattern","RegExp","newRoute","replace","encodeURIComponent","buildQueryParams","additionalParams","queryParams","URLSearchParams","undefined","item","append","set"],"mappings":"AAAA;AACA;AAEA;;;;IAKA,SAASA,iBAAiBC,KAAc,EAAA;AACpC,IAAA,IAAIA,iBAAiBC,IAAAA,EAAM;AACvB,QAAA,OAAOD,MAAME,WAAW,EAAA;AAC5B,IAAA;AACA,IAAA,OAAOC,MAAAA,CAAOH,KAAAA,CAAAA;AAClB;AAEO,MAAMI,UAAAA,CAAAA;AACT;;;;;;AAMA,OACA,OAAOC,aAAAA,CAAcC,MAAc,EAAEC,WAAmB,EAAEC,KAAa,EAAO;QAC1E,IAAK,CAAA,CAACF,MAAAA,IAAUA,MAAAA,CAAOG,MAAM,KAAK,CAAA,KAAM,OAAOC,QAAAA,KAAa,WAAA,EAAa;YACrEJ,MAAAA,GAASI,QAAAA,CAASC,QAAQ,EAAEL,MAAAA,IAAU,EAAA;AAC1C,QAAA;AAEA,QAAA,OAAO,IAAIM,GAAAA,CAAIJ,KAAAA,EAAO,CAAA,EAAGF,SAASC,WAAAA,CAAAA,CAAa,CAAA;AACnD,IAAA;AAEA;;;;;;AAMC,QACD,OAAOM,sBAAAA,CAAyCL,KAAa,EAAEM,UAAc,EAAmD;AAC5H,QAAA,IAAI,CAACA,UAAAA,EAAY;YACb,OAAO;AAAEN,gBAAAA,KAAAA;AAAOO,gBAAAA,gBAAAA,EAAkB;AAAG,aAAA;AACzC,QAAA;AAEA,QAAA,IAAIC,MAAAA,GAASR,KAAAA;AACb,QAAA,MAAMO,g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,CAAA,MAAO;oBACHH,WAAAA,CAAYK,GAAG,CAACjB,GAAAA,EAAKlB,gBAAAA,CAAiBC,KAAAA,CAAAA,CAAAA;AAC1C,gBAAA;AACJ,YAAA;AACJ,QAAA;AAEA,QAAA,IAAI4B,gBAAAA,EAAkB;YAClB,KAAK,MAAM,CAACX,GAAAA,EAAKjB,KAAAA,CAAM,IAAIkB,MAAAA,CAAOC,OAAO,CAACS,gBAAAA,CAAAA,CAAmB;gBACzDC,WAAAA,CAAYK,GAAG,CAACjB,GAAAA,EAAKlB,gBAAAA,CAAiBC,KAAAA,CAAAA,CAAAA;AAC1C,YAAA;AACJ,QAAA;QAEA,OAAO6B,WAAAA;AACX,IAAA;AACJ;;;;"}
1
+ {"version":3,"file":"UrlHelpers.js","sources":["../../UrlHelpers.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\n/**\n * Format a single query / route parameter value into a string the .NET TypeConverter\n * infrastructure can round-trip. Date values are emitted as ISO 8601 so DateTimeOffset\n * binding succeeds; everything else falls back to the JS String coercion.\n */\nfunction formatQueryValue(value: unknown): string {\n if (value instanceof Date) {\n return value.toISOString();\n }\n return String(value);\n}\n\nexport class UrlHelpers {\n /**\n * Creates a URL from the given origin, API base path, and route.\n * @param origin The origin of the request. If not provided, it defaults to the current document's origin.\n * @param apiBasePath The base path for the API.\n * @param route The specific route for the request.\n * @returns The constructed URL.\n */\n static createUrlFrom(origin: string, apiBasePath: string, route: string): URL {\n if ((!origin || origin.length === 0) && typeof document !== 'undefined') {\n origin = document.location?.origin ?? '';\n }\n\n return new URL(route, `${origin}${apiBasePath}`);\n }\n\n /**\n * Replaces route parameters in the route template with values from the parameters object.\n * Returns both the updated route and the parameters that were not used in the route.\n * @param route The route template with placeholders like {paramName}.\n * @param parameters The parameters to replace in the route.\n * @returns An object containing the updated route and unused parameters.\n */\n static replaceRouteParameters<T extends object>(route: string, parameters?: T): { route: string; unusedParameters: Partial<T> } {\n if (!parameters) {\n return { route, unusedParameters: {} };\n }\n\n let result = route;\n const unusedParameters: Partial<T> = { ...parameters };\n\n for (const [key, value] of Object.entries(parameters)) {\n // Array values cannot be encoded as a single route segment — leave them as unused so\n // they are serialized as repeated query string parameters (e.g. ?ids=1&ids=2&ids=3).\n if (Array.isArray(value)) {\n continue;\n }\n\n const pattern = new RegExp(`\\\\{${key}\\\\}`, 'gi');\n const newRoute = result.replace(pattern, encodeURIComponent(formatQueryValue(value)));\n\n if (newRoute !== result) {\n delete unusedParameters[key as keyof T];\n result = newRoute;\n }\n }\n\n return { route: result, unusedParameters };\n }\n\n /**\n * Builds URLSearchParams from the given parameters and additional query parameters.\n * Array values are serialized as repeated key=value pairs (e.g. ?ids=1&ids=2&ids=3).\n * @param unusedParameters Parameters that were not used in route replacement.\n * @param additionalParams Additional query parameters to include.\n * @returns URLSearchParams containing all parameters.\n */\n static buildQueryParams(unusedParameters: object, additionalParams?: Record<string, string | number>): URLSearchParams {\n const queryParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(unusedParameters)) {\n if (value !== undefined && value !== null) {\n if (Array.isArray(value)) {\n for (const item of value) {\n queryParams.append(key, formatQueryValue(item));\n }\n } else {\n queryParams.set(key, formatQueryValue(value));\n }\n }\n }\n\n if (additionalParams) {\n for (const [key, value] of Object.entries(additionalParams)) {\n queryParams.set(key, formatQueryValue(value));\n }\n }\n\n return queryParams;\n }\n}\n"],"names":["formatQueryValue","value","Date","toISOString","String","UrlHelpers","createUrlFrom","origin","apiBasePath","route","length","document","location","URL","replaceRouteParameters","parameters","unusedParameters","result","key","Object","entries","Array","isArray","pattern","RegExp","newRoute","replace","encodeURIComponent","buildQueryParams","additionalParams","queryParams","URLSearchParams","undefined","item","append","set"],"mappings":"AAAA;AACA;AAEA;;;;IAKA,SAASA,iBAAiBC,KAAc,EAAA;AACpC,IAAA,IAAIA,iBAAiBC,IAAAA,EAAM;AACvB,QAAA,OAAOD,MAAME,WAAW,EAAA;AA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/Command.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 { ICommand, PropertyChanged } from './ICommand';\nimport { CommandResult } from \"./CommandResult\";\nimport { CommandValidator } from './CommandValidator';\nimport { Constructor, JsonSerializer } from '@cratis/fundamentals';\nimport { Globals } from '../Globals';\nimport { joinPaths } from '../joinPaths';\nimport { UrlHelpers } from '../UrlHelpers';\nimport { GetHttpHeaders } from '../GetHttpHeaders';\nimport { PropertyDescriptor } from '../reflection/PropertyDescriptor';\nimport { ValidationResult } from '../validation/ValidationResult';\nimport { ValidationResultSeverity } from '../validation/ValidationResultSeverity';\n\ntype Callback = {\n callback: WeakRef<PropertyChanged>;\n thisArg: WeakRef<object>;\n}\n\n/**\n * Represents an implementation of {@link ICommand} that works with HTTP fetch.\n */\nexport abstract class Command<TCommandContent = object, TCommandResponse = object> implements ICommand<TCommandContent, TCommandResponse> {\n private _microservice: string;\n private _apiBasePath: string;\n private _origin: string;\n private _httpHeadersCallback: GetHttpHeaders;\n abstract readonly route: string;\n /* eslint-disable @typescript-eslint/no-explicit-any */\n readonly validation?: CommandValidator<any>;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n readonly roles: string[] = [];\n abstract readonly propertyDescriptors: PropertyDescriptor[];\n abstract get requestParameters(): string[];\n\n private _initialValues: object = {};\n private _hasChanges = false;\n private _callbacks: Callback[] = [];\n\n /**\n * Initializes a new instance of the {@link Command<,>} class.\n * @param _responseType Type of response.\n * @param _isResponseTypeEnumerable Whether or not the response type is enumerable.\n */\n constructor(readonly _responseType: Constructor = Object, readonly _isResponseTypeEnumerable: boolean) {\n this._microservice = Globals.microservice ?? '';\n this._apiBasePath = Globals.apiBasePath ?? '';\n this._origin = Globals.origin ?? '';\n this._httpHeadersCallback = () => ({});\n }\n\n /** @inheritdoc */\n setMicroservice(microservice: string) {\n this._microservice = microservice;\n }\n\n /** @inheritdoc */\n setApiBasePath(apiBasePath: string): void {\n this._apiBasePath = apiBasePath;\n }\n\n /** @inheritdoc */\n setOrigin(origin: string): void {\n this._origin = origin;\n }\n\n /** @inheritdoc */\n setHttpHeadersCallback(callback: GetHttpHeaders): void {\n this._httpHeadersCallback = callback;\n }\n\n /** @inheritdoc */\n async execute(allowedSeverity?: ValidationResultSeverity, ignoreWarnings?: boolean): Promise<CommandResult<TCommandResponse>> {\n const clientValidationErrors = this.validation?.validate(this) || [];\n const filteredClientErrors = this.filterValidationResultsBySeverity(clientValidationErrors, allowedSeverity, ignoreWarnings);\n if (filteredClientErrors.length > 0) {\n return CommandResult.validationFailed(filteredClientErrors) as CommandResult<TCommandResponse>;\n }\n\n const validationErrors = this.validateRequiredProperties();\n const filteredRequiredErrors = this.filterValidationResultsBySeverity(validationErrors, allowedSeverity, ignoreWarnings);\n if (filteredRequiredErrors.length > 0) {\n return CommandResult.validationFailed(filteredRequiredErrors) as CommandResult<TCommandResponse>;\n }\n\n let actualRoute = this.route;\n\n if (this.requestParameters && this.requestParameters.length > 0) {\n const payload = this.buildPayload();\n const { route } = UrlHelpers.replaceRouteParameters(this.route, payload);\n actualRoute = route;\n }\n\n const result = await this.performRequest(actualRoute, 'Command not found at route', 'Error during server call', allowedSeverity, ignoreWarnings);\n this.setInitialValuesFromCurrentValues();\n return result;\n }\n\n /** @inheritdoc */\n async validate(): Promise<CommandResult<TCommandResponse>> {\n const clientValidationErrors = this.validation?.validate(this) || [];\n if (clientValidationErrors.length > 0) {\n return CommandResult.validationFailed(clientValidationErrors) as CommandResult<TCommandResponse>;\n }\n\n const validationErrors = this.validateRequiredProperties();\n if (validationErrors.length > 0) {\n return CommandResult.validationFailed(validationErrors) as CommandResult<TCommandResponse>;\n }\n\n let actualRoute = this.route;\n\n if (this.requestParameters && this.requestParameters.length > 0) {\n const payload = this.buildPayload();\n const { route } = UrlHelpers.replaceRouteParameters(this.route, payload);\n actualRoute = route;\n }\n\n actualRoute = `${actualRoute}/validate`;\n return this.performRequest(actualRoute, 'Command validation endpoint not found at route', 'Error during validation call');\n }\n\n /** @inheritdoc */\n validateClientSide(): CommandResult<TCommandResponse> {\n const clientValidationErrors = this.validation?.validate(this) || [];\n if (clientValidationErrors.length > 0) {\n return CommandResult.validationFailed(clientValidationErrors) as CommandResult<TCommandResponse>;\n }\n\n const validationErrors = this.validateRequiredProperties();\n if (validationErrors.length > 0) {\n return CommandResult.validationFailed(validationErrors) as CommandResult<TCommandResponse>;\n }\n\n return CommandResult.empty as unknown as CommandResult<TCommandResponse>;\n }\n\n private buildPayload(): object {\n const payload = {};\n this.propertyDescriptors.forEach(propertyDescriptor => {\n const property = propertyDescriptor.name;\n payload[property] = this[property];\n });\n return payload;\n }\n\n private validateRequiredProperties(): ValidationResult[] {\n const validationErrors: ValidationResult[] = [];\n this.propertyDescriptors.forEach(propertyDescriptor => {\n if (!propertyDescriptor.isOptional && !this.requestParameters.includes(propertyDescriptor.name)) {\n const value = this[propertyDescriptor.name];\n if (value === undefined || value === null) {\n validationErrors.push(new ValidationResult(\n ValidationResultSeverity.Error,\n `${propertyDescriptor.name} is required`,\n [propertyDescriptor.name],\n null\n ));\n }\n }\n });\n return validationErrors;\n }\n\n private filterValidationResultsBySeverity(validationResults: ValidationResult[], allowedSeverity?: ValidationResultSeverity, ignoreWarnings?: boolean): ValidationResult[] {\n if (ignoreWarnings === true) {\n return validationResults.filter(result => result.severity === ValidationResultSeverity.Error);\n }\n if (allowedSeverity === undefined) {\n return validationResults.filter(result => result.severity === ValidationResultSeverity.Error);\n }\n return validationResults.filter(result => result.severity > allowedSeverity);\n }\n\n private buildHeaders(allowedSeverity?: ValidationResultSeverity, ignoreWarnings?: boolean): HeadersInit {\n const customHeaders = this._httpHeadersCallback?.() ?? {};\n const headers = {\n ...customHeaders,\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n };\n\n if (this._microservice?.length > 0) {\n headers[Globals.microserviceHttpHeader] = this._microservice;\n }\n\n if (allowedSeverity !== undefined) {\n headers['X-Allowed-Severity'] = allowedSeverity.toString();\n }\n\n if (ignoreWarnings === true) {\n headers['X-Ignore-Warnings'] = 'true';\n }\n\n return headers;\n }\n\n private async performRequest(\n route: string,\n notFoundMessage: string,\n errorMessage: string,\n allowedSeverity?: ValidationResultSeverity,\n ignoreWarnings?: boolean\n ): Promise<CommandResult<TCommandResponse>> {\n const payload = this.buildPayload();\n const headers = this.buildHeaders(allowedSeverity, ignoreWarnings);\n const actualRoute = joinPaths(this._apiBasePath, route);\n const url = UrlHelpers.createUrlFrom(this._origin, this._apiBasePath, actualRoute);\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: JsonSerializer.serialize(payload)\n });\n\n if (response.status === 404) {\n return CommandResult.failed([`${notFoundMessage} '${actualRoute}'`]) as CommandResult<TCommandResponse>;\n }\n\n const result = await response.json();\n return new CommandResult(result, this._responseType, this._isResponseTypeEnumerable);\n } catch (ex) {\n return CommandResult.failed([`${errorMessage}: ${ex}`]) as CommandResult<TCommandResponse>;\n }\n }\n\n /** @inheritdoc */\n clear(): void {\n this.propertyDescriptors.forEach(propertyDescriptor => {\n const property = propertyDescriptor.name;\n this[property] = undefined;\n });\n this._initialValues = {};\n this._hasChanges = false;\n }\n\n /** @inheritdoc */\n setInitialValues(values: TCommandContent) {\n this.propertyDescriptors.forEach(propertyDescriptor => {\n const property = propertyDescriptor.name;\n if (Object.prototype.hasOwnProperty.call(values, property)) {\n this._initialValues[property] = values[property];\n this[property] = values[property];\n }\n });\n this.updateHasChanges();\n }\n\n /** @inheritdoc */\n setInitialValuesFromCurrentValues() {\n this.propertyDescriptors.forEach(propertyDescriptor => {\n const property = propertyDescriptor.name;\n if (this[property]) {\n this._initialValues[property] = this[property];\n }\n });\n this.updateHasChanges();\n }\n\n /** @inheritdoc */\n revertChanges(): void {\n this.propertyDescriptors.forEach(propertyDescriptor => {\n const property = propertyDescriptor.name;\n this[property] = this._initialValues[property];\n });\n }\n\n /** @inheritdoc */\n get hasChanges() {\n return this._hasChanges;\n }\n\n /** @inheritdoc */\n propertyChanged(property: string) {\n this.updateHasChanges();\n\n this._callbacks.forEach(callbackContainer => {\n const callback = callbackContainer.callback.deref();\n const thisArg = callbackContainer.thisArg.deref();\n if (callback && thisArg) {\n callback.call(thisArg, property);\n } else {\n this._callbacks = this._callbacks.filter(_ => _.callback !== callbackContainer.callback);\n }\n });\n }\n\n /** @inheritdoc */\n onPropertyChanged(callback: PropertyChanged, thisArg: object) {\n this._callbacks.push({\n callback: new WeakRef(callback),\n thisArg: new WeakRef(thisArg)\n });\n }\n\n private updateHasChanges() {\n this._hasChanges = this.propertyDescriptors.some(propertyDescriptor => {\n const property = propertyDescriptor.name;\n return this[property] !== this._initialValues[property];\n });\n }\n}\n"],"names":["Command","_microservice","_apiBasePath","_origin","_httpHeadersCallback","validation","roles","_initialValues","_hasChanges","_callbacks","_responseType","Object","_isResponseTypeEnumerable","Globals","microservice","apiBasePath","origin","setMicroservice","setApiBasePath","setOrigin","setHttpHeadersCallback","callback","execute","allowedSeverity","ignoreWarnings","clientValidationErrors","validate","filteredClientErrors","filterValidationResultsBySeverity","length","CommandResult","validationFailed","validationErrors","validateRequiredProperties","filteredRequiredErrors","actualRoute","route","requestParameters","payload","buildPayload","UrlHelpers","replaceRouteParameters","result","performRequest","setInitialValuesFromCurrentValues","validateClientSide","empty","propertyDescriptors","forEach","propertyDescriptor","property","name","isOptional","includes","value","undefined","push","ValidationResult","ValidationResultSeverity","Error","validationResults","filter","severity","buildHeaders","customHeaders","headers","microserviceHttpHeader","toString","notFoundMessage","errorMessage","joinPaths","url","createUrlFrom","response","fetch","method","body","JsonSerializer","serialize","status","failed","json","ex","clear","setInitialValues","values","prototype","hasOwnProperty","call","updateHasChanges","revertChanges","hasChanges","propertyChanged","callbackContainer","deref","thisArg","_","onPropertyChanged","WeakRef","some"],"mappings":";;;;;;;;AAAA;AACA;AAmBA;;AAEC,IACM,MAAeA,OAAAA,CAAAA;;;IACVC,aAAAA;IACAC,YAAAA;IACAC,OAAAA;IACAC,oBAAAA;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A;AACjD,YAAA,MAAMC,OAAAA,GAAUF,iBAAAA,CAAkBE,OAAO,CAACD,KAAK,EAAA;AAC/C,YAAA,IAAIzE,YAAY0E,OAAAA,EAAS;gBACrB1E,QAAAA,CAASmE,IAAI,CAACO,OAAAA,EAAS7C,QAAAA,CAAAA;YAC3B,CAAA,MAAO;AACH,gBAAA,IAAI,CAACzC,UAAU,GAAG,IAAI,CAACA,UAAU,CAACoD,MAAM,CAACmC,CAAAA,CAAAA,GAAKA,CAAAA,CAAE3E,QAAQ,KAAKwE,kBAAkBxE,QAAQ,CAAA;AAC3F,YAAA;AACJ,QAAA,CAAA,CAAA;AACJ,IAAA;AAEA,uBACA4E,iBAAAA,CAAkB5E,QAAyB,EAAE0E,OAAe,EAAE;AAC1D,QAAA,IAAI,CAACtF,UAAU,CAAC+C,IAAI,CAAC;AACjBnC,YAAAA,QAAAA,EAAU,IAAI6E,OAAAA,CAAQ7E,QAAAA,CAAAA;AACtB0E,YAAAA,OAAAA,EAAS,IAAIG,OAAAA,CAAQH,OAAAA;AACzB,SAAA,CAAA;AACJ,IAAA;IAEQN,gBAAAA,GAAmB;QACvB,IAAI,CAACjF,WAAW,GAAG,IAAI,CAACuC,mBAAmB,CAACoD,IAAI,CAAClD,CAAAA,kBAAAA,GAAAA;YAC7C,MAAMC,QAAAA,GAAWD,mBAAmBE,IAAI;YACxC,OAAO,IAAI,CAACD,QAAAA,CAAS,KAAK,IAAI,CAAC3C,cAAc,CAAC2C,QAAAA,CAAS;AAC3D,QAAA,CAAA,CAAA;AACJ,IAAA;AACJ;;;;"}
1
+ {"version":3,"file":"Command.js","sources":["../../../commands/Command.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 { ICommand, PropertyChanged } from './ICommand';\nimport { CommandResult } from \"./CommandResult\";\nimport { CommandValidator } from './CommandValidator';\nimport { Constructor, JsonSerializer } from '@cratis/fundamentals';\nimport { Globals } from '../Globals';\nimport { joinPaths } from '../joinPaths';\nimport { UrlHelpers } from '../UrlHelpers';\nimport { GetHttpHeaders } from '../GetHttpHeaders';\nimport { PropertyDescriptor } from '../reflection/PropertyDescriptor';\nimport { ValidationResult } from '../validation/ValidationResult';\nimport { ValidationResultSeverity } from '../validation/ValidationResultSeverity';\n\ntype Callback = {\n callback: WeakRef<PropertyChanged>;\n thisArg: WeakRef<object>;\n}\n\n/**\n * Represents an implementation of {@link ICommand} that works with HTTP fetch.\n */\nexport abstract class Command<TCommandContent = object, TCommandResponse = object> implements ICommand<TCommandContent, TCommandResponse> {\n private _microservice: string;\n private _apiBasePath: string;\n private _origin: string;\n private _httpHeadersCallback: GetHttpHeaders;\n abstract readonly route: string;\n /* eslint-disable @typescript-eslint/no-explicit-any */\n readonly validation?: CommandValidator<any>;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n readonly roles: string[] = [];\n abstract readonly propertyDescriptors: PropertyDescriptor[];\n abstract get requestParameters(): string[];\n\n private _initialValues: object = {};\n private _hasChanges = false;\n private _callbacks: Callback[] = [];\n\n /**\n * Initializes a new instance of the {@link Command<,>} class.\n * @param _responseType Type of response.\n * @param _isResponseTypeEnumerable Whether or not the response type is enumerable.\n */\n constructor(readonly _responseType: Constructor = Object, readonly _isResponseTypeEnumerable: boolean) {\n this._microservice = Globals.microservice ?? '';\n this._apiBasePath = Globals.apiBasePath ?? '';\n this._origin = Globals.origin ?? '';\n this._httpHeadersCallback = () => ({});\n }\n\n /** @inheritdoc */\n setMicroservice(microservice: string) {\n this._microservice = microservice;\n }\n\n /** @inheritdoc */\n setApiBasePath(apiBasePath: string): void {\n this._apiBasePath = apiBasePath;\n }\n\n /** @inheritdoc */\n setOrigin(origin: string): void {\n this._origin = origin;\n }\n\n /** @inheritdoc */\n setHttpHeadersCallback(callback: GetHttpHeaders): void {\n this._httpHeadersCallback = callback;\n }\n\n /** @inheritdoc */\n async execute(allowedSeverity?: ValidationResultSeverity, ignoreWarnings?: boolean): Promise<CommandResult<TCommandResponse>> {\n const clientValidationErrors = this.validation?.validate(this) || [];\n const filteredClientErrors = this.filterValidationResultsBySeverity(clientValidationErrors, allowedSeverity, ignoreWarnings);\n if (filteredClientErrors.length > 0) {\n return CommandResult.validationFailed(filteredClientErrors) as CommandResult<TCommandResponse>;\n }\n\n const validationErrors = this.validateRequiredProperties();\n const filteredRequiredErrors = this.filterValidationResultsBySeverity(validationErrors, allowedSeverity, ignoreWarnings);\n if (filteredRequiredErrors.length > 0) {\n return CommandResult.validationFailed(filteredRequiredErrors) as CommandResult<TCommandResponse>;\n }\n\n let actualRoute = this.route;\n\n if (this.requestParameters && this.requestParameters.length > 0) {\n const payload = this.buildPayload();\n const { route } = UrlHelpers.replaceRouteParameters(this.route, payload);\n actualRoute = route;\n }\n\n const result = await this.performRequest(actualRoute, 'Command not found at route', 'Error during server call', allowedSeverity, ignoreWarnings);\n this.setInitialValuesFromCurrentValues();\n return result;\n }\n\n /** @inheritdoc */\n async validate(): Promise<CommandResult<TCommandResponse>> {\n const clientValidationErrors = this.validation?.validate(this) || [];\n if (clientValidationErrors.length > 0) {\n return CommandResult.validationFailed(clientValidationErrors) as CommandResult<TCommandResponse>;\n }\n\n const validationErrors = this.validateRequiredProperties();\n if (validationErrors.length > 0) {\n return CommandResult.validationFailed(validationErrors) as CommandResult<TCommandResponse>;\n }\n\n let actualRoute = this.route;\n\n if (this.requestParameters && this.requestParameters.length > 0) {\n const payload = this.buildPayload();\n const { route } = UrlHelpers.replaceRouteParameters(this.route, payload);\n actualRoute = route;\n }\n\n actualRoute = `${actualRoute}/validate`;\n return this.performRequest(actualRoute, 'Command validation endpoint not found at route', 'Error during validation call');\n }\n\n /** @inheritdoc */\n validateClientSide(): CommandResult<TCommandResponse> {\n const clientValidationErrors = this.validation?.validate(this) || [];\n if (clientValidationErrors.length > 0) {\n return CommandResult.validationFailed(clientValidationErrors) as CommandResult<TCommandResponse>;\n }\n\n const validationErrors = this.validateRequiredProperties();\n if (validationErrors.length > 0) {\n return CommandResult.validationFailed(validationErrors) as CommandResult<TCommandResponse>;\n }\n\n return CommandResult.empty as unknown as CommandResult<TCommandResponse>;\n }\n\n private buildPayload(): object {\n const payload = {};\n this.propertyDescriptors.forEach(propertyDescriptor => {\n const property = propertyDescriptor.name;\n payload[property] = this[property];\n });\n return payload;\n }\n\n private validateRequiredProperties(): ValidationResult[] {\n const validationErrors: ValidationResult[] = [];\n this.propertyDescriptors.forEach(propertyDescriptor => {\n if (!propertyDescriptor.isOptional && !this.requestParameters.includes(propertyDescriptor.name)) {\n const value = this[propertyDescriptor.name];\n if (value === undefined || value === null) {\n validationErrors.push(new ValidationResult(\n ValidationResultSeverity.Error,\n `${propertyDescriptor.name} is required`,\n [propertyDescriptor.name],\n null\n ));\n }\n }\n });\n return validationErrors;\n }\n\n private filterValidationResultsBySeverity(validationResults: ValidationResult[], allowedSeverity?: ValidationResultSeverity, ignoreWarnings?: boolean): ValidationResult[] {\n if (ignoreWarnings === true) {\n return validationResults.filter(result => result.severity === ValidationResultSeverity.Error);\n }\n if (allowedSeverity === undefined) {\n return validationResults.filter(result => result.severity === ValidationResultSeverity.Error);\n }\n return validationResults.filter(result => result.severity > allowedSeverity);\n }\n\n private buildHeaders(allowedSeverity?: ValidationResultSeverity, ignoreWarnings?: boolean): HeadersInit {\n const customHeaders = this._httpHeadersCallback?.() ?? {};\n const headers = {\n ...customHeaders,\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n };\n\n if (this._microservice?.length > 0) {\n headers[Globals.microserviceHttpHeader] = this._microservice;\n }\n\n if (allowedSeverity !== undefined) {\n headers['X-Allowed-Severity'] = allowedSeverity.toString();\n }\n\n if (ignoreWarnings === true) {\n headers['X-Ignore-Warnings'] = 'true';\n }\n\n return headers;\n }\n\n private async performRequest(\n route: string,\n notFoundMessage: string,\n errorMessage: string,\n allowedSeverity?: ValidationResultSeverity,\n ignoreWarnings?: boolean\n ): Promise<CommandResult<TCommandResponse>> {\n const payload = this.buildPayload();\n const headers = this.buildHeaders(allowedSeverity, ignoreWarnings);\n const actualRoute = joinPaths(this._apiBasePath, route);\n const url = UrlHelpers.createUrlFrom(this._origin, this._apiBasePath, actualRoute);\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: JsonSerializer.serialize(payload)\n });\n\n if (response.status === 404) {\n return CommandResult.failed([`${notFoundMessage} '${actualRoute}'`]) as CommandResult<TCommandResponse>;\n }\n\n const result = await response.json();\n return new CommandResult(result, this._responseType, this._isResponseTypeEnumerable);\n } catch (ex) {\n return CommandResult.failed([`${errorMessage}: ${ex}`]) as CommandResult<TCommandResponse>;\n }\n }\n\n /** @inheritdoc */\n clear(): void {\n this.propertyDescriptors.forEach(propertyDescriptor => {\n const property = propertyDescriptor.name;\n this[property] = undefined;\n });\n this._initialValues = {};\n this._hasChanges = false;\n }\n\n /** @inheritdoc */\n setInitialValues(values: TCommandContent) {\n this.propertyDescriptors.forEach(propertyDescriptor => {\n const property = propertyDescriptor.name;\n if (Object.prototype.hasOwnProperty.call(values, property)) {\n this._initialValues[property] = values[property];\n this[property] = values[property];\n }\n });\n this.updateHasChanges();\n }\n\n /** @inheritdoc */\n setInitialValuesFromCurrentValues() {\n this.propertyDescriptors.forEach(propertyDescriptor => {\n const property = propertyDescriptor.name;\n if (this[property]) {\n this._initialValues[property] = this[property];\n }\n });\n this.updateHasChanges();\n }\n\n /** @inheritdoc */\n revertChanges(): void {\n this.propertyDescriptors.forEach(propertyDescriptor => {\n const property = propertyDescriptor.name;\n this[property] = this._initialValues[property];\n });\n }\n\n /** @inheritdoc */\n get hasChanges() {\n return this._hasChanges;\n }\n\n /** @inheritdoc */\n propertyChanged(property: string) {\n this.updateHasChanges();\n\n this._callbacks.forEach(callbackContainer => {\n const callback = callbackContainer.callback.deref();\n const thisArg = callbackContainer.thisArg.deref();\n if (callback && thisArg) {\n callback.call(thisArg, property);\n } else {\n this._callbacks = this._callbacks.filter(_ => _.callback !== callbackContainer.callback);\n }\n });\n }\n\n /** @inheritdoc */\n onPropertyChanged(callback: PropertyChanged, thisArg: object) {\n this._callbacks.push({\n callback: new WeakRef(callback),\n thisArg: new WeakRef(thisArg)\n });\n }\n\n private updateHasChanges() {\n this._hasChanges = this.propertyDescriptors.some(propertyDescriptor => {\n const property = propertyDescriptor.name;\n return this[property] !== this._initialValues[property];\n });\n }\n}\n"],"names":["Command","_microservice","_apiBasePath","_origin","_httpHeadersCallback","validation","roles","_initialValues","_hasChanges","_callbacks","_responseType","Object","_isResponseTypeEnumerable","Globals","microservice","apiBasePath","origin","setMicroservice","setApiBasePath","setOrigin","setHttpHeadersCallback","callback","execute","allowedSeverity","ignoreWarnings","clientValidationErrors","validate","filteredClientErrors","filterValidationResultsBySeverity","length","CommandResult","validationFailed","validationErrors","validateRequiredProperties","filteredRequiredErrors","actualRoute","route","requestParameters","payload","buildPayload","UrlHelpers","replaceRouteParameters","result","performRequest","setInitialValuesFromCurrentValues","validateClientSide","empty","propertyDescriptors","forEach","propertyDescriptor","property","name","isOptional","includes","value","undefined","push","ValidationResult","ValidationResultSeverity","Error","validationResults","filter","severity","buildHeaders","customHeaders","headers","microserviceHttpHeader","toString","notFoundMessage","errorMessage","joinPaths","url","createUrlFrom","response","fetch","method","body","JsonSerializer","serialize","status","failed","json","ex","clear","setInitialValues","values","prototype","hasOwnProperty","call","updateHasChanges","revertChanges","hasChanges","propertyChanged","callbackContainer","deref","thisArg","_","onPropertyChanged","WeakRef","some"],"mappings":";;;;;;;;AAAA;AACA;AAmBA;;AAEC,IACM,MAAeA,OAAAA,CAAAA;;;IACVC,aAAAA;IACAC,YAAAA;IACAC,OAAAA;IACAC,oBAAAA;4DAGR,UAASC;AACT,2DACSC,KAAAA,GAAkB,EAAE;AAIrBC,IAAAA,cAAAA,GAAyB,EAAC;AAC1BC,IAAAA,WAAAA,GAAc,KAAA;AACdC,IAAAA,UAAAA,GAAyB,EAAE;AAEnC;;;;AAIC,QACD,YAAY,aAASC,GAA6BC,MAAM,EAAWC,yBAAkC,CAAE;a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I,CAACzC,UAAU,GAAG,IAAI,CAACA,UAAU,CAACoD,MAAM,CAACmC,CAAAA,CAAAA,GAAKA,CAAAA,CAAE3E,QAAQ,KAAKwE,kBAAkBxE,QAAQ,CAAA;AAC3F,YAAA;AACJ,QAAA,CAAA,CAAA;AACJ,IAAA;AAEA,uBACA4E,iBAAAA,CAAkB5E,QAAyB,EAAE0E,OAAe,EAAE;AAC1D,QAAA,IAAI,CAACtF,UAAU,CAAC+C,IAAI,CAAC;AACjBnC,YAAAA,QAAAA,EAAU,IAAI6E,OAAAA,CAAQ7E,QAAAA,CAAAA;AACtB0E,YAAAA,OAAAA,EAAS,IAAIG,OAAAA,CAAQH,OAAAA;AACzB,SAAA,CAAA;AACJ,IAAA;IAEQN,gBAAAA,GAAmB;QACvB,IAAI,CAACjF,WAAW,GAAG,IAAI,CAACuC,mBAAmB,CAACoD,IAAI,CAAClD,CAAAA,kBAAAA,GAAAA;YAC7C,MAAMC,QAAAA,GAAWD,mBAAmBE,IAAI;YACxC,OAAO,IAAI,CAACD,QAAAA,CAAS,KAAK,IAAI,CAAC3C,cAAc,CAAC2C,QAAAA,CAAS;AAC3D,QAAA,CAAA,CAAA;AACJ,IAAA;AACJ;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"CommandResult.js","sources":["../../../commands/CommandResult.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 { Guid } from '@cratis/fundamentals';\nimport { ICommandResult } from './ICommandResult';\nimport { ValidationResult } from '../validation/ValidationResult';\nimport { Constructor, JsonSerializer } from '@cratis/fundamentals';\n\n/**\n * Delegate type for the onSuccess callback.\n */\ntype OnSuccess = (<TResponse>(response: TResponse) => void) | (() => void);\n\n/**\n * Delegate type for the onFailed callback.\n */\ntype OnFailed<TResponse> = ((commandResult: CommandResult<TResponse>) => void) | (() => void);\n\n/**\n * Delegate type for the onException callback.\n */\ntype OnException = (messages: string[], stackTrace: string) => void;\n\n/**\n * Delegate type for the onUnauthorized callback.\n */\ntype OnUnauthorized = () => void;\n\n/**\n * Delegate type for the onValidationFailure callback.\n */\ntype OnValidationFailure = (validationResults: ValidationResult[]) => void;\n\ntype ServerCommandResult = {\n correlationId: string;\n isSuccess: boolean;\n isAuthorized: boolean;\n isValid: boolean;\n hasExceptions: boolean;\n validationResults: {\n severity: number;\n message: string;\n members: string[];\n state: object;\n reason?: string;\n reasonDetail?: string;\n }[];\n exceptionMessages: string[];\n exceptionStackTrace: string;\n authorizationFailureReason: string;\n\n /* eslint-disable @typescript-eslint/no-explicit-any */\n response: any;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n}\n\n/**\n * Represents the result from executing a {@link ICommand}.\n */\nexport class CommandResult<TResponse = object> implements ICommandResult<TResponse> {\n\n static empty: CommandResult = new CommandResult({\n correlationId: Guid.empty.toString(),\n isSuccess: true,\n isAuthorized: true,\n isValid: true,\n hasExceptions: false,\n validationResults: [],\n exceptionMessages: [],\n exceptionStackTrace: '',\n authorizationFailureReason: '',\n response: null\n }, Object, false);\n\n static failed = (exceptionMessages: string[]): CommandResult => {\n return new CommandResult({\n correlationId: Guid.empty.toString(),\n isSuccess: false,\n isAuthorized: true,\n isValid: true,\n hasExceptions: true,\n validationResults: [],\n exceptionMessages: exceptionMessages,\n exceptionStackTrace: '',\n authorizationFailureReason: '',\n response: null\n }, Object, false);\n };\n\n static validationFailed = (validationResults: ValidationResult[]): CommandResult => {\n return new CommandResult({\n correlationId: Guid.empty.toString(),\n isSuccess: false,\n isAuthorized: true,\n isValid: false,\n hasExceptions: false,\n validationResults: validationResults.map(_ => ({\n severity: _.severity,\n message: _.message,\n members: _.members,\n state: _.state,\n reason: _.reason,\n reasonDetail: _.reasonDetail\n })),\n exceptionMessages: [],\n exceptionStackTrace: '',\n authorizationFailureReason: '',\n response: null\n }, Object, false);\n };\n\n /** @inheritdoc */\n readonly correlationId: Guid;\n\n /** @inheritdoc */\n readonly isSuccess: boolean;\n\n /** @inheritdoc */\n readonly isAuthorized: boolean;\n\n /** @inheritdoc */\n readonly isValid: boolean;\n\n /** @inheritdoc */\n readonly hasExceptions: boolean;\n\n /** @inheritdoc */\n readonly validationResults: ValidationResult[];\n\n /** @inheritdoc */\n readonly exceptionMessages: string[];\n\n /** @inheritdoc */\n readonly exceptionStackTrace: string;\n\n /** @inheritdoc */\n readonly authorizationFailureReason: string;\n\n /** @inheritdoc */\n readonly response?: TResponse;\n\n /**\n * Creates an instance of command result.\n * @param {*} result The JSON/any representation of the command result;\n * @param {Constructor} responseInstanceType The {@see Constructor} that represents the type of response, if any. Defaults to {@see Object}.\n * @param {boolean} isResponseTypeEnumerable Whether or not the response type is an enumerable or not.\n */\n constructor(result: ServerCommandResult, responseInstanceType: Constructor = Object, isResponseTypeEnumerable: boolean) {\n this.correlationId = Guid.parse(result.correlationId);\n this.isSuccess = result.isSuccess;\n this.isAuthorized = result.isAuthorized;\n this.isValid = result.isValid;\n this.hasExceptions = result.hasExceptions;\n this.validationResults = result.validationResults.map(_ => new ValidationResult(_.severity, _.message, _.members, _.state, _.reason, _.reasonDetail));\n this.exceptionMessages = result.exceptionMessages;\n this.exceptionStackTrace = result.exceptionStackTrace;\n this.authorizationFailureReason = result.authorizationFailureReason;\n\n if (result.response !== undefined && result.response !== null) {\n const isPrimitive = responseInstanceType === String || responseInstanceType === Number || responseInstanceType === Boolean;\n if (isResponseTypeEnumerable) {\n this.response = (Array.isArray(result.response)\n ? (isPrimitive\n ? Array.from(result.response)\n : JsonSerializer.deserializeArrayFromInstance(responseInstanceType, result.response))\n : []) as TResponse;\n } else {\n this.response = (isPrimitive\n ? result.response\n : JsonSerializer.deserializeFromInstance(responseInstanceType, result.response)) as TResponse;\n }\n }\n }\n\n /**\n * Set up a callback for when the command was successful.\n * @param {OnSuccess} callback The callback to call when the command was successful.\n * @returns {CommandResult} The instance of the command result.\n */\n onSuccess(callback: OnSuccess): CommandResult<TResponse> {\n if (this.isSuccess) {\n callback(this.response as TResponse);\n }\n return this;\n }\n\n /**\n * Set up a callback for when the command failed.\n * @param {OnFailed} callback The callback to call when the command failed.\n * @returns {CommandResult} The instance of the command result.\n */\n onFailed(callback: OnFailed<TResponse>): CommandResult<TResponse> {\n if (!this.isSuccess) {\n callback(this);\n }\n return this;\n }\n\n /**\n * Set up a callback for when the command failed with an exception.\n * @param {OnException} callback The callback to call when the command had an exception.\n * @returns {CommandResult} The instance of the command result.\n */\n onException(callback: OnException): CommandResult<TResponse> {\n if (this.hasExceptions) {\n callback(this.exceptionMessages, this.exceptionStackTrace);\n }\n return this;\n }\n\n /**\n * Set up a callback for when the command was unauthorized.\n * @param {OnUnauthorized} callback The callback to call when the command was unauthorized.\n * @returns {CommandResult} The instance of the command result.\n */\n onUnauthorized(callback: OnUnauthorized): CommandResult<TResponse> {\n if (!this.isAuthorized) {\n callback();\n }\n return this;\n }\n\n /**\n * Set up a callback for when the command had validation errors.\n * @param {OnSuccess} callback The callback to call when the command was invalid.\n * @returns {CommandResult} The instance of the command result.\n */\n onValidationFailure(callback: OnValidationFailure): CommandResult<TResponse> {\n if (!this.isValid) {\n callback(this.validationResults);\n }\n return this;\n }\n}\n"],"names":["CommandResult","empty","correlationId","Guid","toString","isSuccess","isAuthorized","isValid","hasExceptions","validationResults","exceptionMessages","exceptionStackTrace","authorizationFailureReason","response","Object","failed","validationFailed","map","_","severity","message","members","state","reason","reasonDetail","result","responseInstanceType","isResponseTypeEnumerable","parse","ValidationResult","undefined","isPrimitive","String","Number","Boolean","Array","isArray","from","JsonSerializer","deserializeArrayFromInstance","deserializeFromInstance","onSuccess","callback","onFailed","onException","onUnauthorized","onValidationFailure"],"mappings":";;;AAAA;AACA;AAuDA;;AAEC,IACM,MAAMA,aAAAA,CAAAA;IAET,OAAOC,KAAAA,GAAuB,IAAID,aAAAA,CAAc;QAC5CE,aAAAA,EAAeC,IAAAA,CAAKF,KAAK,CAACG,QAAQ,EAAA;QAClCC,SAAAA,EAAW,IAAA;QACXC,YAAAA,EAAc,IAAA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iBAAiB,EAAE,IAAI,CAACC,mBAAmB,CAAA;AAC7D,QAAA;AACA,QAAA,OAAO,IAAI;AACf,IAAA;AAEA;;;;QAKAkC,cAAAA,CAAeH,QAAwB,EAA4B;AAC/D,QAAA,IAAI,CAAC,IAAI,CAACpC,YAAY,EAAE;AACpBoC,YAAAA,QAAAA,EAAAA;AACJ,QAAA;AACA,QAAA,OAAO,IAAI;AACf,IAAA;AAEA;;;;QAKAI,mBAAAA,CAAoBJ,QAA6B,EAA4B;AACzE,QAAA,IAAI,CAAC,IAAI,CAACnC,OAAO,EAAE;YACfmC,QAAAA,CAAS,IAAI,CAACjC,iBAAiB,CAAA;AACnC,QAAA;AACA,QAAA,OAAO,IAAI;AACf,IAAA;AACJ;;;;"}
1
+ {"version":3,"file":"CommandResult.js","sources":["../../../commands/CommandResult.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 { Guid } from '@cratis/fundamentals';\nimport { ICommandResult } from './ICommandResult';\nimport { ValidationResult } from '../validation/ValidationResult';\nimport { Constructor, JsonSerializer } from '@cratis/fundamentals';\n\n/**\n * Delegate type for the onSuccess callback.\n */\ntype OnSuccess = (<TResponse>(response: TResponse) => void) | (() => void);\n\n/**\n * Delegate type for the onFailed callback.\n */\ntype OnFailed<TResponse> = ((commandResult: CommandResult<TResponse>) => void) | (() => void);\n\n/**\n * Delegate type for the onException callback.\n */\ntype OnException = (messages: string[], stackTrace: string) => void;\n\n/**\n * Delegate type for the onUnauthorized callback.\n */\ntype OnUnauthorized = () => void;\n\n/**\n * Delegate type for the onValidationFailure callback.\n */\ntype OnValidationFailure = (validationResults: ValidationResult[]) => void;\n\ntype ServerCommandResult = {\n correlationId: string;\n isSuccess: boolean;\n isAuthorized: boolean;\n isValid: boolean;\n hasExceptions: boolean;\n validationResults: {\n severity: number;\n message: string;\n members: string[];\n state: object;\n reason?: string;\n reasonDetail?: string;\n }[];\n exceptionMessages: string[];\n exceptionStackTrace: string;\n authorizationFailureReason: string;\n\n /* eslint-disable @typescript-eslint/no-explicit-any */\n response: any;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n}\n\n/**\n * Represents the result from executing a {@link ICommand}.\n */\nexport class CommandResult<TResponse = object> implements ICommandResult<TResponse> {\n\n static empty: CommandResult = new CommandResult({\n correlationId: Guid.empty.toString(),\n isSuccess: true,\n isAuthorized: true,\n isValid: true,\n hasExceptions: false,\n validationResults: [],\n exceptionMessages: [],\n exceptionStackTrace: '',\n authorizationFailureReason: '',\n response: null\n }, Object, false);\n\n static failed = (exceptionMessages: string[]): CommandResult => {\n return new CommandResult({\n correlationId: Guid.empty.toString(),\n isSuccess: false,\n isAuthorized: true,\n isValid: true,\n hasExceptions: true,\n validationResults: [],\n exceptionMessages: exceptionMessages,\n exceptionStackTrace: '',\n authorizationFailureReason: '',\n response: null\n }, Object, false);\n };\n\n static validationFailed = (validationResults: ValidationResult[]): CommandResult => {\n return new CommandResult({\n correlationId: Guid.empty.toString(),\n isSuccess: false,\n isAuthorized: true,\n isValid: false,\n hasExceptions: false,\n validationResults: validationResults.map(_ => ({\n severity: _.severity,\n message: _.message,\n members: _.members,\n state: _.state,\n reason: _.reason,\n reasonDetail: _.reasonDetail\n })),\n exceptionMessages: [],\n exceptionStackTrace: '',\n authorizationFailureReason: '',\n response: null\n }, Object, false);\n };\n\n /** @inheritdoc */\n readonly correlationId: Guid;\n\n /** @inheritdoc */\n readonly isSuccess: boolean;\n\n /** @inheritdoc */\n readonly isAuthorized: boolean;\n\n /** @inheritdoc */\n readonly isValid: boolean;\n\n /** @inheritdoc */\n readonly hasExceptions: boolean;\n\n /** @inheritdoc */\n readonly validationResults: ValidationResult[];\n\n /** @inheritdoc */\n readonly exceptionMessages: string[];\n\n /** @inheritdoc */\n readonly exceptionStackTrace: string;\n\n /** @inheritdoc */\n readonly authorizationFailureReason: string;\n\n /** @inheritdoc */\n readonly response?: TResponse;\n\n /**\n * Creates an instance of command result.\n * @param {*} result The JSON/any representation of the command result;\n * @param {Constructor} responseInstanceType The {@see Constructor} that represents the type of response, if any. Defaults to {@see Object}.\n * @param {boolean} isResponseTypeEnumerable Whether or not the response type is an enumerable or not.\n */\n constructor(result: ServerCommandResult, responseInstanceType: Constructor = Object, isResponseTypeEnumerable: boolean) {\n this.correlationId = Guid.parse(result.correlationId);\n this.isSuccess = result.isSuccess;\n this.isAuthorized = result.isAuthorized;\n this.isValid = result.isValid;\n this.hasExceptions = result.hasExceptions;\n this.validationResults = result.validationResults.map(_ => new ValidationResult(_.severity, _.message, _.members, _.state, _.reason, _.reasonDetail));\n this.exceptionMessages = result.exceptionMessages;\n this.exceptionStackTrace = result.exceptionStackTrace;\n this.authorizationFailureReason = result.authorizationFailureReason;\n\n if (result.response !== undefined && result.response !== null) {\n const isPrimitive = responseInstanceType === String || responseInstanceType === Number || responseInstanceType === Boolean;\n if (isResponseTypeEnumerable) {\n this.response = (Array.isArray(result.response)\n ? (isPrimitive\n ? Array.from(result.response)\n : JsonSerializer.deserializeArrayFromInstance(responseInstanceType, result.response))\n : []) as TResponse;\n } else {\n this.response = (isPrimitive\n ? result.response\n : JsonSerializer.deserializeFromInstance(responseInstanceType, result.response)) as TResponse;\n }\n }\n }\n\n /**\n * Set up a callback for when the command was successful.\n * @param {OnSuccess} callback The callback to call when the command was successful.\n * @returns {CommandResult} The instance of the command result.\n */\n onSuccess(callback: OnSuccess): CommandResult<TResponse> {\n if (this.isSuccess) {\n callback(this.response as TResponse);\n }\n return this;\n }\n\n /**\n * Set up a callback for when the command failed.\n * @param {OnFailed} callback The callback to call when the command failed.\n * @returns {CommandResult} The instance of the command result.\n */\n onFailed(callback: OnFailed<TResponse>): CommandResult<TResponse> {\n if (!this.isSuccess) {\n callback(this);\n }\n return this;\n }\n\n /**\n * Set up a callback for when the command failed with an exception.\n * @param {OnException} callback The callback to call when the command had an exception.\n * @returns {CommandResult} The instance of the command result.\n */\n onException(callback: OnException): CommandResult<TResponse> {\n if (this.hasExceptions) {\n callback(this.exceptionMessages, this.exceptionStackTrace);\n }\n return this;\n }\n\n /**\n * Set up a callback for when the command was unauthorized.\n * @param {OnUnauthorized} callback The callback to call when the command was unauthorized.\n * @returns {CommandResult} The instance of the command result.\n */\n onUnauthorized(callback: OnUnauthorized): CommandResult<TResponse> {\n if (!this.isAuthorized) {\n callback();\n }\n return this;\n }\n\n /**\n * Set up a callback for when the command had validation errors.\n * @param {OnSuccess} callback The callback to call when the command was invalid.\n * @returns {CommandResult} The instance of the command result.\n */\n onValidationFailure(callback: OnValidationFailure): CommandResult<TResponse> {\n if (!this.isValid) {\n callback(this.validationResults);\n }\n return this;\n }\n}\n"],"names":["CommandResult","empty","correlationId","Guid","toString","isSuccess","isAuthorized","isValid","hasExceptions","validationResults","exceptionMessages","exceptionStackTrace","authorizationFailureReason","response","Object","failed","validationFailed","map","_","severity","message","members","state","reason","reasonDetail","result","responseInstanceType","isResponseTypeEnumerable","parse","ValidationResult","undefined","isPrimitive","String","Number","Boolean","Array","isArray","from","JsonSerializer","deserializeArrayFromInstance","deserializeFromInstance","onSuccess","callback","onFailed","onException","onUnauthorized","onValidationFailure"],"mappings":";;;AAAA;AACA;AAuDA;;AAEC,IACM,MAAMA,aAAAA,CAAAA;IAET,OAAOC,KAAAA,GAAuB,IAAID,aAAAA,CAAc;QAC5CE,aAAAA,EAAeC,IAAAA,CAAKF,KAAK,CAACG,QAAQ,EAAA;QAClCC,SAAAA,EAAW,IAAA;QACXC,YAAAA,EAAc,IAAA;QACdC,OAAAA,EAAS,IAAA;QACTC,aAAAA,EAAe,KAAA;AACfC,QAAAA,iBAAAA,EAAmB,EAAE;AACrBC,QAAAA,iBAAAA,EAAmB,EAAE;QACrBC,mBAAAA,EAAqB,EAAA;QACrBC,0BAAAA,EAA4B,EAAA;QAC5BC,QAAAA,EAAU;AACd,KAAA,EAAGC,QAAQ,KAAA,CAAA;AAEX,IAAA,OAAOC,SAAS,CAACL,iBAAAA,GAAAA;AACb,QAAA,OA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6B,EAA4B;AACzE,QAAA,IAAI,CAAC,IAAI,CAACnC,OAAO,EAAE;YACfmC,QAAAA,CAAS,IAAI,CAACjC,iBAAiB,CAAA;AACnC,QAAA;AACA,QAAA,OAAO,IAAI;AACf,IAAA;AACJ;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"CommandResults.js","sources":["../../../commands/CommandResults.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 { Guid } from '@cratis/fundamentals';\nimport { ValidationResult } from '../validation/ValidationResult';\nimport { Command } from './Command';\nimport { CommandResult } from './CommandResult';\nimport { ICommandResult } from './ICommandResult';\n\ntype GetSpecificState = (commandResult: CommandResult) => boolean;\n\n\nexport class CommandResults implements ICommandResult {\n constructor(private readonly _commandResultsPerCommand: Map<Command, CommandResult>) {\n }\n\n /** @inheritdoc */\n readonly correlationId: Guid = Guid.empty;\n\n /** @inheritdoc */\n get isSuccess(): boolean {\n return this.isAnyFalse(_ => _.isSuccess);\n }\n\n /** @inheritdoc */\n get isAuthorized(): boolean {\n return this.isAnyFalse(_ => _.isAuthorized);\n }\n\n /** @inheritdoc */\n get isValid(): boolean {\n return this.isAnyFalse(_ => _.isValid);\n }\n\n /** @inheritdoc */\n get hasExceptions(): boolean {\n return this.isAnyTrue(_ => _.hasExceptions);\n }\n\n /** @inheritdoc */\n get validationResults(): ValidationResult[] {\n const errors: ValidationResult[] = [];\n\n for (const result of this._commandResultsPerCommand.values()) {\n result.validationResults.forEach(_ => errors.push(_));\n }\n\n return errors;\n }\n\n /** @inheritdoc */\n get exceptionMessages(): string[] {\n const messages: string[] = [];\n\n for (const result of this._commandResultsPerCommand.values()) {\n result.exceptionMessages.forEach(_ => messages.push(_));\n }\n\n return messages;\n }\n\n /** @inheritdoc */\n get authorizationFailureReason(): string {\n const reasons: string[] = [];\n\n for (const result of this._commandResultsPerCommand.values()) {\n if (result.authorizationFailureReason) {\n reasons.push(result.authorizationFailureReason);\n }\n }\n\n return reasons.join('; ');\n }\n\n /** @inheritdoc */\n get exceptionStackTrace(): string {\n let stackTraces = '';\n\n for (const result of this._commandResultsPerCommand.values()) {\n stackTraces = stackTraces + '\\n' + result.exceptionStackTrace;\n }\n\n return stackTraces;\n\n }\n\n\n isAnyFalse(callback: GetSpecificState) {\n for (const result of this._commandResultsPerCommand.values()) {\n if (!callback(result)) {\n return false;\n }\n }\n return true;\n }\n\n isAnyTrue(callback: GetSpecificState) {\n for (const result of this._commandResultsPerCommand.values()) {\n if (callback(result)) {\n return true;\n }\n }\n return false;\n }\n}\n"],"names":["CommandResults","_commandResultsPerCommand","correlationId","Guid","empty","isSuccess","isAnyFalse","_","isAuthorized","isValid","hasExceptions","isAnyTrue","validationResults","errors","result","values","forEach","push","exceptionMessages","messages","authorizationFailureReason","reasons","join","exceptionStackTrace","stackTraces","callback"],"mappings":";;AAAA;AACA;AAWO,MAAMA,cAAAA,CAAAA;;IACT,WAAA,CAA6BC,yBAAsD,CAAE;aAAxDA,yBAAAA,GAAAA,yBAAAA;AAC7B,IAAA;AAEA,uBACSC,aAAAA,GAAsBC,IAAAA,CAAKC,KAAK;uBAGzC,IAAIC,SAAAA,GAAqB;AACrB,QAAA,OAAO,IAAI,CAACC,UAAU,CAACC,CAAAA,CAAAA,GAAKA,EAAEF,SAAS,CAAA;AAC3C,IAAA;uBAGA,IAAIG,YAAAA,GAAwB;AACxB,QAAA,OAAO,IAAI,CAACF,UAAU,CAACC,CAAAA,CAAAA,GAAKA,EAAEC,YAAY,CAAA;AAC9C,IAAA;uBAGA,IAAIC,OAAAA,GAAmB;AACnB,QAAA,OAAO,IAAI,CAACH,UAAU,CAACC,CAAAA,CAAAA,GAAKA,EAAEE,OAAO,CAAA;AACzC,IAAA;uBAGA,IAAIC,aAAAA,GAAyB;AACzB,QAAA,OAAO,IAAI,CAACC,SAAS,CAACJ,CAAAA,CAAAA,GAAKA,EAAEG,aAAa,CAAA;AAC9C,IAAA;uBAGA,IAAIE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AAA,CAAWmB,QAA0B,EAAE;AACnC,QAAA,KAAK,MAAMX,MAAAA,IAAU,IAAI,CAACb,yBAAyB,CAACc,MAAM,EAAA,CAAI;YAC1D,IAAI,CAACU,SAASX,MAAAA,CAAAA,EAAS;gBACnB,OAAO,KAAA;AACX,YAAA;AACJ,QAAA;QACA,OAAO,IAAA;AACX,IAAA;AAEAH,IAAAA,SAAAA,CAAUc,QAA0B,EAAE;AAClC,QAAA,KAAK,MAAMX,MAAAA,IAAU,IAAI,CAACb,yBAAyB,CAACc,MAAM,EAAA,CAAI;AAC1D,YAAA,IAAIU,SAASX,MAAAA,CAAAA,EAAS;gBAClB,OAAO,IAAA;AACX,YAAA;AACJ,QAAA;QACA,OAAO,KAAA;AACX,IAAA;AACJ;;;;"}
1
+ {"version":3,"file":"CommandResults.js","sources":["../../../commands/CommandResults.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 { Guid } from '@cratis/fundamentals';\nimport { ValidationResult } from '../validation/ValidationResult';\nimport { Command } from './Command';\nimport { CommandResult } from './CommandResult';\nimport { ICommandResult } from './ICommandResult';\n\ntype GetSpecificState = (commandResult: CommandResult) => boolean;\n\n\nexport class CommandResults implements ICommandResult {\n constructor(private readonly _commandResultsPerCommand: Map<Command, CommandResult>) {\n }\n\n /** @inheritdoc */\n readonly correlationId: Guid = Guid.empty;\n\n /** @inheritdoc */\n get isSuccess(): boolean {\n return this.isAnyFalse(_ => _.isSuccess);\n }\n\n /** @inheritdoc */\n get isAuthorized(): boolean {\n return this.isAnyFalse(_ => _.isAuthorized);\n }\n\n /** @inheritdoc */\n get isValid(): boolean {\n return this.isAnyFalse(_ => _.isValid);\n }\n\n /** @inheritdoc */\n get hasExceptions(): boolean {\n return this.isAnyTrue(_ => _.hasExceptions);\n }\n\n /** @inheritdoc */\n get validationResults(): ValidationResult[] {\n const errors: ValidationResult[] = [];\n\n for (const result of this._commandResultsPerCommand.values()) {\n result.validationResults.forEach(_ => errors.push(_));\n }\n\n return errors;\n }\n\n /** @inheritdoc */\n get exceptionMessages(): string[] {\n const messages: string[] = [];\n\n for (const result of this._commandResultsPerCommand.values()) {\n result.exceptionMessages.forEach(_ => messages.push(_));\n }\n\n return messages;\n }\n\n /** @inheritdoc */\n get authorizationFailureReason(): string {\n const reasons: string[] = [];\n\n for (const result of this._commandResultsPerCommand.values()) {\n if (result.authorizationFailureReason) {\n reasons.push(result.authorizationFailureReason);\n }\n }\n\n return reasons.join('; ');\n }\n\n /** @inheritdoc */\n get exceptionStackTrace(): string {\n let stackTraces = '';\n\n for (const result of this._commandResultsPerCommand.values()) {\n stackTraces = stackTraces + '\\n' + result.exceptionStackTrace;\n }\n\n return stackTraces;\n\n }\n\n\n isAnyFalse(callback: GetSpecificState) {\n for (const result of this._commandResultsPerCommand.values()) {\n if (!callback(result)) {\n return false;\n }\n }\n return true;\n }\n\n isAnyTrue(callback: GetSpecificState) {\n for (const result of this._commandResultsPerCommand.values()) {\n if (callback(result)) {\n return true;\n }\n }\n return false;\n }\n}\n"],"names":["CommandResults","_commandResultsPerCommand","correlationId","Guid","empty","isSuccess","isAnyFalse","_","isAuthorized","isValid","hasExceptions","isAnyTrue","validationResults","errors","result","values","forEach","push","exceptionMessages","messages","authorizationFailureReason","reasons","join","exceptionStackTrace","stackTraces","callback"],"mappings":";;AAAA;AACA;AAWO,MAAMA,cAAAA,CAAAA;;IACT,WAAA,CAA6BC,yBAAsD,CAAE;aAAxDA,yBAAAA,GAAAA,yBAAAA;AAC7B,IAAA;AAEA,uBACSC,aAAAA,GAAsBC,IAAAA,CAAKC,KAAK;uBAGzC,IAAIC,SAAAA,GAAqB;AACrB,QAAA,OAAO,IAAI,CAACC,UAAU,CAACC,CAAAA,CAAAA,GAAKA,EAAEF,SAAS,CAAA;AAC3C,IAAA;uBAGA,IAAIG,YAAAA,GAAwB;AACxB,QAAA,OAAO,IAAI,CAACF,UAAU,CAACC,CAAAA,CAAAA,G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A;AACxB,IAAA;uBAGA,IAAIC,mBAAAA,GAA8B;AAC9B,QAAA,IAAIC,WAAAA,GAAc,EAAA;AAElB,QAAA,KAAK,MAAMV,MAAAA,IAAU,IAAI,CAACb,yBAAyB,CAACc,MAAM,EAAA,CAAI;YAC1DS,WAAAA,GAAcA,WAAAA,GAAc,IAAA,GAAOV,MAAAA,CAAOS,mBAAmB;AACjE,QAAA;QAEA,OAAOC,WAAAA;AAEX,IAAA;AAGAlB,IAAAA,UAAAA,CAAWmB,QAA0B,EAAE;AACnC,QAAA,KAAK,MAAMX,MAAAA,IAAU,IAAI,CAACb,yBAAyB,CAACc,MAAM,EAAA,CAAI;YAC1D,IAAI,CAACU,SAASX,MAAAA,CAAAA,EAAS;gBACnB,OAAO,KAAA;AACX,YAAA;AACJ,QAAA;QACA,OAAO,IAAA;AACX,IAAA;AAEAH,IAAAA,SAAAA,CAAUc,QAA0B,EAAE;AAClC,QAAA,KAAK,MAAMX,MAAAA,IAAU,IAAI,CAACb,yBAAyB,CAACc,MAAM,EAAA,CAAI;AAC1D,YAAA,IAAIU,SAASX,MAAAA,CAAAA,EAAS;gBAClB,OAAO,IAAA;AACX,YAAA;AACJ,QAAA;QACA,OAAO,KAAA;AACX,IAAA;AACJ;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"CommandValidator.js","sources":["../../../commands/CommandValidator.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 { Validator } from '../validation/Validator';\nimport { ValidationResult } from '../validation/ValidationResult';\n\n/**\n * Represents the command validator\n */\nexport abstract class CommandValidator<T = object> extends Validator<T> {\n /**\n * Validate the command.\n * @param command The command to validate.\n * @returns An array of validation results, empty if valid.\n */\n validate(command: T): ValidationResult[] {\n return super.validate(command);\n }\n}\n"],"names":["CommandValidator","Validator","validate","command"],"mappings":";;AAAA;AACA;AAKA;;IAGO,MAAeA,gBAAAA,SAAqCC,SAAAA,CAAAA;AACvD;;;;QAKAC,QAAAA,CAASC,OAAU,EAAsB;QACrC,OAAO,KAAK,CAACD,QAAAA,CAASC,OAAAA,CAAAA;AAC1B,IAAA;AACJ;;;;"}
1
+ {"version":3,"file":"CommandValidator.js","sources":["../../../commands/CommandValidator.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 { Validator } from '../validation/Validator';\nimport { ValidationResult } from '../validation/ValidationResult';\n\n/**\n * Represents the command validator\n */\nexport abstract class CommandValidator<T = object> extends Validator<T> {\n /**\n * Validate the command.\n * @param command The command to validate.\n * @returns An array of validation results, empty if valid.\n */\n validate(command: T): ValidationResult[] {\n return super.validate(command);\n }\n}\n"],"names":["CommandValidator","Validator","validate","command"],"mappings":";;AAAA;AACA;AAKA;;IAGO,MAAeA,gBAAAA,SAAqCC,SAAAA,CAAAA;AACvD;;;;QAKAC,QAAAA,CAASC,OAAU,EAAsB;QACrC,OAAO,KAAK,CAACD,QAAAA,CAASC,OAAAA,CAAAA;AAC1B,IAAA;AACJ;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"deepEqual.js","sources":["../../deepEqual.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\nexport const deepEqual = (obj1, obj2) => {\n if (obj1 === obj2) return true; // Same reference or primitive value\n\n if (obj1 == null || obj2 == null || typeof obj1 !== \"object\" || typeof obj2 !== \"object\") {\n return false; // Handle null, undefined, or different types\n }\n\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n\n if (keys1.length !== keys2.length) {\n return false; // Different number of keys\n }\n\n for (const key of keys1) {\n if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) return false;\n }\n\n return true; // All keys and values match\n};"],"names":["deepEqual","obj1","obj2","keys1","Object","keys","keys2","length","key","includes"],"mappings":"AAAA;AACA;AAEO,MAAMA,SAAAA,GAAY,CAACC,IAAAA,EAAMC,IAAAA,GAAAA;AAC5B,IAAA,IAAID,IAAAA,KAASC,IAAAA,EAAM,OAAO,IAAA,CAAA;IAE1B,IAAID,IAAAA,IAAQ,QAAQC,IAAAA,IAAQ,IAAA,IAAQ,OAAOD,IAAAA,KAAS,QAAA,IAAY,OAAOC,IAAAA,KAAS,QAAA,EAAU;AACtF,QAAA,OAAO;AACX,IAAA;IAEA,MAAMC,KAAAA,GAAQC,MAAAA,CAAOC,IAAI,CAACJ,IAAAA,CAAAA;IAC1B,MAAMK,KAAAA,GAAQF,MAAAA,CAAOC,IAAI,CAACH,IAAAA,CAAAA;AAE1B,IAAA,IAAIC,KAAAA,CAAMI,MAAM,KAAKD,KAAAA,CAAMC,MAAM,EAAE;AAC/B,QAAA,OAAO;AACX,IAAA;IAEA,KAAK,MAAMC,OAAOL,KAAAA,CAAO;AACrB,QAAA,IAAI,CAACG,KAAAA,CAAMG,QAAQ,CAACD,QAAQ,CAACR,SAAAA,CAAUC,IAAI,CAACO,IAAI,EAAEN,IAAI,CAACM,GAAAA,CAAI,GAAG,OAAO,KAAA;AACzE,IAAA;AAEA,IAAA,OAAO;AACX;;;;"}
1
+ {"version":3,"file":"deepEqual.js","sources":["../../deepEqual.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\nexport const deepEqual = (obj1, obj2) => {\n if (obj1 === obj2) return true; // Same reference or primitive value\n\n if (obj1 == null || obj2 == null || typeof obj1 !== \"object\" || typeof obj2 !== \"object\") {\n return false; // Handle null, undefined, or different types\n }\n\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n\n if (keys1.length !== keys2.length) {\n return false; // Different number of keys\n }\n\n for (const key of keys1) {\n if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) return false;\n }\n\n return true; // All keys and values match\n};"],"names":["deepEqual","obj1","obj2","keys1","Object","keys","keys2","length","key","includes"],"mappings":"AAAA;AACA;AAEO,MAAMA,SAAAA,GAAY,CAACC,IAAAA,EAAMC,IAAAA,GAAAA;AAC5B,IAAA,IAAID,IAAAA,KAASC,IAAAA,EAAM,OAAO,IAAA,CAAA;IAE1B,IAAID,IAAAA,IAAQ,QAAQC,IAAAA,IAAQ,IAAA,IAAQ,OAAOD,IAAAA,KAAS,QAAA,IAAY,OAAOC,IAAAA,KAAS,QAAA,EAAU;AACtF,QAAA,OAAO;AACX,IAAA;IAEA,MAAMC,KAAAA,GAAQC,MAAAA,CAAOC,IAAI,CAACJ,IAAAA,CAAAA;IAC1B,MAAMK,KAAAA,GAAQF,MAAAA,CAAOC,IAAI,CAACH,IAAAA,CAAAA;AAE1B,IAAA,IAAIC,KAAAA,CAAMI,MAAM,KAAKD,KAAAA,CAAMC,MAAM,EAAE;AAC/B,QAAA,OAAO;AACX,IAAA;IAEA,KAAK,MAAMC,OAAOL,KAAAA,CAAO;AACrB,QAAA,IAAI,CAACG,KAAAA,CAAMG,QAAQ,CAACD,QAAQ,CAACR,SAAAA,CAAUC,IAAI,CAACO,IAAI,EAAEN,IAAI,CAACM,GAAAA,CAAI,GAAG,OAAO,KAAA;AACzE,IAAA;AAEA,IAAA,OAAO;AACX;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"IIdentityProvider.js","sources":["../../../identity/IIdentityProvider.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 '@cratis/fundamentals';\nimport { IIdentity } from './IIdentity';\n\n/**\n * Defines the identity provider.\n */\nexport abstract class IIdentityProvider {\n\n /**\n * Gets the current identity by optionally specifying the details type.\n * @param type Optional constructor for the details type to enable type-safe deserialization.\n * @returns The current identity as {@link IIdentity}.\n * @remarks The `extends object` constraint is required for compatibility with JsonSerializer.deserializeFromInstance().\n */\n abstract getCurrent<TDetails extends object = object>(type?: Constructor<TDetails>): Promise<IIdentity<TDetails>>;\n}\n"],"names":["IIdentityProvider"],"mappings":"AAAA;AACA;AAKA;;AAEC,IACM,MAAeA,iBAAAA,CAAAA;AAStB;;;;"}
1
+ {"version":3,"file":"IIdentityProvider.js","sources":["../../../identity/IIdentityProvider.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 '@cratis/fundamentals';\nimport { IIdentity } from './IIdentity';\n\n/**\n * Defines the identity provider.\n */\nexport abstract class IIdentityProvider {\n\n /**\n * Gets the current identity by optionally specifying the details type.\n * @param type Optional constructor for the details type to enable type-safe deserialization.\n * @returns The current identity as {@link IIdentity}.\n * @remarks The `extends object` constraint is required for compatibility with JsonSerializer.deserializeFromInstance().\n */\n abstract getCurrent<TDetails extends object = object>(type?: Constructor<TDetails>): Promise<IIdentity<TDetails>>;\n}\n"],"names":["IIdentityProvider"],"mappings":"AAAA;AACA;AAKA;;AAEC,IACM,MAAeA,iBAAAA,CAAAA;AAStB;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"IdentityProvider.js","sources":["../../../identity/IdentityProvider.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, JsonSerializer } from '@cratis/fundamentals';\nimport { IIdentityProvider } from './IIdentityProvider';\nimport { IIdentity } from './IIdentity';\nimport { IdentityProviderResult } from './IdentityProviderResult';\nimport { GetHttpHeaders } from '../GetHttpHeaders';\nimport { Globals } from '../Globals';\nimport { UrlHelpers } from '../UrlHelpers';\nimport { joinPaths } from '../joinPaths';\n\n/**\n * Represents an implementation of {@link IIdentityProvider}.\n*/\nexport class IdentityProvider extends IIdentityProvider {\n\n static readonly CookieName = '.cratis-identity';\n static httpHeadersCallback: GetHttpHeaders | undefined;\n static apiBasePath: string = '';\n static origin: string = '';\n\n /**\n * Sets the HTTP headers callback.\n * @param callback Callback to set.\n */\n static setHttpHeadersCallback(callback: GetHttpHeaders): void {\n IdentityProvider.httpHeadersCallback = callback;\n }\n\n /**\n * Sets the API base path.\n * @param apiBasePath API base path to set.\n */\n static setApiBasePath(apiBasePath: string): void {\n IdentityProvider.apiBasePath = apiBasePath;\n }\n\n /**\n * Sets the origin.\n * @param origin Origin to set.\n */\n static setOrigin(origin: string): void {\n IdentityProvider.origin = origin;\n }\n\n /**\n * Gets the current identity by optionally specifying the details type.\n * @param type Optional constructor for the details type to enable type-safe deserialization.\n * @returns The current identity as {@link IIdentity}.\n * @remarks The `extends object` constraint is required for compatibility with JsonSerializer.deserializeFromInstance().\n */\n static async getCurrent<TDetails extends object = object>(type?: Constructor<TDetails>): Promise<IIdentity<TDetails>> {\n const cookie = this.getCookie();\n if (cookie.length == 2) {\n const json = atob(cookie[1]);\n const result = JSON.parse(json) as IdentityProviderResult;\n const details = type ? JsonSerializer.deserializeFromInstance(type, result.details) : result.details;\n return {\n id: result.id,\n name: result.name,\n roles: result.roles || [],\n details: details as TDetails,\n isSet: true,\n isInRole: (role: string) => (result.roles || []).includes(role),\n refresh: () => IdentityProvider.refresh(type)\n } as IIdentity<TDetails>;\n } else {\n const identity = await this.refresh<TDetails>(type);\n return identity;\n }\n }\n\n /** @inheritdoc */\n async getCurrent<TDetails extends object = object>(type?: Constructor<TDetails>): Promise<IIdentity<TDetails>> {\n return IdentityProvider.getCurrent<TDetails>(type);\n }\n\n static async refresh<TDetails extends object = object>(type?: Constructor<TDetails>): Promise<IIdentity<TDetails>> {\n IdentityProvider.clearIdentityCookie();\n const origin = IdentityProvider.origin || Globals.origin || '';\n const apiBasePath = IdentityProvider.apiBasePath || Globals.apiBasePath || '';\n const route = joinPaths(apiBasePath, '/.cratis/me');\n const url = UrlHelpers.createUrlFrom(origin, apiBasePath, route);\n const response = await fetch(\n url, {\n method: 'GET',\n headers: IdentityProvider.httpHeadersCallback?.() ?? {}\n });\n\n if (!response.ok) {\n return IdentityProvider.notSet(type);\n }\n\n const result = await response.json() as IdentityProviderResult;\n const details = type ? JsonSerializer.deserializeFromInstance(type, result.details) : result.details;\n\n return {\n id: result.id,\n name: result.name,\n roles: result.roles || [],\n details: details as TDetails,\n isSet: true,\n isInRole: (role: string) => (result.roles || []).includes(role),\n refresh: () => IdentityProvider.refresh(type)\n };\n }\n\n private static notSet<TDetails extends object = object>(type?: Constructor<TDetails>): IIdentity<TDetails> {\n return {\n id: '',\n name: '',\n roles: [],\n details: {} as TDetails,\n isSet: false,\n isInRole: () => false,\n refresh: () => IdentityProvider.refresh(type)\n };\n }\n\n private static getCookie() {\n if (typeof document === 'undefined') return [];\n const decoded = decodeURIComponent(document.cookie);\n const cookies = decoded.split(';').map(_ => _.trim());\n const cookie = cookies.find(_ => _.indexOf(`${IdentityProvider.CookieName}=`) == 0);\n if (cookie) {\n const keyValue = cookie.split('=');\n return [keyValue[0].trim(), keyValue[1].trim()];\n }\n return [];\n }\n\n /**\n * Clears the identity cookie used by Arc to cache the current identity.\n * Call this when the user logs out to ensure subsequent requests and WebSocket\n * connections do not carry stale credentials.\n */\n static clearIdentityCookie(): void {\n if (typeof document === 'undefined') return;\n document.cookie = `${IdentityProvider.CookieName}=;expires=Thu, 01 Jan 1970 00:00:00 GMT`;\n }\n}\n"],"names":["IdentityProvider","IIdentityProvider","CookieName","httpHeadersCallback","apiBasePath","origin","setHttpHeadersCallback","callback","setApiBasePath","setOrigin","getCurrent","type","cookie","getCookie","length","json","atob","result","JSON","parse","details","JsonSerializer","deserializeFromInstance","id","name","roles","isSet","isInRole","role","includes","refresh","identity","clearIdentityCookie","Globals","route","joinPaths","url","UrlHelpers","createUrlFrom","response","fetch","method","headers","ok","notSet","document","decoded","decodeURIComponent","cookies","split","map","_","trim","find","indexOf","keyValue"],"mappings":";;;;;;AAAA;AACA;AAWA;;AAEA,GACO,MAAMA,gBAAAA,SAAyBC,iBAAAA,CAAAA;AAElC,IAAA,OAAgBC,aAAa,kBAAA;AAC7B,IAAA,OAAOC,mBAAAA;AACP,IAAA,OAAOC,cAAsB,EAAA;AAC7B,IAAA,OAAOC,SAAiB,EAAA;AAExB;;;Q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AK,CAAC,GAAA,CAAA;YAC9B,OAAO;gBAACM,QAAQ,CAAC,CAAA,CAAE,CAACH,IAAI,EAAA;gBAAIG,QAAQ,CAAC,CAAA,CAAE,CAACH,IAAI;AAAG,aAAA;AACnD,QAAA;AACA,QAAA,OAAO,EAAE;AACb,IAAA;AAEA;;;;AAIC,QACD,OAAOpB,mBAAAA,GAA4B;QAC/B,IAAI,OAAOa,aAAa,WAAA,EAAa;AACrCA,QAAAA,QAAAA,CAASjC,MAAM,GAAG,CAAA,EAAGZ,iBAAiBE,UAAU,CAAC,uCAAuC,CAAC;AAC7F,IAAA;AACJ;;;;"}
1
+ {"version":3,"file":"IdentityProvider.js","sources":["../../../identity/IdentityProvider.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, JsonSerializer } from '@cratis/fundamentals';\nimport { IIdentityProvider } from './IIdentityProvider';\nimport { IIdentity } from './IIdentity';\nimport { IdentityProviderResult } from './IdentityProviderResult';\nimport { GetHttpHeaders } from '../GetHttpHeaders';\nimport { Globals } from '../Globals';\nimport { UrlHelpers } from '../UrlHelpers';\nimport { joinPaths } from '../joinPaths';\n\n/**\n * Represents an implementation of {@link IIdentityProvider}.\n*/\nexport class IdentityProvider extends IIdentityProvider {\n\n static readonly CookieName = '.cratis-identity';\n static httpHeadersCallback: GetHttpHeaders | undefined;\n static apiBasePath: string = '';\n static origin: string = '';\n\n /**\n * Sets the HTTP headers callback.\n * @param callback Callback to set.\n */\n static setHttpHeadersCallback(callback: GetHttpHeaders): void {\n IdentityProvider.httpHeadersCallback = callback;\n }\n\n /**\n * Sets the API base path.\n * @param apiBasePath API base path to set.\n */\n static setApiBasePath(apiBasePath: string): void {\n IdentityProvider.apiBasePath = apiBasePath;\n }\n\n /**\n * Sets the origin.\n * @param origin Origin to set.\n */\n static setOrigin(origin: string): void {\n IdentityProvider.origin = origin;\n }\n\n /**\n * Gets the current identity by optionally specifying the details type.\n * @param type Optional constructor for the details type to enable type-safe deserialization.\n * @returns The current identity as {@link IIdentity}.\n * @remarks The `extends object` constraint is required for compatibility with JsonSerializer.deserializeFromInstance().\n */\n static async getCurrent<TDetails extends object = object>(type?: Constructor<TDetails>): Promise<IIdentity<TDetails>> {\n const cookie = this.getCookie();\n if (cookie.length == 2) {\n const json = atob(cookie[1]);\n const result = JSON.parse(json) as IdentityProviderResult;\n const details = type ? JsonSerializer.deserializeFromInstance(type, result.details) : result.details;\n return {\n id: result.id,\n name: result.name,\n roles: result.roles || [],\n details: details as TDetails,\n isSet: true,\n isInRole: (role: string) => (result.roles || []).includes(role),\n refresh: () => IdentityProvider.refresh(type)\n } as IIdentity<TDetails>;\n } else {\n const identity = await this.refresh<TDetails>(type);\n return identity;\n }\n }\n\n /** @inheritdoc */\n async getCurrent<TDetails extends object = object>(type?: Constructor<TDetails>): Promise<IIdentity<TDetails>> {\n return IdentityProvider.getCurrent<TDetails>(type);\n }\n\n static async refresh<TDetails extends object = object>(type?: Constructor<TDetails>): Promise<IIdentity<TDetails>> {\n IdentityProvider.clearIdentityCookie();\n const origin = IdentityProvider.origin || Globals.origin || '';\n const apiBasePath = IdentityProvider.apiBasePath || Globals.apiBasePath || '';\n const route = joinPaths(apiBasePath, '/.cratis/me');\n const url = UrlHelpers.createUrlFrom(origin, apiBasePath, route);\n const response = await fetch(\n url, {\n method: 'GET',\n headers: IdentityProvider.httpHeadersCallback?.() ?? {}\n });\n\n if (!response.ok) {\n return IdentityProvider.notSet(type);\n }\n\n const result = await response.json() as IdentityProviderResult;\n const details = type ? JsonSerializer.deserializeFromInstance(type, result.details) : result.details;\n\n return {\n id: result.id,\n name: result.name,\n roles: result.roles || [],\n details: details as TDetails,\n isSet: true,\n isInRole: (role: string) => (result.roles || []).includes(role),\n refresh: () => IdentityProvider.refresh(type)\n };\n }\n\n private static notSet<TDetails extends object = object>(type?: Constructor<TDetails>): IIdentity<TDetails> {\n return {\n id: '',\n name: '',\n roles: [],\n details: {} as TDetails,\n isSet: false,\n isInRole: () => false,\n refresh: () => IdentityProvider.refresh(type)\n };\n }\n\n private static getCookie() {\n if (typeof document === 'undefined') return [];\n const decoded = decodeURIComponent(document.cookie);\n const cookies = decoded.split(';').map(_ => _.trim());\n const cookie = cookies.find(_ => _.indexOf(`${IdentityProvider.CookieName}=`) == 0);\n if (cookie) {\n const keyValue = cookie.split('=');\n return [keyValue[0].trim(), keyValue[1].trim()];\n }\n return [];\n }\n\n /**\n * Clears the identity cookie used by Arc to cache the current identity.\n * Call this when the user logs out to ensure subsequent requests and WebSocket\n * connections do not carry stale credentials.\n */\n static clearIdentityCookie(): void {\n if (typeof document === 'undefined') return;\n document.cookie = `${IdentityProvider.CookieName}=;expires=Thu, 01 Jan 1970 00:00:00 GMT`;\n }\n}\n"],"names":["IdentityProvider","IIdentityProvider","CookieName","httpHeadersCallback","apiBasePath","origin","setHttpHeadersCallback","callback","setApiBasePath","setOrigin","getCurrent","type","cookie","getCookie","length","json","atob","result","JSON","parse","details","JsonSerializer","deserializeFromInstance","id","name","roles","isSet","isInRole","role","includes","refresh","identity","clearIdentityCookie","Globals","route","joinPaths","url","UrlHelpers","createUrlFrom","response","fetch","method","headers","ok","notSet","document","decoded","decodeURIComponent","cookies","split","map","_","trim","find","indexOf","keyValue"],"mappings":";;;;;;AAAA;AACA;AAWA;;AAEA,GACO,MAAMA,gBAAAA,SAAyBC,iBAAAA,CAAAA;AAElC,IAAA,OAAgBC,aAAa,kBAAA;AAC7B,IAAA,OAAOC,mBAAAA;AACP,IAAA,OAAOC,cAAsB,EAAA;AAC7B,IAAA,OAAOC,SAAiB,EAAA;AAExB;;;QAIA,OAAOC,sBAAAA,CAAuBC,QAAwB,EAAQ;AAC1DP,QAAAA,gBAAAA,CAAiBG,mBAAmB,GAAGI,QAAAA;AAC3C,IAAA;AAEA;;;QAIA,OAAOC,cAAAA,CAAeJ,WAAmB,EAAQ;AAC7CJ,QAAAA,gBAAAA,CAAiBI,WAAW,GAAGA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OAAOpB,mBAAAA,GAA4B;QAC/B,IAAI,OAAOa,aAAa,WAAA,EAAa;AACrCA,QAAAA,QAAAA,CAASjC,MAAM,GAAG,CAAA,EAAGZ,iBAAiBE,UAAU,CAAC,uCAAuC,CAAC;AAC7F,IAAA;AACJ;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"joinPaths.js","sources":["../../joinPaths.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\nexport function joinPaths(...paths) {\n const joined = paths.join('/');\n return joined.replace('//', '/');\n}"],"names":["joinPaths","paths","joined","join","replace"],"mappings":"AAAA;AACA;AAEO,SAASA,SAAAA,CAAU,GAAGC,KAAK,EAAA;IAC9B,MAAMC,MAAAA,GAASD,KAAAA,CAAME,IAAI,CAAC,GAAA,CAAA;IAC1B,OAAOD,MAAAA,CAAOE,OAAO,CAAC,IAAA,EAAM,GAAA,CAAA;AAChC;;;;"}
1
+ {"version":3,"file":"joinPaths.js","sources":["../../joinPaths.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\nexport function joinPaths(...paths) {\n const joined = paths.join('/');\n return joined.replace('//', '/');\n}"],"names":["joinPaths","paths","joined","join","replace"],"mappings":"AAAA;AACA;AAEO,SAASA,SAAAA,CAAU,GAAGC,KAAK,EAAA;IAC9B,MAAMC,MAAAA,GAASD,KAAAA,CAAME,IAAI,CAAC,GAAA,CAAA;IAC1B,OAAOD,MAAAA,CAAOE,OAAO,CAAC,IAAA,EAAM,GAAA,CAAA;AAChC;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"IMessenger.js","sources":["../../../messaging/IMessenger.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 '@cratis/fundamentals';\nimport { Subscription } from 'rxjs';\n\n/**\n * Represents a message handler.\n */\nexport type MessageHandler<T> = (message: T) => void;\n\n/**\n * Defines a system for publishing and subscribing to messages.\n */\nexport abstract class IMessenger {\n\n /**\n * Gets or sets whether published messages should bubble to the parent messenger.\n * Defaults to false.\n */\n abstract bubbleToParent: boolean;\n\n /**\n * Gets or sets whether messages should trickle down to child messengers.\n * Defaults to true.\n */\n abstract trickleDownToChildren: boolean;\n\n /**\n * Publish a message.\n * @param {*} message Message to publish.\n */\n abstract publish<TMessage extends object>(message: TMessage): void;\n\n /**\n * Subscribe to a specific message type.\n * @param {MessageHandler} callback Callback that gets called when message arrives.\n */\n abstract subscribe<TMessage extends object>(type: Constructor<TMessage>, callback: MessageHandler<TMessage>): Subscription;\n}\n"],"names":["IMessenger"],"mappings":"AAAA;AACA;AAUA;;AAEC,IACM,MAAeA,UAAAA,CAAAA;AAyBtB;;;;"}
1
+ {"version":3,"file":"IMessenger.js","sources":["../../../messaging/IMessenger.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 '@cratis/fundamentals';\nimport { Subscription } from 'rxjs';\n\n/**\n * Represents a message handler.\n */\nexport type MessageHandler<T> = (message: T) => void;\n\n/**\n * Defines a system for publishing and subscribing to messages.\n */\nexport abstract class IMessenger {\n\n /**\n * Gets or sets whether published messages should bubble to the parent messenger.\n * Defaults to false.\n */\n abstract bubbleToParent: boolean;\n\n /**\n * Gets or sets whether messages should trickle down to child messengers.\n * Defaults to true.\n */\n abstract trickleDownToChildren: boolean;\n\n /**\n * Publish a message.\n * @param {*} message Message to publish.\n */\n abstract publish<TMessage extends object>(message: TMessage): void;\n\n /**\n * Subscribe to a specific message type.\n * @param {MessageHandler} callback Callback that gets called when message arrives.\n */\n abstract subscribe<TMessage extends object>(type: Constructor<TMessage>, callback: MessageHandler<TMessage>): Subscription;\n}\n"],"names":["IMessenger"],"mappings":"AAAA;AACA;AAUA;;AAEC,IACM,MAAeA,UAAAA,CAAAA;AAyBtB;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"Message.js","sources":["../../../messaging/Message.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 '@cratis/fundamentals';\n\n/**\n * Represents a message published on the {@link Messenger}.\n */\nexport class Message {\n\n /**\n * Initializes a new instance of {@link Message}.\n * @param {Constructor} type Type of the content in the message.\n * @param {*} content The actual content.\n */\n constructor(readonly type: Constructor, readonly content: object) {\n }\n}\n"],"names":["Message","content","type"],"mappings":"AAAA;AACA;AAIA;;AAEC,IACM,MAAMA,OAAAA,CAAAA;;;AAET;;;;AAIC,QACD,YAAY,IAA0B,EAAWC,OAAe,CAAE;aAA7CC,IAAAA,GAAAA,IAAAA;aAA4BD,OAAAA,GAAAA,OAAAA;AACjD,IAAA;AACJ;;;;"}
1
+ {"version":3,"file":"Message.js","sources":["../../../messaging/Message.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 '@cratis/fundamentals';\n\n/**\n * Represents a message published on the {@link Messenger}.\n */\nexport class Message {\n\n /**\n * Initializes a new instance of {@link Message}.\n * @param {Constructor} type Type of the content in the message.\n * @param {*} content The actual content.\n */\n constructor(readonly type: Constructor, readonly content: object) {\n }\n}\n"],"names":["Message","content","type"],"mappings":"AAAA;AACA;AAIA;;AAEC,IACM,MAAMA,OAAAA,CAAAA;;;AAET;;;;AAIC,QACD,YAAY,IAA0B,EAAWC,OAAe,CAAE;aAA7CC,IAAAA,GAAAA,IAAAA;aAA4BD,OAAAA,GAAAA,OAAAA;AACjD,IAAA;AACJ;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"Messenger.js","sources":["../../../messaging/Messenger.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 '@cratis/fundamentals';\nimport { filter, Subject, Subscription } from 'rxjs';\nimport { IMessenger } from './IMessenger';\nimport { Message } from './Message';\n\n/**\n * Represents an implementation of {@link IMessenger}.\n */\nexport class Messenger extends IMessenger {\n bubbleToParent = false;\n trickleDownToChildren = true;\n\n private readonly _messages = new Subject<Message>();\n private readonly _children = new Set<Messenger>();\n\n constructor(private readonly _parent?: Messenger) {\n super();\n this._parent?._children.add(this);\n }\n\n /**\n * Dispose this messenger and remove it from its parent.\n */\n dispose() {\n this._parent?._children.delete(this);\n }\n\n /** @inheritdoc */\n publish<TMessage extends object>(message: TMessage): void {\n this._publishFromSelf(message);\n }\n\n /** @inheritdoc */\n subscribe<TMessage extends object>(type: Constructor<TMessage>, callback: (message: TMessage) => void): Subscription {\n const observable = this._messages.pipe(filter(m => m.type === type));\n const subscription = observable.subscribe(m => callback(m.content as TMessage));\n return subscription;\n }\n\n private _publishFromSelf<TMessage extends object>(message: TMessage) {\n this._publishLocally(message);\n\n if (this.bubbleToParent && this._parent) {\n this._parent._publishFromChild(message, this);\n }\n\n if (this.trickleDownToChildren) {\n this._publishToChildren(message);\n }\n }\n\n private _publishFromParent<TMessage extends object>(message: TMessage) {\n this._publishLocally(message);\n\n if (this.trickleDownToChildren) {\n this._publishToChildren(message);\n }\n }\n\n private _publishFromChild<TMessage extends object>(message: TMessage, child: Messenger) {\n this._publishLocally(message);\n\n if (this.bubbleToParent && this._parent) {\n this._parent._publishFromChild(message, this);\n }\n\n if (this.trickleDownToChildren) {\n this._publishToChildren(message, child);\n }\n }\n\n private _publishLocally<TMessage extends object>(message: TMessage) {\n this._messages.next(new Message(message.constructor as Constructor, message));\n }\n\n private _publishToChildren<TMessage extends object>(message: TMessage, excludedChild?: Messenger) {\n this._children.forEach(child => {\n if (child === excludedChild) {\n return;\n }\n child._publishFromParent(message);\n });\n }\n}\n"],"names":["Messenger","IMessenger","bubbleToParent","trickleDownToChildren","_messages","Subject","_children","Set","_parent","add","dispose","delete","publish","message","_publishFromSelf","subscribe","type","callback","observable","pipe","filter","m","subscription","content","_publishLocally","_publishFromChild","_publishToChildren","_publishFromParent","child","next","Message","excludedChild","forEach"],"mappings":";;;;AAAA;AACA;AAOA;;IAGO,MAAMA,SAAAA,SAAkBC,UAAAA,CAAAA;;AAC3BC,IAAAA,cAAAA,GAAiB,KAAA;AACjBC,IAAAA,qBAAAA,GAAwB,IAAA;AAEPC,IAAAA,SAAAA,GAAY,IAAIC,OAAAA,EAAAA;AAChBC,IAAAA,SAAAA,GAAY,IAAIC,GAAAA,EAAAA;IAEjC,WAAA,CAA6BC,OAAmB,CAAE;AAC9C,QAAA,KAAK,SADoBA,OAAAA,GAAAA,OAAAA;AAEzB,QAAA,IAAI,CAACA,OAAO,EAAEF,SAAAA,CAAUG,IAAI,IAAI,CAAA;AACpC,IAAA;AAEA;;AAEC,QACDC,OAAAA,GAAU;AACN,QAAA,IAAI,CAACF,OAAO,EAAEF,SAAAA,CAAUK,OAAO,IAAI,CAAA;AACvC,IAAA;uBAGAC,OAAAA,CAAiCC,OAAiB,EAAQ;QACtD,IAAI,CAACC,gBAAgB,CAACD,OAAAA,CAAAA;AAC1B,IAAA;AAEA,uBACAE,SAAAA,CAAmCC,IAA2B,EAAEC,QAAqC,EAAgB;AACjH,QAAA,MAAMC,UAAAA,GAAa,IAAI,CAACd,SAAS,CAACe,IAAI,CAACC,MAAAA,CAAOC,CAAAA,CAAAA,GAAKA,CAAAA,CAAEL,IAAI,KAAKA,IAAAA,CAAAA,CAAAA;QAC9D,MAAMM,YAAAA,GAAeJ,WAAWH,SAAS,CAACM,CAAAA,CAAAA,GAAKJ,QAAAA,CAASI,EAAEE,OAAO,CAAA,CAAA;QACjE,OAAOD,YAAAA;AACX,IAAA;AAEQR,IAAAA,gBAAAA,CAA0CD,OAAiB,EAAE;QACjE,IAAI,CAACW,eAAe,CAACX,OAAAA,CAAAA;AAErB,QAAA,IAAI,IAAI,CAACX,cAAc,IAAI,IAAI,CAACM,OAAO,EAAE;AACrC,YAAA,IAAI,CAACA,OAAO,CAACiB,iBA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sources":["../../../messaging/Messenger.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 '@cratis/fundamentals';\nimport { filter, Subject, Subscription } from 'rxjs';\nimport { IMessenger } from './IMessenger';\nimport { Message } from './Message';\n\n/**\n * Represents an implementation of {@link IMessenger}.\n */\nexport class Messenger extends IMessenger {\n bubbleToParent = false;\n trickleDownToChildren = true;\n\n private readonly _messages = new Subject<Message>();\n private readonly _children = new Set<Messenger>();\n\n constructor(private readonly _parent?: Messenger) {\n super();\n this._parent?._children.add(this);\n }\n\n /**\n * Dispose this messenger and remove it from its parent.\n */\n dispose() {\n this._parent?._children.delete(this);\n }\n\n /** @inheritdoc */\n publish<TMessage extends object>(message: TMessage): void {\n this._publishFromSelf(message);\n }\n\n /** @inheritdoc */\n subscribe<TMessage extends object>(type: Constructor<TMessage>, callback: (message: TMessage) => void): Subscription {\n const observable = this._messages.pipe(filter(m => m.type === type));\n const subscription = observable.subscribe(m => callback(m.content as TMessage));\n return subscription;\n }\n\n private _publishFromSelf<TMessage extends object>(message: TMessage) {\n this._publishLocally(message);\n\n if (this.bubbleToParent && this._parent) {\n this._parent._publishFromChild(message, this);\n }\n\n if (this.trickleDownToChildren) {\n this._publishToChildren(message);\n }\n }\n\n private _publishFromParent<TMessage extends object>(message: TMessage) {\n this._publishLocally(message);\n\n if (this.trickleDownToChildren) {\n this._publishToChildren(message);\n }\n }\n\n private _publishFromChild<TMessage extends object>(message: TMessage, child: Messenger) {\n this._publishLocally(message);\n\n if (this.bubbleToParent && this._parent) {\n this._parent._publishFromChild(message, this);\n }\n\n if (this.trickleDownToChildren) {\n this._publishToChildren(message, child);\n }\n }\n\n private _publishLocally<TMessage extends object>(message: TMessage) {\n this._messages.next(new Message(message.constructor as Constructor, message));\n }\n\n private _publishToChildren<TMessage extends object>(message: TMessage, excludedChild?: Messenger) {\n this._children.forEach(child => {\n if (child === excludedChild) {\n return;\n }\n child._publishFromParent(message);\n });\n }\n}\n"],"names":["Messenger","IMessenger","bubbleToParent","trickleDownToChildren","_messages","Subject","_children","Set","_parent","add","dispose","delete","publish","message","_publishFromSelf","subscribe","type","callback","observable","pipe","filter","m","subscription","content","_publishLocally","_publishFromChild","_publishToChildren","_publishFromParent","child","next","Message","excludedChild","forEach"],"mappings":";;;;AAAA;AACA;AAOA;;IAGO,MAAMA,SAAAA,SAAkBC,UAAAA,CAAAA;;AAC3BC,IAAAA,cAAAA,GAAiB,KAAA;AACjBC,IAAAA,qBAAAA,GAAwB,IAAA;AAEPC,IAAAA,SAAAA,GAAY,IAAIC,OAAAA,EAAAA;AAChBC,IAAAA,SAAAA,GAAY,IAAIC,GAAAA,EAAAA;IAEjC,WAAA,CAA6BC,OAAmB,CAAE;AAC9C,QAAA,KAAK,SADoBA,OAAAA,GAAAA,OAAAA;AAEzB,QAAA,IAAI,CAACA,OAAO,EAAEF,SAAAA,CAAUG,IAAI,IAAI,CAAA;AACpC,IAAA;AAEA;;AAEC,QACDC,OAAAA,GAAU;AACN,QAAA,IAAI,CAACF,OAAO,EAAEF,SAAAA,CAAUK,OAAO,IAAI,CAAA;AACvC,IAAA;uBAGAC,OAAAA,CAAiCC,OAAiB,EAAQ;QACtD,IAAI,CAACC,gBAAgB,CAACD,OAAAA,CAAAA;AAC1B,IAAA;AAEA,uBACAE,SAAAA,CAAmCC,IAA2B,EAAEC,QAAqC,EAAgB;AACjH,QAAA,MAAMC,UAAAA,GAAa,IAAI,CAACd,SAAS,CAACe,IAAI,CAACC,MAAAA,CAAOC,CAAAA,CAAAA,GAAKA,CAAAA,CAAEL,IAAI,KAAKA,IAAAA,CAAAA,CAAAA;QAC9D,MAAMM,YAAAA,GAAeJ,WAAWH,SAAS,CAACM,CAAAA,CAAAA,GAAKJ,QAAAA,CAASI,EAAEE,OAAO,CAAA,CAAA;QACjE,OAAOD,YAAAA;AACX,IAAA;AAEQR,IAAAA,gBAAAA,CAA0CD,OAAiB,EAAE;Q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BAAA;AACJ,YAAA;AACAH,YAAAA,KAAAA,CAAMD,kBAAkB,CAACd,OAAAA,CAAAA;AAC7B,QAAA,CAAA,CAAA;AACJ,IAAA;AACJ;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"HubConnectionKeepAlive.js","sources":["../../../queries/HubConnectionKeepAlive.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\n/**\n * Manages keep-alive behavior for hub connections (both WebSocket and Server-Sent Events).\n *\n * Records connection activity (any message received or sent). An interval fires every\n * {@link intervalMs} milliseconds; if no activity has been recorded since the last\n * {@link idleThresholdMs} milliseconds the provided {@link onIdle} callback is invoked —\n * the caller decides whether to send a ping, trigger a reconnect, or take some other action.\n *\n * The idle threshold defaults to the check interval but can be set higher to tolerate\n * network latency between the server's keep-alive ping and the client's idle check.\n * For SSE connections, where the idle callback triggers a reconnect, a tolerance of\n * 1.5× the server's keep-alive interval prevents spurious reconnects caused by the\n * client's timer firing just before the server's ping arrives.\n *\n * Both {@link WebSocketHubConnection} and {@link ServerSentEventHubConnection} own one instance\n * of this class so the keep-alive logic is written once and behaves identically for both\n * transports.\n */\nexport class HubConnectionKeepAlive {\n private _lastActivityTime = Date.now();\n private _timer?: ReturnType<typeof setInterval>;\n private _intervalMs: number;\n private _idleThresholdMs: number;\n\n /**\n * Initializes a new instance of {@link HubConnectionKeepAlive}.\n * @param {number} intervalMs How often (in milliseconds) to check for idle connections.\n * @param {() => void} onIdle Callback invoked when the interval fires and no activity has\n * been recorded within the idle threshold.\n * @param {number} idleThresholdMs Optional. How long (in milliseconds) without activity\n * before the connection is considered idle. Defaults to {@link intervalMs}. Set this\n * higher than {@link intervalMs} when the peer sends keep-alive messages on a similar\n * cadence to account for network latency and timer jitter.\n */\n constructor(\n intervalMs: number,\n private readonly _onIdle: () => void,\n idleThresholdMs?: number,\n ) {\n this._intervalMs = intervalMs;\n this._idleThresholdMs = idleThresholdMs ?? intervalMs;\n }\n\n /**\n * Gets how long (in milliseconds) without activity before the connection is considered idle.\n */\n get idleThresholdMs(): number {\n return this._idleThresholdMs;\n }\n\n /**\n * Change the check interval and idle threshold, restarting the timer when it is already running.\n *\n * Used when the peer advertises its actual keep-alive cadence after connecting, so the client\n * stops relying on an assumed default that may not match the server's configuration.\n * @param {number} intervalMs How often (in milliseconds) to check for idle connections.\n * @param {number} idleThresholdMs How long (in milliseconds) without activity before the connection is considered idle.\n */\n reconfigure(intervalMs: number, idleThresholdMs: number): void {\n const wasRunning = this._timer !== undefined;\n this._intervalMs = intervalMs;\n this._idleThresholdMs = idleThresholdMs;\n\n if (wasRunning) {\n this.start();\n }\n }\n\n /**\n * Start the keep-alive timer. Safe to call multiple times — a running timer is stopped first.\n */\n start(): void {\n this.stop();\n this._lastActivityTime = Date.now();\n this._timer = setInterval(() => {\n if (Date.now() - this._lastActivityTime >= this._idleThresholdMs) {\n this._onIdle();\n }\n }, this._intervalMs);\n }\n\n /**\n * Stop the keep-alive timer.\n */\n stop(): void {\n if (this._timer !== undefined) {\n clearInterval(this._timer);\n this._timer = undefined;\n }\n }\n\n /**\n * Record that the connection has been active (message sent or received).\n * Resets the idle timer so that a keep-alive is not sent while data is already flowing.\n */\n recordActivity(): void {\n this._lastActivityTime = Date.now();\n }\n}\n"],"names":["HubConnectionKeepAlive","_lastActivityTime","Date","now","_timer","_intervalMs","_idleThresholdMs","intervalMs","idleThresholdMs","_onIdle","reconfigure","wasRunning","undefined","start","stop","setInterval","clearInterval","recordActivity"],"mappings":"AAAA;AACA;AAEA;;;;;;;;;;;;;;;;;AAiBC,IACM,MAAMA,sBAAAA,CAAAA;;IACDC,iBAAAA,GAAoBC,IAAAA,CAAKC,GAAG,EAAA;IAC5BC,MAAAA;IACAC,WAAAA;IACAC,gBAAAA;AAER;;;;;;;;;AASC,QACD,YACIC,UAAkB,EAClB,OAAoC,EACpCC,eAAwB,CAC1B;aAFmBC,OAAAA,GAAAA,OAAAA;QAGjB,IAAI,C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live.js","sources":["../../../queries/HubConnectionKeepAlive.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\n/**\n * Manages keep-alive behavior for hub connections (both WebSocket and Server-Sent Events).\n *\n * Records connection activity (any message received or sent). An interval fires every\n * {@link intervalMs} milliseconds; if no activity has been recorded since the last\n * {@link idleThresholdMs} milliseconds the provided {@link onIdle} callback is invoked —\n * the caller decides whether to send a ping, trigger a reconnect, or take some other action.\n *\n * The idle threshold defaults to the check interval but can be set higher to tolerate\n * network latency between the server's keep-alive ping and the client's idle check.\n * For SSE connections, where the idle callback triggers a reconnect, a tolerance of\n * 1.5× the server's keep-alive interval prevents spurious reconnects caused by the\n * client's timer firing just before the server's ping arrives.\n *\n * Both {@link WebSocketHubConnection} and {@link ServerSentEventHubConnection} own one instance\n * of this class so the keep-alive logic is written once and behaves identically for both\n * transports.\n */\nexport class HubConnectionKeepAlive {\n private _lastActivityTime = Date.now();\n private _timer?: ReturnType<typeof setInterval>;\n private _intervalMs: number;\n private _idleThresholdMs: number;\n\n /**\n * Initializes a new instance of {@link HubConnectionKeepAlive}.\n * @param {number} intervalMs How often (in milliseconds) to check for idle connections.\n * @param {() => void} onIdle Callback invoked when the interval fires and no activity has\n * been recorded within the idle threshold.\n * @param {number} idleThresholdMs Optional. How long (in milliseconds) without activity\n * before the connection is considered idle. Defaults to {@link intervalMs}. Set this\n * higher than {@link intervalMs} when the peer sends keep-alive messages on a similar\n * cadence to account for network latency and timer jitter.\n */\n constructor(\n intervalMs: number,\n private readonly _onIdle: () => void,\n idleThresholdMs?: number,\n ) {\n this._intervalMs = intervalMs;\n this._idleThresholdMs = idleThresholdMs ?? intervalMs;\n }\n\n /**\n * Gets how long (in milliseconds) without activity before the connection is considered idle.\n */\n get idleThresholdMs(): number {\n return this._idleThresholdMs;\n }\n\n /**\n * Change the check interval and idle threshold, restarting the timer when it is already running.\n *\n * Used when the peer advertises its actual keep-alive cadence after connecting, so the client\n * stops relying on an assumed default that may not match the server's configuration.\n * @param {number} intervalMs How often (in milliseconds) to check for idle connections.\n * @param {number} idleThresholdMs How long (in milliseconds) without activity before the connection is considered idle.\n */\n reconfigure(intervalMs: number, idleThresholdMs: number): void {\n const wasRunning = this._timer !== undefined;\n this._intervalMs = intervalMs;\n this._idleThresholdMs = idleThresholdMs;\n\n if (wasRunning) {\n this.start();\n }\n }\n\n /**\n * Start the keep-alive timer. Safe to call multiple times — a running timer is stopped first.\n */\n start(): void {\n this.stop();\n this._lastActivityTime = Date.now();\n this._timer = setInterval(() => {\n if (Date.now() - this._lastActivityTime >= this._idleThresholdMs) {\n this._onIdle();\n }\n }, this._intervalMs);\n }\n\n /**\n * Stop the keep-alive timer.\n */\n stop(): void {\n if (this._timer !== undefined) {\n clearInterval(this._timer);\n this._timer = undefined;\n }\n }\n\n /**\n * Record that the connection has been active (message sent or received).\n * Resets the idle timer so that a keep-alive is not sent while data is already flowing.\n */\n recordActivity(): void {\n this._lastActivityTime = Date.now();\n }\n}\n"],"names":["HubConnectionKeepAlive","_lastActivityTime","Date","now","_timer","_intervalMs","_idleThresholdMs","intervalMs","idleThresholdMs","_onIdle","reconfigure","wasRunning","undefined","start","stop","setInterval","clearInterval","recordActivity"],"mappings":"AAAA;AACA;AAEA;;;;;;;;;;;;;;;;;AAiBC,IACM,MAAMA,sBAAAA,CAAAA;;IACDC,iBAAAA,GAAoBC,IAAAA,CAAKC,GAAG,EAAA;IAC5BC,MAAAA;IACAC,WAAAA;IACAC,gBAAAA;AAER;;;;;;;;;AASC,QACD,YACIC,UAAkB,EAClB,OAAoC,EACpCC,eAAwB,CAC1B;aAFmBC,OAAAA,GAAAA,OAAAA;QAGjB,IAAI,CAACJ,WAAW,GAAGE,UAAAA;QACnB,IAAI,CAACD,gBAAgB,GAAGE,eAAAA,IAAmBD,UAAAA;AAC/C,IAAA;AAEA;;AAEC,QACD,IAAIC,eAAAA,GAA0B;QAC1B,OAAO,IAAI,CAACF,gBAAgB;AAChC,IAAA;AAEA;;;;;;;AAOC,QACDI,WAAAA,CAAYH,UAAkB,EAAEC,eAAuB,EAAQ;AAC3D,QAAA,MAAMG,UAAAA,GAAa,IAAI,CAACP,MAAM,KAAKQ,SAAAA;QACnC,IAAI,CAACP,WAAW,GAAGE,UAAAA;QACnB,IAAI,CAACD,gBAAgB,GAAGE,eAAAA;AAExB,QAAA,IAAIG,UAAAA,EAAY;AACZ,YAAA,IAAI,CAACE,KAAK,EAAA;AACd,QAAA;AACJ,IAAA;AAEA;;AAEC,QACDA,KAAAA,GAAc;AACV,QAAA,IAAI,CAACC,IAAI,EAAA;AACT,QAAA,IAAI,CAACb,iBAAiB,GAAGC,IAAAA,CAAKC,GAAG,EAAA;QACjC,IAAI,CAACC,MAAM,GAAGW,WAAAA,CAAY,IAAA;YACtB,IAAIb,IAAAA,CAAKC,GAAG,EAAA,GAAK,IAAI,CAACF,iBAAiB,IAAI,IAAI,CAACK,gBAAgB,EAAE;AAC9D,gBAAA,IAAI,CAACG,OAAO,EAAA;AAChB,YAAA;QACJ,CAAA,EAAG,IAAI,CAACJ,WAAW,CAAA;AACvB,IAAA;AAEA;;AAEC,QACDS,IAAAA,GAAa;AACT,QAAA,IAAI,IAAI,CAACV,MAAM,KAAKQ,SAAAA,EAAW;YAC3BI,aAAAA,CAAc,IAAI,CAACZ,MAAM,CAAA;YACzB,IAAI,CAACA,MAAM,GAAGQ,SAAAA;AAClB,QAAA;AACJ,IAAA;AAEA;;;AAGC,QACDK,cAAAA,GAAuB;AACnB,QAAA,IAAI,CAAChB,iBAAiB,GAAGC,IAAAA,CAAKC,GAAG,EAAA;AACrC,IAAA;AACJ;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"IQueryProvider.js","sources":["../../../queries/IQueryProvider.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 '@cratis/fundamentals';\nimport { IQuery } from './IQuery';\n\n/**\n * Defines the provider for queries.\n */\nexport abstract class IQueryProvider {\n\n /**\n * Gets a new instance of a specific query type.\n * @param {Constructor} queryType Type of query to get an instance of.\n */\n abstract get<T extends IQuery>(queryType: Constructor<T>): T;\n}"],"names":["IQueryProvider"],"mappings":"AAAA;AACA;AAKA;;AAEC,IACM,MAAeA,cAAAA,CAAAA;AAOtB;;;;"}
1
+ {"version":3,"file":"IQueryProvider.js","sources":["../../../queries/IQueryProvider.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 '@cratis/fundamentals';\nimport { IQuery } from './IQuery';\n\n/**\n * Defines the provider for queries.\n */\nexport abstract class IQueryProvider {\n\n /**\n * Gets a new instance of a specific query type.\n * @param {Constructor} queryType Type of query to get an instance of.\n */\n abstract get<T extends IQuery>(queryType: Constructor<T>): T;\n}"],"names":["IQueryProvider"],"mappings":"AAAA;AACA;AAKA;;AAEC,IACM,MAAeA,cAAAA,CAAAA;AAOtB;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"NullObservableQueryConnection.js","sources":["../../../queries/NullObservableQueryConnection.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 { DataReceived } from './ObservableQueryConnection';\nimport { IObservableQueryConnection } from './IObservableQueryConnection';\nimport { QueryResult } from './QueryResult';\n\n/**\n * Represents a {@link IObservableQueryConnection} when for instance one can't establish a connection.\n */\n\nexport class NullObservableQueryConnection<TDataType> implements IObservableQueryConnection<TDataType> {\n /**\n * Initializes a new instance of the {@link NullObservableQueryConnection} class.\n * @param {TDataType} defaultValue The default value to serve.\n * @param {QueryResult<TDataType>} result Optional result to serve instead of an empty one. Supply it when the\n * subscription failed for a reason the subscriber must be able to see — client-side validation in particular,\n * which would otherwise be indistinguishable from a query that simply has no data yet.\n */\n constructor(readonly defaultValue: TDataType, readonly result?: QueryResult<TDataType>) {\n }\n\n /** @inheritdoc */\n get lastPingLatency(): number {\n return 0;\n }\n\n /** @inheritdoc */\n get averageLatency(): number {\n return 0;\n }\n\n /** @inheritdoc */\n connect(dataReceived: DataReceived<TDataType>) {\n dataReceived(this.result ?? QueryResult.empty(this.defaultValue));\n }\n\n /** @inheritdoc */\n /* eslint-disable @typescript-eslint/no-empty-function */\n disconnect() {\n }\n}\n"],"names":["NullObservableQueryConnection","result","defaultValue","lastPingLatency","averageLatency","connect","dataReceived","QueryResult","empty","disconnect"],"mappings":";;AAAA;AACA;AAMA;;AAEC,IAEM,MAAMA,6BAAAA,CAAAA;;;AACT;;;;;;AAMC,QACD,YAAY,YAAgC,EAAWC,MAA+B,CAAE;aAAnEC,YAAAA,GAAAA,YAAAA;aAAkCD,MAAAA,GAAAA,MAAAA;AACvD,IAAA;uBAGA,IAAIE,eAAAA,GAA0B;QAC1B,OAAO,CAAA;AACX,IAAA;uBAGA,IAAIC,cAAAA,GAAyB;QACzB,OAAO,CAAA;AACX,IAAA;uBAGAC,OAAAA,CAAQC,YAAqC,EAAE;QAC3CA,YAAAA,CAAa,IAAI,CAACL,MAAM,IAAIM,YAAYC,KAAK,CAAC,IAAI,CAACN,YAAY,CAAA,CAAA;AACnE,IAAA;AAEA,iFAEAO,UAAAA,GAAa,CACb;AACJ;;;;"}
1
+ {"version":3,"file":"NullObservableQueryConnection.js","sources":["../../../queries/NullObservableQueryConnection.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 { DataReceived } from './ObservableQueryConnection';\nimport { IObservableQueryConnection } from './IObservableQueryConnection';\nimport { QueryResult } from './QueryResult';\n\n/**\n * Represents a {@link IObservableQueryConnection} when for instance one can't establish a connection.\n */\n\nexport class NullObservableQueryConnection<TDataType> implements IObservableQueryConnection<TDataType> {\n /**\n * Initializes a new instance of the {@link NullObservableQueryConnection} class.\n * @param {TDataType} defaultValue The default value to serve.\n * @param {QueryResult<TDataType>} result Optional result to serve instead of an empty one. Supply it when the\n * subscription failed for a reason the subscriber must be able to see — client-side validation in particular,\n * which would otherwise be indistinguishable from a query that simply has no data yet.\n */\n constructor(readonly defaultValue: TDataType, readonly result?: QueryResult<TDataType>) {\n }\n\n /** @inheritdoc */\n get lastPingLatency(): number {\n return 0;\n }\n\n /** @inheritdoc */\n get averageLatency(): number {\n return 0;\n }\n\n /** @inheritdoc */\n connect(dataReceived: DataReceived<TDataType>) {\n dataReceived(this.result ?? QueryResult.empty(this.defaultValue));\n }\n\n /** @inheritdoc */\n /* eslint-disable @typescript-eslint/no-empty-function */\n disconnect() {\n }\n}\n"],"names":["NullObservableQueryConnection","result","defaultValue","lastPingLatency","averageLatency","connect","dataReceived","QueryResult","empty","disconnect"],"mappings":";;AAAA;AACA;AAMA;;AAEC,IAEM,MAAMA,6BAAAA,CAAAA;;;AACT;;;;;;AAMC,QACD,YAAY,YAAgC,EAAWC,MAA+B,CAAE;aAAnEC,YAAAA,GAAAA,YAAAA;aAAkCD,MAAAA,GAAAA,MAAAA;AACvD,IAAA;uBAGA,IAAIE,eAAAA,GAA0B;QAC1B,OAAO,CAAA;AACX,IAAA;uBAGA,IAAIC,cAAAA,GAAyB;QACzB,OAAO,CAAA;AACX,IAAA;uBAGAC,OAAAA,CAAQC,YAAqC,EAAE;QAC3CA,YAAAA,CAAa,IAAI,CAACL,MAAM,IAAIM,YAAYC,KAAK,CAAC,IAAI,CAACN,YAAY,CAAA,CAAA;AACnE,IAAA;AAEA,iFAEAO,UAAAA,GAAa,CACb;AACJ;;"}