@cratis/arc 22.185.1 → 22.186.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.
- package/commands/Command.ts +13 -20
- package/dist/cjs/commands/Command.d.ts +1 -0
- package/dist/cjs/commands/Command.d.ts.map +1 -1
- package/dist/cjs/commands/Command.js +15 -16
- package/dist/cjs/commands/Command.js.map +1 -1
- package/dist/cjs/queries/ObservableQueryFor.d.ts +2 -0
- package/dist/cjs/queries/ObservableQueryFor.d.ts.map +1 -1
- package/dist/cjs/queries/ObservableQueryFor.js +34 -27
- package/dist/cjs/queries/ObservableQueryFor.js.map +1 -1
- package/dist/cjs/queries/QueryInstanceCache.d.ts +1 -0
- package/dist/cjs/queries/QueryInstanceCache.d.ts.map +1 -1
- package/dist/cjs/queries/QueryInstanceCache.js +11 -16
- package/dist/cjs/queries/QueryInstanceCache.js.map +1 -1
- package/dist/cjs/queries/ServerSentEventHubConnection.d.ts +7 -0
- package/dist/cjs/queries/ServerSentEventHubConnection.d.ts.map +1 -1
- package/dist/cjs/queries/ServerSentEventHubConnection.js +97 -57
- package/dist/cjs/queries/ServerSentEventHubConnection.js.map +1 -1
- package/dist/cjs/queries/WebSocketHubConnection.d.ts +6 -0
- package/dist/cjs/queries/WebSocketHubConnection.d.ts.map +1 -1
- package/dist/cjs/queries/WebSocketHubConnection.js +62 -43
- package/dist/cjs/queries/WebSocketHubConnection.js.map +1 -1
- package/dist/esm/commands/Command.d.ts +1 -0
- package/dist/esm/commands/Command.d.ts.map +1 -1
- package/dist/esm/commands/Command.js +15 -16
- package/dist/esm/commands/Command.js.map +1 -1
- package/dist/esm/queries/ObservableQueryFor.d.ts +2 -0
- package/dist/esm/queries/ObservableQueryFor.d.ts.map +1 -1
- package/dist/esm/queries/ObservableQueryFor.js +35 -28
- package/dist/esm/queries/ObservableQueryFor.js.map +1 -1
- package/dist/esm/queries/QueryInstanceCache.d.ts +1 -0
- package/dist/esm/queries/QueryInstanceCache.d.ts.map +1 -1
- package/dist/esm/queries/QueryInstanceCache.js +11 -16
- package/dist/esm/queries/QueryInstanceCache.js.map +1 -1
- package/dist/esm/queries/ServerSentEventHubConnection.d.ts +7 -0
- package/dist/esm/queries/ServerSentEventHubConnection.d.ts.map +1 -1
- package/dist/esm/queries/ServerSentEventHubConnection.js +97 -57
- package/dist/esm/queries/ServerSentEventHubConnection.js.map +1 -1
- package/dist/esm/queries/WebSocketHubConnection.d.ts +6 -0
- package/dist/esm/queries/WebSocketHubConnection.d.ts.map +1 -1
- package/dist/esm/queries/WebSocketHubConnection.js +62 -43
- package/dist/esm/queries/WebSocketHubConnection.js.map +1 -1
- package/dist/esm/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/queries/ObservableQueryFor.ts +43 -32
- package/queries/QueryInstanceCache.ts +12 -18
- package/queries/ServerSentEventHubConnection.ts +120 -113
- package/queries/WebSocketHubConnection.ts +72 -53
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ObservableQuerySubscription } from './ObservableQuerySubscription.js';
|
|
2
2
|
import { ValidateRequestArguments } from './ValidateRequestArguments.js';
|
|
3
3
|
import { NullObservableQueryConnection } from './NullObservableQueryConnection.js';
|
|
4
|
-
import {
|
|
4
|
+
import { connectsToQueryRoute, createObservableQueryConnection } from './ObservableQueryConnectionFactory.js';
|
|
5
5
|
import { deserializeQueryModels, deserializeQueryModel } from './deserializeQueryModel.js';
|
|
6
6
|
import { QueryResult } from './QueryResult.js';
|
|
7
7
|
import { Sorting } from './Sorting.js';
|
|
@@ -80,25 +80,7 @@ import { executeQueryHttpRequest } from './QueryHttpRequest.js';
|
|
|
80
80
|
if (this._connection) {
|
|
81
81
|
this._connection.disconnect();
|
|
82
82
|
}
|
|
83
|
-
|
|
84
|
-
if (clientValidationErrors.length > 0) {
|
|
85
|
-
// Serve the failure through the connection rather than throwing, so a subscriber sees an invalid result
|
|
86
|
-
// on its normal callback path instead of the empty result an unestablished connection would emit.
|
|
87
|
-
this._connection = new NullObservableQueryConnection(this.defaultValue, QueryResult.validationFailed(clientValidationErrors, this));
|
|
88
|
-
} else if (this.validateArguments(args)) {
|
|
89
|
-
this._connection = createObservableQueryConnection({
|
|
90
|
-
route: this.route,
|
|
91
|
-
queryName: this.queryName ?? this.constructor.name,
|
|
92
|
-
origin: this._origin,
|
|
93
|
-
apiBasePath: this._apiBasePath,
|
|
94
|
-
microservice: this._microservice,
|
|
95
|
-
args: args,
|
|
96
|
-
httpHeadersCallback: this._httpHeadersCallback,
|
|
97
|
-
pollingOptions: this._pollingOptions
|
|
98
|
-
});
|
|
99
|
-
} else {
|
|
100
|
-
this._connection = new NullObservableQueryConnection(this.defaultValue);
|
|
101
|
-
}
|
|
83
|
+
this._connection = this.createConnection(args);
|
|
102
84
|
// Descriptor-backed instance properties provide defaults; fresh args passed to subscribe()
|
|
103
85
|
// must take precedence over any stale instance property values. Spread parameterValues
|
|
104
86
|
// first so that the caller-supplied args can override them.
|
|
@@ -131,6 +113,38 @@ import { executeQueryHttpRequest } from './QueryHttpRequest.js';
|
|
|
131
113
|
}, connectionQueryArguments);
|
|
132
114
|
return subscriber;
|
|
133
115
|
}
|
|
116
|
+
createConnection(args) {
|
|
117
|
+
const clientValidationErrors = this.validation?.validate(args || {}) || [];
|
|
118
|
+
if (clientValidationErrors.length > 0) {
|
|
119
|
+
// Serve the failure through the connection rather than throwing, so a subscriber sees an invalid result
|
|
120
|
+
// on its normal callback path instead of the empty result an unestablished connection would emit.
|
|
121
|
+
return new NullObservableQueryConnection(this.defaultValue, QueryResult.validationFailed(clientValidationErrors, this));
|
|
122
|
+
}
|
|
123
|
+
if (!this.validateArguments(args)) {
|
|
124
|
+
return new NullObservableQueryConnection(this.defaultValue);
|
|
125
|
+
}
|
|
126
|
+
return createObservableQueryConnection({
|
|
127
|
+
route: this.route,
|
|
128
|
+
queryName: this.queryName ?? this.constructor.name,
|
|
129
|
+
origin: this._origin,
|
|
130
|
+
apiBasePath: this._apiBasePath,
|
|
131
|
+
microservice: this._microservice,
|
|
132
|
+
args: args,
|
|
133
|
+
httpHeadersCallback: this._httpHeadersCallback,
|
|
134
|
+
pollingOptions: this._pollingOptions
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
buildRequestHeaders() {
|
|
138
|
+
const headers = {
|
|
139
|
+
...this._httpHeadersCallback?.() || {},
|
|
140
|
+
Accept: 'application/json',
|
|
141
|
+
'Content-Type': 'application/json'
|
|
142
|
+
};
|
|
143
|
+
if (this._microservice?.length > 0) {
|
|
144
|
+
headers[Globals.microserviceHttpHeader] = this._microservice;
|
|
145
|
+
}
|
|
146
|
+
return headers;
|
|
147
|
+
}
|
|
134
148
|
/** @inheritdoc */ async perform(args) {
|
|
135
149
|
const noSuccess = {
|
|
136
150
|
...QueryResult.noSuccess,
|
|
@@ -149,14 +163,7 @@ import { executeQueryHttpRequest } from './QueryHttpRequest.js';
|
|
|
149
163
|
}
|
|
150
164
|
// Collect parameter values from parameterDescriptors that are set
|
|
151
165
|
const parameterValues = ParametersHelper.collectParameterValues(this);
|
|
152
|
-
const headers =
|
|
153
|
-
...this._httpHeadersCallback?.() || {},
|
|
154
|
-
Accept: 'application/json',
|
|
155
|
-
'Content-Type': 'application/json'
|
|
156
|
-
};
|
|
157
|
-
if (this._microservice?.length > 0) {
|
|
158
|
-
headers[Globals.microserviceHttpHeader] = this._microservice;
|
|
159
|
-
}
|
|
166
|
+
const headers = this.buildRequestHeaders();
|
|
160
167
|
const response = await executeQueryHttpRequest(this._httpMethod, {
|
|
161
168
|
route: this.route,
|
|
162
169
|
apiBasePath: this._apiBasePath,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ObservableQueryFor.js","sources":["../../../queries/ObservableQueryFor.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 type { IObservableQueryFor, OnNextResult } from './IObservableQueryFor.js';\nimport { ObservableQuerySubscription } from './ObservableQuerySubscription.js';\nimport { ValidateRequestArguments } from './ValidateRequestArguments.js';\nimport type { QueryValidator } from './QueryValidator.js';\nimport type { IObservableQueryConnection } from './IObservableQueryConnection.js';\nimport { NullObservableQueryConnection } from './NullObservableQueryConnection.js';\nimport { PollingOptions } from './PollingOptions.js';\nimport { createObservableQueryConnection, connectsToQueryRoute } from './ObservableQueryConnectionFactory.js';\nimport type { Constructor } from '@cratis/fundamentals';\nimport { deserializeQueryModel, deserializeQueryModels } from './deserializeQueryModel.js';\nimport { QueryResult } from './QueryResult.js';\nimport { Sorting } from './Sorting.js';\nimport { Paging } from './Paging.js';\nimport { SortDirection } from './SortDirection.js';\nimport { Globals } from '../Globals.js';\nimport { UrlHelpers } from '../UrlHelpers.js';\nimport type { GetHttpHeaders } from '../GetHttpHeaders.js';\nimport type { ParameterDescriptor } from '../reflection/ParameterDescriptor.js';\nimport { ParametersHelper } from '../reflection/ParametersHelper.js';\nimport { SliceLocation } from '../reflection/SliceLocation.js';\nimport type { QueryHttpMethod } from './QueryHttpMethod.js';\nimport { executeQueryHttpRequest } from './QueryHttpRequest.js';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Represents an implementation of {@link IQueryFor}.\n * @template TDataType Type of data returned by the query.\n */\nexport abstract class ObservableQueryFor<\n TDataType,\n TParameters = object,\n> implements IObservableQueryFor<TDataType, TParameters> {\n /**\n * Gets the {@link SliceLocation} of the query. Generated proxies override it with the location resolved from the backend namespace.\n */\n static readonly sliceLocation: SliceLocation = SliceLocation.empty;\n\n private _microservice: string;\n private _apiBasePath: string;\n private _origin: string;\n private _connection?: IObservableQueryConnection<TDataType>;\n private _httpHeadersCallback: GetHttpHeaders;\n private _httpMethod?: QueryHttpMethod;\n private _pollingOptions?: Partial<PollingOptions>;\n\n abstract readonly route: string;\n abstract readonly defaultValue: TDataType;\n readonly roles: string[] = [];\n readonly validation?: QueryValidator<any>;\n /** Backend fully-qualified query name used when subscribing via the SSE hub. Overridden in generated proxies. */\n readonly queryName?: string;\n abstract readonly parameterDescriptors: ParameterDescriptor[];\n abstract get requiredRequestParameters(): string[];\n sorting: Sorting;\n paging: Paging;\n\n /**\n * Initializes a new instance of the {@link ObservableQueryFor<,>}} class.\n * @param modelType Type of model, if an enumerable, this is the instance type.\n * @param enumerable Whether or not it is an enumerable.\n */\n constructor(\n readonly modelType: Constructor,\n readonly enumerable: boolean,\n ) {\n this.sorting = Sorting.none;\n this.paging = Paging.noPaging;\n this._microservice = Globals.microservice ?? '';\n this._apiBasePath = Globals.apiBasePath ?? '';\n this._origin = Globals.origin ?? '';\n this._httpHeadersCallback = () => ({});\n }\n\n /**\n * Disposes the query.\n */\n dispose() {\n this._connection?.disconnect();\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 /**\n * Overrides {@link Globals.queryPollingOptions} for this query instance on its next subscription.\n * @param options The polling timing overrides to apply on the next subscribe.\n */\n setPollingOptions(options: Partial<PollingOptions>): void {\n this._pollingOptions = options;\n }\n\n /** @inheritdoc */\n setHttpMethod(method: QueryHttpMethod): void {\n this._httpMethod = method;\n }\n\n /** @inheritdoc */\n subscribe(\n callback: OnNextResult<QueryResult<TDataType>>,\n args?: TParameters,\n ): ObservableQuerySubscription<TDataType> {\n if (this._connection) {\n this._connection.disconnect();\n }\n\n const clientValidationErrors =\n this.validation?.validate((args as object) || {}) || [];\n if (clientValidationErrors.length > 0) {\n // Serve the failure through the connection rather than throwing, so a subscriber sees an invalid result\n // on its normal callback path instead of the empty result an unestablished connection would emit.\n this._connection = new NullObservableQueryConnection(\n this.defaultValue,\n QueryResult.validationFailed(clientValidationErrors, this),\n );\n } else if (this.validateArguments(args)) {\n this._connection = createObservableQueryConnection({\n route: this.route,\n queryName: this.queryName ?? this.constructor.name,\n origin: this._origin,\n apiBasePath: this._apiBasePath,\n microservice: this._microservice,\n args: args as object,\n httpHeadersCallback: this._httpHeadersCallback,\n pollingOptions: this._pollingOptions,\n });\n } else {\n this._connection = new NullObservableQueryConnection(this.defaultValue);\n }\n\n // Descriptor-backed instance properties provide defaults; fresh args passed to subscribe()\n // must take precedence over any stale instance property values. Spread parameterValues\n // first so that the caller-supplied args can override them.\n //\n // In direct mode or polling the route arguments are already embedded in the URL path, so only\n // the unused (non-route) parameters are appended as additional query arguments.\n // In multiplexed mode ALL arguments — including route-derived ones — must be included\n // in the subscribe payload so the server can execute the query correctly.\n const parameterValues = ParametersHelper.collectParameterValues(this);\n const { unusedParameters } = UrlHelpers.replaceRouteParameters(\n this.route,\n args as object,\n );\n const connectionQueryArguments: any = {\n ...parameterValues,\n ...(connectsToQueryRoute() ? unusedParameters : (args as object) || {}),\n ...this.buildQueryArguments(),\n };\n\n const subscriber = new ObservableQuerySubscription(this._connection);\n this._connection.connect((data) => {\n const result: any = data;\n try {\n // Observable transports deliver structural query-result envelopes directly instead of\n // constructing QueryResult. Servers predating readiness therefore omit the member;\n // those results are complete by definition and must be normalized before subscribers\n // observe them. Preserve an explicit false transient state from newer servers.\n result.isReady ??= true;\n this.deserializeResult(result);\n callback(result);\n } catch (ex) {\n console.log(ex);\n }\n }, connectionQueryArguments);\n return subscriber;\n }\n\n /** @inheritdoc */\n async perform(args?: TParameters): Promise<QueryResult<TDataType>> {\n const noSuccess = {\n ...QueryResult.noSuccess,\n ...{ data: this.defaultValue },\n } as QueryResult<TDataType>;\n\n const clientValidationErrors =\n this.validation?.validate((args as object) || {}) || [];\n if (clientValidationErrors.length > 0) {\n return QueryResult.validationFailed(clientValidationErrors, this);\n }\n\n if (!this.validateArguments(args)) {\n return new Promise<QueryResult<TDataType>>((resolve) => {\n resolve(noSuccess);\n });\n }\n\n // Collect parameter values from parameterDescriptors that are set\n const parameterValues = ParametersHelper.collectParameterValues(this);\n\n const headers = {\n ...(this._httpHeadersCallback?.() || {}),\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 const response = await executeQueryHttpRequest(this._httpMethod, {\n route: this.route,\n apiBasePath: this._apiBasePath,\n origin: this._origin,\n args: (args as object) ?? {},\n parameterValues,\n paging: this.paging,\n sorting: this.sorting,\n headers,\n });\n\n try {\n const result = await response.json();\n return new QueryResult(result, this.modelType, this.enumerable);\n } catch {\n return noSuccess;\n }\n }\n\n private validateArguments(args?: TParameters): boolean {\n const parameterValues = ParametersHelper.collectParameterValues(this);\n const combinedArgs = { ...((args as object) || {}), ...parameterValues };\n return ValidateRequestArguments(\n this.constructor.name,\n this.requiredRequestParameters,\n combinedArgs as object,\n );\n }\n\n private buildQueryArguments(): any {\n const queryArguments: any = {};\n\n if (this.paging && this.paging.pageSize > 0) {\n queryArguments.pageSize = this.paging.pageSize;\n queryArguments.page = this.paging.page;\n }\n\n if (this.sorting.hasSorting) {\n queryArguments.sortBy = this.sorting.field;\n queryArguments.sortDirection =\n this.sorting.direction === SortDirection.descending ? 'desc' : 'asc';\n }\n\n return queryArguments;\n }\n\n private deserializeResult(result: any): void {\n if (this.enumerable) {\n result.data = deserializeQueryModels(this.modelType, result.data);\n } else if (result.data) {\n result.data = deserializeQueryModel(this.modelType, result.data);\n }\n }\n}\n"],"names":["ObservableQueryFor","sliceLocation","SliceLocation","empty","_microservice","_apiBasePath","_origin","_connection","_httpHeadersCallback","_httpMethod","_pollingOptions","roles","validation","queryName","sorting","paging","enumerable","modelType","Sorting","none","Paging","noPaging","Globals","microservice","apiBasePath","origin","dispose","disconnect","setMicroservice","setApiBasePath","setOrigin","setHttpHeadersCallback","callback","setPollingOptions","options","setHttpMethod","method","subscribe","args","clientValidationErrors","validate","length","NullObservableQueryConnection","defaultValue","QueryResult","validationFailed","validateArguments","createObservableQueryConnection","route","name","httpHeadersCallback","pollingOptions","parameterValues","ParametersHelper","collectParameterValues","unusedParameters","UrlHelpers","replaceRouteParameters","connectionQueryArguments","connectsToQueryRoute","buildQueryArguments","subscriber","ObservableQuerySubscription","connect","data","result","isReady","deserializeResult","ex","console","log","perform","noSuccess","Promise","resolve","headers","Accept","microserviceHttpHeader","response","executeQueryHttpRequest","json","combinedArgs","ValidateRequestArguments","requiredRequestParameters","queryArguments","pageSize","page","hasSorting","sortBy","field","sortDirection","direction","SortDirection","descending","deserializeQueryModels","deserializeQueryModel"],"mappings":";;;;;;;;;;;;;;;AAAA;AACA;AAyBA;;;AAKC,IACM,MAAeA,kBAAAA,CAAAA;;;AAIlB;;AAEC,QACD,OAAgBC,aAAAA,GAA+BC,aAAAA,CAAcC,KAAK;IAE1DC,aAAAA;IACAC,YAAAA;IACAC,OAAAA;IACAC,WAAAA;IACAC,oBAAAA;IACAC,WAAAA;IACAC,eAAAA;AAICC,IAAAA,KAAAA,GAAkB,EAAE;IACpBC,UAAAA;sHAET,SAASC;IAGTC,OAAAA;IACAC,MAAAA;AAEA;;;;AAIC,QACD,YACI,SAA+B,EACtBC,UAAmB,CAC9B;aAFWC,SAAAA,GAAAA,SAAAA;aACAD,UAAAA,GAAAA,UAAAA;AAET,QAAA,IAAI,CAACF,OAAO,GAAGI,OAAAA,CAAQC,IAAI;AAC3B,QAAA,IAAI,CAACJ,MAAM,GAAGK,MAAAA,CAAOC,QAAQ;AAC7B,QAAA,IAAI,CAACjB,aAAa,GAAGkB,OAAAA,CAAQC,YAAY,IAAI,EAAA;AAC7C,QAAA,IAAI,CAAClB,YAAY,GAAGiB,OAAAA,CAAQE,WAAW,IAAI,EAAA;AAC3C,QAAA,IAAI,CAAClB,OAAO,GAAGgB,OAAAA,CAAQG,MAAM,IAAI,EAAA;AACjC,QAAA,IAAI,CAACjB,oBAAoB,GAAG,KAAO,EAAC,CAAA;AACxC,IAAA;AAEA;;AAEC,QACDkB,OAAAA,GAAU;Q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H,YAAAA,cAAAA,CAAeI,MAAM,GAAG,IAAI,CAAC1E,OAAO,CAAC2E,KAAK;YAC1CL,cAAAA,CAAeM,aAAa,GACxB,IAAI,CAAC5E,OAAO,CAAC6E,SAAS,KAAKC,aAAAA,CAAcC,UAAU,GAAG,MAAA,GAAS,KAAA;AACvE,QAAA;QAEA,OAAOT,cAAAA;AACX,IAAA;AAEQjB,IAAAA,iBAAAA,CAAkBF,MAAW,EAAQ;QACzC,IAAI,IAAI,CAACjD,UAAU,EAAE;YACjBiD,MAAAA,CAAOD,IAAI,GAAG8B,sBAAAA,CAAuB,IAAI,CAAC7E,SAAS,EAAEgD,OAAOD,IAAI,CAAA;QACpE,CAAA,MAAO,IAAIC,MAAAA,CAAOD,IAAI,EAAE;YACpBC,MAAAA,CAAOD,IAAI,GAAG+B,qBAAAA,CAAsB,IAAI,CAAC9E,SAAS,EAAEgD,OAAOD,IAAI,CAAA;AACnE,QAAA;AACJ,IAAA;AACJ;;"}
|
|
1
|
+
{"version":3,"file":"ObservableQueryFor.js","sources":["../../../queries/ObservableQueryFor.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 type { IObservableQueryFor, OnNextResult } from './IObservableQueryFor.js';\nimport { ObservableQuerySubscription } from './ObservableQuerySubscription.js';\nimport { ValidateRequestArguments } from './ValidateRequestArguments.js';\nimport type { QueryValidator } from './QueryValidator.js';\nimport type { IObservableQueryConnection } from './IObservableQueryConnection.js';\nimport { NullObservableQueryConnection } from './NullObservableQueryConnection.js';\nimport { PollingOptions } from './PollingOptions.js';\nimport { createObservableQueryConnection, connectsToQueryRoute } from './ObservableQueryConnectionFactory.js';\nimport type { Constructor } from '@cratis/fundamentals';\nimport { deserializeQueryModel, deserializeQueryModels } from './deserializeQueryModel.js';\nimport { QueryResult } from './QueryResult.js';\nimport { Sorting } from './Sorting.js';\nimport { Paging } from './Paging.js';\nimport { SortDirection } from './SortDirection.js';\nimport { Globals } from '../Globals.js';\nimport { UrlHelpers } from '../UrlHelpers.js';\nimport type { GetHttpHeaders } from '../GetHttpHeaders.js';\nimport type { ParameterDescriptor } from '../reflection/ParameterDescriptor.js';\nimport { ParametersHelper } from '../reflection/ParametersHelper.js';\nimport { SliceLocation } from '../reflection/SliceLocation.js';\nimport type { QueryHttpMethod } from './QueryHttpMethod.js';\nimport { executeQueryHttpRequest } from './QueryHttpRequest.js';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Represents an implementation of {@link IQueryFor}.\n * @template TDataType Type of data returned by the query.\n */\nexport abstract class ObservableQueryFor<\n TDataType,\n TParameters = object,\n> implements IObservableQueryFor<TDataType, TParameters> {\n /**\n * Gets the {@link SliceLocation} of the query. Generated proxies override it with the location resolved from the backend namespace.\n */\n static readonly sliceLocation: SliceLocation = SliceLocation.empty;\n\n private _microservice: string;\n private _apiBasePath: string;\n private _origin: string;\n private _connection?: IObservableQueryConnection<TDataType>;\n private _httpHeadersCallback: GetHttpHeaders;\n private _httpMethod?: QueryHttpMethod;\n private _pollingOptions?: Partial<PollingOptions>;\n\n abstract readonly route: string;\n abstract readonly defaultValue: TDataType;\n readonly roles: string[] = [];\n readonly validation?: QueryValidator<any>;\n /** Backend fully-qualified query name used when subscribing via the SSE hub. Overridden in generated proxies. */\n readonly queryName?: string;\n abstract readonly parameterDescriptors: ParameterDescriptor[];\n abstract get requiredRequestParameters(): string[];\n sorting: Sorting;\n paging: Paging;\n\n /**\n * Initializes a new instance of the {@link ObservableQueryFor<,>}} class.\n * @param modelType Type of model, if an enumerable, this is the instance type.\n * @param enumerable Whether or not it is an enumerable.\n */\n constructor(\n readonly modelType: Constructor,\n readonly enumerable: boolean,\n ) {\n this.sorting = Sorting.none;\n this.paging = Paging.noPaging;\n this._microservice = Globals.microservice ?? '';\n this._apiBasePath = Globals.apiBasePath ?? '';\n this._origin = Globals.origin ?? '';\n this._httpHeadersCallback = () => ({});\n }\n\n /**\n * Disposes the query.\n */\n dispose() {\n this._connection?.disconnect();\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 /**\n * Overrides {@link Globals.queryPollingOptions} for this query instance on its next subscription.\n * @param options The polling timing overrides to apply on the next subscribe.\n */\n setPollingOptions(options: Partial<PollingOptions>): void {\n this._pollingOptions = options;\n }\n\n /** @inheritdoc */\n setHttpMethod(method: QueryHttpMethod): void {\n this._httpMethod = method;\n }\n\n /** @inheritdoc */\n subscribe(\n callback: OnNextResult<QueryResult<TDataType>>,\n args?: TParameters,\n ): ObservableQuerySubscription<TDataType> {\n if (this._connection) {\n this._connection.disconnect();\n }\n\n this._connection = this.createConnection(args);\n\n // Descriptor-backed instance properties provide defaults; fresh args passed to subscribe()\n // must take precedence over any stale instance property values. Spread parameterValues\n // first so that the caller-supplied args can override them.\n //\n // In direct mode or polling the route arguments are already embedded in the URL path, so only\n // the unused (non-route) parameters are appended as additional query arguments.\n // In multiplexed mode ALL arguments — including route-derived ones — must be included\n // in the subscribe payload so the server can execute the query correctly.\n const parameterValues = ParametersHelper.collectParameterValues(this);\n const { unusedParameters } = UrlHelpers.replaceRouteParameters(\n this.route,\n args as object,\n );\n const connectionQueryArguments: any = {\n ...parameterValues,\n ...(connectsToQueryRoute() ? unusedParameters : (args as object) || {}),\n ...this.buildQueryArguments(),\n };\n\n const subscriber = new ObservableQuerySubscription(this._connection);\n this._connection.connect((data) => {\n const result: any = data;\n try {\n // Observable transports deliver structural query-result envelopes directly instead of\n // constructing QueryResult. Servers predating readiness therefore omit the member;\n // those results are complete by definition and must be normalized before subscribers\n // observe them. Preserve an explicit false transient state from newer servers.\n result.isReady ??= true;\n this.deserializeResult(result);\n callback(result);\n } catch (ex) {\n console.log(ex);\n }\n }, connectionQueryArguments);\n return subscriber;\n }\n\n private createConnection(args?: TParameters): IObservableQueryConnection<TDataType> {\n const clientValidationErrors =\n this.validation?.validate((args as object) || {}) || [];\n if (clientValidationErrors.length > 0) {\n // Serve the failure through the connection rather than throwing, so a subscriber sees an invalid result\n // on its normal callback path instead of the empty result an unestablished connection would emit.\n return new NullObservableQueryConnection(\n this.defaultValue,\n QueryResult.validationFailed(clientValidationErrors, this),\n );\n }\n\n if (!this.validateArguments(args)) {\n return new NullObservableQueryConnection(this.defaultValue);\n }\n\n return createObservableQueryConnection({\n route: this.route,\n queryName: this.queryName ?? this.constructor.name,\n origin: this._origin,\n apiBasePath: this._apiBasePath,\n microservice: this._microservice,\n args: args as object,\n httpHeadersCallback: this._httpHeadersCallback,\n pollingOptions: this._pollingOptions,\n });\n }\n\n private buildRequestHeaders(): Record<string, any> {\n const headers: Record<string, any> = {\n ...(this._httpHeadersCallback?.() || {}),\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 return headers;\n }\n\n /** @inheritdoc */\n async perform(args?: TParameters): Promise<QueryResult<TDataType>> {\n const noSuccess = {\n ...QueryResult.noSuccess,\n ...{ data: this.defaultValue },\n } as QueryResult<TDataType>;\n\n const clientValidationErrors =\n this.validation?.validate((args as object) || {}) || [];\n if (clientValidationErrors.length > 0) {\n return QueryResult.validationFailed(clientValidationErrors, this);\n }\n\n if (!this.validateArguments(args)) {\n return new Promise<QueryResult<TDataType>>((resolve) => {\n resolve(noSuccess);\n });\n }\n\n // Collect parameter values from parameterDescriptors that are set\n const parameterValues = ParametersHelper.collectParameterValues(this);\n\n const headers = this.buildRequestHeaders();\n\n const response = await executeQueryHttpRequest(this._httpMethod, {\n route: this.route,\n apiBasePath: this._apiBasePath,\n origin: this._origin,\n args: (args as object) ?? {},\n parameterValues,\n paging: this.paging,\n sorting: this.sorting,\n headers,\n });\n\n try {\n const result = await response.json();\n return new QueryResult(result, this.modelType, this.enumerable);\n } catch {\n return noSuccess;\n }\n }\n\n private validateArguments(args?: TParameters): boolean {\n const parameterValues = ParametersHelper.collectParameterValues(this);\n const combinedArgs = { ...((args as object) || {}), ...parameterValues };\n return ValidateRequestArguments(\n this.constructor.name,\n this.requiredRequestParameters,\n combinedArgs as object,\n );\n }\n\n private buildQueryArguments(): any {\n const queryArguments: any = {};\n\n if (this.paging && this.paging.pageSize > 0) {\n queryArguments.pageSize = this.paging.pageSize;\n queryArguments.page = this.paging.page;\n }\n\n if (this.sorting.hasSorting) {\n queryArguments.sortBy = this.sorting.field;\n queryArguments.sortDirection =\n this.sorting.direction === SortDirection.descending ? 'desc' : 'asc';\n }\n\n return queryArguments;\n }\n\n private deserializeResult(result: any): void {\n if (this.enumerable) {\n result.data = deserializeQueryModels(this.modelType, result.data);\n } else if (result.data) {\n result.data = deserializeQueryModel(this.modelType, result.data);\n }\n }\n}\n"],"names":["ObservableQueryFor","sliceLocation","SliceLocation","empty","_microservice","_apiBasePath","_origin","_connection","_httpHeadersCallback","_httpMethod","_pollingOptions","roles","validation","queryName","sorting","paging","enumerable","modelType","Sorting","none","Paging","noPaging","Globals","microservice","apiBasePath","origin","dispose","disconnect","setMicroservice","setApiBasePath","setOrigin","setHttpHeadersCallback","callback","setPollingOptions","options","setHttpMethod","method","subscribe","args","createConnection","parameterValues","ParametersHelper","collectParameterValues","unusedParameters","UrlHelpers","replaceRouteParameters","route","connectionQueryArguments","connectsToQueryRoute","buildQueryArguments","subscriber","ObservableQuerySubscription","connect","data","result","isReady","deserializeResult","ex","console","log","clientValidationErrors","validate","length","NullObservableQueryConnection","defaultValue","QueryResult","validationFailed","validateArguments","createObservableQueryConnection","name","httpHeadersCallback","pollingOptions","buildRequestHeaders","headers","Accept","microserviceHttpHeader","perform","noSuccess","Promise","resolve","response","executeQueryHttpRequest","json","combinedArgs","ValidateRequestArguments","requiredRequestParameters","queryArguments","pageSize","page","hasSorting","sortBy","field","sortDirection","direction","SortDirection","descending","deserializeQueryModels","deserializeQueryModel"],"mappings":";;;;;;;;;;;;;;;AAAA;AACA;AAyBA;;;AAKC,IACM,MAAeA,kBAAAA,CAAAA;;;AAIlB;;AAEC,QACD,OAAgBC,aAAAA,GAA+BC,aAAAA,CAAcC,KAAK;IAE1DC,aAAAA;IACAC,YAAAA;IACAC,OAAAA;IACAC,WAAAA;IACAC,oBAAAA;IACAC,WAAAA;IACAC,eAAAA;AAICC,IAAAA,KAAAA,GAAkB,EAAE;IACpBC,UAAAA;sHAET,SAASC;IAGTC,OAAAA;IACAC,MAAAA;AAEA;;;;AAIC,QACD,YACI,SAA+B,EACtBC,UAAmB,CAC9B;aAFWC,SAAAA,GAAAA,SAAAA;aACAD,UAAAA,GAAAA,UAAAA;AAET,QAAA,IAAI,CAACF,OAAO,GAAGI,OAAAA,CAAQC,IAAI;AAC3B,QAAA,IAAI,CAACJ,MAAM,GAAGK,MAAAA,CAAOC,QAAQ;AAC7B,QAAA,IAAI,CAACjB,aAAa,GAAGkB,OAAAA,CAAQC,YAAY,IAAI,EAAA;AAC7C,QAAA,IAAI,CAAClB,YAAY,GAAGiB,OAAAA,CAAQE,WAAW,IAAI,EAAA;AAC3C,QAAA,IAAI,CAAClB,OAAO,GAAGgB,OAAAA,CAAQG,MAAM,IAAI,EAAA;AACjC,QAAA,IAAI,CAACjB,oBAAoB,GAAG,KAAO,EAAC,CAAA;AACxC,IAAA;AAEA;;AAEC,QACDkB,OAAAA,GAAU;QACN,IAAI,CAACnB,WAAW,EAAEoB,UAAAA,EAAAA;AACtB,IAAA;uBAGAC,eAAAA,CAAgBL,YAAoB,EAAE;QAClC,IAAI,CAACnB,aAAa,GAAGmB,YAAAA;AACzB,IAAA;uBAGAM,cAAAA,CAAeL,WAAmB,EAAQ;QACtC,IAAI,CAACnB,YAAY,GAAGmB,WAAAA;AACxB,IAAA;uBAGAM,SAAAA,CAAUL,M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,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,CAgBzC;IASD,OAAO,CAAC,GAAG,EAAE,aAAa,GAAG,IAAI,CAWhC;IAQD,aAAa,CAAC,SAAS,EACnB,GAAG,EAAE,aAAa,GACnB,oBAAoB,CAAC,SAAS,CAAC,GAAG,SAAS,CAI7C;IAQD,aAAa,CAAC,SAAS,EACnB,GAAG,EAAE,aAAa,EAClB,MAAM,EAAE,oBAAoB,CAAC,SAAS,CAAC,GACxC,IAAI,CAoCN;IAUD,OAAO,CAAC,kBAAkB;IA0B1B,OAAO,CAAC,qBAAqB;IAmB7B,WAAW,CAAC,SAAS,EACjB,GAAG,EAAE,aAAa,EAClB,QAAQ,EAAE,kBAAkB,CAAC,SAAS,CAAC,GACxC,IAAI,CAMN;IAQD,cAAc,CAAC,SAAS,EACpB,GAAG,EAAE,aAAa,EAClB,QAAQ,EAAE,kBAAkB,CAAC,SAAS,CAAC,GACxC,IAAI,CAMN;IAQD,WAAW,CAAC,GAAG,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAO1D;IAOD,YAAY,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAExC;IAUD,OAAO,CAAC,GAAG,EAAE,aAAa,GAAG,IAAI,CAuBhC;IAOD,GAAG,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAE/B;IAYD,wBAAwB,IAAI,IAAI,CAI/B;IAED,OAAO,CAAC,aAAa;IAgBrB,OAAO,IAAI,IAAI,CAGd;IAWD,YAAY,IAAI,IAAI,CASnB;IAQD,oBAAoB,IAAI,IAAI,CAK3B;IAMD,sBAAsB,IAAI,gBAAgB,CAwCzC;CACJ"}
|
|
@@ -224,29 +224,24 @@ import { deepEqual } from '../deepEqual.js';
|
|
|
224
224
|
* credentials).
|
|
225
225
|
*/ teardownAllSubscriptions() {
|
|
226
226
|
for (const [, entry] of this._entries){
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
entry.
|
|
233
|
-
entry.
|
|
227
|
+
this.teardownEntry(entry);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
teardownEntry(entry) {
|
|
231
|
+
if (entry.pendingCleanup !== undefined) {
|
|
232
|
+
clearTimeout(entry.pendingCleanup);
|
|
233
|
+
entry.pendingCleanup = undefined;
|
|
234
234
|
}
|
|
235
|
+
entry.subscribed = false;
|
|
236
|
+
entry.teardown?.();
|
|
237
|
+
entry.teardown = undefined;
|
|
235
238
|
}
|
|
236
239
|
/**
|
|
237
240
|
* Immediately tears down all subscriptions, cancels any pending deferred cleanups,
|
|
238
241
|
* and evicts all entries. Call when the owning component (e.g. the {@link Arc} provider)
|
|
239
242
|
* unmounts permanently so that all query connections are closed synchronously.
|
|
240
243
|
*/ dispose() {
|
|
241
|
-
|
|
242
|
-
if (entry.pendingCleanup !== undefined) {
|
|
243
|
-
clearTimeout(entry.pendingCleanup);
|
|
244
|
-
entry.pendingCleanup = undefined;
|
|
245
|
-
}
|
|
246
|
-
entry.subscribed = false;
|
|
247
|
-
entry.teardown?.();
|
|
248
|
-
entry.teardown = undefined;
|
|
249
|
-
}
|
|
244
|
+
this.teardownAllSubscriptions();
|
|
250
245
|
this._entries.clear();
|
|
251
246
|
}
|
|
252
247
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryInstanceCache.js","sources":["../../../queries/QueryInstanceCache.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 { QueryResultWithState } from './QueryResultWithState.js';\nimport type {\n CacheDiagnostics,\n CacheEntryDiagnostics,\n} from './ObservableQueryDiagnosticsSnapshot.js';\nimport { reconcileQueryData } from './reconcileQueryData.js';\nimport { deepEqual } from '../deepEqual.js';\n\n/**\n * Represents a key that uniquely identifies a query instance in the cache, based on the query type name and its serialized arguments.\n */\nexport type QueryCacheKey = string;\n\n/**\n * Callback invoked when the cached result for an entry changes.\n */\nexport type QueryCacheListener<TDataType> = (\n result: QueryResultWithState<TDataType>,\n) => void;\n\n/**\n * Represents a single entry in the {@link QueryInstanceCache}.\n * @template TDataType The type of data returned by the query.\n */\nexport interface QueryCacheEntry<TDataType> {\n /**\n * The cached query instance.\n */\n readonly instance: unknown;\n\n /**\n * The last result received from the query, if any.\n */\n lastResult?: QueryResultWithState<TDataType>;\n\n /**\n * The number of active subscribers holding a reference to this entry.\n */\n subscriberCount: number;\n\n /**\n * Set of listener callbacks that are notified when {@link lastResult} changes.\n */\n readonly listeners: Set<QueryCacheListener<TDataType>>;\n\n /**\n * Cleanup function returned by the first subscriber that starts the query connection.\n * Called when the last subscriber releases the entry.\n */\n teardown?: () => void;\n\n /**\n * Whether an active subscription has been established for this entry.\n */\n subscribed: boolean;\n\n /**\n * Timer handle for deferred cleanup. Allows React StrictMode re-mounts (in any build\n * environment) to cancel the pending teardown so the connection is reused instead of\n * torn down and recreated.\n */\n pendingCleanup?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Provides a cache for query instances, keyed by query type and serialized arguments.\n *\n * Two callers requesting the same query type with identical arguments receive the same\n * cached instance and immediately see the last known result — without an additional\n * round trip to the server. When the last subscriber releases its reference the entry\n * is evicted.\n */\nexport class QueryInstanceCache {\n private readonly _entries = new Map<QueryCacheKey, QueryCacheEntry<unknown>>();\n private _pendingDispose?: ReturnType<typeof setTimeout>;\n\n /**\n * Initializes a new instance of {@link QueryInstanceCache}.\n * @param retentionMs How long in milliseconds to keep a cache entry alive after the last\n * subscriber releases it before evicting the subscription and cached data. A non-zero\n * value lets users navigate away and back without losing cached data. Defaults to\n * 30 000 ms. Pass 0 for immediate eviction.\n */\n constructor(private readonly _retentionMs: number = 30_000) {}\n\n /**\n * Builds the cache key for a query.\n * @param queryTypeName The stable type name for the query. Use the instance's `queryName`\n * (a hardcoded fully-qualified string in generated proxies) rather than {@link Function.name},\n * which is unstable under minification.\n * @param args Optional arguments supplied to the query.\n * @returns A stable string key.\n */\n buildKey(queryTypeName: string, args?: object): QueryCacheKey {\n if (!args || Object.keys(args).length === 0) {\n return `${queryTypeName}::`;\n }\n\n const sorted = Object.keys(args)\n .sort()\n .reduce<Record<string, unknown>>((accumulator, key) => {\n accumulator[key] = (args as Record<string, unknown>)[key];\n return accumulator;\n }, {});\n\n return `${queryTypeName}::${JSON.stringify(sorted)}`;\n }\n\n /**\n * Returns a cached instance for the given key, or creates a new one using the provided factory.\n * The subscriber count of the entry is incremented.\n * @template TInstance The type of the query instance.\n * @param key The cache key produced by {@link buildKey}.\n * @param factory A zero-argument factory that creates a fresh query instance when one is not yet cached.\n * @returns The cached (or newly created) instance and whether it was newly created.\n */\n getOrCreate<TInstance>(\n key: QueryCacheKey,\n factory: () => TInstance,\n ): { instance: TInstance; isNew: boolean } {\n if (!this._entries.has(key)) {\n const entry: QueryCacheEntry<unknown> = {\n instance: factory(),\n lastResult: undefined,\n subscriberCount: 0,\n listeners: new Set(),\n subscribed: false,\n };\n\n this._entries.set(key, entry);\n return { instance: entry.instance as TInstance, isNew: true };\n }\n\n const entry = this._entries.get(key)!;\n return { instance: entry.instance as TInstance, isNew: false };\n }\n\n /**\n * Increments the active subscriber count for the given key.\n * If a deferred cleanup was pending (from a recent {@link release}),\n * it is cancelled so the existing subscription is reused.\n * Call from `useEffect` setup to pair with {@link release} in the cleanup.\n * @param key The cache key produced by {@link buildKey}.\n */\n acquire(key: QueryCacheKey): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscriberCount++;\n }\n }\n\n /**\n * Returns the last cached result for the given key, or `undefined` if no result has been stored yet.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @returns The last {@link QueryResultWithState}, or `undefined`.\n */\n getLastResult<TDataType>(\n key: QueryCacheKey,\n ): QueryResultWithState<TDataType> | undefined {\n return this._entries.get(key)?.lastResult as\n | QueryResultWithState<TDataType>\n | undefined;\n }\n\n /**\n * Stores the most recent result for the given key and notifies all registered listeners.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param result The result to store.\n */\n setLastResult<TDataType>(\n key: QueryCacheKey,\n result: QueryResultWithState<TDataType>,\n ): void {\n const entry = this._entries.get(key);\n\n if (!entry) {\n return;\n }\n\n const previousResult = entry.lastResult as\n | QueryResultWithState<TDataType>\n | undefined;\n\n // Reconcile the incoming payload against the one already held so items that did not actually\n // change keep their previous references. A full snapshot — which is what the server re-sends\n // whenever a subscription is re-established — otherwise arrives as all-new references and\n // makes every consumer treat every item as changed.\n const reconciled =\n previousResult === undefined\n ? result\n : this.withReconciledData(previousResult, result);\n\n entry.lastResult = reconciled as QueryResultWithState<unknown>;\n\n // Reconciliation returns the previous data reference when nothing changed, so identity is\n // enough to detect it. Data and result metadata affect what the user sees; changeSet is\n // ephemeral and does not independently require a notification.\n if (\n previousResult !== undefined &&\n previousResult.data === reconciled.data &&\n this.hasEquivalentMetadata(previousResult, reconciled)\n ) {\n return;\n }\n\n for (const listener of entry.listeners) {\n (listener as QueryCacheListener<TDataType>)(reconciled);\n }\n }\n\n /**\n * Returns the incoming result with its data reconciled against the previous result, or the\n * incoming result unchanged when reconciliation found nothing to carry over.\n * @template TDataType The type of data returned by the query.\n * @param previous The previously held result.\n * @param next The freshly received result.\n * @returns A result whose data preserves references for everything that did not change.\n */\n private withReconciledData<TDataType>(\n previous: QueryResultWithState<TDataType>,\n next: QueryResultWithState<TDataType>,\n ): QueryResultWithState<TDataType> {\n const reconciledData = reconcileQueryData(previous.data, next.data);\n\n if (reconciledData === next.data) {\n return next;\n }\n\n return new QueryResultWithState<TDataType>(\n reconciledData,\n next.paging,\n next.isSuccess,\n next.isAuthorized,\n next.isValid,\n next.validationResults,\n next.hasExceptions,\n next.exceptionMessages,\n next.exceptionStackTrace,\n next.isPerforming,\n next.changeSet,\n next.isReady,\n );\n }\n\n private hasEquivalentMetadata<TDataType>(result: QueryResultWithState<TDataType>, previous: QueryResultWithState<TDataType>): boolean {\n return result.isPerforming === previous.isPerforming\n && result.isSuccess === previous.isSuccess\n && result.isReady === previous.isReady\n && result.isAuthorized === previous.isAuthorized\n && result.isValid === previous.isValid\n && result.hasExceptions === previous.hasExceptions\n && result.exceptionStackTrace === previous.exceptionStackTrace\n && deepEqual(result.paging, previous.paging)\n && deepEqual(result.exceptionMessages, previous.exceptionMessages)\n && deepEqual(result.validationResults, previous.validationResults);\n }\n\n /**\n * Registers a listener that is invoked whenever the cached result for the given key changes.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param listener The callback to register.\n */\n addListener<TDataType>(\n key: QueryCacheKey,\n listener: QueryCacheListener<TDataType>,\n ): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.listeners.add(listener as QueryCacheListener<unknown>);\n }\n }\n\n /**\n * Removes a previously registered listener.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param listener The callback to remove.\n */\n removeListener<TDataType>(\n key: QueryCacheKey,\n listener: QueryCacheListener<TDataType>,\n ): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.listeners.delete(listener as QueryCacheListener<unknown>);\n }\n }\n\n /**\n * Stores a teardown function for the given key and marks the entry as subscribed.\n * Called automatically when the last subscriber releases the entry.\n * @param key The cache key produced by {@link buildKey}.\n * @param teardown Cleanup function that disconnects the underlying query subscription.\n */\n setTeardown(key: QueryCacheKey, teardown: () => void): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.teardown = teardown;\n entry.subscribed = true;\n }\n }\n\n /**\n * Returns whether an active subscription exists for the given key.\n * @param key The cache key to check.\n * @returns `true` if a subscription has been established; `false` otherwise.\n */\n isSubscribed(key: QueryCacheKey): boolean {\n return this._entries.get(key)?.subscribed ?? false;\n }\n\n /**\n * Decrements the subscriber count for the given key. When the count reaches zero, both teardown\n * and eviction are deferred by one microtask so that React StrictMode re-mounts — in any build\n * environment — can re-acquire the entry and cancel the cleanup before the timeout fires. This\n * prevents an unnecessary disconnect/reconnect cycle during the synthetic unmount/remount that\n * StrictMode performs.\n * @param key The cache key produced by {@link buildKey}.\n */\n release(key: QueryCacheKey): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.subscriberCount--;\n\n if (entry.subscriberCount <= 0) {\n // Defer both teardown and eviction. React StrictMode re-mounts can cancel by\n // calling acquire() before the timeout fires. A non-zero _retentionMs keeps the\n // entry alive so users navigating back quickly see cached data immediately.\n entry.pendingCleanup = setTimeout(() => {\n const current = this._entries.get(key);\n\n if (current && current.subscriberCount <= 0) {\n current.subscribed = false;\n current.teardown?.();\n current.teardown = undefined;\n current.pendingCleanup = undefined;\n this._entries.delete(key);\n }\n }, this._retentionMs);\n }\n }\n }\n\n /**\n * Returns whether an entry exists for the given key.\n * @param key The cache key to check.\n * @returns `true` if an entry exists; `false` otherwise.\n */\n has(key: QueryCacheKey): boolean {\n return this._entries.has(key);\n }\n\n /**\n * Tears down all active subscriptions and marks every entry as not subscribed,\n * but preserves entries, subscriber counts, and listeners. This allows\n * hooks whose effects re-run afterward to detect that the entry is no longer\n * subscribed and re-establish a fresh connection.\n *\n * Use this when the underlying transport must be replaced (e.g. after an\n * authentication change that requires new WebSocket connections with updated\n * credentials).\n */\n teardownAllSubscriptions(): void {\n for (const [, entry] of this._entries) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscribed = false;\n entry.teardown?.();\n entry.teardown = undefined;\n }\n }\n\n /**\n * Immediately tears down all subscriptions, cancels any pending deferred cleanups,\n * and evicts all entries. Call when the owning component (e.g. the {@link Arc} provider)\n * unmounts permanently so that all query connections are closed synchronously.\n */\n dispose(): void {\n for (const [, entry] of this._entries) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscribed = false;\n entry.teardown?.();\n entry.teardown = undefined;\n }\n\n this._entries.clear();\n }\n\n /**\n * Schedules a deferred {@link dispose} using {@code setTimeout(0)}.\n *\n * This allows React StrictMode re-mounts to call {@link cancelPendingDispose}\n * before the dispose fires, avoiding the destruction of cache entries that child\n * effects are about to re-acquire.\n *\n * If a deferred dispose is already pending, it is replaced.\n */\n deferDispose(): void {\n if (this._pendingDispose !== undefined) {\n clearTimeout(this._pendingDispose);\n }\n\n this._pendingDispose = setTimeout(() => {\n this._pendingDispose = undefined;\n this.dispose();\n }, 0);\n }\n\n /**\n * Cancels a pending deferred dispose scheduled by {@link deferDispose}.\n *\n * Call from the {@code useEffect} setup phase so that a StrictMode re-mount\n * prevents the synthetic unmount's deferred dispose from firing.\n */\n cancelPendingDispose(): void {\n if (this._pendingDispose !== undefined) {\n clearTimeout(this._pendingDispose);\n this._pendingDispose = undefined;\n }\n }\n\n /**\n * Returns a diagnostics snapshot of the current cache state.\n * @returns A {@link CacheDiagnostics} describing all entries.\n */\n getDiagnosticsSnapshot(): CacheDiagnostics {\n const entries: CacheEntryDiagnostics[] = [];\n let totalBytes = 0;\n let unhealthyCount = 0;\n\n for (const [key, entry] of this._entries) {\n const colonIndex = key.indexOf('::');\n const queryName = colonIndex >= 0 ? key.substring(0, colonIndex) : key;\n\n let estimatedBytes = 0;\n try {\n if (entry.lastResult !== undefined) {\n estimatedBytes = JSON.stringify(entry.lastResult).length;\n }\n } catch {\n // Ignore serialization errors\n }\n\n if (entry.subscriberCount > 0 && !entry.subscribed) {\n unhealthyCount++;\n }\n\n totalBytes += estimatedBytes;\n entries.push({\n key,\n queryName,\n subscriberCount: entry.subscriberCount,\n listenerCount: entry.listeners.size,\n subscribed: entry.subscribed,\n hasResult: entry.lastResult !== undefined,\n estimatedBytes,\n });\n }\n\n return {\n healthy: unhealthyCount === 0,\n entryCount: this._entries.size,\n estimatedBytes: totalBytes,\n entries,\n };\n }\n}\n"],"names":["QueryInstanceCache","_entries","Map","_pendingDispose","_retentionMs","buildKey","queryTypeName","args","Object","keys","length","sorted","sort","reduce","accumulator","key","JSON","stringify","getOrCreate","factory","has","entry","instance","lastResult","undefined","subscriberCount","listeners","Set","subscribed","set","isNew","get","acquire","pendingCleanup","clearTimeout","getLastResult","setLastResult","result","previousResult","reconciled","withReconciledData","data","hasEquivalentMetadata","listener","previous","next","reconciledData","reconcileQueryData","QueryResultWithState","paging","isSuccess","isAuthorized","isValid","validationResults","hasExceptions","exceptionMessages","exceptionStackTrace","isPerforming","changeSet","isReady","deepEqual","addListener","add","removeListener","delete","setTeardown","teardown","isSubscribed","release","setTimeout","current","teardownAllSubscriptions","dispose","clear","deferDispose","cancelPendingDispose","getDiagnosticsSnapshot","entries","totalBytes","unhealthyCount","colonIndex","indexOf","queryName","substring","estimatedBytes","push","listenerCount","size","hasResult","healthy","entryCount"],"mappings":";;;;AAAA;AACA;AAkEA;;;;;;;AAOC,IACM,MAAMA,kBAAAA,CAAAA;;AACQC,IAAAA,QAAAA,GAAW,IAAIC,GAAAA,EAAAA;IACxBC,eAAAA;AAER;;;;;;AAMC,QACD,WAAA,CAA6BC,YAAAA,GAAuB,MAAM,CAAE;aAA/BA,YAAAA,GAAAA,YAAAA;AAAgC,IAAA;AAE7D;;;;;;;AAOC,QACDC,QAAAA,CAASC,aAAqB,EAAEC,IAAa,EAAiB;QAC1D,IAAI,CAACA,QAAQC,MAAAA,CAAOC,IAAI,CAACF,IAAAA,CAAAA,CAAMG,MAAM,KAAK,CAAA,EAAG;YACzC,OAAO,CAAA,EAAGJ,aAAAA,CAAc,EAAE,CAAC;AAC/B,QAAA;QAEA,MAAMK,MAAAA,GAASH,MAAAA,CAAOC,IAAI,CAACF,IAAAA,CAAAA,CACtBK,IAAI,EAAA,CACJC,MAAM,CAA0B,CAACC,WAAAA,EAAaC,GAAAA,GAAAA;AAC3CD,YAAAA,WAAW,CAACC,GAAAA,CAAI,GAAG,IAAiC,CAACA,GAAAA,CAAI;YACzD,OAAO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AAAA;AAEnE,YAAA,IAAIqE,cAAAA,GAAiB,CAAA;YACrB,IAAI;gBACA,IAAI/D,KAAAA,CAAME,UAAU,KAAKC,SAAAA,EAAW;AAChC4D,oBAAAA,cAAAA,GAAiBpE,KAAKC,SAAS,CAACI,KAAAA,CAAME,UAAU,EAAEb,MAAM;AAC5D,gBAAA;AACJ,YAAA,CAAA,CAAE,OAAM;;AAER,YAAA;AAEA,YAAA,IAAIW,MAAMI,eAAe,GAAG,KAAK,CAACJ,KAAAA,CAAMO,UAAU,EAAE;AAChDmD,gBAAAA,cAAAA,EAAAA;AACJ,YAAA;YAEAD,UAAAA,IAAcM,cAAAA;AACdP,YAAAA,OAAAA,CAAQQ,IAAI,CAAC;AACTtE,gBAAAA,GAAAA;AACAmE,gBAAAA,SAAAA;AACAzD,gBAAAA,eAAAA,EAAiBJ,MAAMI,eAAe;gBACtC6D,aAAAA,EAAejE,KAAAA,CAAMK,SAAS,CAAC6D,IAAI;AACnC3D,gBAAAA,UAAAA,EAAYP,MAAMO,UAAU;gBAC5B4D,SAAAA,EAAWnE,KAAAA,CAAME,UAAU,KAAKC,SAAAA;AAChC4D,gBAAAA;AACJ,aAAA,CAAA;AACJ,QAAA;QAEA,OAAO;AACHK,YAAAA,OAAAA,EAASV,cAAAA,KAAmB,CAAA;AAC5BW,YAAAA,UAAAA,EAAY,IAAI,CAACzF,QAAQ,CAACsF,IAAI;YAC9BH,cAAAA,EAAgBN,UAAAA;AAChBD,YAAAA;AACJ,SAAA;AACJ,IAAA;AACJ;;"}
|
|
1
|
+
{"version":3,"file":"QueryInstanceCache.js","sources":["../../../queries/QueryInstanceCache.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 { QueryResultWithState } from './QueryResultWithState.js';\nimport type {\n CacheDiagnostics,\n CacheEntryDiagnostics,\n} from './ObservableQueryDiagnosticsSnapshot.js';\nimport { reconcileQueryData } from './reconcileQueryData.js';\nimport { deepEqual } from '../deepEqual.js';\n\n/**\n * Represents a key that uniquely identifies a query instance in the cache, based on the query type name and its serialized arguments.\n */\nexport type QueryCacheKey = string;\n\n/**\n * Callback invoked when the cached result for an entry changes.\n */\nexport type QueryCacheListener<TDataType> = (\n result: QueryResultWithState<TDataType>,\n) => void;\n\n/**\n * Represents a single entry in the {@link QueryInstanceCache}.\n * @template TDataType The type of data returned by the query.\n */\nexport interface QueryCacheEntry<TDataType> {\n /**\n * The cached query instance.\n */\n readonly instance: unknown;\n\n /**\n * The last result received from the query, if any.\n */\n lastResult?: QueryResultWithState<TDataType>;\n\n /**\n * The number of active subscribers holding a reference to this entry.\n */\n subscriberCount: number;\n\n /**\n * Set of listener callbacks that are notified when {@link lastResult} changes.\n */\n readonly listeners: Set<QueryCacheListener<TDataType>>;\n\n /**\n * Cleanup function returned by the first subscriber that starts the query connection.\n * Called when the last subscriber releases the entry.\n */\n teardown?: () => void;\n\n /**\n * Whether an active subscription has been established for this entry.\n */\n subscribed: boolean;\n\n /**\n * Timer handle for deferred cleanup. Allows React StrictMode re-mounts (in any build\n * environment) to cancel the pending teardown so the connection is reused instead of\n * torn down and recreated.\n */\n pendingCleanup?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Provides a cache for query instances, keyed by query type and serialized arguments.\n *\n * Two callers requesting the same query type with identical arguments receive the same\n * cached instance and immediately see the last known result — without an additional\n * round trip to the server. When the last subscriber releases its reference the entry\n * is evicted.\n */\nexport class QueryInstanceCache {\n private readonly _entries = new Map<QueryCacheKey, QueryCacheEntry<unknown>>();\n private _pendingDispose?: ReturnType<typeof setTimeout>;\n\n /**\n * Initializes a new instance of {@link QueryInstanceCache}.\n * @param retentionMs How long in milliseconds to keep a cache entry alive after the last\n * subscriber releases it before evicting the subscription and cached data. A non-zero\n * value lets users navigate away and back without losing cached data. Defaults to\n * 30 000 ms. Pass 0 for immediate eviction.\n */\n constructor(private readonly _retentionMs: number = 30_000) {}\n\n /**\n * Builds the cache key for a query.\n * @param queryTypeName The stable type name for the query. Use the instance's `queryName`\n * (a hardcoded fully-qualified string in generated proxies) rather than {@link Function.name},\n * which is unstable under minification.\n * @param args Optional arguments supplied to the query.\n * @returns A stable string key.\n */\n buildKey(queryTypeName: string, args?: object): QueryCacheKey {\n if (!args || Object.keys(args).length === 0) {\n return `${queryTypeName}::`;\n }\n\n const sorted = Object.keys(args)\n .sort()\n .reduce<Record<string, unknown>>((accumulator, key) => {\n accumulator[key] = (args as Record<string, unknown>)[key];\n return accumulator;\n }, {});\n\n return `${queryTypeName}::${JSON.stringify(sorted)}`;\n }\n\n /**\n * Returns a cached instance for the given key, or creates a new one using the provided factory.\n * The subscriber count of the entry is incremented.\n * @template TInstance The type of the query instance.\n * @param key The cache key produced by {@link buildKey}.\n * @param factory A zero-argument factory that creates a fresh query instance when one is not yet cached.\n * @returns The cached (or newly created) instance and whether it was newly created.\n */\n getOrCreate<TInstance>(\n key: QueryCacheKey,\n factory: () => TInstance,\n ): { instance: TInstance; isNew: boolean } {\n if (!this._entries.has(key)) {\n const entry: QueryCacheEntry<unknown> = {\n instance: factory(),\n lastResult: undefined,\n subscriberCount: 0,\n listeners: new Set(),\n subscribed: false,\n };\n\n this._entries.set(key, entry);\n return { instance: entry.instance as TInstance, isNew: true };\n }\n\n const entry = this._entries.get(key)!;\n return { instance: entry.instance as TInstance, isNew: false };\n }\n\n /**\n * Increments the active subscriber count for the given key.\n * If a deferred cleanup was pending (from a recent {@link release}),\n * it is cancelled so the existing subscription is reused.\n * Call from `useEffect` setup to pair with {@link release} in the cleanup.\n * @param key The cache key produced by {@link buildKey}.\n */\n acquire(key: QueryCacheKey): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscriberCount++;\n }\n }\n\n /**\n * Returns the last cached result for the given key, or `undefined` if no result has been stored yet.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @returns The last {@link QueryResultWithState}, or `undefined`.\n */\n getLastResult<TDataType>(\n key: QueryCacheKey,\n ): QueryResultWithState<TDataType> | undefined {\n return this._entries.get(key)?.lastResult as\n | QueryResultWithState<TDataType>\n | undefined;\n }\n\n /**\n * Stores the most recent result for the given key and notifies all registered listeners.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param result The result to store.\n */\n setLastResult<TDataType>(\n key: QueryCacheKey,\n result: QueryResultWithState<TDataType>,\n ): void {\n const entry = this._entries.get(key);\n\n if (!entry) {\n return;\n }\n\n const previousResult = entry.lastResult as\n | QueryResultWithState<TDataType>\n | undefined;\n\n // Reconcile the incoming payload against the one already held so items that did not actually\n // change keep their previous references. A full snapshot — which is what the server re-sends\n // whenever a subscription is re-established — otherwise arrives as all-new references and\n // makes every consumer treat every item as changed.\n const reconciled =\n previousResult === undefined\n ? result\n : this.withReconciledData(previousResult, result);\n\n entry.lastResult = reconciled as QueryResultWithState<unknown>;\n\n // Reconciliation returns the previous data reference when nothing changed, so identity is\n // enough to detect it. Data and result metadata affect what the user sees; changeSet is\n // ephemeral and does not independently require a notification.\n if (\n previousResult !== undefined &&\n previousResult.data === reconciled.data &&\n this.hasEquivalentMetadata(previousResult, reconciled)\n ) {\n return;\n }\n\n for (const listener of entry.listeners) {\n (listener as QueryCacheListener<TDataType>)(reconciled);\n }\n }\n\n /**\n * Returns the incoming result with its data reconciled against the previous result, or the\n * incoming result unchanged when reconciliation found nothing to carry over.\n * @template TDataType The type of data returned by the query.\n * @param previous The previously held result.\n * @param next The freshly received result.\n * @returns A result whose data preserves references for everything that did not change.\n */\n private withReconciledData<TDataType>(\n previous: QueryResultWithState<TDataType>,\n next: QueryResultWithState<TDataType>,\n ): QueryResultWithState<TDataType> {\n const reconciledData = reconcileQueryData(previous.data, next.data);\n\n if (reconciledData === next.data) {\n return next;\n }\n\n return new QueryResultWithState<TDataType>(\n reconciledData,\n next.paging,\n next.isSuccess,\n next.isAuthorized,\n next.isValid,\n next.validationResults,\n next.hasExceptions,\n next.exceptionMessages,\n next.exceptionStackTrace,\n next.isPerforming,\n next.changeSet,\n next.isReady,\n );\n }\n\n private hasEquivalentMetadata<TDataType>(result: QueryResultWithState<TDataType>, previous: QueryResultWithState<TDataType>): boolean {\n return result.isPerforming === previous.isPerforming\n && result.isSuccess === previous.isSuccess\n && result.isReady === previous.isReady\n && result.isAuthorized === previous.isAuthorized\n && result.isValid === previous.isValid\n && result.hasExceptions === previous.hasExceptions\n && result.exceptionStackTrace === previous.exceptionStackTrace\n && deepEqual(result.paging, previous.paging)\n && deepEqual(result.exceptionMessages, previous.exceptionMessages)\n && deepEqual(result.validationResults, previous.validationResults);\n }\n\n /**\n * Registers a listener that is invoked whenever the cached result for the given key changes.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param listener The callback to register.\n */\n addListener<TDataType>(\n key: QueryCacheKey,\n listener: QueryCacheListener<TDataType>,\n ): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.listeners.add(listener as QueryCacheListener<unknown>);\n }\n }\n\n /**\n * Removes a previously registered listener.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param listener The callback to remove.\n */\n removeListener<TDataType>(\n key: QueryCacheKey,\n listener: QueryCacheListener<TDataType>,\n ): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.listeners.delete(listener as QueryCacheListener<unknown>);\n }\n }\n\n /**\n * Stores a teardown function for the given key and marks the entry as subscribed.\n * Called automatically when the last subscriber releases the entry.\n * @param key The cache key produced by {@link buildKey}.\n * @param teardown Cleanup function that disconnects the underlying query subscription.\n */\n setTeardown(key: QueryCacheKey, teardown: () => void): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.teardown = teardown;\n entry.subscribed = true;\n }\n }\n\n /**\n * Returns whether an active subscription exists for the given key.\n * @param key The cache key to check.\n * @returns `true` if a subscription has been established; `false` otherwise.\n */\n isSubscribed(key: QueryCacheKey): boolean {\n return this._entries.get(key)?.subscribed ?? false;\n }\n\n /**\n * Decrements the subscriber count for the given key. When the count reaches zero, both teardown\n * and eviction are deferred by one microtask so that React StrictMode re-mounts — in any build\n * environment — can re-acquire the entry and cancel the cleanup before the timeout fires. This\n * prevents an unnecessary disconnect/reconnect cycle during the synthetic unmount/remount that\n * StrictMode performs.\n * @param key The cache key produced by {@link buildKey}.\n */\n release(key: QueryCacheKey): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.subscriberCount--;\n\n if (entry.subscriberCount <= 0) {\n // Defer both teardown and eviction. React StrictMode re-mounts can cancel by\n // calling acquire() before the timeout fires. A non-zero _retentionMs keeps the\n // entry alive so users navigating back quickly see cached data immediately.\n entry.pendingCleanup = setTimeout(() => {\n const current = this._entries.get(key);\n\n if (current && current.subscriberCount <= 0) {\n current.subscribed = false;\n current.teardown?.();\n current.teardown = undefined;\n current.pendingCleanup = undefined;\n this._entries.delete(key);\n }\n }, this._retentionMs);\n }\n }\n }\n\n /**\n * Returns whether an entry exists for the given key.\n * @param key The cache key to check.\n * @returns `true` if an entry exists; `false` otherwise.\n */\n has(key: QueryCacheKey): boolean {\n return this._entries.has(key);\n }\n\n /**\n * Tears down all active subscriptions and marks every entry as not subscribed,\n * but preserves entries, subscriber counts, and listeners. This allows\n * hooks whose effects re-run afterward to detect that the entry is no longer\n * subscribed and re-establish a fresh connection.\n *\n * Use this when the underlying transport must be replaced (e.g. after an\n * authentication change that requires new WebSocket connections with updated\n * credentials).\n */\n teardownAllSubscriptions(): void {\n for (const [, entry] of this._entries) {\n this.teardownEntry(entry);\n }\n }\n\n private teardownEntry(entry: QueryCacheEntry<unknown>): void {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscribed = false;\n entry.teardown?.();\n entry.teardown = undefined;\n }\n\n /**\n * Immediately tears down all subscriptions, cancels any pending deferred cleanups,\n * and evicts all entries. Call when the owning component (e.g. the {@link Arc} provider)\n * unmounts permanently so that all query connections are closed synchronously.\n */\n dispose(): void {\n this.teardownAllSubscriptions();\n this._entries.clear();\n }\n\n /**\n * Schedules a deferred {@link dispose} using {@code setTimeout(0)}.\n *\n * This allows React StrictMode re-mounts to call {@link cancelPendingDispose}\n * before the dispose fires, avoiding the destruction of cache entries that child\n * effects are about to re-acquire.\n *\n * If a deferred dispose is already pending, it is replaced.\n */\n deferDispose(): void {\n if (this._pendingDispose !== undefined) {\n clearTimeout(this._pendingDispose);\n }\n\n this._pendingDispose = setTimeout(() => {\n this._pendingDispose = undefined;\n this.dispose();\n }, 0);\n }\n\n /**\n * Cancels a pending deferred dispose scheduled by {@link deferDispose}.\n *\n * Call from the {@code useEffect} setup phase so that a StrictMode re-mount\n * prevents the synthetic unmount's deferred dispose from firing.\n */\n cancelPendingDispose(): void {\n if (this._pendingDispose !== undefined) {\n clearTimeout(this._pendingDispose);\n this._pendingDispose = undefined;\n }\n }\n\n /**\n * Returns a diagnostics snapshot of the current cache state.\n * @returns A {@link CacheDiagnostics} describing all entries.\n */\n getDiagnosticsSnapshot(): CacheDiagnostics {\n const entries: CacheEntryDiagnostics[] = [];\n let totalBytes = 0;\n let unhealthyCount = 0;\n\n for (const [key, entry] of this._entries) {\n const colonIndex = key.indexOf('::');\n const queryName = colonIndex >= 0 ? key.substring(0, colonIndex) : key;\n\n let estimatedBytes = 0;\n try {\n if (entry.lastResult !== undefined) {\n estimatedBytes = JSON.stringify(entry.lastResult).length;\n }\n } catch {\n // Ignore serialization errors\n }\n\n if (entry.subscriberCount > 0 && !entry.subscribed) {\n unhealthyCount++;\n }\n\n totalBytes += estimatedBytes;\n entries.push({\n key,\n queryName,\n subscriberCount: entry.subscriberCount,\n listenerCount: entry.listeners.size,\n subscribed: entry.subscribed,\n hasResult: entry.lastResult !== undefined,\n estimatedBytes,\n });\n }\n\n return {\n healthy: unhealthyCount === 0,\n entryCount: this._entries.size,\n estimatedBytes: totalBytes,\n entries,\n };\n }\n}\n"],"names":["QueryInstanceCache","_entries","Map","_pendingDispose","_retentionMs","buildKey","queryTypeName","args","Object","keys","length","sorted","sort","reduce","accumulator","key","JSON","stringify","getOrCreate","factory","has","entry","instance","lastResult","undefined","subscriberCount","listeners","Set","subscribed","set","isNew","get","acquire","pendingCleanup","clearTimeout","getLastResult","setLastResult","result","previousResult","reconciled","withReconciledData","data","hasEquivalentMetadata","listener","previous","next","reconciledData","reconcileQueryData","QueryResultWithState","paging","isSuccess","isAuthorized","isValid","validationResults","hasExceptions","exceptionMessages","exceptionStackTrace","isPerforming","changeSet","isReady","deepEqual","addListener","add","removeListener","delete","setTeardown","teardown","isSubscribed","release","setTimeout","current","teardownAllSubscriptions","teardownEntry","dispose","clear","deferDispose","cancelPendingDispose","getDiagnosticsSnapshot","entries","totalBytes","unhealthyCount","colonIndex","indexOf","queryName","substring","estimatedBytes","push","listenerCount","size","hasResult","healthy","entryCount"],"mappings":";;;;AAAA;AACA;AAkEA;;;;;;;AAOC,IACM,MAAMA,kBAAAA,CAAAA;;AACQC,IAAAA,QAAAA,GAAW,IAAIC,GAAAA,EAAAA;IACxBC,eAAAA;AAER;;;;;;AAMC,QACD,WAAA,CAA6BC,YAAAA,GAAuB,MAAM,CAAE;aAA/BA,YAAAA,GAAAA,YAAAA;AAAgC,IAAA;AAE7D;;;;;;;AAOC,QACDC,QAAAA,CAASC,aAAqB,EAAEC,IAAa,EAAiB;QAC1D,IAAI,CAACA,QAAQC,MAAAA,CAAOC,IAAI,CAACF,IAAAA,CAAAA,CAAMG,MAAM,KAAK,CAAA,EAAG;YACzC,OAAO,CAAA,EAAGJ,aAAAA,CAAc,EAAE,CAAC;AAC/B,QAAA;QAEA,MAAMK,MAAAA,GAASH,MAAAA,CAAOC,IAAI,CAACF,IAAAA,CAAAA,CACtBK,IAAI,EAAA,CACJC,MAAM,CAA0B,CAACC,WAAAA,EAAaC,GAAAA,GAAAA;AAC3CD,YAAAA,WAAW,CAACC,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gBAAA;AACJ,YAAA,CAAA,CAAE,OAAM;;AAER,YAAA;AAEA,YAAA,IAAIW,MAAMI,eAAe,GAAG,KAAK,CAACJ,KAAAA,CAAMO,UAAU,EAAE;AAChDoD,gBAAAA,cAAAA,EAAAA;AACJ,YAAA;YAEAD,UAAAA,IAAcM,cAAAA;AACdP,YAAAA,OAAAA,CAAQQ,IAAI,CAAC;AACTvE,gBAAAA,GAAAA;AACAoE,gBAAAA,SAAAA;AACA1D,gBAAAA,eAAAA,EAAiBJ,MAAMI,eAAe;gBACtC8D,aAAAA,EAAelE,KAAAA,CAAMK,SAAS,CAAC8D,IAAI;AACnC5D,gBAAAA,UAAAA,EAAYP,MAAMO,UAAU;gBAC5B6D,SAAAA,EAAWpE,KAAAA,CAAME,UAAU,KAAKC,SAAAA;AAChC6D,gBAAAA;AACJ,aAAA,CAAA;AACJ,QAAA;QAEA,OAAO;AACHK,YAAAA,OAAAA,EAASV,cAAAA,KAAmB,CAAA;AAC5BW,YAAAA,UAAAA,EAAY,IAAI,CAAC1F,QAAQ,CAACuF,IAAI;YAC9BH,cAAAA,EAAgBN,UAAAA;AAChBD,YAAAA;AACJ,SAAA;AACJ,IAAA;AACJ;;"}
|
|
@@ -32,9 +32,14 @@ export declare class ServerSentEventHubConnection implements IObservableQueryHub
|
|
|
32
32
|
private ensureConnected;
|
|
33
33
|
private close;
|
|
34
34
|
private openEventSource;
|
|
35
|
+
private buildEventSourceUrl;
|
|
36
|
+
private isActiveSource;
|
|
37
|
+
private startConnectTimeout;
|
|
35
38
|
private reconnect;
|
|
36
39
|
private clearConnectTimeout;
|
|
37
40
|
private handleMessage;
|
|
41
|
+
private handleUnauthorizedMessage;
|
|
42
|
+
private handleErrorMessage;
|
|
38
43
|
private handleConnected;
|
|
39
44
|
private applyServerKeepAliveInterval;
|
|
40
45
|
private handleQueryResult;
|
|
@@ -42,6 +47,8 @@ export declare class ServerSentEventHubConnection implements IObservableQueryHub
|
|
|
42
47
|
private handleUnauthorized;
|
|
43
48
|
private deliverResult;
|
|
44
49
|
private sendSubscribe;
|
|
50
|
+
private handleSubscribeFailure;
|
|
51
|
+
private scheduleSubscribeRetry;
|
|
45
52
|
private isMessageForCurrentSubscription;
|
|
46
53
|
private isCurrentSubscription;
|
|
47
54
|
private getNextRevision;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ServerSentEventHubConnection.d.ts","sourceRoot":"","sources":["../../../queries/ServerSentEventHubConnection.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AACxF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAEnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAG9D,OAAO,EAGH,KAAK,mBAAmB,EAC3B,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"ServerSentEventHubConnection.d.ts","sourceRoot":"","sources":["../../../queries/ServerSentEventHubConnection.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AACxF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAEnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAG9D,OAAO,EAGH,KAAK,mBAAmB,EAC3B,MAAM,6BAA6B,CAAC;AA2CrC,qBAAa,4BAA6B,YAAW,6BAA6B;IA2B1E,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,eAAe;IAChC,OAAO,CAAC,QAAQ,CAAC,aAAa;IAE9B,OAAO,CAAC,QAAQ,CAAC,iBAAiB;IAClC,OAAO,CAAC,QAAQ,CAAC,OAAO;IAhC5B,OAAO,CAAC,YAAY,CAAC,CAAc;IACnC,OAAO,CAAC,aAAa,CAAC,CAAS;IAC/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