@osdk/react 0.8.0 → 0.9.0-beta.10
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/AGENTS.md +253 -0
- package/CHANGELOG.md +105 -24
- package/build/browser/intellisense.test.helpers/useOsdkObjectsWithProperties.js +1 -1
- package/build/browser/intellisense.test.helpers/useOsdkObjectsWithProperties.js.map +1 -1
- package/build/browser/intellisense.test.js +1 -1
- package/build/browser/intellisense.test.js.map +1 -1
- package/build/browser/new/platform-apis/admin/useCurrentFoundryUser.js +44 -0
- package/build/browser/new/platform-apis/admin/useCurrentFoundryUser.js.map +1 -0
- package/build/browser/new/platform-apis/admin/useFoundryUser.js +50 -0
- package/build/browser/new/platform-apis/admin/useFoundryUser.js.map +1 -0
- package/build/browser/new/platform-apis/admin/useFoundryUsersList.js +54 -0
- package/build/browser/new/platform-apis/admin/useFoundryUsersList.js.map +1 -0
- package/build/browser/new/useLinks.js +15 -8
- package/build/browser/new/useLinks.js.map +1 -1
- package/build/browser/new/useObjectSet.js +3 -2
- package/build/browser/new/useObjectSet.js.map +1 -1
- package/build/browser/new/useOsdkAction.js.map +1 -1
- package/build/browser/new/useOsdkAggregation.js +1 -1
- package/build/browser/new/useOsdkAggregation.js.map +1 -1
- package/build/browser/new/useOsdkFunction.js +101 -0
- package/build/browser/new/useOsdkFunction.js.map +1 -0
- package/build/browser/new/useOsdkObject.js +1 -1
- package/build/browser/new/useOsdkObject.js.map +1 -1
- package/build/browser/new/useOsdkObjects.js +4 -3
- package/build/browser/new/useOsdkObjects.js.map +1 -1
- package/build/browser/public/experimental.js +4 -0
- package/build/browser/public/experimental.js.map +1 -1
- package/build/browser/utils/usePlatformQuery.js +74 -0
- package/build/browser/utils/usePlatformQuery.js.map +1 -0
- package/build/cjs/{chunk-OVBG5VXE.cjs → chunk-V32JHU3O.cjs} +8 -3
- package/build/cjs/chunk-V32JHU3O.cjs.map +1 -0
- package/build/cjs/index.cjs +4 -4
- package/build/cjs/public/experimental.cjs +399 -66
- package/build/cjs/public/experimental.cjs.map +1 -1
- package/build/cjs/public/experimental.d.cts +279 -32
- package/build/esm/intellisense.test.helpers/useOsdkObjectsWithProperties.js +1 -1
- package/build/esm/intellisense.test.helpers/useOsdkObjectsWithProperties.js.map +1 -1
- package/build/esm/intellisense.test.js +1 -1
- package/build/esm/intellisense.test.js.map +1 -1
- package/build/esm/new/platform-apis/admin/useCurrentFoundryUser.js +44 -0
- package/build/esm/new/platform-apis/admin/useCurrentFoundryUser.js.map +1 -0
- package/build/esm/new/platform-apis/admin/useFoundryUser.js +50 -0
- package/build/esm/new/platform-apis/admin/useFoundryUser.js.map +1 -0
- package/build/esm/new/platform-apis/admin/useFoundryUsersList.js +54 -0
- package/build/esm/new/platform-apis/admin/useFoundryUsersList.js.map +1 -0
- package/build/esm/new/useLinks.js +15 -8
- package/build/esm/new/useLinks.js.map +1 -1
- package/build/esm/new/useObjectSet.js +3 -2
- package/build/esm/new/useObjectSet.js.map +1 -1
- package/build/esm/new/useOsdkAction.js.map +1 -1
- package/build/esm/new/useOsdkAggregation.js +1 -1
- package/build/esm/new/useOsdkAggregation.js.map +1 -1
- package/build/esm/new/useOsdkFunction.js +101 -0
- package/build/esm/new/useOsdkFunction.js.map +1 -0
- package/build/esm/new/useOsdkObject.js +1 -1
- package/build/esm/new/useOsdkObject.js.map +1 -1
- package/build/esm/new/useOsdkObjects.js +4 -3
- package/build/esm/new/useOsdkObjects.js.map +1 -1
- package/build/esm/public/experimental.js +4 -0
- package/build/esm/public/experimental.js.map +1 -1
- package/build/esm/utils/usePlatformQuery.js +74 -0
- package/build/esm/utils/usePlatformQuery.js.map +1 -0
- package/build/types/new/platform-apis/admin/useCurrentFoundryUser.d.ts +28 -0
- package/build/types/new/platform-apis/admin/useCurrentFoundryUser.d.ts.map +1 -0
- package/build/types/new/platform-apis/admin/useFoundryUser.d.ts +36 -0
- package/build/types/new/platform-apis/admin/useFoundryUser.d.ts.map +1 -0
- package/build/types/new/platform-apis/admin/useFoundryUsersList.d.ts +52 -0
- package/build/types/new/platform-apis/admin/useFoundryUsersList.d.ts.map +1 -0
- package/build/types/new/useLinks.d.ts +5 -5
- package/build/types/new/useLinks.d.ts.map +1 -1
- package/build/types/new/useObjectSet.d.ts +4 -0
- package/build/types/new/useObjectSet.d.ts.map +1 -1
- package/build/types/new/useOsdkAction.d.ts +3 -3
- package/build/types/new/useOsdkAction.d.ts.map +1 -1
- package/build/types/new/useOsdkAggregation.d.ts +10 -12
- package/build/types/new/useOsdkAggregation.d.ts.map +1 -1
- package/build/types/new/useOsdkFunction.d.ts +112 -0
- package/build/types/new/useOsdkFunction.d.ts.map +1 -0
- package/build/types/new/useOsdkObjects.d.ts +31 -13
- package/build/types/new/useOsdkObjects.d.ts.map +1 -1
- package/build/types/public/experimental.d.ts +5 -0
- package/build/types/public/experimental.d.ts.map +1 -1
- package/build/types/utils/usePlatformQuery.d.ts +25 -0
- package/build/types/utils/usePlatformQuery.d.ts.map +1 -0
- package/docs/actions.md +414 -0
- package/docs/advanced-queries.md +663 -0
- package/docs/cache-management.md +213 -0
- package/docs/getting-started.md +382 -0
- package/docs/platform-apis.md +203 -0
- package/docs/querying-data.md +648 -0
- package/package.json +10 -6
- package/build/browser/new/types.js +0 -2
- package/build/browser/new/types.js.map +0 -1
- package/build/cjs/chunk-OVBG5VXE.cjs.map +0 -1
- package/build/esm/new/types.js +0 -2
- package/build/esm/new/types.js.map +0 -1
- package/build/types/new/types.d.ts +0 -5
- package/build/types/new/types.d.ts.map +0 -1
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright 2025 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 { Users } from "@osdk/foundry.admin";
|
|
18
|
+
import React from "react";
|
|
19
|
+
import { usePlatformQuery } from "../../../utils/usePlatformQuery.js";
|
|
20
|
+
import { OsdkContext2 } from "../../OsdkContext2.js";
|
|
21
|
+
/**
|
|
22
|
+
* Lists all Users. This is a paged endpoint. Each page may be smaller or larger than the requested page size.
|
|
23
|
+
* @param options Options to control the query.
|
|
24
|
+
*/
|
|
25
|
+
export function useFoundryUsersList({
|
|
26
|
+
enabled = true,
|
|
27
|
+
include = "ACTIVE",
|
|
28
|
+
pageSize = 1000,
|
|
29
|
+
pageToken
|
|
30
|
+
} = {}) {
|
|
31
|
+
const {
|
|
32
|
+
client
|
|
33
|
+
} = React.useContext(OsdkContext2);
|
|
34
|
+
const handleQuery = React.useCallback(() => {
|
|
35
|
+
return Users.list(client, {
|
|
36
|
+
include,
|
|
37
|
+
pageSize,
|
|
38
|
+
pageToken
|
|
39
|
+
});
|
|
40
|
+
}, [client, include, pageSize, pageToken]);
|
|
41
|
+
const query = usePlatformQuery({
|
|
42
|
+
query: handleQuery,
|
|
43
|
+
enabled,
|
|
44
|
+
queryName: "foundry-users-list"
|
|
45
|
+
});
|
|
46
|
+
return {
|
|
47
|
+
users: query.data?.data,
|
|
48
|
+
nextPageToken: query.data?.nextPageToken,
|
|
49
|
+
isLoading: query.isLoading,
|
|
50
|
+
error: query.error,
|
|
51
|
+
refetch: query.refetch
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=useFoundryUsersList.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useFoundryUsersList.js","names":["Users","React","usePlatformQuery","OsdkContext2","useFoundryUsersList","enabled","include","pageSize","pageToken","client","useContext","handleQuery","useCallback","list","query","queryName","users","data","nextPageToken","isLoading","error","refetch"],"sources":["useFoundryUsersList.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 ListUsersResponse, Users } from \"@osdk/foundry.admin\";\nimport type { UserStatus } from \"@osdk/foundry.core\";\nimport React from \"react\";\nimport { usePlatformQuery } from \"../../../utils/usePlatformQuery.js\";\nimport { OsdkContext2 } from \"../../OsdkContext2.js\";\n\nexport interface UseFoundryUsersListOptions {\n /**\n * Enable or disable the query.\n *\n * When `false`, the query will not automatically execute.\n *\n * This is useful for:\n * - Lazy/on-demand queries that should wait for user interaction\n * - Dependent queries that need data from another query first\n * - Conditional queries based on component state\n *\n * @default true\n * });\n */\n enabled?: boolean;\n\n /**\n * The default status of the users returned in the list.\n *\n * @default \"ACTIVE\"\n */\n include?: UserStatus;\n\n /**\n * The preferred page size for the list.\n *\n * @default 1000\n */\n pageSize?: number;\n\n /**\n * The page token indicates where to start paging. This should be omitted from the first page's request.\n * To fetch the next page, clients should take the value from the nextPageToken field of the previous\n * response and use it to populate the pageToken field of the next request.\n */\n pageToken?: string;\n}\n\nexport interface UseFoundryUsersListResult {\n users: ListUsersResponse[\"data\"] | undefined;\n /**\n * The page token to be used for the next page of users. If this is undefined, there are no more\n * pages of users to load.\n */\n nextPageToken: string | undefined;\n isLoading: boolean;\n\n error: Error | undefined;\n\n refetch: () => void;\n}\n\n/**\n * Lists all Users. This is a paged endpoint. Each page may be smaller or larger than the requested page size.\n * @param options Options to control the query.\n */\nexport function useFoundryUsersList(\n { enabled = true, include = \"ACTIVE\", pageSize = 1000, pageToken }:\n UseFoundryUsersListOptions = {},\n): UseFoundryUsersListResult {\n const { client } = React.useContext(OsdkContext2);\n\n const handleQuery = React.useCallback(() => {\n return Users.list(client, { include, pageSize, pageToken });\n }, [client, include, pageSize, pageToken]);\n\n const query = usePlatformQuery(\n {\n query: handleQuery,\n enabled,\n queryName: \"foundry-users-list\",\n },\n );\n\n return {\n users: query.data?.data,\n nextPageToken: query.data?.nextPageToken,\n isLoading: query.isLoading,\n error: query.error,\n refetch: query.refetch,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAiCA,KAAK,QAAQ,qBAAqB;AAEnE,OAAOC,KAAK,MAAM,OAAO;AACzB,SAASC,gBAAgB,QAAQ,oCAAoC;AACrE,SAASC,YAAY,QAAQ,uBAAuB;AAsDpD;AACA;AACA;AACA;AACA,OAAO,SAASC,mBAAmBA,CACjC;EAAEC,OAAO,GAAG,IAAI;EAAEC,OAAO,GAAG,QAAQ;EAAEC,QAAQ,GAAG,IAAI;EAAEC;AAC5B,CAAC,GAAG,CAAC,CAAC,EACN;EAC3B,MAAM;IAAEC;EAAO,CAAC,GAAGR,KAAK,CAACS,UAAU,CAACP,YAAY,CAAC;EAEjD,MAAMQ,WAAW,GAAGV,KAAK,CAACW,WAAW,CAAC,MAAM;IAC1C,OAAOZ,KAAK,CAACa,IAAI,CAACJ,MAAM,EAAE;MAAEH,OAAO;MAAEC,QAAQ;MAAEC;IAAU,CAAC,CAAC;EAC7D,CAAC,EAAE,CAACC,MAAM,EAAEH,OAAO,EAAEC,QAAQ,EAAEC,SAAS,CAAC,CAAC;EAE1C,MAAMM,KAAK,GAAGZ,gBAAgB,CAC5B;IACEY,KAAK,EAAEH,WAAW;IAClBN,OAAO;IACPU,SAAS,EAAE;EACb,CACF,CAAC;EAED,OAAO;IACLC,KAAK,EAAEF,KAAK,CAACG,IAAI,EAAEA,IAAI;IACvBC,aAAa,EAAEJ,KAAK,CAACG,IAAI,EAAEC,aAAa;IACxCC,SAAS,EAAEL,KAAK,CAACK,SAAS;IAC1BC,KAAK,EAAEN,KAAK,CAACM,KAAK;IAClBC,OAAO,EAAEP,KAAK,CAACO;EACjB,CAAC;AACH","ignoreList":[]}
|
|
@@ -35,11 +35,18 @@ export function useLinks(objects, linkName, options = {}) {
|
|
|
35
35
|
enabled = true,
|
|
36
36
|
...otherOptions
|
|
37
37
|
} = options;
|
|
38
|
+
const stableWhere = React.useMemo(() => otherOptions.where, [JSON.stringify(otherOptions.where)]);
|
|
39
|
+
const stableOrderBy = React.useMemo(() => otherOptions.orderBy, [JSON.stringify(otherOptions.orderBy)]);
|
|
40
|
+
const objectsKey = React.useMemo(() => {
|
|
41
|
+
if (objects === undefined) return "";
|
|
42
|
+
const arr = Array.isArray(objects) ? objects : [objects];
|
|
43
|
+
return arr.map(obj => `${obj.$apiName}:${obj.$primaryKey}`).join(",");
|
|
44
|
+
}, [objects]);
|
|
38
45
|
|
|
39
46
|
// Convert single object to array for consistent handling
|
|
40
47
|
const objectsArray = React.useMemo(() => {
|
|
41
48
|
return objects === undefined ? emptyArray : Array.isArray(objects) ? objects : [objects];
|
|
42
|
-
}, [objects]);
|
|
49
|
+
}, [objectsKey, objects]);
|
|
43
50
|
const {
|
|
44
51
|
subscribe,
|
|
45
52
|
getSnapShot
|
|
@@ -47,23 +54,23 @@ export function useLinks(objects, linkName, options = {}) {
|
|
|
47
54
|
if (!enabled) {
|
|
48
55
|
return makeExternalStore(() => ({
|
|
49
56
|
unsubscribe: () => {}
|
|
50
|
-
}), `links ${linkName} for ${
|
|
57
|
+
}), `links ${linkName} for ${objectsKey} [DISABLED]`);
|
|
51
58
|
}
|
|
52
59
|
return makeExternalStore(observer => observableClient.observeLinks(objectsArray, linkName, {
|
|
53
60
|
linkName,
|
|
54
|
-
where:
|
|
61
|
+
where: stableWhere,
|
|
55
62
|
pageSize: otherOptions.pageSize,
|
|
56
|
-
orderBy:
|
|
63
|
+
orderBy: stableOrderBy,
|
|
57
64
|
mode: otherOptions.mode
|
|
58
|
-
}, observer), `links ${linkName} for ${
|
|
59
|
-
}, [enabled, observableClient, objectsArray, linkName,
|
|
65
|
+
}, observer), `links ${linkName} for ${objectsKey}`);
|
|
66
|
+
}, [enabled, observableClient, objectsArray, objectsKey, linkName, stableWhere, otherOptions.pageSize, stableOrderBy, otherOptions.mode]);
|
|
60
67
|
const payload = React.useSyncExternalStore(subscribe, getSnapShot);
|
|
61
68
|
return {
|
|
62
69
|
links: payload?.resolvedList,
|
|
63
|
-
isLoading: payload?.status === "loading",
|
|
70
|
+
isLoading: enabled ? payload?.status === "loading" || payload?.status === "init" || !payload : false,
|
|
64
71
|
isOptimistic: payload?.isOptimistic ?? false,
|
|
65
72
|
error: payload?.error,
|
|
66
|
-
fetchMore: payload?.fetchMore,
|
|
73
|
+
fetchMore: payload?.hasMore ? payload?.fetchMore : undefined,
|
|
67
74
|
hasMore: payload?.hasMore ?? false
|
|
68
75
|
};
|
|
69
76
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLinks.js","names":["React","makeExternalStore","OsdkContext2","emptyArray","Object","freeze","useLinks","objects","linkName","options","observableClient","useContext","enabled","otherOptions","
|
|
1
|
+
{"version":3,"file":"useLinks.js","names":["React","makeExternalStore","OsdkContext2","emptyArray","Object","freeze","useLinks","objects","linkName","options","observableClient","useContext","enabled","otherOptions","stableWhere","useMemo","where","JSON","stringify","stableOrderBy","orderBy","objectsKey","undefined","arr","Array","isArray","map","obj","$apiName","$primaryKey","join","objectsArray","subscribe","getSnapShot","unsubscribe","observer","observeLinks","pageSize","mode","payload","useSyncExternalStore","links","resolvedList","isLoading","status","isOptimistic","error","fetchMore","hasMore"],"sources":["useLinks.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 LinkedType,\n LinkNames,\n ObjectOrInterfaceDefinition,\n} from \"@osdk/api\";\nimport type { Osdk, PropertyKeys, WhereClause } from \"@osdk/client\";\nimport type { ObserveLinks } from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { makeExternalStore } from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\nexport interface UseLinksOptions<\n T extends ObjectOrInterfaceDefinition,\n> {\n /**\n * Standard OSDK Where clause for filtering linked objects\n */\n where?: WhereClause<T>;\n\n /**\n * The preferred page size for the links list.\n */\n pageSize?: number;\n\n /** Sorting options for the linked objects */\n orderBy?: {\n [K in PropertyKeys<T>]?: \"asc\" | \"desc\";\n };\n\n /**\n * The mode to use for fetching data.\n * - undefined: Fetch data if not already in cache\n * - \"force\": Always fetch fresh data\n * - \"offline\": Only use cached data, don't make network requests\n */\n mode?: \"force\" | \"offline\";\n\n /**\n * Enable or disable the query.\n *\n * When `false`, the query will not automatically execute. It will still\n * return any cached data, but will not fetch from the server.\n *\n * This is useful for:\n * - Lazy/on-demand queries that should wait for user interaction\n * - Dependent queries that need data from another query first\n * - Conditional queries based on component state\n *\n * @default true\n * @example\n * // Dependent query - wait for employee data\n * const { object: employee } = useOsdkObject(Employee, employeeId);\n * const { links: reports } = useLinks(employee, \"reports\", {\n * enabled: !!employee\n * });\n */\n enabled?: boolean;\n}\n\nexport interface UseLinksResult<\n Q extends ObjectOrInterfaceDefinition,\n> {\n links: Osdk.Instance<Q>[] | undefined;\n isLoading: boolean;\n error: Error | undefined;\n\n /**\n * Refers to whether the links are optimistic or not.\n */\n isOptimistic: boolean;\n\n /**\n * Fetch more linked objects if pagination is supported\n */\n fetchMore: (() => Promise<unknown>) | undefined;\n\n /**\n * Indicates if there are more linked objects available to fetch\n */\n hasMore: boolean;\n}\n\nconst emptyArray = Object.freeze([]);\n\n/**\n * Hook to observe links from an object or array of objects.\n *\n * @param objects The source object(s) to observe links from\n * @param linkName The name of the link to observe\n * @param options Optional configuration for the link query\n * @returns UseLinksResult with links data and metadata\n */\nexport function useLinks<\n T extends ObjectOrInterfaceDefinition,\n L extends LinkNames<T>,\n>(\n objects: Osdk.Instance<T> | Array<Osdk.Instance<T>> | undefined,\n linkName: L,\n options: UseLinksOptions<LinkedType<T, L>> = {},\n): UseLinksResult<LinkedType<T, L>> {\n const { observableClient } = React.useContext(OsdkContext2);\n\n const { enabled = true, ...otherOptions } = options;\n\n const stableWhere = React.useMemo(\n () => otherOptions.where,\n [JSON.stringify(otherOptions.where)],\n );\n\n const stableOrderBy = React.useMemo(\n () => otherOptions.orderBy,\n [JSON.stringify(otherOptions.orderBy)],\n );\n\n const objectsKey = React.useMemo(() => {\n if (objects === undefined) return \"\";\n const arr = Array.isArray(objects) ? objects : [objects];\n return arr.map(obj => `${obj.$apiName}:${obj.$primaryKey}`).join(\",\");\n }, [objects]);\n\n // Convert single object to array for consistent handling\n const objectsArray: ReadonlyArray<Osdk.Instance<T>> = React.useMemo(() => {\n return objects === undefined\n ? emptyArray\n : Array.isArray(objects)\n ? objects\n : [objects];\n }, [objectsKey, objects]);\n\n const { subscribe, getSnapShot } = React.useMemo(\n () => {\n if (!enabled) {\n return makeExternalStore<ObserveLinks.CallbackArgs<T>>(\n () => ({ unsubscribe: () => {} }),\n `links ${linkName} for ${objectsKey} [DISABLED]`,\n );\n }\n return makeExternalStore<ObserveLinks.CallbackArgs<T>>(\n (observer) =>\n observableClient.observeLinks(\n objectsArray,\n linkName,\n {\n linkName,\n where: stableWhere,\n pageSize: otherOptions.pageSize,\n orderBy: stableOrderBy,\n mode: otherOptions.mode,\n },\n observer,\n ),\n `links ${linkName} for ${objectsKey}`,\n );\n },\n [\n enabled,\n observableClient,\n objectsArray,\n objectsKey,\n linkName,\n stableWhere,\n otherOptions.pageSize,\n stableOrderBy,\n otherOptions.mode,\n ],\n );\n\n const payload = React.useSyncExternalStore(\n subscribe,\n getSnapShot,\n );\n\n return {\n links: payload?.resolvedList,\n isLoading: enabled\n ? (payload?.status === \"loading\" || payload?.status === \"init\"\n || !payload)\n : false,\n isOptimistic: payload?.isOptimistic ?? false,\n error: payload?.error,\n fetchMore: payload?.hasMore ? payload?.fetchMore : undefined,\n hasMore: payload?.hasMore ?? false,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AASA,OAAOA,KAAK,MAAM,OAAO;AACzB,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,SAASC,YAAY,QAAQ,mBAAmB;AAyEhD,MAAMC,UAAU,GAAGC,MAAM,CAACC,MAAM,CAAC,EAAE,CAAC;;AAEpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,QAAQA,CAItBC,OAA+D,EAC/DC,QAAW,EACXC,OAA0C,GAAG,CAAC,CAAC,EACb;EAClC,MAAM;IAAEC;EAAiB,CAAC,GAAGV,KAAK,CAACW,UAAU,CAACT,YAAY,CAAC;EAE3D,MAAM;IAAEU,OAAO,GAAG,IAAI;IAAE,GAAGC;EAAa,CAAC,GAAGJ,OAAO;EAEnD,MAAMK,WAAW,GAAGd,KAAK,CAACe,OAAO,CAC/B,MAAMF,YAAY,CAACG,KAAK,EACxB,CAACC,IAAI,CAACC,SAAS,CAACL,YAAY,CAACG,KAAK,CAAC,CACrC,CAAC;EAED,MAAMG,aAAa,GAAGnB,KAAK,CAACe,OAAO,CACjC,MAAMF,YAAY,CAACO,OAAO,EAC1B,CA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QACF,CAAC,EACH,SAAS3B,QAAQ,QAAQa,UAAU,EACrC,CAAC;EACH,CAAC,EACD,CACET,OAAO,EACPF,gBAAgB,EAChBqB,YAAY,EACZV,UAAU,EACVb,QAAQ,EACRM,WAAW,EACXD,YAAY,CAACwB,QAAQ,EACrBlB,aAAa,EACbN,YAAY,CAACyB,IAAI,CAErB,CAAC;EAED,MAAMC,OAAO,GAAGvC,KAAK,CAACwC,oBAAoB,CACxCR,SAAS,EACTC,WACF,CAAC;EAED,OAAO;IACLQ,KAAK,EAAEF,OAAO,EAAEG,YAAY;IAC5BC,SAAS,EAAE/B,OAAO,GACb2B,OAAO,EAAEK,MAAM,KAAK,SAAS,IAAIL,OAAO,EAAEK,MAAM,KAAK,MAAM,IACzD,CAACL,OAAO,GACX,KAAK;IACTM,YAAY,EAAEN,OAAO,EAAEM,YAAY,IAAI,KAAK;IAC5CC,KAAK,EAAEP,OAAO,EAAEO,KAAK;IACrBC,SAAS,EAAER,OAAO,EAAES,OAAO,GAAGT,OAAO,EAAEQ,SAAS,GAAGzB,SAAS;IAC5D0B,OAAO,EAAET,OAAO,EAAES,OAAO,IAAI;EAC/B,CAAC;AACH","ignoreList":[]}
|
|
@@ -97,8 +97,9 @@ export function useObjectSet(baseObjectSet, options = {}) {
|
|
|
97
97
|
data: payload?.resolvedList,
|
|
98
98
|
isLoading: payload?.status === "loading" || !payload && true || false,
|
|
99
99
|
error: payload && "error" in payload ? payload.error : undefined,
|
|
100
|
-
fetchMore: payload?.fetchMore,
|
|
101
|
-
objectSet: payload?.objectSet || baseObjectSet
|
|
100
|
+
fetchMore: payload?.hasMore ? payload.fetchMore : undefined,
|
|
101
|
+
objectSet: payload?.objectSet || baseObjectSet,
|
|
102
|
+
totalCount: payload?.totalCount
|
|
102
103
|
};
|
|
103
104
|
}
|
|
104
105
|
//# sourceMappingURL=useObjectSet.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useObjectSet.js","names":["computeObjectSetCacheKey","React","makeExternalStore","OsdkContext2","useObjectSet","baseObjectSet","options","observableClient","useContext","enabled","streamUpdates","otherOptions","objectTypeKey","$objectSetInternals","def","apiName","previousObjectTypeRef","useRef","previousPayloadRef","objectTypeChanged","current","stableKey","where","withProperties","union","intersect","subtract","pivotTo","pageSize","orderBy","subscribe","getSnapShot","useMemo","unsubscribe","process","env","NODE_ENV","initialValue","undefined","observer","subscription","observeObjectSet","dedupeInterval","dedupeIntervalMs","autoFetchMore","payload","useSyncExternalStore","useEffect","data","resolvedList","isLoading","status","error","fetchMore","objectSet"],"sources":["useObjectSet.tsx"],"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 DerivedProperty,\n LinkNames,\n ObjectSet,\n ObjectTypeDefinition,\n Osdk,\n PropertyKeys,\n SimplePropertyDef,\n WhereClause,\n} from \"@osdk/api\";\n\nimport {\n computeObjectSetCacheKey,\n type ObserveObjectSetArgs,\n} from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { makeExternalStore, type Snapshot } from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\nexport interface UseObjectSetOptions<\n Q extends ObjectTypeDefinition,\n RDPs extends Record<string, SimplePropertyDef> = {},\n> {\n /**\n * Where clause for filtering\n */\n where?: WhereClause<Q, RDPs>;\n\n /**\n * Derived properties to add to the object set\n */\n withProperties?: { [K in keyof RDPs]: DerivedProperty.Creator<Q, RDPs[K]> };\n\n /**\n * Object sets to union with\n */\n union?: ObjectSet<Q>[];\n\n /**\n * Object sets to intersect with\n */\n intersect?: ObjectSet<Q>[];\n\n /**\n * Object sets to subtract from\n */\n subtract?: ObjectSet<Q>[];\n\n /**\n * Link to pivot to (changes the type)\n */\n pivotTo?: LinkNames<Q>;\n\n /**\n * The preferred page size for the list\n */\n pageSize?: number;\n\n /**\n * Sort order for the results\n */\n orderBy?: {\n [K in PropertyKeys<Q>]?: \"asc\" | \"desc\";\n };\n\n /**\n * Minimum time between fetch requests in milliseconds (defaults to 2000ms)\n */\n dedupeIntervalMs?: number;\n\n /**\n * Automatically fetch additional pages on initial load.\n *\n * - `true`: Fetch all available pages automatically\n * - `number`: Fetch pages until at least this many items are loaded\n * - `undefined` (default): Only fetch the first page, user must call fetchMore()\n */\n autoFetchMore?: boolean | number;\n\n /**\n * Enable streaming updates via websocket subscription.\n * When true, the object set will automatically update when matching objects are\n * added, updated, or removed.\n *\n * @default false\n */\n streamUpdates?: boolean;\n\n /**\n * Enable or disable the query.\n *\n * When `false`, the query will not automatically execute. It will still\n * return any cached data, but will not fetch from the server.\n *\n * This is useful for:\n * - Lazy/on-demand queries that should wait for user interaction\n * - Dependent queries that need data from another query first\n * - Conditional queries based on component state\n *\n * @default true\n * @example\n * // Dependent query - wait for filter selection\n * const { data: filteredObjects } = useObjectSet(MyObject.all(), {\n * where: { status: selectedStatus },\n * enabled: !!selectedStatus\n * });\n */\n enabled?: boolean;\n}\n\nexport interface UseObjectSetResult<\n Q extends ObjectTypeDefinition,\n RDPs extends Record<string, SimplePropertyDef> = {},\n> {\n /**\n * The fetched data with derived properties\n */\n data:\n | Osdk.Instance<Q, \"$allBaseProperties\", PropertyKeys<Q>, RDPs>[]\n | undefined;\n\n /**\n * Whether data is currently being loaded\n */\n isLoading: boolean;\n\n /**\n * Any error that occurred during fetching\n */\n error: Error | undefined;\n\n /**\n * Function to fetch more pages (undefined if no more pages)\n */\n fetchMore: (() => Promise<void>) | undefined;\n\n /**\n * The final ObjectSet after all transformations\n */\n objectSet: ObjectSet<Q, RDPs>;\n}\n\ndeclare const process: {\n env: {\n NODE_ENV: \"development\" | \"production\";\n };\n};\n\n/**\n * React hook for observing and interacting with OSDK object sets.\n *\n * @typeParam Q - The object type definition\n * @typeParam BaseRDPs - Derived properties that already exist on the input ObjectSet\n * @typeParam RDPs - New derived properties to be added via options.withProperties\n *\n * @param baseObjectSet - The ObjectSet to observe (may already have derived properties)\n * @param options - Options for filtering, sorting, and adding new derived properties\n * @returns Object set data with both existing and new derived properties\n */\nexport function useObjectSet<\n Q extends ObjectTypeDefinition,\n BaseRDPs extends Record<string, SimplePropertyDef> = never,\n RDPs extends Record<string, SimplePropertyDef> = {},\n>(\n baseObjectSet: ObjectSet<Q, BaseRDPs>,\n options: UseObjectSetOptions<Q, RDPs> = {},\n): UseObjectSetResult<Q, RDPs> {\n const { observableClient } = React.useContext(OsdkContext2);\n\n const { enabled = true, streamUpdates, ...otherOptions } = options;\n\n // Track object type to detect when we switch to a different object type\n const objectTypeKey = baseObjectSet.$objectSetInternals.def.apiName;\n const previousObjectTypeRef = React.useRef<string>(objectTypeKey);\n const previousPayloadRef = React.useRef<\n Snapshot<ObserveObjectSetArgs<Q, RDPs>> | undefined\n >();\n\n const objectTypeChanged = previousObjectTypeRef.current !== objectTypeKey;\n if (objectTypeChanged) {\n previousObjectTypeRef.current = objectTypeKey;\n }\n\n // Compute a stable cache key for the ObjectSet and options\n // dedupeIntervalMs and enabled are excluded as they don't affect the data\n const stableKey = computeObjectSetCacheKey(baseObjectSet, {\n where: otherOptions.where,\n withProperties: otherOptions.withProperties,\n union: otherOptions.union,\n intersect: otherOptions.intersect,\n subtract: otherOptions.subtract,\n pivotTo: otherOptions.pivotTo,\n pageSize: otherOptions.pageSize,\n orderBy: otherOptions.orderBy,\n });\n\n const { subscribe, getSnapShot } = React.useMemo(\n () => {\n if (!enabled) {\n return makeExternalStore<ObserveObjectSetArgs<Q, RDPs>>(\n () => ({ unsubscribe: () => {} }),\n process.env.NODE_ENV !== \"production\"\n ? `objectSet ${stableKey} [DISABLED]`\n : void 0,\n );\n }\n\n const initialValue = objectTypeChanged\n ? undefined\n : previousPayloadRef.current;\n\n return makeExternalStore<ObserveObjectSetArgs<Q, RDPs>>(\n (observer) => {\n const subscription = observableClient.observeObjectSet(\n baseObjectSet as ObjectSet<Q>,\n {\n where: otherOptions.where,\n withProperties: otherOptions.withProperties,\n union: otherOptions.union,\n intersect: otherOptions.intersect,\n subtract: otherOptions.subtract,\n pivotTo: otherOptions.pivotTo,\n pageSize: otherOptions.pageSize,\n orderBy: otherOptions.orderBy,\n dedupeInterval: otherOptions.dedupeIntervalMs ?? 2_000,\n autoFetchMore: otherOptions.autoFetchMore,\n streamUpdates,\n },\n observer,\n );\n return subscription;\n },\n process.env.NODE_ENV !== \"production\"\n ? `objectSet ${stableKey}`\n : void 0,\n initialValue,\n );\n },\n [enabled, observableClient, stableKey, streamUpdates, objectTypeChanged],\n );\n\n const payload = React.useSyncExternalStore(subscribe, getSnapShot);\n React.useEffect(() => {\n if (payload) {\n previousPayloadRef.current = payload;\n }\n }, [payload]);\n\n return {\n data: payload?.resolvedList as Osdk.Instance<\n Q,\n \"$allBaseProperties\",\n PropertyKeys<Q>,\n RDPs\n >[],\n isLoading: payload?.status === \"loading\" || (!payload && true) || false,\n error: payload && \"error\" in payload\n ? payload.error\n : undefined,\n fetchMore: payload?.fetchMore,\n objectSet: payload?.objectSet as ObjectSet<Q, RDPs> || baseObjectSet,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAaA,SACEA,wBAAwB,QAEnB,kCAAkC;AACzC,OAAOC,KAAK,MAAM,OAAO;AACzB,SAASC,iBAAiB,QAAuB,wBAAwB;AACzE,SAASC,YAAY,QAAQ,mBAAmB;AAmIhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,YAAYA,CAK1BC,aAAqC,EACrCC,OAAqC,GAAG,CAAC,CAA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AAS,IAAK,CAACN,OAAO,IAAI,IAAK,IAAI,KAAK;IACvEO,KAAK,EAAEP,OAAO,IAAI,OAAO,IAAIA,OAAO,GAChCA,OAAO,CAACO,KAAK,GACbd,SAAS;IACbe,SAAS,EAAER,OAAO,EAAEQ,SAAS;IAC7BC,SAAS,EAAET,OAAO,EAAES,SAAS,IAA0BjD;EACzD,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useObjectSet.js","names":["computeObjectSetCacheKey","React","makeExternalStore","OsdkContext2","useObjectSet","baseObjectSet","options","observableClient","useContext","enabled","streamUpdates","otherOptions","objectTypeKey","$objectSetInternals","def","apiName","previousObjectTypeRef","useRef","previousPayloadRef","objectTypeChanged","current","stableKey","where","withProperties","union","intersect","subtract","pivotTo","pageSize","orderBy","subscribe","getSnapShot","useMemo","unsubscribe","process","env","NODE_ENV","initialValue","undefined","observer","subscription","observeObjectSet","dedupeInterval","dedupeIntervalMs","autoFetchMore","payload","useSyncExternalStore","useEffect","data","resolvedList","isLoading","status","error","fetchMore","hasMore","objectSet","totalCount"],"sources":["useObjectSet.tsx"],"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 DerivedProperty,\n LinkNames,\n ObjectSet,\n ObjectTypeDefinition,\n Osdk,\n PropertyKeys,\n SimplePropertyDef,\n WhereClause,\n} from \"@osdk/api\";\n\nimport {\n computeObjectSetCacheKey,\n type ObserveObjectSetArgs,\n} from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { makeExternalStore, type Snapshot } from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\nexport interface UseObjectSetOptions<\n Q extends ObjectTypeDefinition,\n RDPs extends Record<string, SimplePropertyDef> = {},\n> {\n /**\n * Where clause for filtering\n */\n where?: WhereClause<Q, RDPs>;\n\n /**\n * Derived properties to add to the object set\n */\n withProperties?: { [K in keyof RDPs]: DerivedProperty.Creator<Q, RDPs[K]> };\n\n /**\n * Object sets to union with\n */\n union?: ObjectSet<Q>[];\n\n /**\n * Object sets to intersect with\n */\n intersect?: ObjectSet<Q>[];\n\n /**\n * Object sets to subtract from\n */\n subtract?: ObjectSet<Q>[];\n\n /**\n * Link to pivot to (changes the type)\n */\n pivotTo?: LinkNames<Q>;\n\n /**\n * The preferred page size for the list\n */\n pageSize?: number;\n\n /**\n * Sort order for the results\n */\n orderBy?: {\n [K in PropertyKeys<Q>]?: \"asc\" | \"desc\";\n };\n\n /**\n * Minimum time between fetch requests in milliseconds (defaults to 2000ms)\n */\n dedupeIntervalMs?: number;\n\n /**\n * Automatically fetch additional pages on initial load.\n *\n * - `true`: Fetch all available pages automatically\n * - `number`: Fetch pages until at least this many items are loaded\n * - `undefined` (default): Only fetch the first page, user must call fetchMore()\n */\n autoFetchMore?: boolean | number;\n\n /**\n * Enable streaming updates via websocket subscription.\n * When true, the object set will automatically update when matching objects are\n * added, updated, or removed.\n *\n * @default false\n */\n streamUpdates?: boolean;\n\n /**\n * Enable or disable the query.\n *\n * When `false`, the query will not automatically execute. It will still\n * return any cached data, but will not fetch from the server.\n *\n * This is useful for:\n * - Lazy/on-demand queries that should wait for user interaction\n * - Dependent queries that need data from another query first\n * - Conditional queries based on component state\n *\n * @default true\n * @example\n * // Dependent query - wait for filter selection\n * const { data: filteredObjects } = useObjectSet(MyObject.all(), {\n * where: { status: selectedStatus },\n * enabled: !!selectedStatus\n * });\n */\n enabled?: boolean;\n}\n\nexport interface UseObjectSetResult<\n Q extends ObjectTypeDefinition,\n RDPs extends Record<string, SimplePropertyDef> = {},\n> {\n /**\n * The fetched data with derived properties\n */\n data:\n | Osdk.Instance<Q, \"$allBaseProperties\", PropertyKeys<Q>, RDPs>[]\n | undefined;\n\n /**\n * Whether data is currently being loaded\n */\n isLoading: boolean;\n\n /**\n * Any error that occurred during fetching\n */\n error: Error | undefined;\n\n /**\n * Function to fetch more pages (undefined if no more pages)\n */\n fetchMore: (() => Promise<void>) | undefined;\n\n /**\n * The final ObjectSet after all transformations\n */\n objectSet: ObjectSet<Q, RDPs>;\n\n /**\n * The total count of objects matching the query (if available from the API)\n */\n totalCount?: string;\n}\n\ndeclare const process: {\n env: {\n NODE_ENV: \"development\" | \"production\";\n };\n};\n\n/**\n * React hook for observing and interacting with OSDK object sets.\n *\n * @typeParam Q - The object type definition\n * @typeParam BaseRDPs - Derived properties that already exist on the input ObjectSet\n * @typeParam RDPs - New derived properties to be added via options.withProperties\n *\n * @param baseObjectSet - The ObjectSet to observe (may already have derived properties)\n * @param options - Options for filtering, sorting, and adding new derived properties\n * @returns Object set data with both existing and new derived properties\n */\nexport function useObjectSet<\n Q extends ObjectTypeDefinition,\n BaseRDPs extends Record<string, SimplePropertyDef> = never,\n RDPs extends Record<string, SimplePropertyDef> = {},\n>(\n baseObjectSet: ObjectSet<Q, BaseRDPs>,\n options: UseObjectSetOptions<Q, RDPs> = {},\n): UseObjectSetResult<Q, RDPs> {\n const { observableClient } = React.useContext(OsdkContext2);\n\n const { enabled = true, streamUpdates, ...otherOptions } = options;\n\n // Track object type to detect when we switch to a different object type\n const objectTypeKey = baseObjectSet.$objectSetInternals.def.apiName;\n const previousObjectTypeRef = React.useRef<string>(objectTypeKey);\n const previousPayloadRef = React.useRef<\n Snapshot<ObserveObjectSetArgs<Q, RDPs>> | undefined\n >();\n\n const objectTypeChanged = previousObjectTypeRef.current !== objectTypeKey;\n if (objectTypeChanged) {\n previousObjectTypeRef.current = objectTypeKey;\n }\n\n // Compute a stable cache key for the ObjectSet and options\n // dedupeIntervalMs and enabled are excluded as they don't affect the data\n const stableKey = computeObjectSetCacheKey(baseObjectSet, {\n where: otherOptions.where,\n withProperties: otherOptions.withProperties,\n union: otherOptions.union,\n intersect: otherOptions.intersect,\n subtract: otherOptions.subtract,\n pivotTo: otherOptions.pivotTo,\n pageSize: otherOptions.pageSize,\n orderBy: otherOptions.orderBy,\n });\n\n const { subscribe, getSnapShot } = React.useMemo(\n () => {\n if (!enabled) {\n return makeExternalStore<ObserveObjectSetArgs<Q, RDPs>>(\n () => ({ unsubscribe: () => {} }),\n process.env.NODE_ENV !== \"production\"\n ? `objectSet ${stableKey} [DISABLED]`\n : void 0,\n );\n }\n\n const initialValue = objectTypeChanged\n ? undefined\n : previousPayloadRef.current;\n\n return makeExternalStore<ObserveObjectSetArgs<Q, RDPs>>(\n (observer) => {\n const subscription = observableClient.observeObjectSet(\n baseObjectSet as ObjectSet<Q>,\n {\n where: otherOptions.where,\n withProperties: otherOptions.withProperties,\n union: otherOptions.union,\n intersect: otherOptions.intersect,\n subtract: otherOptions.subtract,\n pivotTo: otherOptions.pivotTo,\n pageSize: otherOptions.pageSize,\n orderBy: otherOptions.orderBy,\n dedupeInterval: otherOptions.dedupeIntervalMs ?? 2_000,\n autoFetchMore: otherOptions.autoFetchMore,\n streamUpdates,\n },\n observer,\n );\n return subscription;\n },\n process.env.NODE_ENV !== \"production\"\n ? `objectSet ${stableKey}`\n : void 0,\n initialValue,\n );\n },\n [enabled, observableClient, stableKey, streamUpdates, objectTypeChanged],\n );\n\n const payload = React.useSyncExternalStore(subscribe, getSnapShot);\n React.useEffect(() => {\n if (payload) {\n previousPayloadRef.current = payload;\n }\n }, [payload]);\n\n return {\n data: payload?.resolvedList as Osdk.Instance<\n Q,\n \"$allBaseProperties\",\n PropertyKeys<Q>,\n RDPs\n >[],\n isLoading: payload?.status === \"loading\" || (!payload && true) || false,\n error: payload && \"error\" in payload\n ? payload.error\n : undefined,\n fetchMore: payload?.hasMore ? payload.fetchMore : undefined,\n objectSet: payload?.objectSet as ObjectSet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,gBAAgB,EAAEc,SAAS,EAAEX,aAAa,EAAES,iBAAiB,CACzE,CAAC;EAED,MAAM0B,OAAO,GAAG5C,KAAK,CAAC6C,oBAAoB,CAAChB,SAAS,EAAEC,WAAW,CAAC;EAClE9B,KAAK,CAAC8C,SAAS,CAAC,MAAM;IACpB,IAAIF,OAAO,EAAE;MACX3B,kBAAkB,CAACE,OAAO,GAAGyB,OAAO;IACtC;EACF,CAAC,EAAE,CAACA,OAAO,CAAC,CAAC;EAEb,OAAO;IACLG,IAAI,EAAEH,OAAO,EAAEI,YAKZ;IACHC,SAAS,EAAEL,OAAO,EAAEM,MAAM,KAAK,SAAS,IAAK,CAACN,OAAO,IAAI,IAAK,IAAI,KAAK;IACvEO,KAAK,EAAEP,OAAO,IAAI,OAAO,IAAIA,OAAO,GAChCA,OAAO,CAACO,KAAK,GACbd,SAAS;IACbe,SAAS,EAAER,OAAO,EAAES,OAAO,GAAGT,OAAO,CAACQ,SAAS,GAAGf,SAAS;IAC3DiB,SAAS,EAAEV,OAAO,EAAEU,SAAS,IAA0BlD,aAAa;IACpEmD,UAAU,EAAEX,OAAO,EAAEW;EACvB,CAAC;AACH","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useOsdkAction.js","names":["ActionValidationError","React","OsdkContext2","useOsdkAction","actionDef","observableClient","useContext","error","setError","useState","data","setData","isPending","setPending","isValidating","setValidating","validationResult","setValidationResult","abortControllerRef","useRef","applyAction","useCallback","hookArgs","current","abort","undefined","Array","isArray","updates","args","map","a","$optimisticUpdate","push","r","optimisticUpdate","ctx","update","e","actionValidation","unknown","validateAction","abortController","AbortController","result","signal","aborted","Error","name","useEffect"],"sources":["useOsdkAction.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 { ActionDefinition, ActionValidationResponse } from \"@osdk/client\";\nimport { ActionValidationError } from \"@osdk/client\";\nimport type {\n ActionSignatureFromDef,\n ObservableClient,\n} from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\ntype ApplyActionParams<Q extends ActionDefinition<any>> =\n & Parameters<ActionSignatureFromDef<Q>[\"applyAction\"]>[0]\n & {\n [K in keyof ObservableClient.ApplyActionOptions as `$${K}`]:\n ObservableClient.ApplyActionOptions[K];\n };\n\nexport interface UseOsdkActionResult<Q extends ActionDefinition<any>> {\n applyAction: (\n args: ApplyActionParams<Q> | Array<ApplyActionParams<Q>>,\n ) => Promise<unknown>;\n\n error:\n | undefined\n | Partial<{\n actionValidation: ActionValidationError;\n unknown: unknown;\n }>;\n data: unknown;\n\n isPending: boolean;\n isValidating: boolean;\n\n /**\n * Validates the action with the provided arguments without executing it.\n * Calling this function again before the previous validation finishes will cancel\n * the first validation and start a new one.\n * @param args The action arguments to validate\n * @returns A promise that resolves to the validation response, or undefined if aborted\n */\n validateAction: (\n args: Parameters<ActionSignatureFromDef<Q>[\"applyAction\"]>[0],\n ) => Promise<ActionValidationResponse | undefined>;\n\n validationResult?: ActionValidationResponse;\n}\n\nexport function useOsdkAction<Q extends ActionDefinition<any>>(\n actionDef: Q,\n): UseOsdkActionResult<Q> {\n const { observableClient } = React.useContext(OsdkContext2);\n const [error, setError] = React.useState<UseOsdkActionResult<Q>[\"error\"]>();\n const [data, setData] = React.useState<unknown>();\n const [isPending, setPending] = React.useState(false);\n const [isValidating, setValidating] = React.useState(false);\n const [validationResult, setValidationResult] = React.useState<\n ActionValidationResponse | undefined\n >();\n const abortControllerRef = React.useRef<AbortController | null>(null);\n\n const applyAction = React.useCallback(async function applyAction(\n hookArgs: ApplyActionParams<Q> | Array<ApplyActionParams<Q>>,\n ) {\n try {\n // If validation is in progress, abort it\n if (isValidating && abortControllerRef.current) {\n abortControllerRef.current.abort();\n setValidating(false);\n }\n\n setPending(true);\n setError(undefined);\n\n if (Array.isArray(hookArgs)) {\n const updates: Array<\n ObservableClient.ApplyActionOptions[\"optimisticUpdate\"]\n > = [];\n const args = hookArgs.map(a => {\n const { $optimisticUpdate, ...args } = a;\n if ($optimisticUpdate) {\n updates.push($optimisticUpdate);\n }\n return args;\n });\n\n const r = await observableClient.applyAction(actionDef, args, {\n optimisticUpdate: (ctx) => {\n for (const update of updates) {\n update?.(ctx);\n }\n },\n });\n setData(r);\n return r;\n } else {\n const { $optimisticUpdate, ...args } = hookArgs;\n\n const r = await observableClient.applyAction(actionDef, args, {\n optimisticUpdate: $optimisticUpdate,\n });\n setData(r);\n return r;\n }\n } catch (e) {\n if (e instanceof ActionValidationError) {\n setError({\n actionValidation: e,\n });\n } else {\n setError({ unknown: e });\n }\n } finally {\n setPending(false);\n }\n }, [observableClient, actionDef, isValidating]);\n\n const validateAction = React.useCallback(async function validateAction(\n args: Parameters<ActionSignatureFromDef<Q>[\"applyAction\"]>[0],\n ): Promise<ActionValidationResponse | undefined> {\n try {\n // Check if action is being applied\n if (isPending) {\n return undefined;\n }\n\n // Abort any existing validation\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n\n // Create new AbortController\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setValidating(true);\n setError(undefined);\n\n const result = await observableClient.validateAction(actionDef, args);\n\n // Check if aborted\n if (abortController.signal.aborted) {\n return undefined;\n }\n\n setValidationResult(result);\n return result;\n } catch (e) {\n // Check if it was aborted\n if (e instanceof Error && e.name === \"AbortError\") {\n return undefined;\n }\n\n if (e instanceof ActionValidationError) {\n setError({\n actionValidation: e,\n });\n } else {\n setError({ unknown: e });\n }\n throw e;\n } finally {\n setValidating(false);\n }\n }, [observableClient, actionDef, isPending]);\n\n // Cleanup on unmount\n React.useEffect(() => {\n return () => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n };\n }, []);\n\n return {\n applyAction,\n validateAction,\n error,\n data,\n isPending,\n isValidating,\n validationResult,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,qBAAqB,QAAQ,cAAc;AAKpD,OAAOC,KAAK,MAAM,OAAO;AACzB,SAASC,YAAY,QAAQ,mBAAmB;AAuChD,OAAO,SAASC,aAAaA,CAC3BC,SAAY,EACY;EACxB,MAAM;IAAEC;EAAiB,CAAC,GAAGJ,KAAK,CAACK,UAAU,CAACJ,YAAY,CAAC;EAC3D,MAAM,CAACK,KAAK,EAAEC,QAAQ,CAAC,GAAGP,KAAK,CAACQ,QAAQ,CAAkC,CAAC;EAC3E,MAAM,CAACC,IAAI,EAAEC,OAAO,CAAC,GAAGV,KAAK,CAACQ,QAAQ,CAAU,CAAC;EACjD,MAAM,CAACG,SAAS,EAAEC,UAAU,CAAC,GAAGZ,KAAK,CAACQ,QAAQ,CAAC,KAAK,CAAC;EACrD,MAAM,CAACK,YAAY,EAAEC,aAAa,CAAC,GAAGd,KAAK,CAACQ,QAAQ,CAAC,KAAK,CAAC;EAC3D,MAAM,CAACO,gBAAgB,EAAEC,mBAAmB,CAAC,GAAGhB,KAAK,CAACQ,QAAQ,CAE5D,CAAC;EACH,MAAMS,kBAAkB,GAAGjB,KAAK,CAACkB,MAAM,CAAyB,IAAI,CAAC;EAErE,MAAMC,WAAW,GAAGnB,KAAK,CAACoB,WAAW,CAAC,gBACpCC,QAA4D,EAC5D;IACA,IAAI;MACF;MACA,IAAIR,YAAY,IAAII,kBAAkB,CAACK,OAAO,EAAE;QAC9CL,kBAAkB,CAACK,OAAO,CAACC,KAAK,CAAC,CAAC;QAClCT,aAAa,CAAC,KAAK,CAAC;MACtB;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ACpB,OAAO,MAAM;MACX,IAAI/B,kBAAkB,CAACK,OAAO,EAAE;QAC9BL,kBAAkB,CAACK,OAAO,CAACC,KAAK,CAAC,CAAC;MACpC;IACF,CAAC;EACH,CAAC,EAAE,EAAE,CAAC;EAEN,OAAO;IACLJ,WAAW;IACXqB,cAAc;IACdlC,KAAK;IACLG,IAAI;IACJE,SAAS;IACTE,YAAY;IACZE;EACF,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useOsdkAction.js","names":["ActionValidationError","React","OsdkContext2","useOsdkAction","actionDef","observableClient","useContext","error","setError","useState","data","setData","isPending","setPending","isValidating","setValidating","validationResult","setValidationResult","abortControllerRef","useRef","applyAction","useCallback","hookArgs","current","abort","undefined","Array","isArray","updates","args","map","a","$optimisticUpdate","push","r","optimisticUpdate","ctx","update","e","actionValidation","unknown","validateAction","abortController","AbortController","result","signal","aborted","Error","name","useEffect"],"sources":["useOsdkAction.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 ActionDefinition,\n ActionEditResponse,\n ActionValidationResponse,\n} from \"@osdk/client\";\nimport { ActionValidationError } from \"@osdk/client\";\nimport type {\n ActionSignatureFromDef,\n ObservableClient,\n} from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\ntype ApplyActionParams<Q extends ActionDefinition<any>> =\n & Parameters<ActionSignatureFromDef<Q>[\"applyAction\"]>[0]\n & {\n [K in keyof ObservableClient.ApplyActionOptions as `$${K}`]:\n ObservableClient.ApplyActionOptions[K];\n };\n\nexport interface UseOsdkActionResult<Q extends ActionDefinition<any>> {\n applyAction: (\n args: ApplyActionParams<Q> | Array<ApplyActionParams<Q>>,\n ) => Promise<ActionEditResponse | undefined>;\n\n error:\n | undefined\n | Partial<{\n actionValidation: ActionValidationError;\n unknown: unknown;\n }>;\n data: ActionEditResponse | undefined;\n\n isPending: boolean;\n isValidating: boolean;\n\n /**\n * Validates the action with the provided arguments without executing it.\n * Calling this function again before the previous validation finishes will cancel\n * the first validation and start a new one.\n * @param args The action arguments to validate\n * @returns A promise that resolves to the validation response, or undefined if aborted\n */\n validateAction: (\n args: Parameters<ActionSignatureFromDef<Q>[\"applyAction\"]>[0],\n ) => Promise<ActionValidationResponse | undefined>;\n\n validationResult?: ActionValidationResponse;\n}\n\nexport function useOsdkAction<Q extends ActionDefinition<any>>(\n actionDef: Q,\n): UseOsdkActionResult<Q> {\n const { observableClient } = React.useContext(OsdkContext2);\n const [error, setError] = React.useState<UseOsdkActionResult<Q>[\"error\"]>();\n const [data, setData] = React.useState<ActionEditResponse | undefined>();\n const [isPending, setPending] = React.useState(false);\n const [isValidating, setValidating] = React.useState(false);\n const [validationResult, setValidationResult] = React.useState<\n ActionValidationResponse | undefined\n >();\n const abortControllerRef = React.useRef<AbortController | null>(null);\n\n const applyAction = React.useCallback(async function applyAction(\n hookArgs: ApplyActionParams<Q> | Array<ApplyActionParams<Q>>,\n ) {\n try {\n // If validation is in progress, abort it\n if (isValidating && abortControllerRef.current) {\n abortControllerRef.current.abort();\n setValidating(false);\n }\n\n setPending(true);\n setError(undefined);\n\n if (Array.isArray(hookArgs)) {\n const updates: Array<\n ObservableClient.ApplyActionOptions[\"optimisticUpdate\"]\n > = [];\n const args = hookArgs.map(a => {\n const { $optimisticUpdate, ...args } = a;\n if ($optimisticUpdate) {\n updates.push($optimisticUpdate);\n }\n return args;\n });\n\n const r = await observableClient.applyAction(actionDef, args, {\n optimisticUpdate: (ctx) => {\n for (const update of updates) {\n update?.(ctx);\n }\n },\n });\n setData(r);\n return r;\n } else {\n const { $optimisticUpdate, ...args } = hookArgs;\n\n const r = await observableClient.applyAction(actionDef, args, {\n optimisticUpdate: $optimisticUpdate,\n });\n setData(r);\n return r;\n }\n } catch (e) {\n if (e instanceof ActionValidationError) {\n setError({\n actionValidation: e,\n });\n } else {\n setError({ unknown: e });\n }\n } finally {\n setPending(false);\n }\n }, [observableClient, actionDef, isValidating]);\n\n const validateAction = React.useCallback(async function validateAction(\n args: Parameters<ActionSignatureFromDef<Q>[\"applyAction\"]>[0],\n ): Promise<ActionValidationResponse | undefined> {\n try {\n // Check if action is being applied\n if (isPending) {\n return undefined;\n }\n\n // Abort any existing validation\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n\n // Create new AbortController\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setValidating(true);\n setError(undefined);\n\n const result = await observableClient.validateAction(actionDef, args);\n\n // Check if aborted\n if (abortController.signal.aborted) {\n return undefined;\n }\n\n setValidationResult(result);\n return result;\n } catch (e) {\n // Check if it was aborted\n if (e instanceof Error && e.name === \"AbortError\") {\n return undefined;\n }\n\n if (e instanceof ActionValidationError) {\n setError({\n actionValidation: e,\n });\n } else {\n setError({ unknown: e });\n }\n throw e;\n } finally {\n setValidating(false);\n }\n }, [observableClient, actionDef, isPending]);\n\n // Cleanup on unmount\n React.useEffect(() => {\n return () => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n };\n }, []);\n\n return {\n applyAction,\n validateAction,\n error,\n data,\n isPending,\n isValidating,\n validationResult,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA,SAASA,qBAAqB,QAAQ,cAAc;AAKpD,OAAOC,KAAK,MAAM,OAAO;AACzB,SAASC,YAAY,QAAQ,mBAAmB;AAuChD,OAAO,SAASC,aAAaA,CAC3BC,SAAY,EACY;EACxB,MAA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C3B,aAAa,CAAC,IAAI,CAAC;MACnBP,QAAQ,CAACiB,SAAS,CAAC;MAEnB,MAAMmB,MAAM,GAAG,MAAMvC,gBAAgB,CAACoC,cAAc,CAACrC,SAAS,EAAEyB,IAAI,CAAC;;MAErE;MACA,IAAIa,eAAe,CAACG,MAAM,CAACC,OAAO,EAAE;QAClC,OAAOrB,SAAS;MAClB;MAEAR,mBAAmB,CAAC2B,MAAM,CAAC;MAC3B,OAAOA,MAAM;IACf,CAAC,CAAC,OAAON,CAAC,EAAE;MACV;MACA,IAAIA,CAAC,YAAYS,KAAK,IAAIT,CAAC,CAACU,IAAI,KAAK,YAAY,EAAE;QACjD,OAAOvB,SAAS;MAClB;MAEA,IAAIa,CAAC,YAAYtC,qBAAqB,EAAE;QACtCQ,QAAQ,CAAC;UACP+B,gBAAgB,EAAED;QACpB,CAAC,CAAC;MACJ,CAAC,MAAM;QACL9B,QAAQ,CAAC;UAAEgC,OAAO,EAAEF;QAAE,CAAC,CAAC;MAC1B;MACA,MAAMA,CAAC;IACT,CAAC,SAAS;MACRvB,aAAa,CAAC,KAAK,CAAC;IACtB;EACF,CAAC,EAAE,CAACV,gBAAgB,EAAED,SAAS,EAAEQ,SAAS,CAAC,CAAC;;EAE5C;EACAX,KAAK,CAACgD,SAAS,CAAC,MAAM;IACpB,OAAO,MAAM;MACX,IAAI/B,kBAAkB,CAACK,OAAO,EAAE;QAC9BL,kBAAkB,CAACK,OAAO,CAACC,KAAK,CAAC,CAAC;MACpC;IACF,CAAC;EACH,CAAC,EAAE,EAAE,CAAC;EAEN,OAAO;IACLJ,WAAW;IACXqB,cAAc;IACdlC,KAAK;IACLG,IAAI;IACJE,SAAS;IACTE,YAAY;IACZE;EACF,CAAC;AACH","ignoreList":[]}
|
|
@@ -75,7 +75,7 @@ export function useOsdkAggregation(type, {
|
|
|
75
75
|
}, [observableClient, type.apiName]);
|
|
76
76
|
return {
|
|
77
77
|
data: payload?.result,
|
|
78
|
-
isLoading: payload?.status === "loading",
|
|
78
|
+
isLoading: payload?.status === "loading" || payload?.status === "init" || !payload,
|
|
79
79
|
error,
|
|
80
80
|
refetch
|
|
81
81
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useOsdkAggregation.js","names":["React","makeExternalStore","OsdkContext2","useOsdkAggregation","type","where","withProperties","aggregate","dedupeIntervalMs","observableClient","useContext","canonWhere","canonicalizeWhereClause","stableWithProperties","useMemo","JSON","stringify","stableAggregate","subscribe","getSnapShot","observer","observeAggregation","dedupeInterval","process","env","NODE_ENV","apiName","payload","useSyncExternalStore","error","status","Error","refetch","useCallback","invalidateObjectType","data","result","isLoading"],"sources":["useOsdkAggregation.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 AggregateOpts,\n AggregationsResults,\n DerivedProperty,\n WhereClause,\n} from \"@osdk/api\";\nimport type {
|
|
1
|
+
{"version":3,"file":"useOsdkAggregation.js","names":["React","makeExternalStore","OsdkContext2","useOsdkAggregation","type","where","withProperties","aggregate","dedupeIntervalMs","observableClient","useContext","canonWhere","canonicalizeWhereClause","stableWithProperties","useMemo","JSON","stringify","stableAggregate","subscribe","getSnapShot","observer","observeAggregation","dedupeInterval","process","env","NODE_ENV","apiName","payload","useSyncExternalStore","error","status","Error","refetch","useCallback","invalidateObjectType","data","result","isLoading"],"sources":["useOsdkAggregation.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 AggregateOpts,\n AggregationsResults,\n DerivedProperty,\n ObjectOrInterfaceDefinition,\n SimplePropertyDef,\n WhereClause,\n} from \"@osdk/api\";\nimport type { ObserveAggregationArgs } from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { makeExternalStore } from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\nexport interface UseOsdkAggregationOptions<\n T extends ObjectOrInterfaceDefinition,\n A extends AggregateOpts<T>,\n RDPs extends Record<string, SimplePropertyDef> = {},\n> {\n /**\n * Standard OSDK Where clause to filter objects before aggregation\n */\n where?: WhereClause<T, RDPs>;\n\n /**\n * Define derived properties (RDPs) to be computed server-side.\n * The derived properties can be used in the where clause and aggregation groupBy/select.\n */\n withProperties?: { [K in keyof RDPs]: DerivedProperty.Creator<T, RDPs[K]> };\n\n /**\n * Aggregation options including groupBy and select\n */\n aggregate: A;\n\n /**\n * The number of milliseconds to wait after the last observed aggregation change.\n *\n * Two uses of `useOsdkAggregation` with the same parameters will only trigger one\n * network request if the second is within `dedupeIntervalMs`.\n */\n dedupeIntervalMs?: number;\n}\n\nexport interface UseOsdkAggregationResult<\n T extends ObjectOrInterfaceDefinition,\n A extends AggregateOpts<T>,\n> {\n data: AggregationsResults<T, A> | undefined;\n isLoading: boolean;\n error: Error | undefined;\n refetch: () => void;\n}\n\ndeclare const process: {\n env: {\n NODE_ENV: \"development\" | \"production\";\n };\n};\n\n/**\n * React hook for performing aggregations on OSDK object sets.\n *\n * Executes server-side aggregations with groupBy and metric calculations on filtered object sets.\n * Supports runtime derived properties and where clauses.\n *\n * @param type - The object or interface type to aggregate\n * @param options - Aggregation configuration including where clause, aggregation spec, and optional derived properties\n * @returns Object containing aggregation results, loading state, error state, and refetch function\n *\n * @example\n * ```tsx\n * const { data, isLoading, error } = useOsdkAggregation(Employee, {\n * where: { department: \"Engineering\" },\n * aggregate: {\n * groupBy: { department: \"exact\" },\n * select: {\n * avgSalary: { $avg: \"salary\" },\n * count: { $count: {} }\n * }\n * }\n * });\n * ```\n */\nexport function useOsdkAggregation<\n Q extends ObjectOrInterfaceDefinition,\n const A extends AggregateOpts<Q>,\n RDPs extends Record<string, SimplePropertyDef> = {},\n>(\n type: Q,\n {\n where = {},\n withProperties,\n aggregate,\n dedupeIntervalMs,\n }: UseOsdkAggregationOptions<Q, A, RDPs>,\n): UseOsdkAggregationResult<Q, A> {\n const { observableClient } = React.useContext(OsdkContext2);\n\n const canonWhere = observableClient.canonicalizeWhereClause<Q>(where ?? {});\n\n const stableWithProperties = React.useMemo(\n () => withProperties,\n [JSON.stringify(withProperties)],\n );\n\n const stableAggregate = React.useMemo(\n () => aggregate,\n [JSON.stringify(aggregate)],\n );\n\n const { subscribe, getSnapShot } = React.useMemo(\n () =>\n makeExternalStore<ObserveAggregationArgs<Q, A>>(\n (observer) =>\n observableClient.observeAggregation(\n {\n type: type,\n where: canonWhere,\n withProperties: stableWithProperties,\n aggregate: stableAggregate,\n dedupeInterval: dedupeIntervalMs ?? 2_000,\n },\n observer,\n ),\n process.env.NODE_ENV !== \"production\"\n ? `aggregation ${type.apiName} ${JSON.stringify(canonWhere)}`\n : void 0,\n ),\n [\n observableClient,\n type.apiName,\n type.type,\n canonWhere,\n stableWithProperties,\n stableAggregate,\n dedupeIntervalMs,\n ],\n );\n\n const payload = React.useSyncExternalStore(subscribe, getSnapShot);\n\n let error: Error | undefined;\n if (payload && \"error\" in payload && payload.error) {\n error = payload.error;\n } else if (payload?.status === \"error\") {\n error = new Error(\"Failed to execute aggregation\");\n }\n\n const refetch = React.useCallback(async () => {\n await observableClient.invalidateObjectType(type.apiName);\n }, [observableClient, type.apiName]);\n\n return {\n data: payload?.result as AggregationsResults<Q, A> | undefined,\n isLoading: payload?.status === \"loading\" || payload?.status === \"init\"\n || !payload,\n error,\n refetch,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAWA,OAAOA,KAAK,MAAM,OAAO;AACzB,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,SAASC,YAAY,QAAQ,mBAAmB;AAgDhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,kBAAkBA,CAKhCC,IAAO,EACP;EACEC,KAAK,GAAG,CAAC,CAAC;EACVC,cAAc;EACdC,SAAS;EACTC;AACqC,CAAC,EACR;EAChC,MAAM;IAAEC;EAAiB,CAAC,GAAGT,KAAK,CAACU,UAAU,CAACR,YAAY,CAAC;EAE3D,MAAMS,UAAU,GAAGF,gBAAgB,CAACG,uBAAuB,CAAIP,KAAK,IAAI,CAAC,CAAC,CAAC;EAE3E,MAAMQ,oBAAoB,GAAGb,KAAK,CAACc,OAAO,CACxC,MAAMR,cAAc,EACpB,CAACS,IAAI,CAACC,SAAS,CAACV,cAAc,CAAC,CACjC,CAAC;EAED,MAAMW,eAAe,GAAGjB,KAAK,CAACc,OAAO,CACnC,MAAMP,SAAS,EACf,CAACQ,IAAI,CAACC,SAAS,CAACT,SAAS,CAAC,CAC5B,CAAC;EAED,MAAM;IAAEW,SAAS;IAAEC;EAAY,CAAC,GAAGnB,KAAK,CAACc,OAAO,CAC9C,MACEb,iBAAiB,CACdmB,QAAQ,IACPX,gBAAgB,CAACY,kBAAkB,CACjC;IACEjB,IAAI,EAAEA,IAAI;IACVC,KAAK,EAAEM,UAAU;IACjBL,cAAc,EAAEO,oBAAoB;IACpCN,SAAS,EAAEU,eAAe;IAC1BK,cAAc,EAAEd,gBAAgB,IAAI;EACtC,CAAC,EACDY,QACF,CAAC,EACHG,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,GACjC,eAAerB,IAAI,CAACsB,OAAO,IAAIX,IAAI,CAACC,SAAS,CAACL,UAAU,CAAC,EAAE,GAC3D,KAAK,CACX,CAAC,EACH,CACEF,gBAAgB,EAChBL,IAAI,CAACsB,OAAO,EACZtB,IAAI,CAACA,IAAI,EACTO,UAAU,EACVE,oBAAoB,EACpBI,eAAe,EACfT,gBAAgB,CAEpB,CAAC;EAED,MAAMmB,OAAO,GAAG3B,KAAK,CAAC4B,oBAAoB,CAACV,SAAS,EAAEC,WAAW,CAAC;EAElE,IAAIU,KAAwB;EAC5B,IAAIF,OAAO,IAAI,OAAO,IAAIA,OAAO,IAAIA,OAAO,CAACE,KAAK,EAAE;IAClDA,KAAK,GAAGF,OAAO,CAACE,KAAK;EACvB,CAAC,MAAM,IAAIF,OAAO,EAAEG,MAAM,KAAK,OAAO,EAAE;IACtCD,KAAK,GAAG,IAAIE,KAAK,CAAC,+BAA+B,CAAC;EACpD;EAEA,MAAMC,OAAO,GAAGhC,KAAK,CAACiC,WAAW,CAAC,YAAY;IAC5C,MAAMxB,gBAAgB,CAACyB,oBAAoB,CAAC9B,IAAI,CAACsB,OAAO,CAAC;EAC3D,CAAC,EAAE,CAACjB,gBAAgB,EAAEL,IAAI,CAACsB,OAAO,CAAC,CAAC;EAEpC,OAAO;IACLS,IAAI,EAAER,OAAO,EAAES,MAA+C;IAC9DC,SAAS,EAAEV,OAAO,EAAEG,MAAM,KAAK,SAAS,IAAIH,OAAO,EAAEG,MAAM,KAAK,MAAM,IACjE,CAACH,OAAO;IACbE,KAAK;IACLG;EACF,CAAC;AACH","ignoreList":[]}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright 2025 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 React from "react";
|
|
18
|
+
import { makeExternalStore } from "./makeExternalStore.js";
|
|
19
|
+
import { OsdkContext2 } from "./OsdkContext2.js";
|
|
20
|
+
/**
|
|
21
|
+
* React hook for executing and observing OSDK functions.
|
|
22
|
+
*
|
|
23
|
+
* Provides automatic caching, deduplication, and reactive updates for function calls.
|
|
24
|
+
* Functions are automatically re-fetched when dependencies change (configured via options).
|
|
25
|
+
*
|
|
26
|
+
* @param queryDef - The QueryDefinition to execute
|
|
27
|
+
* @param options - Configuration options for the function call
|
|
28
|
+
* @returns Object containing result, loading state, error, and refetch function
|
|
29
|
+
*
|
|
30
|
+
* @example Basic usage
|
|
31
|
+
* ```tsx
|
|
32
|
+
* const { data, isLoading, error } = useOsdkFunction(getEmployeeStats, {
|
|
33
|
+
* params: { departmentId: "engineering" }
|
|
34
|
+
* });
|
|
35
|
+
* ```
|
|
36
|
+
*
|
|
37
|
+
* @example With dependency tracking
|
|
38
|
+
* ```tsx
|
|
39
|
+
* const { data, refetch } = useOsdkFunction(calculateMetrics, {
|
|
40
|
+
* params: { startDate, endDate },
|
|
41
|
+
* dependsOn: [Employee, Project],
|
|
42
|
+
* });
|
|
43
|
+
* ```
|
|
44
|
+
*
|
|
45
|
+
* @example With specific object dependencies
|
|
46
|
+
* ```tsx
|
|
47
|
+
* const { data } = useOsdkFunction(getEmployeeReport, {
|
|
48
|
+
* params: { employeeId: employee.$primaryKey },
|
|
49
|
+
* dependsOnObjects: [employee],
|
|
50
|
+
* });
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
export function useOsdkFunction(queryDef, options = {}) {
|
|
54
|
+
const {
|
|
55
|
+
observableClient
|
|
56
|
+
} = React.useContext(OsdkContext2);
|
|
57
|
+
const {
|
|
58
|
+
params,
|
|
59
|
+
dependsOn,
|
|
60
|
+
dependsOnObjects,
|
|
61
|
+
dedupeIntervalMs,
|
|
62
|
+
enabled = true
|
|
63
|
+
} = options;
|
|
64
|
+
const stableParams = React.useMemo(() => params, [JSON.stringify(params)]);
|
|
65
|
+
const stableDependsOn = React.useMemo(() => dependsOn, [JSON.stringify(dependsOn?.map(d => typeof d === "string" ? d : d.apiName))]);
|
|
66
|
+
const stableDependsOnObjects = React.useMemo(() => dependsOnObjects, [JSON.stringify(dependsOnObjects?.map(o => ({
|
|
67
|
+
$apiName: o.$apiName,
|
|
68
|
+
$primaryKey: o.$primaryKey
|
|
69
|
+
})))]);
|
|
70
|
+
|
|
71
|
+
// Record<string, unknown> required as typing is figured out at runtime
|
|
72
|
+
const paramsForApi = stableParams;
|
|
73
|
+
const {
|
|
74
|
+
subscribe,
|
|
75
|
+
getSnapShot
|
|
76
|
+
} = React.useMemo(() => {
|
|
77
|
+
if (!enabled) {
|
|
78
|
+
return makeExternalStore(() => ({
|
|
79
|
+
unsubscribe: () => {}
|
|
80
|
+
}), process.env.NODE_ENV !== "production" ? `function ${queryDef.apiName} ${JSON.stringify(stableParams)} [DISABLED]` : void 0);
|
|
81
|
+
}
|
|
82
|
+
return makeExternalStore(observer => observableClient.observeFunction(queryDef, paramsForApi, {
|
|
83
|
+
dependsOn: stableDependsOn,
|
|
84
|
+
dependsOnObjects: stableDependsOnObjects,
|
|
85
|
+
dedupeInterval: dedupeIntervalMs ?? 2_000
|
|
86
|
+
}, observer), process.env.NODE_ENV !== "production" ? `function ${queryDef.apiName} ${JSON.stringify(stableParams)}` : void 0);
|
|
87
|
+
}, [observableClient, queryDef.apiName, queryDef.version, paramsForApi, stableDependsOn, stableDependsOnObjects, dedupeIntervalMs, enabled]);
|
|
88
|
+
const payload = React.useSyncExternalStore(subscribe, getSnapShot);
|
|
89
|
+
const error = payload?.error ?? (payload?.status === "error" ? new Error("Failed to execute function") : undefined);
|
|
90
|
+
const refetch = React.useCallback(() => {
|
|
91
|
+
void observableClient.invalidateFunction(queryDef, paramsForApi);
|
|
92
|
+
}, [observableClient, queryDef, paramsForApi]);
|
|
93
|
+
return {
|
|
94
|
+
data: payload?.result,
|
|
95
|
+
isLoading: payload?.status === "loading",
|
|
96
|
+
error,
|
|
97
|
+
lastUpdated: payload?.lastUpdated ?? 0,
|
|
98
|
+
refetch
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
//# sourceMappingURL=useOsdkFunction.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useOsdkFunction.js","names":["React","makeExternalStore","OsdkContext2","useOsdkFunction","queryDef","options","observableClient","useContext","params","dependsOn","dependsOnObjects","dedupeIntervalMs","enabled","stableParams","useMemo","JSON","stringify","stableDependsOn","map","d","apiName","stableDependsOnObjects","o","$apiName","$primaryKey","paramsForApi","subscribe","getSnapShot","unsubscribe","process","env","NODE_ENV","observer","observeFunction","dedupeInterval","version","payload","useSyncExternalStore","error","status","Error","undefined","refetch","useCallback","invalidateFunction","data","result","isLoading","lastUpdated"],"sources":["useOsdkFunction.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 CompileTimeMetadata,\n ObjectTypeDefinition,\n Osdk,\n QueryDefinition,\n} from \"@osdk/api\";\nimport type {\n ObserveFunctionCallbackArgs,\n QueryParameterType,\n QueryReturnType,\n} from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { makeExternalStore } from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\nexport interface UseOsdkFunctionOptions<Q extends QueryDefinition<unknown>> {\n /**\n * Parameters to pass to the function.\n * Must include all required parameters; optional parameters can be omitted.\n */\n params?: CompileTimeMetadata<Q>[\"parameters\"] extends Record<string, never>\n ? undefined\n : QueryParameterType<CompileTimeMetadata<Q>[\"parameters\"]>;\n\n /**\n * Object types this function depends on.\n * When actions modify objects of these types, the function will automatically refetch.\n *\n * @example\n * ```tsx\n * // Refetch when any Employee object changes\n * { dependsOn: [Employee] }\n * ```\n */\n dependsOn?: Array<ObjectTypeDefinition | string>;\n\n /**\n * Specific object instances this function depends on.\n * When any of these specific objects change, the function will refetch.\n * More fine-grained than dependsOn for precise invalidation control.\n *\n * @example\n * ```tsx\n * // Refetch when this specific employee changes\n * { dependsOnObjects: [employee] }\n * ```\n */\n dependsOnObjects?: Array<Osdk.Instance<ObjectTypeDefinition>>;\n\n /**\n * The number of milliseconds to dedupe identical function calls.\n * Two calls with the same function and params will share results\n * if the second call is within this interval of the first.\n * @default 2000\n */\n dedupeIntervalMs?: number;\n\n /**\n * Whether to enable the query. When false, the query will not execute.\n * Useful for:\n * - Dependent queries that need to wait for other data\n * - Conditional queries based on component state\n *\n * @default true\n * @example\n * // Dependent query - wait for required data\n * const { data: employee } = useOsdkObject(Employee, employeeId);\n * const { data: report } = useOsdkFunction(getEmployeeReport, {\n * params: { employeeId: employee?.$primaryKey },\n * enabled: !!employee\n * });\n */\n enabled?: boolean;\n}\n\nexport interface UseOsdkFunctionResult<Q extends QueryDefinition<unknown>> {\n /**\n * The function result, or undefined if not yet loaded or on error.\n */\n data: QueryReturnType<CompileTimeMetadata<Q>[\"output\"]> | undefined;\n\n /**\n * True while the function is executing.\n */\n isLoading: boolean;\n\n /**\n * Error if the function execution failed.\n */\n error: Error | undefined;\n\n /**\n * Timestamp (ms since epoch) of when the result was last fetched.\n */\n lastUpdated: number;\n\n /**\n * Manually refetch the function.\n * Useful for \"pull to refresh\" or retry patterns.\n */\n refetch: () => void;\n}\n\ndeclare const process: {\n env: {\n NODE_ENV: \"development\" | \"production\";\n };\n};\n\n/**\n * React hook for executing and observing OSDK functions.\n *\n * Provides automatic caching, deduplication, and reactive updates for function calls.\n * Functions are automatically re-fetched when dependencies change (configured via options).\n *\n * @param queryDef - The QueryDefinition to execute\n * @param options - Configuration options for the function call\n * @returns Object containing result, loading state, error, and refetch function\n *\n * @example Basic usage\n * ```tsx\n * const { data, isLoading, error } = useOsdkFunction(getEmployeeStats, {\n * params: { departmentId: \"engineering\" }\n * });\n * ```\n *\n * @example With dependency tracking\n * ```tsx\n * const { data, refetch } = useOsdkFunction(calculateMetrics, {\n * params: { startDate, endDate },\n * dependsOn: [Employee, Project],\n * });\n * ```\n *\n * @example With specific object dependencies\n * ```tsx\n * const { data } = useOsdkFunction(getEmployeeReport, {\n * params: { employeeId: employee.$primaryKey },\n * dependsOnObjects: [employee],\n * });\n * ```\n */\nexport function useOsdkFunction<Q extends QueryDefinition<unknown>>(\n queryDef: Q,\n options: UseOsdkFunctionOptions<Q> = {},\n): UseOsdkFunctionResult<Q> {\n const { observableClient } = React.useContext(OsdkContext2);\n const {\n params,\n dependsOn,\n dependsOnObjects,\n dedupeIntervalMs,\n enabled = true,\n } = options;\n\n const stableParams = React.useMemo(\n () => params,\n [JSON.stringify(params)],\n );\n const stableDependsOn = React.useMemo(\n () => dependsOn,\n [JSON.stringify(\n dependsOn?.map(d => typeof d === \"string\" ? d : d.apiName),\n )],\n );\n const stableDependsOnObjects = React.useMemo(\n () => dependsOnObjects,\n [JSON.stringify(\n dependsOnObjects?.map(o => ({\n $apiName: o.$apiName,\n $primaryKey: o.$primaryKey,\n })),\n )],\n );\n\n // Record<string, unknown> required as typing is figured out at runtime\n const paramsForApi = stableParams as Record<string, unknown> | undefined;\n\n const { subscribe, getSnapShot } = React.useMemo(\n () => {\n if (!enabled) {\n return makeExternalStore<ObserveFunctionCallbackArgs<Q>>(\n () => ({ unsubscribe: () => {} }),\n process.env.NODE_ENV !== \"production\"\n ? `function ${queryDef.apiName} ${\n JSON.stringify(stableParams)\n } [DISABLED]`\n : void 0,\n );\n }\n return makeExternalStore<ObserveFunctionCallbackArgs<Q>>(\n (observer) =>\n observableClient.observeFunction(\n queryDef,\n paramsForApi,\n {\n dependsOn: stableDependsOn,\n dependsOnObjects: stableDependsOnObjects,\n dedupeInterval: dedupeIntervalMs ?? 2_000,\n },\n observer,\n ),\n process.env.NODE_ENV !== \"production\"\n ? `function ${queryDef.apiName} ${JSON.stringify(stableParams)}`\n : void 0,\n );\n },\n [\n observableClient,\n queryDef.apiName,\n queryDef.version,\n paramsForApi,\n stableDependsOn,\n stableDependsOnObjects,\n dedupeIntervalMs,\n enabled,\n ],\n );\n\n const payload = React.useSyncExternalStore(subscribe, getSnapShot);\n\n const error = payload?.error\n ?? (payload?.status === \"error\"\n ? new Error(\"Failed to execute function\")\n : undefined);\n\n const refetch = React.useCallback(() => {\n void observableClient.invalidateFunction(queryDef, paramsForApi);\n }, [observableClient, queryDef, paramsForApi]);\n\n return {\n data: payload?.result as\n | QueryReturnType<CompileTimeMetadata<Q>[\"output\"]>\n | undefined,\n isLoading: payload?.status === \"loading\",\n error,\n lastUpdated: payload?.lastUpdated ?? 0,\n refetch,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAaA,OAAOA,KAAK,MAAM,OAAO;AACzB,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,SAASC,YAAY,QAAQ,mBAAmB;AAgGhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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KAAK,SAAS;IACxCD,KAAK;IACLU,WAAW,EAAEZ,OAAO,EAAEY,WAAW,IAAI,CAAC;IACtCN;EACF,CAAC;AACH","ignoreList":[]}
|
|
@@ -73,7 +73,7 @@ export function useOsdkObject(...args) {
|
|
|
73
73
|
}
|
|
74
74
|
return {
|
|
75
75
|
object: payload?.object,
|
|
76
|
-
isLoading: payload?.status === "loading",
|
|
76
|
+
isLoading: enabled ? payload?.status === "loading" || payload?.status === "init" || !payload : false,
|
|
77
77
|
isOptimistic: !!payload?.isOptimistic,
|
|
78
78
|
error,
|
|
79
79
|
forceUpdate: () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useOsdkObject.js","names":["React","makeExternalStore","OsdkContext2","useOsdkObject","args","observableClient","useContext","isInstanceSignature","enabled","mode","undefined","objectType","$objectType","apiName","primaryKey","$primaryKey","subscribe","getSnapShot","useMemo","unsubscribe","observer","observeObject","payload","useSyncExternalStore","error","status","Error","object","isLoading","isOptimistic","forceUpdate"],"sources":["useOsdkObject.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 { ObjectTypeDefinition, Osdk, PrimaryKeyType } from \"@osdk/api\";\nimport type {
|
|
1
|
+
{"version":3,"file":"useOsdkObject.js","names":["React","makeExternalStore","OsdkContext2","useOsdkObject","args","observableClient","useContext","isInstanceSignature","enabled","mode","undefined","objectType","$objectType","apiName","primaryKey","$primaryKey","subscribe","getSnapShot","useMemo","unsubscribe","observer","observeObject","payload","useSyncExternalStore","error","status","Error","object","isLoading","isOptimistic","forceUpdate"],"sources":["useOsdkObject.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 { ObjectTypeDefinition, Osdk, PrimaryKeyType } from \"@osdk/api\";\nimport type { ObserveObjectCallbackArgs } from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { makeExternalStore } from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\nexport interface UseOsdkObjectResult<Q extends ObjectTypeDefinition> {\n object: Osdk.Instance<Q> | undefined;\n isLoading: boolean;\n\n error: Error | undefined;\n\n /**\n * Refers to whether the object is optimistic or not.\n */\n isOptimistic: boolean;\n forceUpdate: () => void;\n}\n\n/**\n * @param obj an existing `Osdk.Instance` object to get metadata for.\n * @param enabled Enable or disable the query (defaults to true)\n */\nexport function useOsdkObject<Q extends ObjectTypeDefinition>(\n obj: Osdk.Instance<Q>,\n enabled?: boolean,\n): UseOsdkObjectResult<Q>;\n/**\n * Loads an object by type and primary key.\n *\n * @param type\n * @param primaryKey\n * @param enabled Enable or disable the query (defaults to true)\n */\nexport function useOsdkObject<Q extends ObjectTypeDefinition>(\n type: Q,\n primaryKey: PrimaryKeyType<Q>,\n enabled?: boolean,\n): UseOsdkObjectResult<Q>;\n/*\n Implementation of useOsdkObject\n */\nexport function useOsdkObject<Q extends ObjectTypeDefinition>(\n ...args:\n | [obj: Osdk.Instance<Q>, enabled?: boolean]\n | [type: Q, primaryKey: PrimaryKeyType<Q>, enabled?: boolean]\n): UseOsdkObjectResult<Q> {\n const { observableClient } = React.useContext(OsdkContext2);\n\n // Check if first arg is an instance to discriminate signatures\n // TypeScript cannot narrow rest parameter unions with optional parameters,\n // so we must use type assertions after runtime discrimination\n const isInstanceSignature = \"$objectType\" in args[0];\n\n // Extract enabled flag - 2nd param for instance signature, 3rd for type signature\n const enabled = isInstanceSignature\n ? (typeof args[1] === \"boolean\" ? args[1] : true)\n : (typeof args[2] === \"boolean\" ? args[2] : true);\n\n // TODO: Figure out what the correct default behavior is for the various scenarios\n const mode = isInstanceSignature ? \"offline\" : undefined;\n const objectType = isInstanceSignature\n ? (args[0] as Osdk.Instance<Q>).$objectType\n : (args[0] as Q).apiName;\n const primaryKey = isInstanceSignature\n ? (args[0] as Osdk.Instance<Q>).$primaryKey\n : (args[1] as PrimaryKeyType<Q>);\n\n const { subscribe, getSnapShot } = React.useMemo(\n () => {\n if (!enabled) {\n return makeExternalStore<ObserveObjectCallbackArgs<Q>>(\n () => ({ unsubscribe: () => {} }),\n `object ${objectType} ${primaryKey} [DISABLED]`,\n );\n }\n return makeExternalStore<ObserveObjectCallbackArgs<Q>>(\n (observer) =>\n observableClient.observeObject(\n objectType,\n primaryKey,\n {\n mode,\n },\n observer,\n ),\n `object ${objectType} ${primaryKey}`,\n );\n },\n [enabled, observableClient, objectType, primaryKey, mode],\n );\n\n const payload = React.useSyncExternalStore(subscribe, getSnapShot);\n\n let error: Error | undefined;\n if (payload && \"error\" in payload && payload.error) {\n error = payload.error;\n } else if (payload?.status === \"error\") {\n error = new Error(\"Failed to load object\");\n }\n\n return {\n object: payload?.object as Osdk.Instance<Q> | undefined,\n isLoading: enabled\n ? (payload?.status === \"loading\" || payload?.status === \"init\"\n || !payload)\n : false,\n isOptimistic: !!payload?.isOptimistic,\n error,\n forceUpdate: () => {\n throw new Error(\"not implemented\");\n },\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA,OAAOA,KAAK,MAAM,OAAO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ACVG,UAAU,EACV;MACEL;IACF,CAAC,EACDW,QACF,CAAC,EACH,UAAUT,UAAU,IAAIG,UAAU,EACpC,CAAC;EACH,CAAC,EACD,CAACN,OAAO,EAAEH,gBAAgB,EAAEM,UAAU,EAAEG,UAAU,EAAEL,IAAI,CAC1D,CAAC;EAED,MAAMa,OAAO,GAAGtB,KAAK,CAACuB,oBAAoB,CAACP,SAAS,EAAEC,WAAW,CAAC;EAElE,IAAIO,KAAwB;EAC5B,IAAIF,OAAO,IAAI,OAAO,IAAIA,OAAO,IAAIA,OAAO,CAACE,KAAK,EAAE;IAClDA,KAAK,GAAGF,OAAO,CAACE,KAAK;EACvB,CAAC,MAAM,IAAIF,OAAO,EAAEG,MAAM,KAAK,OAAO,EAAE;IACtCD,KAAK,GAAG,IAAIE,KAAK,CAAC,uBAAuB,CAAC;EAC5C;EAEA,OAAO;IACLC,MAAM,EAAEL,OAAO,EAAEK,MAAsC;IACvDC,SAAS,EAAEpB,OAAO,GACbc,OAAO,EAAEG,MAAM,KAAK,SAAS,IAAIH,OAAO,EAAEG,MAAM,KAAK,MAAM,IACzD,CAACH,OAAO,GACX,KAAK;IACTO,YAAY,EAAE,CAAC,CAACP,OAAO,EAAEO,YAAY;IACrCL,KAAK;IACLM,WAAW,EAAEA,CAAA,KAAM;MACjB,MAAM,IAAIJ,KAAK,CAAC,iBAAiB,CAAC;IACpC;EACF,CAAC;AACH","ignoreList":[]}
|
|
@@ -76,11 +76,12 @@ export function useOsdkObjects(type, options) {
|
|
|
76
76
|
error = new Error("Failed to load objects");
|
|
77
77
|
}
|
|
78
78
|
return {
|
|
79
|
-
fetchMore: listPayload?.fetchMore,
|
|
79
|
+
fetchMore: listPayload?.hasMore ? listPayload.fetchMore : undefined,
|
|
80
80
|
error,
|
|
81
81
|
data: listPayload?.resolvedList,
|
|
82
|
-
isLoading: listPayload?.status === "loading",
|
|
83
|
-
isOptimistic: listPayload?.isOptimistic ?? false
|
|
82
|
+
isLoading: enabled ? listPayload?.status === "loading" || listPayload?.status === "init" || !listPayload : false,
|
|
83
|
+
isOptimistic: listPayload?.isOptimistic ?? false,
|
|
84
|
+
totalCount: listPayload?.totalCount
|
|
84
85
|
};
|
|
85
86
|
}
|
|
86
87
|
//# sourceMappingURL=useOsdkObjects.js.map
|