@metamask-previews/react-data-query 1.0.0-preview-abca9bcea → 2.0.0-preview-0a30e47

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/CHANGELOG.md CHANGED
@@ -7,9 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.0.0]
11
+
10
12
  ### Changed
11
13
 
14
+ - **BREAKING:** Drop CommonJS support ([#9536](https://github.com/MetaMask/core/pull/9536))
15
+ - This package is now ESM-only, but can still be used in CommonJS projects via `require(esm)` in modern Node.js versions (22+), or dynamic imports in older Node.js versions.
16
+ - **BREAKING:** Bump minimum Node.js version to 22 ([#9976](https://github.com/MetaMask/core/pull/9976))
17
+ - **BREAKING:** Bump TypeScript target to ES2022 ([#10019](https://github.com/MetaMask/core/pull/10019))
18
+ - This package now ships ES2022 code, requiring a compatible modern environment or bundler configuration to consume.
12
19
  - Bump `@metamask/utils` from `^11.11.0` to `^11.12.0` ([#10076](https://github.com/MetaMask/core/pull/10076))
20
+ - Bump `@metamask/base-data-service` from `^1.0.0` to `^2.0.0` ([#10160](https://github.com/MetaMask/core/pull/10160))
13
21
 
14
22
  ## [1.0.0]
15
23
 
@@ -58,7 +66,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
58
66
 
59
67
  - Initial release ([#8039](https://github.com/MetaMask/core/pull/8039), [#8292](https://github.com/MetaMask/core/pull/8292))
60
68
 
61
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/react-data-query@1.0.0...HEAD
69
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/react-data-query@2.0.0...HEAD
70
+ [2.0.0]: https://github.com/MetaMask/core/compare/@metamask/react-data-query@1.0.0...@metamask/react-data-query@2.0.0
62
71
  [1.0.0]: https://github.com/MetaMask/core/compare/@metamask/react-data-query@0.2.2...@metamask/react-data-query@1.0.0
63
72
  [0.2.2]: https://github.com/MetaMask/core/compare/@metamask/react-data-query@0.2.1...@metamask/react-data-query@0.2.2
64
73
  [0.2.1]: https://github.com/MetaMask/core/compare/@metamask/react-data-query@0.2.0...@metamask/react-data-query@0.2.1
@@ -1,5 +1,5 @@
1
- import type { DataServiceGranularCacheUpdatedEvent, DataServiceGranularCacheUpdatedPayload } from "@metamask/base-data-service";
2
- import { QueryClient, QueryClientConfig } from "@tanstack/query-core";
1
+ import type { DataServiceGranularCacheUpdatedEvent, DataServiceGranularCacheUpdatedPayload } from '@metamask/base-data-service';
2
+ import { QueryClient, QueryClientConfig } from '@tanstack/query-core';
3
3
  /**
4
4
  * Handles granular cache update events emitted by data services.
5
5
  */
@@ -48,4 +48,4 @@ type MessengerAdapter<DataServiceName extends string> = {
48
48
  */
49
49
  export declare function createUIQueryClient<DataServiceNames extends readonly string[]>(dataServices: DataServiceNames, messenger: MessengerAdapter<DataServiceNames[number]>, config?: QueryClientConfig): QueryClient;
50
50
  export {};
51
- //# sourceMappingURL=createUIQueryClient.d.mts.map
51
+ //# sourceMappingURL=createUIQueryClient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createUIQueryClient.d.ts","sourceRoot":"","sources":["../src/createUIQueryClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oCAAoC,EACpC,sCAAsC,EACvC,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAEL,WAAW,EAIX,iBAAiB,EAClB,MAAM,sBAAsB,CAAC;AAE9B;;GAEG;AACH,KAAK,sCAAsC,GAAG,CAC5C,OAAO,EAAE,sCAAsC,KAC5C,IAAI,CAAC;AAEV;;;GAGG;AACH,KAAK,gBAAgB,CAAC,eAAe,SAAS,MAAM,IAAI;IACtD;;;;;;;OAOG;IACH,IAAI,CACF,UAAU,EAAE,GAAG,eAAe,IAAI,MAAM,EAAE,EAC1C,GAAG,MAAM,EAAE,OAAO,EAAE,GACnB,OAAO,CAAC;IAEX;;;OAGG;IACH,SAAS,CACP,SAAS,EAAE,oCAAoC,CAAC,eAAe,CAAC,CAAC,MAAM,CAAC,EACxE,OAAO,EAAE,sCAAsC,GAC9C,IAAI,CAAC;IAER;;;OAGG;IACH,WAAW,CACT,SAAS,EAAE,oCAAoC,CAAC,eAAe,CAAC,CAAC,MAAM,CAAC,EACxE,OAAO,EAAE,sCAAsC,GAC9C,IAAI,CAAC;CACT,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,mBAAmB,CAAC,gBAAgB,SAAS,SAAS,MAAM,EAAE,EAC5E,YAAY,EAAE,gBAAgB,EAC9B,SAAS,EAAE,gBAAgB,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC,EACrD,MAAM,GAAE,iBAAsB,GAC7B,WAAW,CA8Jb"}
@@ -1,5 +1,5 @@
1
- import { assert } from "@metamask/utils";
2
- import { hydrate, QueryClient } from "@tanstack/query-core";
1
+ import { assert } from '@metamask/utils';
2
+ import { hydrate, QueryClient, } from '@tanstack/query-core';
3
3
  /**
4
4
  * Create a QueryClient that queries and subscribes to data services using a
5
5
  * messenger adapter. This is a messenger-like object that carries some
@@ -125,4 +125,4 @@ export function createUIQueryClient(dataServices, messenger, config = {}) {
125
125
  };
126
126
  return client;
127
127
  }
128
- //# sourceMappingURL=createUIQueryClient.mjs.map
128
+ //# sourceMappingURL=createUIQueryClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createUIQueryClient.js","sourceRoot":"","sources":["../src/createUIQueryClient.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EACL,OAAO,EACP,WAAW,GAKZ,MAAM,sBAAsB,CAAC;AA8C9B;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,mBAAmB,CACjC,YAA8B,EAC9B,SAAqD,EACrD,MAAM,GAAsB,EAAE;IAE9B,MAAM,aAAa,GAAG,IAAI,GAAG,EAG1B,CAAC;IAEJ;;;;;OAKG;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,\n} from '@metamask/base-data-service';\nimport { assert } from '@metamask/utils';\nimport {\n hydrate,\n QueryClient,\n InvalidateQueryFilters,\n InvalidateOptions,\n QueryKey,\n QueryClientConfig,\n} from '@tanstack/query-core';\n\n/**\n * Handles granular cache update events emitted by data services.\n */\ntype DataServiceGranularCacheUpdatedHandler = (\n payload: DataServiceGranularCacheUpdatedPayload,\n) => void;\n\n/**\n * A narrower subset of the `Messenger` type, tailored to the messenger\n * that `createUIQueryClient` interacts with.\n */\ntype MessengerAdapter<DataServiceName extends string> = {\n /**\n * Call an action on one of the configured data services.\n *\n * Note: The parameters are typed as `unknown[]` rather than `Json[]`. For\n * concrete messengers, each action's parameters exist as fixed-length tuple,\n * and a variadic `Json[]` is not assignable to a fixed-length tuple, so using\n * `Json[]` here would reject otherwise valid messengers.\n */\n call(\n actionType: `${DataServiceName}:${string}`,\n ...params: unknown[]\n ): unknown;\n\n /**\n * Subscribe to a granular cache update event on one of the configured data\n * services.\n */\n subscribe(\n eventType: DataServiceGranularCacheUpdatedEvent<DataServiceName>['type'],\n handler: DataServiceGranularCacheUpdatedHandler,\n ): void;\n\n /**\n * Unsubscribe from a granular cache update event on one of the configured\n * data services.\n */\n unsubscribe(\n eventType: DataServiceGranularCacheUpdatedEvent<DataServiceName>['type'],\n handler: DataServiceGranularCacheUpdatedHandler,\n ): void;\n};\n\n/**\n * Create a QueryClient that queries and subscribes to data services using a\n * messenger adapter. This is a messenger-like object that carries some\n * constraints:\n *\n * 1. The messenger must support the `call`, `subscribe` and\n * `unsubscribe` methods.\n * 2. All action handler arguments and event payloads must be JSON-compatible.\n * 3. The messenger must minimally support actions that are scoped to the\n * designated data services and must minimally support the\n * `:cacheUpdated:${hash}` event scoped to the designated data services.\n *\n * @param dataServices - A list of data services.\n * @param messenger - A messenger adapter.\n * @param config - Optional query client configuration options.\n * @returns The QueryClient.\n */\nexport function createUIQueryClient<DataServiceNames extends readonly string[]>(\n dataServices: DataServiceNames,\n messenger: MessengerAdapter<DataServiceNames[number]>,\n config: QueryClientConfig = {},\n): QueryClient {\n const subscriptions = new Map<\n string,\n DataServiceGranularCacheUpdatedHandler\n >();\n\n /**\n * Check whether a name is one of the provided data service names.\n *\n * @param service - The service name to check.\n * @returns Whether the service name is configured.\n */\n function isRecognizedDataService(\n service: string,\n ): service is DataServiceNames[number] {\n return dataServices.some((dataService) => dataService === service);\n }\n\n /**\n * Check whether an action belongs to one of the provided data services.\n *\n * @param action - The action name to check.\n * @returns Whether the action belongs to a configured data service.\n */\n function isRecognizedDataServiceAction(\n action: string,\n ): action is `${DataServiceNames[number]}:${string}` {\n return isRecognizedDataService(action.split(':')[0]);\n }\n\n /**\n * Parse a query key to detect a service name.\n *\n * @param queryKey - The query key.\n * @returns The service name if it parsing succeeded, otherwise null.\n */\n function parseQueryKey(queryKey: QueryKey): DataServiceNames[number] | null {\n const action = queryKey[0];\n\n if (typeof action !== 'string') {\n return null;\n }\n\n const service = action.split(':')[0];\n\n if (!isRecognizedDataService(service)) {\n return null;\n }\n\n return service;\n }\n\n const client: QueryClient = new QueryClient({\n ...config,\n defaultOptions: {\n queries: {\n ...config.defaultOptions?.queries,\n queryFn: async (options): Promise<unknown> => {\n const { queryKey } = options;\n\n const action = queryKey[0];\n\n assert(\n typeof action === 'string' && isRecognizedDataServiceAction(action),\n \"Queries must call actions on the messenger provided to createUIQueryClient, e.g. `queryKey: ['ExampleDataService:getAssets', ...]`.\",\n );\n\n const params = options.queryKey.slice(1);\n if (options.pageParam !== undefined) {\n params.push(options.pageParam);\n }\n\n return await messenger.call(action, ...params);\n },\n },\n mutations: config.defaultOptions?.mutations,\n },\n });\n\n const cache = client.getQueryCache();\n\n cache.subscribe((event) => {\n const { query } = event;\n\n const hash = query.queryHash;\n const hasSubscription = subscriptions.has(hash);\n const observerCount = query.getObserversCount();\n\n const service = parseQueryKey(query.queryKey);\n\n if (!service) {\n return;\n }\n\n if (\n !hasSubscription &&\n event.type === 'observerAdded' &&\n observerCount === 1\n ) {\n const cacheListener: DataServiceGranularCacheUpdatedHandler = (\n payload,\n ) => {\n if (payload.type === 'removed') {\n return;\n }\n\n hydrate(client, payload.state);\n };\n\n subscriptions.set(hash, cacheListener);\n messenger.subscribe(`${service}:cacheUpdated:${hash}`, cacheListener);\n } else if (\n event.type === 'observerRemoved' &&\n observerCount === 0 &&\n hasSubscription\n ) {\n const subscriptionListener = subscriptions.get(hash);\n\n // We can't write a test for this, as it's unrealistic\n // (we just need a check to appease TypeScript).\n // istanbul ignore next\n if (subscriptionListener) {\n messenger.unsubscribe(\n `${service}:cacheUpdated:${hash}`,\n subscriptionListener,\n );\n }\n subscriptions.delete(hash);\n }\n });\n\n // Override invalidateQueries to ensure the data service is invalidated as well.\n const originalInvalidate = client.invalidateQueries.bind(client);\n\n client.invalidateQueries = async (\n filters?: InvalidateQueryFilters,\n options?: InvalidateOptions,\n ): Promise<void> => {\n const queries = client.getQueryCache().findAll(filters);\n\n const services = [\n ...new Set(queries.map((query) => parseQueryKey(query.queryKey))),\n ];\n\n await Promise.all(\n services.map(async (service) => {\n if (!service) {\n return null;\n }\n\n return messenger.call(`${service}:invalidateQueries`, filters, options);\n }),\n );\n\n return originalInvalidate(filters, options);\n };\n\n return client;\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { QueryKey } from "@metamask/base-data-service";
2
- import { OmitKeyof, UseQueryOptions, InitialDataFunction, NonUndefinedGuard, UseInfiniteQueryOptions, UseQueryResult, UseInfiniteQueryResult, DefaultError, InfiniteData } from "@tanstack/react-query";
1
+ import { QueryKey } from '@metamask/base-data-service';
2
+ import { OmitKeyof, UseQueryOptions, InitialDataFunction, NonUndefinedGuard, UseInfiniteQueryOptions, UseQueryResult, UseInfiniteQueryResult, DefaultError, InfiniteData } from '@tanstack/react-query';
3
3
  /**
4
4
  * Consume a query from a data service.
5
5
  *
@@ -18,4 +18,4 @@ export declare function useQuery<TQueryFnData = unknown, TError = DefaultError,
18
18
  * @returns The paginated query results.
19
19
  */
20
20
  export declare function useInfiniteQuery<TQueryFnData = unknown, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: OmitKeyof<UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, 'staleTime' | 'queryFn'>): UseInfiniteQueryResult<TData, TError>;
21
- //# sourceMappingURL=hooks.d.mts.map
21
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAGL,SAAS,EACT,eAAe,EACf,mBAAmB,EACnB,iBAAiB,EACjB,uBAAuB,EACvB,cAAc,EACd,sBAAsB,EACtB,YAAY,EACZ,YAAY,EACb,MAAM,uBAAuB,CAAC;AAY/B;;;;;;GAMG;AACH,wBAAgB,QAAQ,CACtB,YAAY,GAAG,OAAO,EACtB,MAAM,GAAG,YAAY,EACrB,KAAK,GAAG,YAAY,EACpB,SAAS,SAAS,QAAQ,GAAG,QAAQ,EAErC,OAAO,EAAE,SAAS,CAChB,eAAe,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,EACvD,aAAa,GAAG,WAAW,GAAG,SAAS,CACxC,GAAG;IACF,WAAW,CAAC,EACR,SAAS,GACT,mBAAmB,CAAC,iBAAiB,CAAC,YAAY,CAAC,CAAC,GACpD,iBAAiB,CAAC,YAAY,CAAC,CAAC;CACrC,GACA,cAAc,CAAC,KAAK,EAAE,MAAM,CAAC,CAE/B;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,YAAY,GAAG,OAAO,EACtB,MAAM,GAAG,YAAY,EACrB,KAAK,GAAG,YAAY,CAAC,YAAY,CAAC,EAClC,SAAS,SAAS,QAAQ,GAAG,QAAQ,EACrC,UAAU,GAAG,OAAO,EAEpB,OAAO,EAAE,SAAS,CAChB,uBAAuB,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,CAAC,EAC3E,WAAW,GAAG,SAAS,CACxB,GACA,sBAAsB,CAAC,KAAK,EAAE,MAAM,CAAC,CAKvC"}
@@ -1,4 +1,4 @@
1
- import { useQuery as useQueryTanStack, useInfiniteQuery as useInfiniteQueryTanStack } from "@tanstack/react-query";
1
+ import { useQuery as useQueryTanStack, useInfiniteQuery as useInfiniteQueryTanStack, } from '@tanstack/react-query';
2
2
  /**
3
3
  * We provide re-exports of the underlying TanStack Query hooks with narrower types,
4
4
  * removing `staleTime` and `queryFn` which aren't useful when using data services.
@@ -30,4 +30,4 @@ export function useInfiniteQuery(options) {
30
30
  ...options,
31
31
  });
32
32
  }
33
- //# sourceMappingURL=hooks.mjs.map
33
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AACA,OAAO,EACL,QAAQ,IAAI,gBAAgB,EAC5B,gBAAgB,IAAI,wBAAwB,GAU7C,MAAM,uBAAuB,CAAC;AAE/B;;;GAGG;AAEH,MAAM,2BAA2B,GAAG;IAClC,SAAS,EAAE,CAAC;IACZ,KAAK,EAAE,KAAK;CACb,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,QAAQ,CAMtB,OAQC;IAED,OAAO,gBAAgB,CAAC,EAAE,GAAG,2BAA2B,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;AAC1E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAO9B,OAGC;IAED,OAAO,wBAAwB,CAAC;QAC9B,GAAG,2BAA2B;QAC9B,GAAG,OAAO;KACX,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { QueryKey } from '@metamask/base-data-service';\nimport {\n useQuery as useQueryTanStack,\n useInfiniteQuery as useInfiniteQueryTanStack,\n OmitKeyof,\n UseQueryOptions,\n InitialDataFunction,\n NonUndefinedGuard,\n UseInfiniteQueryOptions,\n UseQueryResult,\n UseInfiniteQueryResult,\n DefaultError,\n InfiniteData,\n} from '@tanstack/react-query';\n\n/**\n * We provide re-exports of the underlying TanStack Query hooks with narrower types,\n * removing `staleTime` and `queryFn` which aren't useful when using data services.\n */\n\nconst DATA_SERVICE_QUERY_DEFAULTS = {\n staleTime: 0,\n retry: false,\n};\n\n/**\n * Consume a query from a data service.\n *\n * @param options - The query options. Keep in mind that `staleTime` and `queryFn` are not supported\n * when querying data services.\n * @returns The query results.\n */\nexport function useQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: OmitKeyof<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'initialData' | 'staleTime' | 'queryFn'\n > & {\n initialData?:\n | undefined\n | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>\n | NonUndefinedGuard<TQueryFnData>;\n },\n): UseQueryResult<TData, TError> {\n return useQueryTanStack({ ...DATA_SERVICE_QUERY_DEFAULTS, ...options });\n}\n\n/**\n * Consume a paginated query from a data service.\n *\n * @param options - The query options. Keep in mind that `staleTime` and `queryFn` are not supported\n * when querying data services.\n * @returns The paginated query results.\n */\nexport function useInfiniteQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: OmitKeyof<\n UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>,\n 'staleTime' | 'queryFn'\n >,\n): UseInfiniteQueryResult<TData, TError> {\n return useInfiniteQueryTanStack({\n ...DATA_SERVICE_QUERY_DEFAULTS,\n ...options,\n });\n}\n"]}
@@ -0,0 +1,3 @@
1
+ export { createUIQueryClient } from './createUIQueryClient.js';
2
+ export { useQuery, useInfiniteQuery } from './hooks.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { createUIQueryClient } from './createUIQueryClient.js';
2
+ export { useQuery, useInfiniteQuery } from './hooks.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC","sourcesContent":["export { createUIQueryClient } from './createUIQueryClient.js';\nexport { useQuery, useInfiniteQuery } from './hooks.js';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/react-data-query",
3
- "version": "1.0.0-preview-abca9bcea",
3
+ "version": "2.0.0-preview-0a30e47",
4
4
  "description": "Provides React utilities for consuming data services",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -18,19 +18,12 @@
18
18
  "files": [
19
19
  "dist/"
20
20
  ],
21
+ "type": "module",
21
22
  "sideEffects": false,
22
- "main": "./dist/index.cjs",
23
- "types": "./dist/index.d.cts",
24
23
  "exports": {
25
24
  ".": {
26
- "import": {
27
- "types": "./dist/index.d.mts",
28
- "default": "./dist/index.mjs"
29
- },
30
- "require": {
31
- "types": "./dist/index.d.cts",
32
- "default": "./dist/index.cjs"
33
- }
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
34
27
  },
35
28
  "./package.json": "./package.json"
36
29
  },
@@ -39,9 +32,11 @@
39
32
  "registry": "https://registry.npmjs.org/"
40
33
  },
41
34
  "scripts": {
42
- "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
43
- "build:all": "ts-bridge --project tsconfig.build.json --verbose --clean",
35
+ "build": "tsc --project tsconfig.build.json",
36
+ "build:all": "tsc --build tsconfig.build.json --verbose",
37
+ "build:clean": "yarn build:only-clean && yarn build",
44
38
  "build:docs": "typedoc",
39
+ "build:only-clean": "rimraf './dist' './tsconfig.build.tsbuildinfo'",
45
40
  "changelog:update": "../../scripts/update-changelog.sh @metamask/react-data-query",
46
41
  "changelog:validate": "../../scripts/validate-changelog.sh @metamask/react-data-query",
47
42
  "lint:tsconfigs": "tsx ../../scripts/lint-tsconfigs/lint-tsconfigs.mts",
@@ -53,23 +48,24 @@
53
48
  "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
54
49
  },
55
50
  "dependencies": {
56
- "@metamask/base-data-service": "^1.0.0",
51
+ "@metamask/base-data-service": "^2.0.0",
57
52
  "@metamask/utils": "^11.12.0",
58
53
  "@tanstack/query-core": "^5.62.16",
59
54
  "@tanstack/react-query": "^5.62.16"
60
55
  },
61
56
  "devDependencies": {
62
57
  "@metamask/auto-changelog": "^6.1.0",
63
- "@metamask/messenger": "^2.0.0",
64
- "@ts-bridge/cli": "^0.6.4",
58
+ "@metamask/messenger": "^3.0.0",
65
59
  "@types/jest": "^30.0.0",
60
+ "@typescript/native": "npm:typescript@^7.0.2",
66
61
  "deepmerge": "^4.2.2",
67
62
  "jest": "^30.4.2",
63
+ "rimraf": "^5.0.5",
68
64
  "ts-jest": "^29.4.11",
69
65
  "tsx": "^4.20.5",
70
66
  "typedoc": "^0.25.13",
71
67
  "typedoc-plugin-missing-exports": "^2.0.0",
72
- "typescript": "~5.3.3"
68
+ "typescript": "npm:@typescript/typescript6@^6.0.2"
73
69
  },
74
70
  "peerDependencies": {
75
71
  "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
@@ -85,6 +81,6 @@
85
81
  }
86
82
  },
87
83
  "engines": {
88
- "node": "^18.18 || >=20"
84
+ "node": "^22.14.0 || ^24"
89
85
  }
90
86
  }
@@ -1,132 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createUIQueryClient = void 0;
4
- const utils_1 = require("@metamask/utils");
5
- const query_core_1 = require("@tanstack/query-core");
6
- /**
7
- * Create a QueryClient that queries and subscribes to data services using a
8
- * messenger adapter. This is a messenger-like object that carries some
9
- * constraints:
10
- *
11
- * 1. The messenger must support the `call`, `subscribe` and
12
- * `unsubscribe` methods.
13
- * 2. All action handler arguments and event payloads must be JSON-compatible.
14
- * 3. The messenger must minimally support actions that are scoped to the
15
- * designated data services and must minimally support the
16
- * `:cacheUpdated:${hash}` event scoped to the designated data services.
17
- *
18
- * @param dataServices - A list of data services.
19
- * @param messenger - A messenger adapter.
20
- * @param config - Optional query client configuration options.
21
- * @returns The QueryClient.
22
- */
23
- function createUIQueryClient(dataServices, messenger, config = {}) {
24
- const subscriptions = new Map();
25
- /**
26
- * Check whether a name is one of the provided data service names.
27
- *
28
- * @param service - The service name to check.
29
- * @returns Whether the service name is configured.
30
- */
31
- function isRecognizedDataService(service) {
32
- return dataServices.some((dataService) => dataService === service);
33
- }
34
- /**
35
- * Check whether an action belongs to one of the provided data services.
36
- *
37
- * @param action - The action name to check.
38
- * @returns Whether the action belongs to a configured data service.
39
- */
40
- function isRecognizedDataServiceAction(action) {
41
- return isRecognizedDataService(action.split(':')[0]);
42
- }
43
- /**
44
- * Parse a query key to detect a service name.
45
- *
46
- * @param queryKey - The query key.
47
- * @returns The service name if it parsing succeeded, otherwise null.
48
- */
49
- function parseQueryKey(queryKey) {
50
- const action = queryKey[0];
51
- if (typeof action !== 'string') {
52
- return null;
53
- }
54
- const service = action.split(':')[0];
55
- if (!isRecognizedDataService(service)) {
56
- return null;
57
- }
58
- return service;
59
- }
60
- const client = new query_core_1.QueryClient({
61
- ...config,
62
- defaultOptions: {
63
- queries: {
64
- ...config.defaultOptions?.queries,
65
- queryFn: async (options) => {
66
- const { queryKey } = options;
67
- const action = queryKey[0];
68
- (0, utils_1.assert)(typeof action === 'string' && isRecognizedDataServiceAction(action), "Queries must call actions on the messenger provided to createUIQueryClient, e.g. `queryKey: ['ExampleDataService:getAssets', ...]`.");
69
- const params = options.queryKey.slice(1);
70
- if (options.pageParam !== undefined) {
71
- params.push(options.pageParam);
72
- }
73
- return await messenger.call(action, ...params);
74
- },
75
- },
76
- mutations: config.defaultOptions?.mutations,
77
- },
78
- });
79
- const cache = client.getQueryCache();
80
- cache.subscribe((event) => {
81
- const { query } = event;
82
- const hash = query.queryHash;
83
- const hasSubscription = subscriptions.has(hash);
84
- const observerCount = query.getObserversCount();
85
- const service = parseQueryKey(query.queryKey);
86
- if (!service) {
87
- return;
88
- }
89
- if (!hasSubscription &&
90
- event.type === 'observerAdded' &&
91
- observerCount === 1) {
92
- const cacheListener = (payload) => {
93
- if (payload.type === 'removed') {
94
- return;
95
- }
96
- (0, query_core_1.hydrate)(client, payload.state);
97
- };
98
- subscriptions.set(hash, cacheListener);
99
- messenger.subscribe(`${service}:cacheUpdated:${hash}`, cacheListener);
100
- }
101
- else if (event.type === 'observerRemoved' &&
102
- observerCount === 0 &&
103
- hasSubscription) {
104
- const subscriptionListener = subscriptions.get(hash);
105
- // We can't write a test for this, as it's unrealistic
106
- // (we just need a check to appease TypeScript).
107
- // istanbul ignore next
108
- if (subscriptionListener) {
109
- messenger.unsubscribe(`${service}:cacheUpdated:${hash}`, subscriptionListener);
110
- }
111
- subscriptions.delete(hash);
112
- }
113
- });
114
- // Override invalidateQueries to ensure the data service is invalidated as well.
115
- const originalInvalidate = client.invalidateQueries.bind(client);
116
- client.invalidateQueries = async (filters, options) => {
117
- const queries = client.getQueryCache().findAll(filters);
118
- const services = [
119
- ...new Set(queries.map((query) => parseQueryKey(query.queryKey))),
120
- ];
121
- await Promise.all(services.map(async (service) => {
122
- if (!service) {
123
- return null;
124
- }
125
- return messenger.call(`${service}:invalidateQueries`, filters, options);
126
- }));
127
- return originalInvalidate(filters, options);
128
- };
129
- return client;
130
- }
131
- exports.createUIQueryClient = createUIQueryClient;
132
- //# sourceMappingURL=createUIQueryClient.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"createUIQueryClient.cjs","sourceRoot":"","sources":["../src/createUIQueryClient.ts"],"names":[],"mappings":";;;AAIA,2CAAyC;AACzC,qDAO8B;AA8C9B;;;;;;;;;;;;;;;;GAgBG;AACH,SAAgB,mBAAmB,CACjC,YAA8B,EAC9B,SAAqD,EACrD,SAA4B,EAAE;IAE9B,MAAM,aAAa,GAAG,IAAI,GAAG,EAG1B,CAAC;IAEJ;;;;;OAKG;IACH,SAAS,uBAAuB,CAC9B,OAAe;QAEf,OAAO,YAAY,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,KAAK,OAAO,CAAC,CAAC;IACrE,CAAC;IAED;;;;;OAKG;IACH,SAAS,6BAA6B,CACpC,MAAc;QAEd,OAAO,uBAAuB,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,CAAC;IAED;;;;;OAKG;IACH,SAAS,aAAa,CAAC,QAAkB;QACvC,MAAM,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;QAE3B,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;YAC/B,OAAO,IAAI,CAAC;QACd,CAAC;QAED,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QAErC,IAAI,CAAC,uBAAuB,CAAC,OAAO,CAAC,EAAE,CAAC;YACtC,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,MAAM,MAAM,GAAgB,IAAI,wBAAW,CAAC;QAC1C,GAAG,MAAM;QACT,cAAc,EAAE;YACd,OAAO,EAAE;gBACP,GAAG,MAAM,CAAC,cAAc,EAAE,OAAO;gBACjC,OAAO,EAAE,KAAK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EAAE,OAAO,EAAE,EAAE;YAC7B,IAAI,CAAC,OAAO,EAAE,CAAC;gBACb,OAAO,IAAI,CAAC;YACd,CAAC;YAED,OAAO,SAAS,CAAC,IAAI,CAAC,GAAG,OAAO,oBAAoB,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAC1E,CAAC,CAAC,CACH,CAAC;QAEF,OAAO,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC9C,CAAC,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC;AAlKD,kDAkKC","sourcesContent":["import type {\n DataServiceGranularCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedPayload,\n} from '@metamask/base-data-service';\nimport { assert } from '@metamask/utils';\nimport {\n hydrate,\n QueryClient,\n InvalidateQueryFilters,\n InvalidateOptions,\n QueryKey,\n QueryClientConfig,\n} from '@tanstack/query-core';\n\n/**\n * Handles granular cache update events emitted by data services.\n */\ntype DataServiceGranularCacheUpdatedHandler = (\n payload: DataServiceGranularCacheUpdatedPayload,\n) => void;\n\n/**\n * A narrower subset of the `Messenger` type, tailored to the messenger\n * that `createUIQueryClient` interacts with.\n */\ntype MessengerAdapter<DataServiceName extends string> = {\n /**\n * Call an action on one of the configured data services.\n *\n * Note: The parameters are typed as `unknown[]` rather than `Json[]`. For\n * concrete messengers, each action's parameters exist as fixed-length tuple,\n * and a variadic `Json[]` is not assignable to a fixed-length tuple, so using\n * `Json[]` here would reject otherwise valid messengers.\n */\n call(\n actionType: `${DataServiceName}:${string}`,\n ...params: unknown[]\n ): unknown;\n\n /**\n * Subscribe to a granular cache update event on one of the configured data\n * services.\n */\n subscribe(\n eventType: DataServiceGranularCacheUpdatedEvent<DataServiceName>['type'],\n handler: DataServiceGranularCacheUpdatedHandler,\n ): void;\n\n /**\n * Unsubscribe from a granular cache update event on one of the configured\n * data services.\n */\n unsubscribe(\n eventType: DataServiceGranularCacheUpdatedEvent<DataServiceName>['type'],\n handler: DataServiceGranularCacheUpdatedHandler,\n ): void;\n};\n\n/**\n * Create a QueryClient that queries and subscribes to data services using a\n * messenger adapter. This is a messenger-like object that carries some\n * constraints:\n *\n * 1. The messenger must support the `call`, `subscribe` and\n * `unsubscribe` methods.\n * 2. All action handler arguments and event payloads must be JSON-compatible.\n * 3. The messenger must minimally support actions that are scoped to the\n * designated data services and must minimally support the\n * `:cacheUpdated:${hash}` event scoped to the designated data services.\n *\n * @param dataServices - A list of data services.\n * @param messenger - A messenger adapter.\n * @param config - Optional query client configuration options.\n * @returns The QueryClient.\n */\nexport function createUIQueryClient<DataServiceNames extends readonly string[]>(\n dataServices: DataServiceNames,\n messenger: MessengerAdapter<DataServiceNames[number]>,\n config: QueryClientConfig = {},\n): QueryClient {\n const subscriptions = new Map<\n string,\n DataServiceGranularCacheUpdatedHandler\n >();\n\n /**\n * Check whether a name is one of the provided data service names.\n *\n * @param service - The service name to check.\n * @returns Whether the service name is configured.\n */\n function isRecognizedDataService(\n service: string,\n ): service is DataServiceNames[number] {\n return dataServices.some((dataService) => dataService === service);\n }\n\n /**\n * Check whether an action belongs to one of the provided data services.\n *\n * @param action - The action name to check.\n * @returns Whether the action belongs to a configured data service.\n */\n function isRecognizedDataServiceAction(\n action: string,\n ): action is `${DataServiceNames[number]}:${string}` {\n return isRecognizedDataService(action.split(':')[0]);\n }\n\n /**\n * Parse a query key to detect a service name.\n *\n * @param queryKey - The query key.\n * @returns The service name if it parsing succeeded, otherwise null.\n */\n function parseQueryKey(queryKey: QueryKey): DataServiceNames[number] | null {\n const action = queryKey[0];\n\n if (typeof action !== 'string') {\n return null;\n }\n\n const service = action.split(':')[0];\n\n if (!isRecognizedDataService(service)) {\n return null;\n }\n\n return service;\n }\n\n const client: QueryClient = new QueryClient({\n ...config,\n defaultOptions: {\n queries: {\n ...config.defaultOptions?.queries,\n queryFn: async (options): Promise<unknown> => {\n const { queryKey } = options;\n\n const action = queryKey[0];\n\n assert(\n typeof action === 'string' && isRecognizedDataServiceAction(action),\n \"Queries must call actions on the messenger provided to createUIQueryClient, e.g. `queryKey: ['ExampleDataService:getAssets', ...]`.\",\n );\n\n const params = options.queryKey.slice(1);\n if (options.pageParam !== undefined) {\n params.push(options.pageParam);\n }\n\n return await messenger.call(action, ...params);\n },\n },\n mutations: config.defaultOptions?.mutations,\n },\n });\n\n const cache = client.getQueryCache();\n\n cache.subscribe((event) => {\n const { query } = event;\n\n const hash = query.queryHash;\n const hasSubscription = subscriptions.has(hash);\n const observerCount = query.getObserversCount();\n\n const service = parseQueryKey(query.queryKey);\n\n if (!service) {\n return;\n }\n\n if (\n !hasSubscription &&\n event.type === 'observerAdded' &&\n observerCount === 1\n ) {\n const cacheListener: DataServiceGranularCacheUpdatedHandler = (\n payload,\n ) => {\n if (payload.type === 'removed') {\n return;\n }\n\n hydrate(client, payload.state);\n };\n\n subscriptions.set(hash, cacheListener);\n messenger.subscribe(`${service}:cacheUpdated:${hash}`, cacheListener);\n } else if (\n event.type === 'observerRemoved' &&\n observerCount === 0 &&\n hasSubscription\n ) {\n const subscriptionListener = subscriptions.get(hash);\n\n // We can't write a test for this, as it's unrealistic\n // (we just need a check to appease TypeScript).\n // istanbul ignore next\n if (subscriptionListener) {\n messenger.unsubscribe(\n `${service}:cacheUpdated:${hash}`,\n subscriptionListener,\n );\n }\n subscriptions.delete(hash);\n }\n });\n\n // Override invalidateQueries to ensure the data service is invalidated as well.\n const originalInvalidate = client.invalidateQueries.bind(client);\n\n client.invalidateQueries = async (\n filters?: InvalidateQueryFilters,\n options?: InvalidateOptions,\n ): Promise<void> => {\n const queries = client.getQueryCache().findAll(filters);\n\n const services = [\n ...new Set(queries.map((query) => parseQueryKey(query.queryKey))),\n ];\n\n await Promise.all(\n services.map(async (service) => {\n if (!service) {\n return null;\n }\n\n return messenger.call(`${service}:invalidateQueries`, filters, options);\n }),\n );\n\n return originalInvalidate(filters, options);\n };\n\n return client;\n}\n"]}
@@ -1,51 +0,0 @@
1
- import type { DataServiceGranularCacheUpdatedEvent, DataServiceGranularCacheUpdatedPayload } from "@metamask/base-data-service";
2
- import { QueryClient, QueryClientConfig } from "@tanstack/query-core";
3
- /**
4
- * Handles granular cache update events emitted by data services.
5
- */
6
- type DataServiceGranularCacheUpdatedHandler = (payload: DataServiceGranularCacheUpdatedPayload) => void;
7
- /**
8
- * A narrower subset of the `Messenger` type, tailored to the messenger
9
- * that `createUIQueryClient` interacts with.
10
- */
11
- type MessengerAdapter<DataServiceName extends string> = {
12
- /**
13
- * Call an action on one of the configured data services.
14
- *
15
- * Note: The parameters are typed as `unknown[]` rather than `Json[]`. For
16
- * concrete messengers, each action's parameters exist as fixed-length tuple,
17
- * and a variadic `Json[]` is not assignable to a fixed-length tuple, so using
18
- * `Json[]` here would reject otherwise valid messengers.
19
- */
20
- call(actionType: `${DataServiceName}:${string}`, ...params: unknown[]): unknown;
21
- /**
22
- * Subscribe to a granular cache update event on one of the configured data
23
- * services.
24
- */
25
- subscribe(eventType: DataServiceGranularCacheUpdatedEvent<DataServiceName>['type'], handler: DataServiceGranularCacheUpdatedHandler): void;
26
- /**
27
- * Unsubscribe from a granular cache update event on one of the configured
28
- * data services.
29
- */
30
- unsubscribe(eventType: DataServiceGranularCacheUpdatedEvent<DataServiceName>['type'], handler: DataServiceGranularCacheUpdatedHandler): void;
31
- };
32
- /**
33
- * Create a QueryClient that queries and subscribes to data services using a
34
- * messenger adapter. This is a messenger-like object that carries some
35
- * constraints:
36
- *
37
- * 1. The messenger must support the `call`, `subscribe` and
38
- * `unsubscribe` methods.
39
- * 2. All action handler arguments and event payloads must be JSON-compatible.
40
- * 3. The messenger must minimally support actions that are scoped to the
41
- * designated data services and must minimally support the
42
- * `:cacheUpdated:${hash}` event scoped to the designated data services.
43
- *
44
- * @param dataServices - A list of data services.
45
- * @param messenger - A messenger adapter.
46
- * @param config - Optional query client configuration options.
47
- * @returns The QueryClient.
48
- */
49
- export declare function createUIQueryClient<DataServiceNames extends readonly string[]>(dataServices: DataServiceNames, messenger: MessengerAdapter<DataServiceNames[number]>, config?: QueryClientConfig): QueryClient;
50
- export {};
51
- //# sourceMappingURL=createUIQueryClient.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"createUIQueryClient.d.cts","sourceRoot":"","sources":["../src/createUIQueryClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oCAAoC,EACpC,sCAAsC,EACvC,oCAAoC;AAErC,OAAO,EAEL,WAAW,EAIX,iBAAiB,EAClB,6BAA6B;AAE9B;;GAEG;AACH,KAAK,sCAAsC,GAAG,CAC5C,OAAO,EAAE,sCAAsC,KAC5C,IAAI,CAAC;AAEV;;;GAGG;AACH,KAAK,gBAAgB,CAAC,eAAe,SAAS,MAAM,IAAI;IACtD;;;;;;;OAOG;IACH,IAAI,CACF,UAAU,EAAE,GAAG,eAAe,IAAI,MAAM,EAAE,EAC1C,GAAG,MAAM,EAAE,OAAO,EAAE,GACnB,OAAO,CAAC;IAEX;;;OAGG;IACH,SAAS,CACP,SAAS,EAAE,oCAAoC,CAAC,eAAe,CAAC,CAAC,MAAM,CAAC,EACxE,OAAO,EAAE,sCAAsC,GAC9C,IAAI,CAAC;IAER;;;OAGG;IACH,WAAW,CACT,SAAS,EAAE,oCAAoC,CAAC,eAAe,CAAC,CAAC,MAAM,CAAC,EACxE,OAAO,EAAE,sCAAsC,GAC9C,IAAI,CAAC;CACT,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,mBAAmB,CAAC,gBAAgB,SAAS,SAAS,MAAM,EAAE,EAC5E,YAAY,EAAE,gBAAgB,EAC9B,SAAS,EAAE,gBAAgB,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC,EACrD,MAAM,GAAE,iBAAsB,GAC7B,WAAW,CA8Jb"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"createUIQueryClient.d.mts","sourceRoot":"","sources":["../src/createUIQueryClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oCAAoC,EACpC,sCAAsC,EACvC,oCAAoC;AAErC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AAG,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YAErD,sDAAsD;YACtD,gDAAgD;YAChD,uBAAuB;YACvB,IAAI,oBAAoB,EAAE,CAAC;gBACzB,SAAS,CAAC,WAAW,CACnB,GAAG,OAAO,iBAAiB,IAAI,EAAE,EACjC,oBAAoB,CACrB,CAAC;YACJ,CAAC;YACD,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC7B,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,gFAAgF;IAChF,MAAM,kBAAkB,GAAG,MAAM,CAAC,iBAAiB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAEjE,MAAM,CAAC,iBAAiB,GAAG,KAAK,EAC9B,OAAgC,EAChC,OAA2B,EACZ,EAAE;QACjB,MAAM,OAAO,GAAG,MAAM,CAAC,aAAa,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAExD,MAAM,QAAQ,GAAG;YACf,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC;SAClE,CAAC;QAEF,MAAM,OAAO,CAAC,GAAG,CACf,QAAQ,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;YAC7B,IAAI,CAAC,OAAO,EAAE,CAAC;gBACb,OAAO,IAAI,CAAC;YACd,CAAC;YAED,OAAO,SAAS,CAAC,IAAI,CAAC,GAAG,OAAO,oBAAoB,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAC1E,CAAC,CAAC,CACH,CAAC;QAEF,OAAO,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC9C,CAAC,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type {\n DataServiceGranularCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedPayload,\n} from '@metamask/base-data-service';\nimport { assert } from '@metamask/utils';\nimport {\n hydrate,\n QueryClient,\n InvalidateQueryFilters,\n InvalidateOptions,\n QueryKey,\n QueryClientConfig,\n} from '@tanstack/query-core';\n\n/**\n * Handles granular cache update events emitted by data services.\n */\ntype DataServiceGranularCacheUpdatedHandler = (\n payload: DataServiceGranularCacheUpdatedPayload,\n) => void;\n\n/**\n * A narrower subset of the `Messenger` type, tailored to the messenger\n * that `createUIQueryClient` interacts with.\n */\ntype MessengerAdapter<DataServiceName extends string> = {\n /**\n * Call an action on one of the configured data services.\n *\n * Note: The parameters are typed as `unknown[]` rather than `Json[]`. For\n * concrete messengers, each action's parameters exist as fixed-length tuple,\n * and a variadic `Json[]` is not assignable to a fixed-length tuple, so using\n * `Json[]` here would reject otherwise valid messengers.\n */\n call(\n actionType: `${DataServiceName}:${string}`,\n ...params: unknown[]\n ): unknown;\n\n /**\n * Subscribe to a granular cache update event on one of the configured data\n * services.\n */\n subscribe(\n eventType: DataServiceGranularCacheUpdatedEvent<DataServiceName>['type'],\n handler: DataServiceGranularCacheUpdatedHandler,\n ): void;\n\n /**\n * Unsubscribe from a granular cache update event on one of the configured\n * data services.\n */\n unsubscribe(\n eventType: DataServiceGranularCacheUpdatedEvent<DataServiceName>['type'],\n handler: DataServiceGranularCacheUpdatedHandler,\n ): void;\n};\n\n/**\n * Create a QueryClient that queries and subscribes to data services using a\n * messenger adapter. This is a messenger-like object that carries some\n * constraints:\n *\n * 1. The messenger must support the `call`, `subscribe` and\n * `unsubscribe` methods.\n * 2. All action handler arguments and event payloads must be JSON-compatible.\n * 3. The messenger must minimally support actions that are scoped to the\n * designated data services and must minimally support the\n * `:cacheUpdated:${hash}` event scoped to the designated data services.\n *\n * @param dataServices - A list of data services.\n * @param messenger - A messenger adapter.\n * @param config - Optional query client configuration options.\n * @returns The QueryClient.\n */\nexport function createUIQueryClient<DataServiceNames extends readonly string[]>(\n dataServices: DataServiceNames,\n messenger: MessengerAdapter<DataServiceNames[number]>,\n config: QueryClientConfig = {},\n): QueryClient {\n const subscriptions = new Map<\n string,\n DataServiceGranularCacheUpdatedHandler\n >();\n\n /**\n * Check whether a name is one of the provided data service names.\n *\n * @param service - The service name to check.\n * @returns Whether the service name is configured.\n */\n function isRecognizedDataService(\n service: string,\n ): service is DataServiceNames[number] {\n return dataServices.some((dataService) => dataService === service);\n }\n\n /**\n * Check whether an action belongs to one of the provided data services.\n *\n * @param action - The action name to check.\n * @returns Whether the action belongs to a configured data service.\n */\n function isRecognizedDataServiceAction(\n action: string,\n ): action is `${DataServiceNames[number]}:${string}` {\n return isRecognizedDataService(action.split(':')[0]);\n }\n\n /**\n * Parse a query key to detect a service name.\n *\n * @param queryKey - The query key.\n * @returns The service name if it parsing succeeded, otherwise null.\n */\n function parseQueryKey(queryKey: QueryKey): DataServiceNames[number] | null {\n const action = queryKey[0];\n\n if (typeof action !== 'string') {\n return null;\n }\n\n const service = action.split(':')[0];\n\n if (!isRecognizedDataService(service)) {\n return null;\n }\n\n return service;\n }\n\n const client: QueryClient = new QueryClient({\n ...config,\n defaultOptions: {\n queries: {\n ...config.defaultOptions?.queries,\n queryFn: async (options): Promise<unknown> => {\n const { queryKey } = options;\n\n const action = queryKey[0];\n\n assert(\n typeof action === 'string' && isRecognizedDataServiceAction(action),\n \"Queries must call actions on the messenger provided to createUIQueryClient, e.g. `queryKey: ['ExampleDataService:getAssets', ...]`.\",\n );\n\n const params = options.queryKey.slice(1);\n if (options.pageParam !== undefined) {\n params.push(options.pageParam);\n }\n\n return await messenger.call(action, ...params);\n },\n },\n mutations: config.defaultOptions?.mutations,\n },\n });\n\n const cache = client.getQueryCache();\n\n cache.subscribe((event) => {\n const { query } = event;\n\n const hash = query.queryHash;\n const hasSubscription = subscriptions.has(hash);\n const observerCount = query.getObserversCount();\n\n const service = parseQueryKey(query.queryKey);\n\n if (!service) {\n return;\n }\n\n if (\n !hasSubscription &&\n event.type === 'observerAdded' &&\n observerCount === 1\n ) {\n const cacheListener: DataServiceGranularCacheUpdatedHandler = (\n payload,\n ) => {\n if (payload.type === 'removed') {\n return;\n }\n\n hydrate(client, payload.state);\n };\n\n subscriptions.set(hash, cacheListener);\n messenger.subscribe(`${service}:cacheUpdated:${hash}`, cacheListener);\n } else if (\n event.type === 'observerRemoved' &&\n observerCount === 0 &&\n hasSubscription\n ) {\n const subscriptionListener = subscriptions.get(hash);\n\n // We can't write a test for this, as it's unrealistic\n // (we just need a check to appease TypeScript).\n // istanbul ignore next\n if (subscriptionListener) {\n messenger.unsubscribe(\n `${service}:cacheUpdated:${hash}`,\n subscriptionListener,\n );\n }\n subscriptions.delete(hash);\n }\n });\n\n // Override invalidateQueries to ensure the data service is invalidated as well.\n const originalInvalidate = client.invalidateQueries.bind(client);\n\n client.invalidateQueries = async (\n filters?: InvalidateQueryFilters,\n options?: InvalidateOptions,\n ): Promise<void> => {\n const queries = client.getQueryCache().findAll(filters);\n\n const services = [\n ...new Set(queries.map((query) => parseQueryKey(query.queryKey))),\n ];\n\n await Promise.all(\n services.map(async (service) => {\n if (!service) {\n return null;\n }\n\n return messenger.call(`${service}:invalidateQueries`, filters, options);\n }),\n );\n\n return originalInvalidate(filters, options);\n };\n\n return client;\n}\n"]}
package/dist/hooks.cjs DELETED
@@ -1,38 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useInfiniteQuery = exports.useQuery = void 0;
4
- const react_query_1 = require("@tanstack/react-query");
5
- /**
6
- * We provide re-exports of the underlying TanStack Query hooks with narrower types,
7
- * removing `staleTime` and `queryFn` which aren't useful when using data services.
8
- */
9
- const DATA_SERVICE_QUERY_DEFAULTS = {
10
- staleTime: 0,
11
- retry: false,
12
- };
13
- /**
14
- * Consume a query from a data service.
15
- *
16
- * @param options - The query options. Keep in mind that `staleTime` and `queryFn` are not supported
17
- * when querying data services.
18
- * @returns The query results.
19
- */
20
- function useQuery(options) {
21
- return (0, react_query_1.useQuery)({ ...DATA_SERVICE_QUERY_DEFAULTS, ...options });
22
- }
23
- exports.useQuery = useQuery;
24
- /**
25
- * Consume a paginated query from a data service.
26
- *
27
- * @param options - The query options. Keep in mind that `staleTime` and `queryFn` are not supported
28
- * when querying data services.
29
- * @returns The paginated query results.
30
- */
31
- function useInfiniteQuery(options) {
32
- return (0, react_query_1.useInfiniteQuery)({
33
- ...DATA_SERVICE_QUERY_DEFAULTS,
34
- ...options,
35
- });
36
- }
37
- exports.useInfiniteQuery = useInfiniteQuery;
38
- //# sourceMappingURL=hooks.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"hooks.cjs","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":";;;AACA,uDAY+B;AAE/B;;;GAGG;AAEH,MAAM,2BAA2B,GAAG;IAClC,SAAS,EAAE,CAAC;IACZ,KAAK,EAAE,KAAK;CACb,CAAC;AAEF;;;;;;GAMG;AACH,SAAgB,QAAQ,CAMtB,OAQC;IAED,OAAO,IAAA,sBAAgB,EAAC,EAAE,GAAG,2BAA2B,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;AAC1E,CAAC;AAjBD,4BAiBC;AAED;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAO9B,OAGC;IAED,OAAO,IAAA,8BAAwB,EAAC;QAC9B,GAAG,2BAA2B;QAC9B,GAAG,OAAO;KACX,CAAC,CAAC;AACL,CAAC;AAhBD,4CAgBC","sourcesContent":["import { QueryKey } from '@metamask/base-data-service';\nimport {\n useQuery as useQueryTanStack,\n useInfiniteQuery as useInfiniteQueryTanStack,\n OmitKeyof,\n UseQueryOptions,\n InitialDataFunction,\n NonUndefinedGuard,\n UseInfiniteQueryOptions,\n UseQueryResult,\n UseInfiniteQueryResult,\n DefaultError,\n InfiniteData,\n} from '@tanstack/react-query';\n\n/**\n * We provide re-exports of the underlying TanStack Query hooks with narrower types,\n * removing `staleTime` and `queryFn` which aren't useful when using data services.\n */\n\nconst DATA_SERVICE_QUERY_DEFAULTS = {\n staleTime: 0,\n retry: false,\n};\n\n/**\n * Consume a query from a data service.\n *\n * @param options - The query options. Keep in mind that `staleTime` and `queryFn` are not supported\n * when querying data services.\n * @returns The query results.\n */\nexport function useQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: OmitKeyof<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'initialData' | 'staleTime' | 'queryFn'\n > & {\n initialData?:\n | undefined\n | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>\n | NonUndefinedGuard<TQueryFnData>;\n },\n): UseQueryResult<TData, TError> {\n return useQueryTanStack({ ...DATA_SERVICE_QUERY_DEFAULTS, ...options });\n}\n\n/**\n * Consume a paginated query from a data service.\n *\n * @param options - The query options. Keep in mind that `staleTime` and `queryFn` are not supported\n * when querying data services.\n * @returns The paginated query results.\n */\nexport function useInfiniteQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: OmitKeyof<\n UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>,\n 'staleTime' | 'queryFn'\n >,\n): UseInfiniteQueryResult<TData, TError> {\n return useInfiniteQueryTanStack({\n ...DATA_SERVICE_QUERY_DEFAULTS,\n ...options,\n });\n}\n"]}
package/dist/hooks.d.cts DELETED
@@ -1,21 +0,0 @@
1
- import { QueryKey } from "@metamask/base-data-service";
2
- import { OmitKeyof, UseQueryOptions, InitialDataFunction, NonUndefinedGuard, UseInfiniteQueryOptions, UseQueryResult, UseInfiniteQueryResult, DefaultError, InfiniteData } from "@tanstack/react-query";
3
- /**
4
- * Consume a query from a data service.
5
- *
6
- * @param options - The query options. Keep in mind that `staleTime` and `queryFn` are not supported
7
- * when querying data services.
8
- * @returns The query results.
9
- */
10
- export declare function useQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: OmitKeyof<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'initialData' | 'staleTime' | 'queryFn'> & {
11
- initialData?: undefined | InitialDataFunction<NonUndefinedGuard<TQueryFnData>> | NonUndefinedGuard<TQueryFnData>;
12
- }): UseQueryResult<TData, TError>;
13
- /**
14
- * Consume a paginated query from a data service.
15
- *
16
- * @param options - The query options. Keep in mind that `staleTime` and `queryFn` are not supported
17
- * when querying data services.
18
- * @returns The paginated query results.
19
- */
20
- export declare function useInfiniteQuery<TQueryFnData = unknown, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: OmitKeyof<UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, 'staleTime' | 'queryFn'>): UseInfiniteQueryResult<TData, TError>;
21
- //# sourceMappingURL=hooks.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"hooks.d.cts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AACvD,OAAO,EAGL,SAAS,EACT,eAAe,EACf,mBAAmB,EACnB,iBAAiB,EACjB,uBAAuB,EACvB,cAAc,EACd,sBAAsB,EACtB,YAAY,EACZ,YAAY,EACb,8BAA8B;AAY/B;;;;;;GAMG;AACH,wBAAgB,QAAQ,CACtB,YAAY,GAAG,OAAO,EACtB,MAAM,GAAG,YAAY,EACrB,KAAK,GAAG,YAAY,EACpB,SAAS,SAAS,QAAQ,GAAG,QAAQ,EAErC,OAAO,EAAE,SAAS,CAChB,eAAe,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,EACvD,aAAa,GAAG,WAAW,GAAG,SAAS,CACxC,GAAG;IACF,WAAW,CAAC,EACR,SAAS,GACT,mBAAmB,CAAC,iBAAiB,CAAC,YAAY,CAAC,CAAC,GACpD,iBAAiB,CAAC,YAAY,CAAC,CAAC;CACrC,GACA,cAAc,CAAC,KAAK,EAAE,MAAM,CAAC,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,YAAY,CAAC,EAClC,SAAS,SAAS,QAAQ,GAAG,QAAQ,EACrC,UAAU,GAAG,OAAO,EAEpB,OAAO,EAAE,SAAS,CAChB,uBAAuB,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,CAAC,EAC3E,WAAW,GAAG,SAAS,CACxB,GACA,sBAAsB,CAAC,KAAK,EAAE,MAAM,CAAC,CAKvC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"hooks.mjs","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AACA,OAAO,EACL,QAAQ,IAAI,gBAAgB,EAC5B,gBAAgB,IAAI,wBAAwB,EAU7C,8BAA8B;AAE/B;;;GAGG;AAEH,MAAM,2BAA2B,GAAG;IAClC,SAAS,EAAE,CAAC;IACZ,KAAK,EAAE,KAAK;CACb,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,QAAQ,CAMtB,OAQC;IAED,OAAO,gBAAgB,CAAC,EAAE,GAAG,2BAA2B,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;AAC1E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAO9B,OAGC;IAED,OAAO,wBAAwB,CAAC;QAC9B,GAAG,2BAA2B;QAC9B,GAAG,OAAO;KACX,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { QueryKey } from '@metamask/base-data-service';\nimport {\n useQuery as useQueryTanStack,\n useInfiniteQuery as useInfiniteQueryTanStack,\n OmitKeyof,\n UseQueryOptions,\n InitialDataFunction,\n NonUndefinedGuard,\n UseInfiniteQueryOptions,\n UseQueryResult,\n UseInfiniteQueryResult,\n DefaultError,\n InfiniteData,\n} from '@tanstack/react-query';\n\n/**\n * We provide re-exports of the underlying TanStack Query hooks with narrower types,\n * removing `staleTime` and `queryFn` which aren't useful when using data services.\n */\n\nconst DATA_SERVICE_QUERY_DEFAULTS = {\n staleTime: 0,\n retry: false,\n};\n\n/**\n * Consume a query from a data service.\n *\n * @param options - The query options. Keep in mind that `staleTime` and `queryFn` are not supported\n * when querying data services.\n * @returns The query results.\n */\nexport function useQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: OmitKeyof<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'initialData' | 'staleTime' | 'queryFn'\n > & {\n initialData?:\n | undefined\n | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>\n | NonUndefinedGuard<TQueryFnData>;\n },\n): UseQueryResult<TData, TError> {\n return useQueryTanStack({ ...DATA_SERVICE_QUERY_DEFAULTS, ...options });\n}\n\n/**\n * Consume a paginated query from a data service.\n *\n * @param options - The query options. Keep in mind that `staleTime` and `queryFn` are not supported\n * when querying data services.\n * @returns The paginated query results.\n */\nexport function useInfiniteQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: OmitKeyof<\n UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>,\n 'staleTime' | 'queryFn'\n >,\n): UseInfiniteQueryResult<TData, TError> {\n return useInfiniteQueryTanStack({\n ...DATA_SERVICE_QUERY_DEFAULTS,\n ...options,\n });\n}\n"]}
package/dist/index.cjs DELETED
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useInfiniteQuery = exports.useQuery = exports.createUIQueryClient = void 0;
4
- var createUIQueryClient_js_1 = require("./createUIQueryClient.cjs");
5
- Object.defineProperty(exports, "createUIQueryClient", { enumerable: true, get: function () { return createUIQueryClient_js_1.createUIQueryClient; } });
6
- var hooks_js_1 = require("./hooks.cjs");
7
- Object.defineProperty(exports, "useQuery", { enumerable: true, get: function () { return hooks_js_1.useQuery; } });
8
- Object.defineProperty(exports, "useInfiniteQuery", { enumerable: true, get: function () { return hooks_js_1.useInfiniteQuery; } });
9
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,oEAA+D;AAAtD,6HAAA,mBAAmB,OAAA;AAC5B,wCAAwD;AAA/C,oGAAA,QAAQ,OAAA;AAAE,4GAAA,gBAAgB,OAAA","sourcesContent":["export { createUIQueryClient } from './createUIQueryClient.js';\nexport { useQuery, useInfiniteQuery } from './hooks.js';\n"]}
package/dist/index.d.cts DELETED
@@ -1,3 +0,0 @@
1
- export { createUIQueryClient } from "./createUIQueryClient.cjs";
2
- export { useQuery, useInfiniteQuery } from "./hooks.cjs";
3
- //# sourceMappingURL=index.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kCAAiC;AAC/D,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,oBAAmB"}
package/dist/index.d.mts DELETED
@@ -1,3 +0,0 @@
1
- export { createUIQueryClient } from "./createUIQueryClient.mjs";
2
- export { useQuery, useInfiniteQuery } from "./hooks.mjs";
3
- //# sourceMappingURL=index.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kCAAiC;AAC/D,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,oBAAmB"}
package/dist/index.mjs DELETED
@@ -1,3 +0,0 @@
1
- export { createUIQueryClient } from "./createUIQueryClient.mjs";
2
- export { useQuery, useInfiniteQuery } from "./hooks.mjs";
3
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kCAAiC;AAC/D,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,oBAAmB","sourcesContent":["export { createUIQueryClient } from './createUIQueryClient.js';\nexport { useQuery, useInfiniteQuery } from './hooks.js';\n"]}