@osdk/client 2.8.0-beta.5 → 2.8.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/build/browser/observable/internal/AbstractHelper.js +37 -2
  3. package/build/browser/observable/internal/AbstractHelper.js.map +1 -1
  4. package/build/browser/observable/internal/AbstractHelper.test.js +114 -0
  5. package/build/browser/observable/internal/AbstractHelper.test.js.map +1 -0
  6. package/build/browser/observable/internal/CacheKeys.js +19 -8
  7. package/build/browser/observable/internal/CacheKeys.js.map +1 -1
  8. package/build/browser/observable/internal/ListQueryView.js +8 -3
  9. package/build/browser/observable/internal/ListQueryView.js.map +1 -1
  10. package/build/browser/observable/internal/ObservableClientImpl.js +104 -17
  11. package/build/browser/observable/internal/ObservableClientImpl.js.map +1 -1
  12. package/build/browser/observable/internal/RdpCanonicalizer.test.js +23 -7
  13. package/build/browser/observable/internal/RdpCanonicalizer.test.js.map +1 -1
  14. package/build/browser/observable/internal/Store.js +18 -1
  15. package/build/browser/observable/internal/Store.js.map +1 -1
  16. package/build/browser/observable/internal/Store.test.js +184 -0
  17. package/build/browser/observable/internal/Store.test.js.map +1 -1
  18. package/build/browser/observable/internal/actions/ActionApplication.js +8 -6
  19. package/build/browser/observable/internal/actions/ActionApplication.js.map +1 -1
  20. package/build/browser/observable/internal/base-list/BaseListQuery.js +5 -6
  21. package/build/browser/observable/internal/base-list/BaseListQuery.js.map +1 -1
  22. package/build/browser/observable/internal/list/ListQuery.test.js +154 -0
  23. package/build/browser/observable/internal/list/ListQuery.test.js.map +1 -1
  24. package/build/browser/observable/internal/list/ObjectListQuery.js +15 -4
  25. package/build/browser/observable/internal/list/ObjectListQuery.js.map +1 -1
  26. package/build/browser/observable/internal/object/ObjectsHelper.js +9 -2
  27. package/build/browser/observable/internal/object/ObjectsHelper.js.map +1 -1
  28. package/build/browser/observable/internal/object/ObjectsHelper.test.js +200 -0
  29. package/build/browser/observable/internal/object/ObjectsHelper.test.js.map +1 -0
  30. package/build/browser/observable/internal/objectset/ObjectSetCacheKey.js.map +1 -1
  31. package/build/browser/observable/internal/objectset/ObjectSetHelper.js +3 -2
  32. package/build/browser/observable/internal/objectset/ObjectSetHelper.js.map +1 -1
  33. package/build/browser/observable/internal/objectset/ObjectSetHelper.test.js +94 -0
  34. package/build/browser/observable/internal/objectset/ObjectSetHelper.test.js.map +1 -0
  35. package/build/browser/observable/internal/objectset/ObjectSetQuery.js +3 -0
  36. package/build/browser/observable/internal/objectset/ObjectSetQuery.js.map +1 -1
  37. package/build/browser/observable/internal/utils/rdpFieldOperations.js +7 -2
  38. package/build/browser/observable/internal/utils/rdpFieldOperations.js.map +1 -1
  39. package/build/browser/observable/internal/utils/rdpFieldOperations.test.js +55 -0
  40. package/build/browser/observable/internal/utils/rdpFieldOperations.test.js.map +1 -1
  41. package/build/browser/util/UserAgent.js +2 -2
  42. package/build/cjs/{chunk-LESMKESG.cjs → chunk-7K7TSF7C.cjs} +4 -4
  43. package/build/cjs/{chunk-LESMKESG.cjs.map → chunk-7K7TSF7C.cjs.map} +1 -1
  44. package/build/cjs/index.cjs +7 -7
  45. package/build/cjs/public/unstable-do-not-use.cjs +232 -76
  46. package/build/cjs/public/unstable-do-not-use.cjs.map +1 -1
  47. package/build/esm/observable/internal/AbstractHelper.js +37 -2
  48. package/build/esm/observable/internal/AbstractHelper.js.map +1 -1
  49. package/build/esm/observable/internal/AbstractHelper.test.js +114 -0
  50. package/build/esm/observable/internal/AbstractHelper.test.js.map +1 -0
  51. package/build/esm/observable/internal/CacheKeys.js +19 -8
  52. package/build/esm/observable/internal/CacheKeys.js.map +1 -1
  53. package/build/esm/observable/internal/ListQueryView.js +8 -3
  54. package/build/esm/observable/internal/ListQueryView.js.map +1 -1
  55. package/build/esm/observable/internal/ObservableClientImpl.js +104 -17
  56. package/build/esm/observable/internal/ObservableClientImpl.js.map +1 -1
  57. package/build/esm/observable/internal/RdpCanonicalizer.test.js +23 -7
  58. package/build/esm/observable/internal/RdpCanonicalizer.test.js.map +1 -1
  59. package/build/esm/observable/internal/Store.js +18 -1
  60. package/build/esm/observable/internal/Store.js.map +1 -1
  61. package/build/esm/observable/internal/Store.test.js +184 -0
  62. package/build/esm/observable/internal/Store.test.js.map +1 -1
  63. package/build/esm/observable/internal/actions/ActionApplication.js +8 -6
  64. package/build/esm/observable/internal/actions/ActionApplication.js.map +1 -1
  65. package/build/esm/observable/internal/base-list/BaseListQuery.js +5 -6
  66. package/build/esm/observable/internal/base-list/BaseListQuery.js.map +1 -1
  67. package/build/esm/observable/internal/list/ListQuery.test.js +154 -0
  68. package/build/esm/observable/internal/list/ListQuery.test.js.map +1 -1
  69. package/build/esm/observable/internal/list/ObjectListQuery.js +15 -4
  70. package/build/esm/observable/internal/list/ObjectListQuery.js.map +1 -1
  71. package/build/esm/observable/internal/object/ObjectsHelper.js +9 -2
  72. package/build/esm/observable/internal/object/ObjectsHelper.js.map +1 -1
  73. package/build/esm/observable/internal/object/ObjectsHelper.test.js +200 -0
  74. package/build/esm/observable/internal/object/ObjectsHelper.test.js.map +1 -0
  75. package/build/esm/observable/internal/objectset/ObjectSetCacheKey.js.map +1 -1
  76. package/build/esm/observable/internal/objectset/ObjectSetHelper.js +3 -2
  77. package/build/esm/observable/internal/objectset/ObjectSetHelper.js.map +1 -1
  78. package/build/esm/observable/internal/objectset/ObjectSetHelper.test.js +94 -0
  79. package/build/esm/observable/internal/objectset/ObjectSetHelper.test.js.map +1 -0
  80. package/build/esm/observable/internal/objectset/ObjectSetQuery.js +3 -0
  81. package/build/esm/observable/internal/objectset/ObjectSetQuery.js.map +1 -1
  82. package/build/esm/observable/internal/utils/rdpFieldOperations.js +7 -2
  83. package/build/esm/observable/internal/utils/rdpFieldOperations.js.map +1 -1
  84. package/build/esm/observable/internal/utils/rdpFieldOperations.test.js +55 -0
  85. package/build/esm/observable/internal/utils/rdpFieldOperations.test.js.map +1 -1
  86. package/build/esm/util/UserAgent.js +2 -2
  87. package/build/types/observable/internal/AbstractHelper.d.ts.map +1 -1
  88. package/build/types/observable/internal/AbstractHelper.test.d.ts +1 -0
  89. package/build/types/observable/internal/AbstractHelper.test.d.ts.map +1 -0
  90. package/build/types/observable/internal/CacheKeys.d.ts +5 -0
  91. package/build/types/observable/internal/CacheKeys.d.ts.map +1 -1
  92. package/build/types/observable/internal/ListQueryView.d.ts.map +1 -1
  93. package/build/types/observable/internal/Store.d.ts.map +1 -1
  94. package/build/types/observable/internal/Store.test.d.ts.map +1 -1
  95. package/build/types/observable/internal/actions/ActionApplication.d.ts.map +1 -1
  96. package/build/types/observable/internal/base-list/BaseListQuery.d.ts +1 -0
  97. package/build/types/observable/internal/base-list/BaseListQuery.d.ts.map +1 -1
  98. package/build/types/observable/internal/list/ObjectListQuery.d.ts.map +1 -1
  99. package/build/types/observable/internal/object/ObjectsHelper.d.ts +5 -1
  100. package/build/types/observable/internal/object/ObjectsHelper.d.ts.map +1 -1
  101. package/build/types/observable/internal/object/ObjectsHelper.test.d.ts +1 -0
  102. package/build/types/observable/internal/object/ObjectsHelper.test.d.ts.map +1 -0
  103. package/build/types/observable/internal/objectset/ObjectSetCacheKey.d.ts +2 -1
  104. package/build/types/observable/internal/objectset/ObjectSetCacheKey.d.ts.map +1 -1
  105. package/build/types/observable/internal/objectset/ObjectSetHelper.d.ts +3 -1
  106. package/build/types/observable/internal/objectset/ObjectSetHelper.d.ts.map +1 -1
  107. package/build/types/observable/internal/objectset/ObjectSetHelper.test.d.ts +1 -0
  108. package/build/types/observable/internal/objectset/ObjectSetHelper.test.d.ts.map +1 -0
  109. package/build/types/observable/internal/objectset/ObjectSetQuery.d.ts +2 -0
  110. package/build/types/observable/internal/objectset/ObjectSetQuery.d.ts.map +1 -1
  111. package/package.json +8 -8
  112. package/build/cjs/delay-W2TSML2P.cjs +0 -75
  113. package/build/cjs/delay-W2TSML2P.cjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # @osdk/client
2
2
 
3
+ ## 2.8.0-beta.7
4
+
5
+ ### Minor Changes
6
+
7
+ - 4cd7389: Remove delay dependency
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [034081a]
12
+ - @osdk/client.unstable@2.8.0-beta.7
13
+ - @osdk/api@2.8.0-beta.7
14
+ - @osdk/generator-converters@2.8.0-beta.7
15
+
16
+ ## 2.8.0-beta.6
17
+
18
+ ### Minor Changes
19
+
20
+ - 8c60682: Fix shared ListQuery pageSize not respected for late-joining views
21
+ - 15e1686: support rids with pivotTo in observable list queries
22
+ - c9d954d: Add `tokenStorage` option to `createPublicOauthClient` to control refresh token storage. Supports `'localStorage'` (default), `'sessionStorage'` (recommended for shared devices), or `'none'` (most secure, re-authenticates on every page load).
23
+ - 044eb80: unify RDP canonicalization between useOsdkObjects and useObjectSet
24
+ - 9d234b9: support multi object usage in useLinks
25
+
26
+ ### Patch Changes
27
+
28
+ - @osdk/api@2.8.0-beta.6
29
+ - @osdk/client.unstable@2.8.0-beta.6
30
+ - @osdk/generator-converters@2.8.0-beta.6
31
+
3
32
  ## 2.8.0-beta.5
4
33
 
5
34
  ### Patch Changes
@@ -39,7 +39,20 @@ export class AbstractHelper {
39
39
  }
40
40
  _subscribe(query, options, subFn) {
41
41
  // the ListQuery represents the shared state of the list
42
- this.store.cacheKeys.retain(query.cacheKey);
42
+ // If there is a deferred release pending for this key (from a prior
43
+ // unmount), cancel exactly one pending release and avoid an extra retain.
44
+ // This keeps refcounts balanced during unmount→remount within the same tick
45
+ // (e.g. React StrictMode effect cleanup + re-run).
46
+ const pendingCleanupCount = this.store.pendingCleanup.get(query.cacheKey) ?? 0;
47
+ if (pendingCleanupCount > 0) {
48
+ if (pendingCleanupCount === 1) {
49
+ this.store.pendingCleanup.delete(query.cacheKey);
50
+ } else {
51
+ this.store.pendingCleanup.set(query.cacheKey, pendingCleanupCount - 1);
52
+ }
53
+ } else {
54
+ this.store.cacheKeys.retain(query.cacheKey);
55
+ }
43
56
  if (options.mode !== "offline") {
44
57
  query.revalidate(options.mode === "force").catch(e => {
45
58
  subFn.error(e);
@@ -64,7 +77,29 @@ export class AbstractHelper {
64
77
  query.registerSubscriptionDedupeInterval(querySub.subscriptionId, options.dedupeInterval);
65
78
  sub.add(() => {
66
79
  query.unregisterSubscriptionDedupeInterval(querySub.subscriptionId);
67
- this.store.cacheKeys.release(query.cacheKey);
80
+
81
+ // Defer the release to the next microtask so React unmount-remount
82
+ // cycles can re-subscribe before the cache key is released.
83
+ // This prevents propagateWrite from skipping keys that are
84
+ // momentarily between subscriptions.
85
+ //
86
+ // Note: microtask ordering is only guaranteed within a single
87
+ // queueMicrotask call, not across separate invocations. If
88
+ // additional microtasks are introduced that interact with
89
+ // pendingCleanup or cacheKeys, ensure they don't rely on
90
+ // running before or after this one.
91
+ this.store.pendingCleanup.set(query.cacheKey, (this.store.pendingCleanup.get(query.cacheKey) ?? 0) + 1);
92
+ queueMicrotask(() => {
93
+ const currentPending = this.store.pendingCleanup.get(query.cacheKey) ?? 0;
94
+ if (currentPending > 0) {
95
+ if (currentPending === 1) {
96
+ this.store.pendingCleanup.delete(query.cacheKey);
97
+ } else {
98
+ this.store.pendingCleanup.set(query.cacheKey, currentPending - 1);
99
+ }
100
+ this.store.cacheKeys.release(query.cacheKey);
101
+ }
102
+ });
68
103
  });
69
104
  return querySub;
70
105
  }
@@ -1 +1 @@
1
- {"version":3,"file":"AbstractHelper.js","names":["ListQueryView","QuerySubscription","supportsViews","query","registerFetchPageSize","getLoadedCount","hasMorePages","notifySubscribers","fetchMore","AbstractHelper","constructor","store","cacheKeys","observe","options","subFn","getQuery","_subscribe","retain","cacheKey","mode","revalidate","catch","e","error","logger","listOptions","useView","pageSize","undefined","autoFetchMore","sub","subscribe","querySub","registerSubscriptionDedupeInterval","subscriptionId","dedupeInterval","add","unregisterSubscriptionDedupeInterval","release"],"sources":["AbstractHelper.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CommonObserveOptions,\n Observer,\n} from \"../ObservableClient/common.js\";\nimport type { BaseListPayloadShape } from \"./base-list/BaseListQuery.js\";\nimport type { CacheKeys } from \"./CacheKeys.js\";\nimport type { KnownCacheKey } from \"./KnownCacheKey.js\";\nimport { ListQueryView, type ListQueryViewTarget } from \"./ListQueryView.js\";\nimport type { Query } from \"./Query.js\";\nimport { QuerySubscription } from \"./QuerySubscription.js\";\nimport type { Store } from \"./Store.js\";\n\n/**\n * Check if a query supports view-based pagination (has the required methods).\n * Generic over PAYLOAD to preserve type information when the guard passes.\n */\nfunction supportsViews<PAYLOAD extends BaseListPayloadShape>(\n query: unknown,\n): query is ListQueryViewTarget<PAYLOAD> {\n return (\n query != null\n && typeof (query as ListQueryViewTarget<PAYLOAD>).registerFetchPageSize\n === \"function\"\n && typeof (query as ListQueryViewTarget<PAYLOAD>).getLoadedCount\n === \"function\"\n && typeof (query as ListQueryViewTarget<PAYLOAD>).hasMorePages\n === \"function\"\n && typeof (query as ListQueryViewTarget<PAYLOAD>).notifySubscribers\n === \"function\"\n && typeof (query as ListQueryViewTarget<PAYLOAD>).fetchMore === \"function\"\n );\n}\n\n/**\n * Options that may include list-specific pagination settings.\n */\ninterface ListObserveOptions {\n pageSize?: number;\n autoFetchMore?: boolean | number;\n}\n\nexport abstract class AbstractHelper<\n TQuery extends Query<KnownCacheKey, any, CommonObserveOptions>,\n TObserveOptions extends CommonObserveOptions,\n> {\n protected readonly store: Store;\n protected readonly cacheKeys: CacheKeys<KnownCacheKey>;\n\n constructor(store: Store, cacheKeys: CacheKeys<KnownCacheKey>) {\n this.store = store;\n this.cacheKeys = cacheKeys;\n }\n\n observe(\n options: TObserveOptions,\n subFn: Observer<\n TQuery extends Query<any, infer PAYLOAD, any> ? PAYLOAD : never\n >,\n ): QuerySubscription<TQuery> {\n const query = this.getQuery(options);\n return this._subscribe(query, options, subFn);\n }\n\n abstract getQuery(options: TObserveOptions): TQuery;\n\n protected _subscribe<\n PAYLOAD extends (TQuery extends Query<any, infer P, any> ? P : never),\n >(\n query: TQuery,\n options: TObserveOptions,\n subFn: Observer<PAYLOAD>,\n ): QuerySubscription<TQuery> {\n // the ListQuery represents the shared state of the list\n this.store.cacheKeys.retain(query.cacheKey);\n\n if (options.mode !== \"offline\") {\n query.revalidate(options.mode === \"force\").catch((e: unknown) => {\n subFn.error(e);\n\n // we don't want observeObject() to return a promise,\n // so we settle for logging an error here instead of\n // dropping it on the floor.\n if (this.store.logger) {\n this.store.logger.error(\"Unhandled error in observeObject\", e);\n } else {\n throw e;\n }\n });\n }\n\n // For queries that support views (list-like queries), wrap with ListQueryView\n // to handle per-subscriber view data such as pageSize\n const listOptions = options as ListObserveOptions;\n const useView = supportsViews<PAYLOAD & BaseListPayloadShape>(query)\n && (listOptions.pageSize !== undefined\n || listOptions.autoFetchMore !== undefined);\n\n const sub = useView\n ? new ListQueryView<PAYLOAD & BaseListPayloadShape>(\n query,\n listOptions.pageSize ?? 100,\n listOptions.autoFetchMore,\n ).subscribe(subFn as Observer<PAYLOAD & BaseListPayloadShape>)\n : query.subscribe(subFn);\n\n const querySub = new QuerySubscription(query, sub);\n\n query.registerSubscriptionDedupeInterval(\n querySub.subscriptionId,\n options.dedupeInterval,\n );\n\n sub.add(() => {\n query.unregisterSubscriptionDedupeInterval(querySub.subscriptionId);\n this.store.cacheKeys.release(query.cacheKey);\n });\n\n return querySub;\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AASA,S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kCAAkC,EAAED,CAAC,CAAC;QAChE,CAAC,MAAM;UACL,MAAMA,CAAC;QACT;MACF,CAAC,CAAC;IACJ;;IAEA;IACA;IACA,MAAMG,WAAW,GAAGZ,OAA6B;IACjD,MAAMa,OAAO,GAAGzB,aAAa,CAAiCC,KAAK,CAAC,KAC9DuB,WAAW,CAACE,QAAQ,KAAKC,SAAS,IACjCH,WAAW,CAACI,aAAa,KAAKD,SAAS,CAAC;IAE/C,MAAME,GAAG,GAAGJ,OAAO,GACf,IAAI3B,aAAa,CACjBG,KAAK,EACLuB,WAAW,CAACE,QAAQ,IAAI,GAAG,EAC3BF,WAAW,CAACI,aACd,CAAC,CAACE,SAAS,CAACjB,KAAiD,CAAC,GAC5DZ,KAAK,CAAC6B,SAAS,CAACjB,KAAK,CAAC;IAE1B,MAAMkB,QAAQ,GAAG,IAAIhC,iBAAiB,CAACE,KAAK,EAAE4B,GAAG,CAAC;IAElD5B,KAAK,CAAC+B,kCAAkC,CACtCD,QAAQ,CAACE,cAAc,EACvBrB,OAAO,CAACsB,cACV,CAAC;IAEDL,GAAG,CAACM,GAAG,CAAC,MAAM;MACZlC,KAAK,CAACmC,oCAAoC,CAACL,QAAQ,CAACE,cAAc,CAAC;MACnE,IAAI,CAACxB,KAAK,CAACC,SAAS,CAAC2B,OAAO,CAACpC,KAAK,CAACgB,QAAQ,CAAC;IAC9C,CAAC,CAAC;IAEF,OAAOc,QAAQ;EACjB;AACF","ignoreList":[]}
1
+ {"version":3,"file":"AbstractHelper.js","names":["ListQueryView","QuerySubscription","supportsViews","query","registerFetchPageSize","getLoadedCount","hasMorePages","notifySubscribers","fetchMore","AbstractHelper","constructor","store","cacheKeys","observe","options","subFn","getQuery","_subscribe","pendingCleanupCount","pendingCleanup","get","cacheKey","delete","set","retain","mode","revalidate","catch","e","error","logger","listOptions","useView","pageSize","undefined","autoFetchMore","sub","subscribe","querySub","registerSubscriptionDedupeInterval","subscriptionId","dedupeInterval","add","unregisterSubscriptionDedupeInterval","queueMicrotask","currentPending","release"],"sources":["AbstractHelper.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CommonObserveOptions,\n Observer,\n} from \"../ObservableClient/common.js\";\nimport type { BaseListPayloadShape } from \"./base-list/BaseListQuery.js\";\nimport type { CacheKeys } from \"./CacheKeys.js\";\nimport type { KnownCacheKey } from \"./KnownCacheKey.js\";\nimport { ListQueryView, type ListQueryViewTarget } from \"./ListQueryView.js\";\nimport type { Query } from \"./Query.js\";\nimport { QuerySubscription } from \"./QuerySubscription.js\";\nimport type { Store } from \"./Store.js\";\n\n/**\n * Check if a query supports view-based pagination (has the required methods).\n * Generic over PAYLOAD to preserve type information when the guard passes.\n */\nfunction supportsViews<PAYLOAD extends BaseListPayloadShape>(\n query: unknown,\n): query is ListQueryViewTarget<PAYLOAD> {\n return (\n query != null\n && typeof (query as ListQueryViewTarget<PAYLOAD>).registerFetchPageSize\n === \"function\"\n && typeof (query as ListQueryViewTarget<PAYLOAD>).getLoadedCount\n === \"function\"\n && typeof (query as ListQueryViewTarget<PAYLOAD>).hasMorePages\n === \"function\"\n && typeof (query as ListQueryViewTarget<PAYLOAD>).notifySubscribers\n === \"function\"\n && typeof (query as ListQueryViewTarget<PAYLOAD>).fetchMore === \"function\"\n );\n}\n\n/**\n * Options that may include list-specific pagination settings.\n */\ninterface ListObserveOptions {\n pageSize?: number;\n autoFetchMore?: boolean | number;\n}\n\nexport abstract class AbstractHelper<\n TQuery extends Query<KnownCacheKey, any, CommonObserveOptions>,\n TObserveOptions extends CommonObserveOptions,\n> {\n protected readonly store: Store;\n protected readonly cacheKeys: CacheKeys<KnownCacheKey>;\n\n constructor(store: Store, cacheKeys: CacheKeys<KnownCacheKey>) {\n this.store = store;\n this.cacheKeys = cacheKeys;\n }\n\n observe(\n options: TObserveOptions,\n subFn: Observer<\n TQuery extends Query<any, infer PAYLOAD, any> ? PAYLOAD : never\n >,\n ): QuerySubscription<TQuery> {\n const query = this.getQuery(options);\n return this._subscribe(query, options, subFn);\n }\n\n abstract getQuery(options: TObserveOptions): TQuery;\n\n protected _subscribe<\n PAYLOAD extends (TQuery extends Query<any, infer P, any> ? P : never),\n >(\n query: TQuery,\n options: TObserveOptions,\n subFn: Observer<PAYLOAD>,\n ): QuerySubscription<TQuery> {\n // the ListQuery represents the shared state of the list\n // If there is a deferred release pending for this key (from a prior\n // unmount), cancel exactly one pending release and avoid an extra retain.\n // This keeps refcounts balanced during unmount→remount within the same tick\n // (e.g. React StrictMode effect cleanup + re-run).\n const pendingCleanupCount = this.store.pendingCleanup.get(query.cacheKey)\n ?? 0;\n if (pendingCleanupCount > 0) {\n if (pendingCleanupCount === 1) {\n this.store.pendingCleanup.delete(query.cacheKey);\n } else {\n this.store.pendingCleanup.set(\n query.cacheKey,\n pendingCleanupCount - 1,\n );\n }\n } else {\n this.store.cacheKeys.retain(query.cacheKey);\n }\n\n if (options.mode !== \"offline\") {\n query.revalidate(options.mode === \"force\").catch((e: unknown) => {\n subFn.error(e);\n\n // we don't want observeObject() to return a promise,\n // so we settle for logging an error here instead of\n // dropping it on the floor.\n if (this.store.logger) {\n this.store.logger.error(\"Unhandled error in observeObject\", e);\n } else {\n throw e;\n }\n });\n }\n\n // For queries that support views (list-like queries), wrap with ListQueryView\n // to handle per-subscriber view data such as pageSize\n const listOptions = options as ListObserveOptions;\n const useView = supportsViews<PAYLOAD & BaseListPayloadShape>(query)\n && (listOptions.pageSize !== undefined\n || listOptions.autoFetchMore !== undefined);\n\n const sub = useView\n ? new ListQueryView<PAYLOAD & BaseListPayloadShape>(\n query,\n listOptions.pageSize ?? 100,\n listOptions.autoFetchMore,\n ).subscribe(subFn as Observer<PAYLOAD & BaseListPayloadShape>)\n : query.subscribe(subFn);\n\n const querySub = new QuerySubscription(query, sub);\n\n query.registerSubscriptionDedupeInterval(\n querySub.subscriptionId,\n options.dedupeInterval,\n );\n\n sub.add(() => {\n query.unregisterSubscriptionDedupeInterval(querySub.subscriptionId);\n\n // Defer the release to the next microtask so React unmount-remount\n // cycles can re-subscribe before the cache key is released.\n // This prevents propagateWrite from skipping keys that are\n // momentarily between subscriptions.\n //\n // Note: microtask ordering is only guaranteed within a single\n // queueMicrotask call, not across separate invocations. If\n // additional microtasks are introduced that interact with\n // pendingCleanup or cacheKeys, ensure they don't rely on\n // running before or after this one.\n this.store.pendingCleanup.set(\n query.cacheKey,\n (this.store.pendingCleanup.get(query.cacheKey) ?? 0) + 1,\n );\n queueMicrotask(() => {\n const currentPending = this.store.pendingCleanup.get(query.cacheKey)\n ?? 0;\n if (currentPending > 0) {\n if (currentPending === 1) {\n this.store.pendingCleanup.delete(query.cacheKey);\n } else {\n this.store.pendingCleanup.set(query.cacheKey, currentPending - 1);\n }\n this.store.cacheKeys.release(query.cacheKey);\n }\n });\n });\n\n return querySub;\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AASA,SAASA,aAAa,QAAkC,oBAAoB;AAE5E,SAASC,iBAAiB,QAAQ,wBAAwB;AAG1D;AACA;AACA;AACA;AACA,SAASC,aAAaA,CACpBC,KAAc,EACyB;EACvC,OACEA,KAAK,IAAI,IAAI,IACV,OAAQA,KAAK,CAAkCC,qBAAqB,KACjE,UAAU,IACb,OAAQD,KAAK,CAAkCE,cAAc,KAC1D,UAAU,IACb,OAAQF,KAAK,CAAkCG,YAAY,KACxD,UAAU,IACb,OAAQH,KAAK,CAAkCI,iBAAiB,KAC7D,UAAU,IACb,OAAQJ,KAAK,C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,CAAC,IAC/D,CAAC;QACN,IAAIwB,cAAc,GAAG,CAAC,EAAE;UACtB,IAAIA,cAAc,KAAK,CAAC,EAAE;YACxB,IAAI,CAAClC,KAAK,CAACQ,cAAc,CAACG,MAAM,CAACnB,KAAK,CAACkB,QAAQ,CAAC;UAClD,CAAC,MAAM;YACL,IAAI,CAACV,KAAK,CAACQ,cAAc,CAACI,GAAG,CAACpB,KAAK,CAACkB,QAAQ,EAAEwB,cAAc,GAAG,CAAC,CAAC;UACnE;UACA,IAAI,CAAClC,KAAK,CAACC,SAAS,CAACkC,OAAO,CAAC3C,KAAK,CAACkB,QAAQ,CAAC;QAC9C;MACF,CAAC,CAAC;IACJ,CAAC,CAAC;IAEF,OAAOiB,QAAQ;EACjB;AACF","ignoreList":[]}
@@ -0,0 +1,114 @@
1
+ /*
2
+ * Copyright 2026 Palantir Technologies, Inc. All rights reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { Subscription } from "rxjs";
18
+ import { describe, expect, it, vi } from "vitest";
19
+ import { AbstractHelper } from "./AbstractHelper.js";
20
+ function flushMicrotasks() {
21
+ return new Promise(resolve => queueMicrotask(resolve));
22
+ }
23
+ describe("AbstractHelper pending cleanup", () => {
24
+ it("coalesces unsubscribe→resubscribe within the same tick", async () => {
25
+ const retain = vi.fn();
26
+ const release = vi.fn();
27
+ const store = {
28
+ cacheKeys: {
29
+ retain,
30
+ release
31
+ },
32
+ pendingCleanup: new Map(),
33
+ logger: undefined
34
+ };
35
+ const query = {
36
+ cacheKey: {
37
+ type: "object",
38
+ otherKeys: ["Foo", 1]
39
+ },
40
+ subscribe: () => new Subscription(),
41
+ registerSubscriptionDedupeInterval: () => {},
42
+ unregisterSubscriptionDedupeInterval: () => {}
43
+ };
44
+ const helper = new class extends AbstractHelper {
45
+ getQuery() {
46
+ return query;
47
+ }
48
+ }(store, store.cacheKeys);
49
+ const observer = {
50
+ next: () => {},
51
+ error: () => {},
52
+ complete: () => {}
53
+ };
54
+ const sub1 = helper.observe({
55
+ mode: "offline"
56
+ }, observer);
57
+ expect(retain).toHaveBeenCalledTimes(1);
58
+ sub1.unsubscribe();
59
+ const sub2 = helper.observe({
60
+ mode: "offline"
61
+ }, observer);
62
+ expect(retain).toHaveBeenCalledTimes(1);
63
+ await flushMicrotasks();
64
+ expect(release).toHaveBeenCalledTimes(0);
65
+ sub2.unsubscribe();
66
+ await flushMicrotasks();
67
+ expect(release).toHaveBeenCalledTimes(1);
68
+ expect(store.pendingCleanup.size).toBe(0);
69
+ });
70
+ it("releases once per unsubscribe when multiple occur in the same tick", async () => {
71
+ const retain = vi.fn();
72
+ const release = vi.fn();
73
+ const store = {
74
+ cacheKeys: {
75
+ retain,
76
+ release
77
+ },
78
+ pendingCleanup: new Map(),
79
+ logger: undefined
80
+ };
81
+ const query = {
82
+ cacheKey: {
83
+ type: "object",
84
+ otherKeys: ["Foo", 1]
85
+ },
86
+ subscribe: () => new Subscription(),
87
+ registerSubscriptionDedupeInterval: () => {},
88
+ unregisterSubscriptionDedupeInterval: () => {}
89
+ };
90
+ const helper = new class extends AbstractHelper {
91
+ getQuery() {
92
+ return query;
93
+ }
94
+ }(store, store.cacheKeys);
95
+ const observer = {
96
+ next: () => {},
97
+ error: () => {},
98
+ complete: () => {}
99
+ };
100
+ const sub1 = helper.observe({
101
+ mode: "offline"
102
+ }, observer);
103
+ const sub2 = helper.observe({
104
+ mode: "offline"
105
+ }, observer);
106
+ expect(retain).toHaveBeenCalledTimes(2);
107
+ sub1.unsubscribe();
108
+ sub2.unsubscribe();
109
+ await flushMicrotasks();
110
+ expect(release).toHaveBeenCalledTimes(2);
111
+ expect(store.pendingCleanup.size).toBe(0);
112
+ });
113
+ });
114
+ //# sourceMappingURL=AbstractHelper.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AbstractHelper.test.js","names":["Subscription","describe","expect","it","vi","AbstractHelper","flushMicrotasks","Promise","resolve","queueMicrotask","retain","fn","release","store","cacheKeys","pendingCleanup","Map","logger","undefined","query","cacheKey","type","otherKeys","subscribe","registerSubscriptionDedupeInterval","unregisterSubscriptionDedupeInterval","helper","getQuery","observer","next","error","complete","sub1","observe","mode","toHaveBeenCalledTimes","unsubscribe","sub2","size","toBe"],"sources":["AbstractHelper.test.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Subscription } from \"rxjs\";\nimport { describe, expect, it, vi } from \"vitest\";\nimport { AbstractHelper } from \"./AbstractHelper.js\";\n\nfunction flushMicrotasks(): Promise<void> {\n return new Promise(resolve => queueMicrotask(resolve));\n}\n\ndescribe(\"AbstractHelper pending cleanup\", () => {\n it(\"coalesces unsubscribe→resubscribe within the same tick\", async () => {\n const cacheKey = { type: \"object\", otherKeys: [\"Foo\", 1] } as any;\n\n const retain = vi.fn();\n const release = vi.fn();\n const store = {\n cacheKeys: { retain, release },\n pendingCleanup: new Map<any, number>(),\n logger: undefined,\n } as any;\n\n const query = {\n cacheKey,\n subscribe: () => new Subscription(),\n registerSubscriptionDedupeInterval: () => {},\n unregisterSubscriptionDedupeInterval: () => {},\n } as any;\n\n const helper = new (class extends AbstractHelper<any, any> {\n getQuery(): any {\n return query;\n }\n })(store, store.cacheKeys);\n\n const observer = { next: () => {}, error: () => {}, complete: () => {} };\n\n const sub1 = helper.observe({ mode: \"offline\" }, observer);\n expect(retain).toHaveBeenCalledTimes(1);\n\n sub1.unsubscribe();\n const sub2 = helper.observe({ mode: \"offline\" }, observer);\n expect(retain).toHaveBeenCalledTimes(1);\n\n await flushMicrotasks();\n expect(release).toHaveBeenCalledTimes(0);\n\n sub2.unsubscribe();\n await flushMicrotasks();\n expect(release).toHaveBeenCalledTimes(1);\n expect(store.pendingCleanup.size).toBe(0);\n });\n\n it(\"releases once per unsubscribe when multiple occur in the same tick\", async () => {\n const cacheKey = { type: \"object\", otherKeys: [\"Foo\", 1] } as any;\n\n const retain = vi.fn();\n const release = vi.fn();\n const store = {\n cacheKeys: { retain, release },\n pendingCleanup: new Map<any, number>(),\n logger: undefined,\n } as any;\n\n const query = {\n cacheKey,\n subscribe: () => new Subscription(),\n registerSubscriptionDedupeInterval: () => {},\n unregisterSubscriptionDedupeInterval: () => {},\n } as any;\n\n const helper = new (class extends AbstractHelper<any, any> {\n getQuery(): any {\n return query;\n }\n })(store, store.cacheKeys);\n\n const observer = { next: () => {}, error: () => {}, complete: () => {} };\n\n const sub1 = helper.observe({ mode: \"offline\" }, observer);\n const sub2 = helper.observe({ mode: \"offline\" }, observer);\n expect(retain).toHaveBeenCalledTimes(2);\n\n sub1.unsubscribe();\n sub2.unsubscribe();\n await flushMicrotasks();\n\n expect(release).toHaveBeenCalledTimes(2);\n expect(store.pendingCleanup.size).toBe(0);\n });\n});\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,YAAY,QAAQ,MAAM;AACnC,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,EAAEC,EAAE,QAAQ,QAAQ;AACjD,SAASC,cAAc,QAAQ,qBAAqB;AAEpD,SAASC,eAAe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QACd,OAAOR,KAAK;MACd;IACF,CAAC,CAAEN,KAAK,EAAEA,KAAK,CAACC,SAAS,CAAC;IAE1B,MAAMc,QAAQ,GAAG;MAAEC,IAAI,EAAEA,CAAA,KAAM,CAAC,CAAC;MAAEC,KAAK,EAAEA,CAAA,KAAM,CAAC,CAAC;MAAEC,QAAQ,EAAEA,CAAA,KAAM,CAAC;IAAE,CAAC;IAExE,MAAMC,IAAI,GAAGN,MAAM,CAACO,OAAO,CAAC;MAAEC,IAAI,EAAE;IAAU,CAAC,EAAEN,QAAQ,CAAC;IAC1D,MAAMS,IAAI,GAAGX,MAAM,CAACO,OAAO,CAAC;MAAEC,IAAI,EAAE;IAAU,CAAC,EAAEN,QAAQ,CAAC;IAC1D1B,MAAM,CAACQ,MAAM,CAAC,CAACyB,qBAAqB,CAAC,CAAC,CAAC;IAEvCH,IAAI,CAACI,WAAW,CAAC,CAAC;IAClBC,IAAI,CAACD,WAAW,CAAC,CAAC;IAClB,MAAM9B,eAAe,CAAC,CAAC;IAEvBJ,MAAM,CAACU,OAAO,CAAC,CAACuB,qBAAqB,CAAC,CAAC,CAAC;IACxCjC,MAAM,CAACW,KAAK,CAACE,cAAc,CAACuB,IAAI,CAAC,CAACC,IAAI,CAAC,CAAC,CAAC;EAC3C,CAAC,CAAC;AACJ,CAAC,CAAC","ignoreList":[]}
@@ -65,17 +65,11 @@ export class CacheKeys {
65
65
  });
66
66
  }
67
67
  get(type, ...args) {
68
- // Normalize trailing undefined values to ensure consistent cache key creation
69
- // This makes get("object", "Foo", 1, undefined) === get("object", "Foo", 1)
70
- const normalizedArgs = [...args];
71
- while (normalizedArgs.length > 0 && normalizedArgs[normalizedArgs.length - 1] === undefined) {
72
- normalizedArgs.pop();
73
- }
74
- const cacheKeyArgs = [type, ...normalizedArgs];
68
+ const cacheKeyArgs = this.#normalizeArgs(type, args);
75
69
  if (process.env.NODE_ENV !== "production" && DEBUG_CACHE_KEYS) {
76
70
  // eslint-disable-next-line no-console
77
71
  console.debug(`CacheKeys.get([${type},
78
- ${normalizedArgs.map(x => JSON.stringify(x)).join(", ")}]) - already exists? `, this.#cacheKeys.peekArray(cacheKeyArgs) != null);
72
+ ${cacheKeyArgs.slice(1).map(x => JSON.stringify(x)).join(", ")}]) - already exists? `, this.#cacheKeys.peekArray(cacheKeyArgs) != null);
79
73
  }
80
74
  const cacheKey = this.#cacheKeys.lookupArray(cacheKeyArgs);
81
75
 
@@ -84,6 +78,23 @@ export class CacheKeys {
84
78
  this.#refCounts.register(cacheKey);
85
79
  return cacheKey;
86
80
  }
81
+
82
+ /**
83
+ * Look up an existing cache key without creating or registering it.
84
+ * Returns undefined if the key does not exist in the trie.
85
+ */
86
+ peek(type, ...args) {
87
+ return this.#cacheKeys.peekArray(this.#normalizeArgs(type, args));
88
+ }
89
+ #normalizeArgs(type, args) {
90
+ // Normalize trailing undefined values to ensure consistent cache key lookup
91
+ // This makes ("object", "Foo", 1, undefined) equivalent to ("object", "Foo", 1)
92
+ const normalizedArgs = [...args];
93
+ while (normalizedArgs.length > 0 && normalizedArgs[normalizedArgs.length - 1] === undefined) {
94
+ normalizedArgs.pop();
95
+ }
96
+ return [type, ...normalizedArgs];
97
+ }
87
98
  retain(cacheKey) {
88
99
  this.#refCounts.retain(cacheKey);
89
100
  }
@@ -1 +1 @@
1
- {"version":3,"file":"CacheKeys.js","names":["Trie","DEBUG_CACHE_KEYS","DEBUG_REFCOUNTS","RefCounts","CacheKeys","cacheKeys","keys","cacheKey","type","otherKeys","slice","onCreate","console","log","JSON","stringify","finalizationRegistry","register","refCounts","k","cleanupCacheKey","onDestroy","constructor","setInterval","gc","FinalizationRegistry","cleanupCallback","e","error","get","args","normalizedArgs","length","undefined","pop","cacheKeyArgs","process","env","NODE_ENV","debug","map","x","join","peekArray","lookupArray","retain","release","remove","#remove","key"],"sources":["CacheKeys.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Trie } from \"@wry/trie\";\nimport { DEBUG_CACHE_KEYS, DEBUG_REFCOUNTS } from \"../DebugFlags.js\";\nimport type { CacheKey } from \"./CacheKey.js\";\nimport { RefCounts } from \"./RefCounts.js\";\n\n/**\n * Cache key management with canonicalization.\n * - Uses Trie structure for efficient storage and lookup\n */\nexport class CacheKeys<TCacheKey extends CacheKey> {\n #cacheKeys = new Trie<TCacheKey>(false, (keys) => {\n const cacheKey = {\n type: keys[0],\n otherKeys: keys.slice(1),\n } as unknown as TCacheKey;\n this.#onCreate?.(cacheKey);\n\n if (DEBUG_REFCOUNTS) {\n // eslint-disable-next-line no-console\n console.log(\n `CacheKeys.onCreate(${cacheKey.type}, ${\n JSON.stringify(cacheKey.otherKeys)\n })`,\n );\n\n this.#finalizationRegistry.register(cacheKey, () => {\n // eslint-disable-next-line no-console\n console.log(\n `CacheKey Finalization(${cacheKey.type}, ${\n JSON.stringify(cacheKey.otherKeys)\n })`,\n );\n });\n }\n return cacheKey;\n });\n\n #refCounts = new RefCounts<TCacheKey>(\n DEBUG_REFCOUNTS ? 15_000 : 60_000,\n (k) => this.#cleanupCacheKey(k),\n );\n\n // we are currently only using this for debug logging and should just remove it in the future if that\n // continues to be true\n #finalizationRegistry: FinalizationRegistry<() => void>;\n\n #onCreate?: (cacheKey: TCacheKey) => void;\n #onDestroy?: (cacheKey: TCacheKey) => void;\n\n constructor(\n { onCreate, onDestroy }: {\n onCreate?: (cacheKey: TCacheKey) => void;\n onDestroy?: (cacheKey: TCacheKey) => void;\n },\n ) {\n this.#onCreate = onCreate;\n this.#onDestroy = onDestroy;\n\n setInterval(() => {\n this.#refCounts.gc();\n }, 1000);\n\n this.#finalizationRegistry = new FinalizationRegistry<() => void>(\n (cleanupCallback) => {\n try {\n cleanupCallback();\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(\n \"Caught an error while running a finalization callback\",\n e,\n );\n }\n },\n );\n }\n\n get<K extends TCacheKey>(\n type: K[\"type\"],\n ...args: K[\"__cacheKey\"][\"args\"]\n ): K {\n // Normalize trailing undefined values to ensure consistent cache key creation\n // This makes get(\"object\", \"Foo\", 1, undefined) === get(\"object\", \"Foo\", 1)\n const normalizedArgs = [...args];\n while (\n normalizedArgs.length > 0\n && normalizedArgs[normalizedArgs.length - 1] === undefined\n ) {\n normalizedArgs.pop();\n }\n\n const cacheKeyArgs = [type, ...normalizedArgs];\n if (process.env.NODE_ENV !== \"production\" && DEBUG_CACHE_KEYS) {\n // eslint-disable-next-line no-console\n console.debug(\n `CacheKeys.get([${type},\n ${\n normalizedArgs.map(x => JSON.stringify(x)).join(\", \")\n }]) - already exists? `,\n this.#cacheKeys.peekArray(cacheKeyArgs) != null,\n );\n }\n\n const cacheKey = this.#cacheKeys.lookupArray(\n cacheKeyArgs,\n ) as K;\n\n // This is an idempotent call that ensures the cache key is registered for\n // cleanup. If already registered, this does nothing.\n this.#refCounts.register(cacheKey);\n\n return cacheKey;\n }\n\n retain(cacheKey: TCacheKey): void {\n this.#refCounts.retain(cacheKey);\n }\n\n release(cacheKey: TCacheKey): void {\n this.#refCounts.release(cacheKey);\n }\n\n #remove<K extends TCacheKey>(cacheKey: K): void {\n this.#cacheKeys.remove(cacheKey.type, ...cacheKey.otherKeys);\n }\n\n /**\n * Called after a key is no longer retained and the timeout has elapsed\n * @param key\n */\n #cleanupCacheKey = (key: TCacheKey) => {\n this.#onDestroy?.(key);\n this.#remove(key);\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,IAAI,QAAQ,WAAW;AACh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AC2B,MAAM,CAACtC,QAAQ,CAAC;EAClC;EAEAuC,OAAOA,CAACvC,QAAmB,EAAQ;IACjC,IAAI,CAAC,CAACW,SAAS,CAAC4B,OAAO,CAACvC,QAAQ,CAAC;EACnC;EAEA,CAACwC,MAAMC,CAAsBzC,QAAW,EAAQ;IAC9C,IAAI,CAAC,CAACF,SAAS,CAAC0C,MAAM,CAACxC,QAAQ,CAACC,IAAI,EAAE,GAAGD,QAAQ,CAACE,SAAS,CAAC;EAC9D;;EAEA;AACF;AACA;AACA;EACE,CAACW,eAAe,GAAI6B,GAAc,IAAK;IACrC,IAAI,CAAC,CAAC5B,SAAS,GAAG4B,GAAG,CAAC;IACtB,IAAI,CAAC,CAACF,MAAM,CAACE,GAAG,CAAC;EACnB,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"CacheKeys.js","names":["Trie","DEBUG_CACHE_KEYS","DEBUG_REFCOUNTS","RefCounts","CacheKeys","cacheKeys","keys","cacheKey","type","otherKeys","slice","onCreate","console","log","JSON","stringify","finalizationRegistry","register","refCounts","k","cleanupCacheKey","onDestroy","constructor","setInterval","gc","FinalizationRegistry","cleanupCallback","e","error","get","args","cacheKeyArgs","normalizeArgs","process","env","NODE_ENV","debug","map","x","join","peekArray","lookupArray","peek","#normalizeArgs","normalizedArgs","length","undefined","pop","retain","release","remove","#remove","key"],"sources":["CacheKeys.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Trie } from \"@wry/trie\";\nimport { DEBUG_CACHE_KEYS, DEBUG_REFCOUNTS } from \"../DebugFlags.js\";\nimport type { CacheKey } from \"./CacheKey.js\";\nimport { RefCounts } from \"./RefCounts.js\";\n\n/**\n * Cache key management with canonicalization.\n * - Uses Trie structure for efficient storage and lookup\n */\nexport class CacheKeys<TCacheKey extends CacheKey> {\n #cacheKeys = new Trie<TCacheKey>(false, (keys) => {\n const cacheKey = {\n type: keys[0],\n otherKeys: keys.slice(1),\n } as unknown as TCacheKey;\n this.#onCreate?.(cacheKey);\n\n if (DEBUG_REFCOUNTS) {\n // eslint-disable-next-line no-console\n console.log(\n `CacheKeys.onCreate(${cacheKey.type}, ${\n JSON.stringify(cacheKey.otherKeys)\n })`,\n );\n\n this.#finalizationRegistry.register(cacheKey, () => {\n // eslint-disable-next-line no-console\n console.log(\n `CacheKey Finalization(${cacheKey.type}, ${\n JSON.stringify(cacheKey.otherKeys)\n })`,\n );\n });\n }\n return cacheKey;\n });\n\n #refCounts = new RefCounts<TCacheKey>(\n DEBUG_REFCOUNTS ? 15_000 : 60_000,\n (k) => this.#cleanupCacheKey(k),\n );\n\n // we are currently only using this for debug logging and should just remove it in the future if that\n // continues to be true\n #finalizationRegistry: FinalizationRegistry<() => void>;\n\n #onCreate?: (cacheKey: TCacheKey) => void;\n #onDestroy?: (cacheKey: TCacheKey) => void;\n\n constructor(\n { onCreate, onDestroy }: {\n onCreate?: (cacheKey: TCacheKey) => void;\n onDestroy?: (cacheKey: TCacheKey) => void;\n },\n ) {\n this.#onCreate = onCreate;\n this.#onDestroy = onDestroy;\n\n setInterval(() => {\n this.#refCounts.gc();\n }, 1000);\n\n this.#finalizationRegistry = new FinalizationRegistry<() => void>(\n (cleanupCallback) => {\n try {\n cleanupCallback();\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(\n \"Caught an error while running a finalization callback\",\n e,\n );\n }\n },\n );\n }\n\n get<K extends TCacheKey>(\n type: K[\"type\"],\n ...args: K[\"__cacheKey\"][\"args\"]\n ): K {\n const cacheKeyArgs = this.#normalizeArgs(type, args);\n if (process.env.NODE_ENV !== \"production\" && DEBUG_CACHE_KEYS) {\n // eslint-disable-next-line no-console\n console.debug(\n `CacheKeys.get([${type},\n ${\n cacheKeyArgs.slice(1).map(x => JSON.stringify(x)).join(\", \")\n }]) - already exists? `,\n this.#cacheKeys.peekArray(cacheKeyArgs) != null,\n );\n }\n\n const cacheKey = this.#cacheKeys.lookupArray(\n cacheKeyArgs,\n ) as K;\n\n // This is an idempotent call that ensures the cache key is registered for\n // cleanup. If already registered, this does nothing.\n this.#refCounts.register(cacheKey);\n\n return cacheKey;\n }\n\n /**\n * Look up an existing cache key without creating or registering it.\n * Returns undefined if the key does not exist in the trie.\n */\n peek<K extends TCacheKey>(\n type: K[\"type\"],\n ...args: K[\"__cacheKey\"][\"args\"]\n ): K | undefined {\n return this.#cacheKeys.peekArray(\n this.#normalizeArgs(type, args),\n ) as K | undefined;\n }\n\n #normalizeArgs(\n type: TCacheKey[\"type\"],\n args: unknown[],\n ): unknown[] {\n // Normalize trailing undefined values to ensure consistent cache key lookup\n // This makes (\"object\", \"Foo\", 1, undefined) equivalent to (\"object\", \"Foo\", 1)\n const normalizedArgs = [...args];\n while (\n normalizedArgs.length > 0\n && normalizedArgs[normalizedArgs.length - 1] === undefined\n ) {\n normalizedArgs.pop();\n }\n return [type, ...normalizedArgs];\n }\n\n retain(cacheKey: TCacheKey): void {\n this.#refCounts.retain(cacheKey);\n }\n\n release(cacheKey: TCacheKey): void {\n this.#refCounts.release(cacheKey);\n }\n\n #remove<K extends TCacheKey>(cacheKey: K): void {\n this.#cacheKeys.remove(cacheKey.type, ...cacheKey.otherKeys);\n }\n\n /**\n * Called after a key is no longer retained and the timeout has elapsed\n * @param key\n */\n #cleanupCacheKey = (key: TCacheKey) => {\n this.#onDestroy?.(key);\n this.#remove(key);\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,IAAI,QAAQ,WAAW;AA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IAAe,EACJ;IACX;IACA;IACA,MAAMc,cAAc,GAAG,CAAC,GAAGd,IAAI,CAAC;IAChC,OACEc,cAAc,CAACC,MAAM,GAAG,CAAC,IACtBD,cAAc,CAACA,cAAc,CAACC,MAAM,GAAG,CAAC,CAAC,KAAKC,SAAS,EAC1D;MACAF,cAAc,CAACG,GAAG,CAAC,CAAC;IACtB;IACA,OAAO,CAACvC,IAAI,EAAE,GAAGoC,cAAc,CAAC;EAClC;EAEAI,MAAMA,CAACzC,QAAmB,EAAQ;IAChC,IAAI,CAAC,CAACW,SAAS,CAAC8B,MAAM,CAACzC,QAAQ,CAAC;EAClC;EAEA0C,OAAOA,CAAC1C,QAAmB,EAAQ;IACjC,IAAI,CAAC,CAACW,SAAS,CAAC+B,OAAO,CAAC1C,QAAQ,CAAC;EACnC;EAEA,CAAC2C,MAAMC,CAAsB5C,QAAW,EAAQ;IAC9C,IAAI,CAAC,CAACF,SAAS,CAAC6C,MAAM,CAAC3C,QAAQ,CAACC,IAAI,EAAE,GAAGD,QAAQ,CAACE,SAAS,CAAC;EAC9D;;EAEA;AACF;AACA;AACA;EACE,CAACW,eAAe,GAAIgC,GAAc,IAAK;IACrC,IAAI,CAAC,CAAC/B,SAAS,GAAG+B,GAAG,CAAC;IACtB,IAAI,CAAC,CAACF,MAAM,CAACE,GAAG,CAAC;EACnB,CAAC;AACH","ignoreList":[]}
@@ -37,6 +37,7 @@ export class ListQueryView {
37
37
  #viewLimit;
38
38
  #pageSize;
39
39
  #viewId;
40
+ #hasAutoFetch;
40
41
  #fetchMore;
41
42
  #pendingFetchMore;
42
43
  #lastPayload;
@@ -48,8 +49,8 @@ export class ListQueryView {
48
49
 
49
50
  // With autoFetchMore, subscriber sees all loaded data (no view limit)
50
51
  // Otherwise, limit to their pageSize
51
-
52
- this.#viewLimit = autoFetchMore === true || typeof autoFetchMore === "number" && autoFetchMore > 0 ? Number.MAX_SAFE_INTEGER : pageSize;
52
+ this.#hasAutoFetch = autoFetchMore === true || typeof autoFetchMore === "number" && autoFetchMore > 0;
53
+ this.#viewLimit = this.#hasAutoFetch ? Number.MAX_SAFE_INTEGER : pageSize;
53
54
 
54
55
  // Memoize fetchMore to maintain stable function identity
55
56
  this.#fetchMore = this.#createFetchMore();
@@ -63,6 +64,9 @@ export class ListQueryView {
63
64
  next: payload => {
64
65
  this.#lastPayload = payload;
65
66
  observer.next?.(this.#transformPayload(payload));
67
+ if (!this.#hasAutoFetch && payload.status === "loaded" && payload.resolvedList.length < this.#viewLimit && this.#query.hasMorePages()) {
68
+ void this.#query.fetchMore();
69
+ }
66
70
  },
67
71
  error: err => observer.error?.(err),
68
72
  complete: () => observer.complete?.()
@@ -87,7 +91,8 @@ export class ListQueryView {
87
91
  ...payload,
88
92
  resolvedList: payload.resolvedList.slice(0, this.#viewLimit),
89
93
  hasMore: this.#viewLimit < loadedCount || payload.hasMore,
90
- fetchMore: this.#fetchMore
94
+ fetchMore: this.#fetchMore,
95
+ status: loadedCount >= this.#viewLimit && payload.status === "loading" ? "loaded" : payload.status
91
96
  };
92
97
  }
93
98
  #createFetchMore() {
@@ -1 +1 @@
1
- {"version":3,"file":"ListQueryView.js","names":["viewIdCounter","ListQueryView","query","viewLimit","pageSize","viewId","fetchMore","pendingFetchMore","lastPayload","observer","constructor","autoFetchMore","Number","MAX_SAFE_INTEGER","createFetchMore","registerFetchPageSize","subscribe","sub","next","payload","transformPayload","error","err","complete","add","unregisterFetchPageSize","undefined","reEmitWithNewViewLimit","#reEmitWithNewViewLimit","#transformPayload","loadedCount","resolvedList","length","slice","hasMore","#createFetchMore","getLoadedCount","hasMoreOnServer","hasMorePages","finally","Promise","resolve"],"sources":["ListQueryView.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Subscription } from \"rxjs\";\nimport type { Observer } from \"../ObservableClient/common.js\";\nimport type { BaseListPayloadShape } from \"./base-list/BaseListQuery.js\";\n\n/**\n * Interface for the query methods that ListQueryView needs.\n * This allows ListQueryView to work with any query that supports these operations.\n */\nexport interface ListQueryViewTarget<PAYLOAD extends BaseListPayloadShape> {\n subscribe(observer: Observer<PAYLOAD>): Subscription;\n registerFetchPageSize(viewId: string, pageSize: number): void;\n unregisterFetchPageSize(viewId: string): void;\n getLoadedCount(): number;\n hasMorePages(): boolean;\n notifySubscribers(): void;\n fetchMore(): Promise<void>;\n}\n\n/**\n * A view into a shared ListQuery cache.\n *\n * Each subscriber gets their own View instance that tracks how much of the\n * shared cache they want to see (viewLimit). This allows multiple components\n * with different pageSize requirements to share the same underlying cache.\n *\n * The View:\n * - Slices the shared data to the subscriber's viewLimit\n * - Provides a fetchMore that increments viewLimit and fetches if needed\n * - Reports hasMore based on both local viewLimit and server pagination\n */\nlet viewIdCounter = 0;\n\nexport class ListQueryView<PAYLOAD extends BaseListPayloadShape> {\n #query: ListQueryViewTarget<PAYLOAD>;\n #viewLimit: number;\n #pageSize: number;\n #viewId: string;\n #fetchMore: () => Promise<void>;\n #pendingFetchMore: Promise<void> | undefined;\n #lastPayload: PAYLOAD | undefined;\n #observer: Observer<PAYLOAD> | undefined;\n\n constructor(\n query: ListQueryViewTarget<PAYLOAD>,\n pageSize: number,\n autoFetchMore?: boolean | number,\n ) {\n this.#query = query;\n this.#pageSize = pageSize;\n this.#viewId = `view_${++viewIdCounter}`;\n\n // With autoFetchMore, subscriber sees all loaded data (no view limit)\n // Otherwise, limit to their pageSize\n const hasAutoFetch = autoFetchMore === true\n || (typeof autoFetchMore === \"number\" && autoFetchMore > 0);\n this.#viewLimit = hasAutoFetch ? Number.MAX_SAFE_INTEGER : pageSize;\n\n // Memoize fetchMore to maintain stable function identity\n this.#fetchMore = this.#createFetchMore();\n\n // Tell the query to fetch with at least this pageSize\n query.registerFetchPageSize(this.#viewId, pageSize);\n }\n\n subscribe(observer: Observer<PAYLOAD>): Subscription {\n this.#observer = observer;\n const sub = this.#query.subscribe({\n next: (payload) => {\n this.#lastPayload = payload;\n observer.next?.(this.#transformPayload(payload));\n },\n error: (err) => observer.error?.(err),\n complete: () => observer.complete?.(),\n });\n\n // Cleanup: unregister pageSize when subscriber unsubscribes\n sub.add(() => {\n this.#query.unregisterFetchPageSize(this.#viewId);\n this.#observer = undefined;\n this.#lastPayload = undefined;\n });\n\n return sub;\n }\n\n #reEmitWithNewViewLimit(): void {\n if (this.#lastPayload && this.#observer) {\n this.#observer.next?.(this.#transformPayload(this.#lastPayload));\n }\n }\n\n #transformPayload(payload: PAYLOAD): PAYLOAD {\n const loadedCount = payload.resolvedList.length;\n\n return {\n ...payload,\n resolvedList: payload.resolvedList.slice(0, this.#viewLimit),\n hasMore: this.#viewLimit < loadedCount || payload.hasMore,\n fetchMore: this.#fetchMore,\n };\n }\n\n #createFetchMore(): () => Promise<void> {\n return () => {\n if (this.#pendingFetchMore) {\n return this.#pendingFetchMore;\n }\n\n this.#viewLimit += this.#pageSize;\n\n const loadedCount = this.#query.getLoadedCount();\n const hasMoreOnServer = this.#query.hasMorePages();\n\n if (this.#viewLimit > loadedCount && hasMoreOnServer) {\n // Need to fetch more data from server\n this.#pendingFetchMore = this.#query.fetchMore().finally(() => {\n this.#pendingFetchMore = undefined;\n });\n return this.#pendingFetchMore;\n }\n\n // We have enough data in cache, just re-emit with new viewLimit (sync)\n this.#reEmitWithNewViewLimit();\n return Promise.resolve();\n };\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA;;AAWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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AK,CAACoC,YAAY,CAAC,CAAC;MAElD,IAAI,IAAI,CAAC,CAACnC,SAAS,GAAG2B,WAAW,IAAIO,eAAe,EAAE;QACpD;QACA,IAAI,CAAC,CAAC9B,gBAAgB,GAAG,IAAI,CAAC,CAACL,KAAK,CAACI,SAAS,CAAC,CAAC,CAACiC,OAAO,CAAC,MAAM;UAC7D,IAAI,CAAC,CAAChC,gBAAgB,GAAGmB,SAAS;QACpC,CAAC,CAAC;QACF,OAAO,IAAI,CAAC,CAACnB,gBAAgB;MAC/B;;MAEA;MACA,IAAI,CAAC,CAACoB,sBAAsB,CAAC,CAAC;MAC9B,OAAOa,OAAO,CAACC,OAAO,CAAC,CAAC;IAC1B,CAAC;EACH;AACF","ignoreList":[]}
1
+ {"version":3,"file":"ListQueryView.js","names":["viewIdCounter","ListQueryView","query","viewLimit","pageSize","viewId","hasAutoFetch","fetchMore","pendingFetchMore","lastPayload","observer","constructor","autoFetchMore","Number","MAX_SAFE_INTEGER","createFetchMore","registerFetchPageSize","subscribe","sub","next","payload","transformPayload","status","resolvedList","length","hasMorePages","error","err","complete","add","unregisterFetchPageSize","undefined","reEmitWithNewViewLimit","#reEmitWithNewViewLimit","#transformPayload","loadedCount","slice","hasMore","#createFetchMore","getLoadedCount","hasMoreOnServer","finally","Promise","resolve"],"sources":["ListQueryView.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Subscription } from \"rxjs\";\nimport type { Observer } from \"../ObservableClient/common.js\";\nimport type { BaseListPayloadShape } from \"./base-list/BaseListQuery.js\";\n\n/**\n * Interface for the query methods that ListQueryView needs.\n * This allows ListQueryView to work with any query that supports these operations.\n */\nexport interface ListQueryViewTarget<PAYLOAD extends BaseListPayloadShape> {\n subscribe(observer: Observer<PAYLOAD>): Subscription;\n registerFetchPageSize(viewId: string, pageSize: number): void;\n unregisterFetchPageSize(viewId: string): void;\n getLoadedCount(): number;\n hasMorePages(): boolean;\n notifySubscribers(): void;\n fetchMore(): Promise<void>;\n}\n\n/**\n * A view into a shared ListQuery cache.\n *\n * Each subscriber gets their own View instance that tracks how much of the\n * shared cache they want to see (viewLimit). This allows multiple components\n * with different pageSize requirements to share the same underlying cache.\n *\n * The View:\n * - Slices the shared data to the subscriber's viewLimit\n * - Provides a fetchMore that increments viewLimit and fetches if needed\n * - Reports hasMore based on both local viewLimit and server pagination\n */\nlet viewIdCounter = 0;\n\nexport class ListQueryView<PAYLOAD extends BaseListPayloadShape> {\n #query: ListQueryViewTarget<PAYLOAD>;\n #viewLimit: number;\n #pageSize: number;\n #viewId: string;\n #hasAutoFetch: boolean;\n #fetchMore: () => Promise<void>;\n #pendingFetchMore: Promise<void> | undefined;\n #lastPayload: PAYLOAD | undefined;\n #observer: Observer<PAYLOAD> | undefined;\n\n constructor(\n query: ListQueryViewTarget<PAYLOAD>,\n pageSize: number,\n autoFetchMore?: boolean | number,\n ) {\n this.#query = query;\n this.#pageSize = pageSize;\n this.#viewId = `view_${++viewIdCounter}`;\n\n // With autoFetchMore, subscriber sees all loaded data (no view limit)\n // Otherwise, limit to their pageSize\n this.#hasAutoFetch = autoFetchMore === true\n || (typeof autoFetchMore === \"number\" && autoFetchMore > 0);\n this.#viewLimit = this.#hasAutoFetch ? Number.MAX_SAFE_INTEGER : pageSize;\n\n // Memoize fetchMore to maintain stable function identity\n this.#fetchMore = this.#createFetchMore();\n\n // Tell the query to fetch with at least this pageSize\n query.registerFetchPageSize(this.#viewId, pageSize);\n }\n\n subscribe(observer: Observer<PAYLOAD>): Subscription {\n this.#observer = observer;\n const sub = this.#query.subscribe({\n next: (payload) => {\n this.#lastPayload = payload;\n observer.next?.(this.#transformPayload(payload));\n\n if (\n !this.#hasAutoFetch\n && payload.status === \"loaded\"\n && payload.resolvedList.length < this.#viewLimit\n && this.#query.hasMorePages()\n ) {\n void this.#query.fetchMore();\n }\n },\n error: (err) => observer.error?.(err),\n complete: () => observer.complete?.(),\n });\n\n // Cleanup: unregister pageSize when subscriber unsubscribes\n sub.add(() => {\n this.#query.unregisterFetchPageSize(this.#viewId);\n this.#observer = undefined;\n this.#lastPayload = undefined;\n });\n\n return sub;\n }\n\n #reEmitWithNewViewLimit(): void {\n if (this.#lastPayload && this.#observer) {\n this.#observer.next?.(this.#transformPayload(this.#lastPayload));\n }\n }\n\n #transformPayload(payload: PAYLOAD): PAYLOAD {\n const loadedCount = payload.resolvedList.length;\n\n return {\n ...payload,\n resolvedList: payload.resolvedList.slice(0, this.#viewLimit),\n hasMore: this.#viewLimit < loadedCount || payload.hasMore,\n fetchMore: this.#fetchMore,\n status: loadedCount >= this.#viewLimit && payload.status === \"loading\"\n ? \"loaded\"\n : payload.status,\n };\n }\n\n #createFetchMore(): () => Promise<void> {\n return () => {\n if (this.#pendingFetchMore) {\n return this.#pendingFetchMore;\n }\n\n this.#viewLimit += this.#pageSize;\n\n const loadedCount = this.#query.getLoadedCount();\n const hasMoreOnServer = this.#query.hasMorePages();\n\n if (this.#viewLimit > loadedCount && hasMoreOnServer) {\n // Need to fetch more data from server\n this.#pendingFetchMore = this.#query.fetchMore().finally(() => {\n this.#pendingFetchMore = undefined;\n });\n return this.#pendingFetchMore;\n }\n\n // We have enough data in cache, just re-emit with new viewLimit (sync)\n this.#reEmitWithNewViewLimit();\n return Promise.resolve();\n };\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA;;AAWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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S;MAC1Be,MAAM,EAAEa,WAAW,IAAI,IAAI,CAAC,CAAChC,SAAS,IAAIiB,OAAO,CAACE,MAAM,KAAK,SAAS,GAClE,QAAQ,GACRF,OAAO,CAACE;IACd,CAAC;EACH;EAEA,CAACP,eAAeuB,CAAA,EAAwB;IACtC,OAAO,MAAM;MACX,IAAI,IAAI,CAAC,CAAC9B,gBAAgB,EAAE;QAC1B,OAAO,IAAI,CAAC,CAACA,gBAAgB;MAC/B;MAEA,IAAI,CAAC,CAACL,SAAS,IAAI,IAAI,CAAC,CAACC,QAAQ;MAEjC,MAAM+B,WAAW,GAAG,IAAI,CAAC,CAACjC,KAAK,CAACqC,cAAc,CAAC,CAAC;MAChD,MAAMC,eAAe,GAAG,IAAI,CAAC,CAACtC,KAAK,CAACuB,YAAY,CAAC,CAAC;MAElD,IAAI,IAAI,CAAC,CAACtB,SAAS,GAAGgC,WAAW,IAAIK,eAAe,EAAE;QACpD;QACA,IAAI,CAAC,CAAChC,gBAAgB,GAAG,IAAI,CAAC,CAACN,KAAK,CAACK,SAAS,CAAC,CAAC,CAACkC,OAAO,CAAC,MAAM;UAC7D,IAAI,CAAC,CAACjC,gBAAgB,GAAGuB,SAAS;QACpC,CAAC,CAAC;QACF,OAAO,IAAI,CAAC,CAACvB,gBAAgB;MAC/B;;MAEA;MACA,IAAI,CAAC,CAACwB,sBAAsB,CAAC,CAAC;MAC9B,OAAOU,OAAO,CAACC,OAAO,CAAC,CAAC;IAC1B,CAAC;EACH;AACF","ignoreList":[]}
@@ -81,24 +81,9 @@ export class ObservableClientImpl {
81
81
  }, subFn);
82
82
  };
83
83
  observeLinks = (objects, linkName, options, subFn) => {
84
- // Convert to array if single object provided
85
84
  const objectsArray = Array.isArray(objects) ? objects : [objects];
86
- const parentSub = new Subscription();
87
- for (const obj of objectsArray) {
88
- const querySubscription = this.__experimentalStore.links.observe({
89
- ...options,
90
- srcType: {
91
- type: "object",
92
- apiName: obj.$objectType ?? obj.$apiName
93
- },
94
- linkName,
95
- pk: obj.$primaryKey
96
- },
97
- // cast to cross typed to untyped barrier
98
- subFn);
99
- parentSub.add(querySubscription);
100
- }
101
- return new UnsubscribableWrapper(parentSub);
85
+ const observer = subFn;
86
+ return objectsArray.length <= 1 ? observeSingleLink(this.__experimentalStore, objectsArray, linkName, options, observer) : observeMultiLinks(this.__experimentalStore, objectsArray, linkName, options, observer);
102
87
  };
103
88
  observeObjectSet(baseObjectSet, options, subFn) {
104
89
  return this.__experimentalStore.objectSets.observe({
@@ -127,4 +112,106 @@ export class ObservableClientImpl {
127
112
  return this.__experimentalStore.whereCanonicalizer.canonicalize(where);
128
113
  }
129
114
  }
115
+ function observeSingleLink(store, objectsArray, linkName, options, observer) {
116
+ if (objectsArray.length === 0) {
117
+ observer.next({
118
+ resolvedList: [],
119
+ isOptimistic: false,
120
+ lastUpdated: 0,
121
+ fetchMore: () => Promise.resolve(),
122
+ hasMore: false,
123
+ status: "loaded",
124
+ totalCount: "0"
125
+ });
126
+ return new UnsubscribableWrapper(new Subscription());
127
+ }
128
+ const parentSub = new Subscription();
129
+ for (const obj of objectsArray) {
130
+ parentSub.add(store.links.observe({
131
+ ...options,
132
+ srcType: {
133
+ type: "object",
134
+ apiName: obj.$objectType ?? obj.$apiName
135
+ },
136
+ linkName,
137
+ pk: obj.$primaryKey
138
+ }, observer));
139
+ }
140
+ return new UnsubscribableWrapper(parentSub);
141
+ }
142
+ function observeMultiLinks(store, objectsArray, linkName, options, observer) {
143
+ const parentSub = new Subscription();
144
+ const totalExpected = objectsArray.length;
145
+ const perObjectResults = new Map();
146
+ let errored = false;
147
+ function mergeAndEmit() {
148
+ if (errored) {
149
+ return;
150
+ }
151
+ const seen = new Map();
152
+ const fetchMores = [];
153
+ let latestUpdated = 0;
154
+ let hasMore = false;
155
+ let isOptimistic = false;
156
+ for (const payload of perObjectResults.values()) {
157
+ for (const obj of payload.resolvedList) {
158
+ seen.set(`${obj.$objectType}:${obj.$primaryKey}`, obj);
159
+ }
160
+ if (payload.lastUpdated > latestUpdated) {
161
+ latestUpdated = payload.lastUpdated;
162
+ }
163
+ if (payload.isOptimistic) {
164
+ isOptimistic = true;
165
+ }
166
+ if (payload.hasMore) {
167
+ hasMore = true;
168
+ fetchMores.push(payload.fetchMore);
169
+ }
170
+ }
171
+ const payloads = [...perObjectResults.values()];
172
+ const loading = perObjectResults.size < totalExpected || payloads.some(p => p.status === "init" || p.status === "loading");
173
+ observer.next({
174
+ resolvedList: Array.from(seen.values()),
175
+ isOptimistic,
176
+ lastUpdated: latestUpdated,
177
+ fetchMore: hasMore ? () => Promise.all(fetchMores.map(fn => fn())).then(() => {}) : () => Promise.resolve(),
178
+ hasMore,
179
+ status: loading ? "loading" : payloads.some(p => p.status === "error") ? "error" : "loaded",
180
+ ...(!hasMore ? {
181
+ totalCount: String(seen.size)
182
+ } : {})
183
+ });
184
+ }
185
+ for (const obj of objectsArray) {
186
+ const objKey = `${obj.$objectType ?? obj.$apiName}:${obj.$primaryKey}`;
187
+ parentSub.add(store.links.observe({
188
+ ...options,
189
+ srcType: {
190
+ type: "object",
191
+ apiName: obj.$objectType ?? obj.$apiName
192
+ },
193
+ linkName,
194
+ pk: obj.$primaryKey
195
+ }, {
196
+ next: payload => {
197
+ if (errored) {
198
+ return;
199
+ }
200
+ perObjectResults.set(objKey, payload);
201
+ mergeAndEmit();
202
+ },
203
+ error: err => {
204
+ if (errored) {
205
+ return;
206
+ }
207
+ errored = true;
208
+ parentSub.unsubscribe();
209
+ observer.error(err);
210
+ },
211
+ // store link queries are long-lived and do not complete
212
+ complete: () => {}
213
+ }));
214
+ }
215
+ return new UnsubscribableWrapper(parentSub);
216
+ }
130
217
  //# sourceMappingURL=ObservableClientImpl.js.map