@osdk/react 0.10.0-beta.4 → 0.10.0-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/build/browser/intellisense.test.helpers/useOsdkObjectsWithRids.js +37 -0
- package/build/browser/intellisense.test.helpers/useOsdkObjectsWithRids.js.map +1 -0
- package/build/browser/intellisense.test.js +24 -0
- package/build/browser/intellisense.test.js.map +1 -1
- package/build/browser/new/makeExternalStore.js +61 -0
- package/build/browser/new/makeExternalStore.js.map +1 -1
- package/build/browser/new/useLinks.js +2 -2
- package/build/browser/new/useLinks.js.map +1 -1
- package/build/browser/new/useObjectSet.js +4 -3
- package/build/browser/new/useObjectSet.js.map +1 -1
- package/build/browser/new/useOsdkAction.js +2 -2
- package/build/browser/new/useOsdkAction.js.map +1 -1
- package/build/browser/new/useOsdkAggregation.js +63 -27
- package/build/browser/new/useOsdkAggregation.js.map +1 -1
- package/build/browser/new/useOsdkFunction.js +10 -8
- package/build/browser/new/useOsdkFunction.js.map +1 -1
- package/build/browser/new/useOsdkObject.js +26 -24
- package/build/browser/new/useOsdkObject.js.map +1 -1
- package/build/browser/new/useOsdkObjects.js +16 -14
- package/build/browser/new/useOsdkObjects.js.map +1 -1
- package/build/cjs/public/experimental.cjs +161 -72
- package/build/cjs/public/experimental.cjs.map +1 -1
- package/build/cjs/public/experimental.d.cts +43 -11
- package/build/esm/intellisense.test.helpers/useOsdkObjectsWithRids.js +37 -0
- package/build/esm/intellisense.test.helpers/useOsdkObjectsWithRids.js.map +1 -0
- package/build/esm/intellisense.test.js +24 -0
- package/build/esm/intellisense.test.js.map +1 -1
- package/build/esm/new/makeExternalStore.js +61 -0
- package/build/esm/new/makeExternalStore.js.map +1 -1
- package/build/esm/new/useLinks.js +2 -2
- package/build/esm/new/useLinks.js.map +1 -1
- package/build/esm/new/useObjectSet.js +4 -3
- package/build/esm/new/useObjectSet.js.map +1 -1
- package/build/esm/new/useOsdkAction.js +2 -2
- package/build/esm/new/useOsdkAction.js.map +1 -1
- package/build/esm/new/useOsdkAggregation.js +63 -27
- package/build/esm/new/useOsdkAggregation.js.map +1 -1
- package/build/esm/new/useOsdkFunction.js +10 -8
- package/build/esm/new/useOsdkFunction.js.map +1 -1
- package/build/esm/new/useOsdkObject.js +26 -24
- package/build/esm/new/useOsdkObject.js.map +1 -1
- package/build/esm/new/useOsdkObjects.js +16 -14
- package/build/esm/new/useOsdkObjects.js.map +1 -1
- package/build/types/intellisense.test.helpers/useOsdkObjectsWithRids.d.ts +1 -0
- package/build/types/intellisense.test.helpers/useOsdkObjectsWithRids.d.ts.map +1 -0
- package/build/types/new/makeExternalStore.d.ts +11 -0
- package/build/types/new/makeExternalStore.d.ts.map +1 -1
- package/build/types/new/useObjectSet.d.ts.map +1 -1
- package/build/types/new/useOsdkAggregation.d.ts +41 -3
- package/build/types/new/useOsdkAggregation.d.ts.map +1 -1
- package/build/types/new/useOsdkObject.d.ts +7 -7
- package/build/types/new/useOsdkObject.d.ts.map +1 -1
- package/build/types/new/useOsdkObjects.d.ts +16 -2
- package/build/types/new/useOsdkObjects.d.ts.map +1 -1
- package/package.json +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,34 @@
|
|
|
1
1
|
# @osdkkit/react
|
|
2
2
|
|
|
3
|
+
## 0.10.0-beta.6
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 993c023: ObjectTable supports objectSet input
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [8825f8c]
|
|
12
|
+
- @osdk/client@2.8.0-beta.12
|
|
13
|
+
- @osdk/api@2.8.0-beta.12
|
|
14
|
+
|
|
15
|
+
## 0.10.0-beta.5
|
|
16
|
+
|
|
17
|
+
### Minor Changes
|
|
18
|
+
|
|
19
|
+
- 525f277: update useOsdkAggregation to support composed object sets, async
|
|
20
|
+
- d80c234: add interface support to useOsdkObject
|
|
21
|
+
- 996d8e4: memoize hook responses
|
|
22
|
+
|
|
23
|
+
### Patch Changes
|
|
24
|
+
|
|
25
|
+
- Updated dependencies [642be5f]
|
|
26
|
+
- Updated dependencies [525f277]
|
|
27
|
+
- Updated dependencies [f5f95e2]
|
|
28
|
+
- Updated dependencies [d80c234]
|
|
29
|
+
- @osdk/client@2.8.0-beta.11
|
|
30
|
+
- @osdk/api@2.8.0-beta.11
|
|
31
|
+
|
|
3
32
|
## 0.10.0-beta.4
|
|
4
33
|
|
|
5
34
|
### Minor Changes
|
|
@@ -0,0 +1,37 @@
|
|
|
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
|
+
// WARNING!
|
|
18
|
+
// WARNING!
|
|
19
|
+
// This file is used for tests that check intellisense. Editing this file by hand will likely
|
|
20
|
+
// break tests that have hard coded line numbers and line offsets.
|
|
21
|
+
|
|
22
|
+
import { Employee } from "@osdk/client.test.ontology";
|
|
23
|
+
import { useOsdkObjects } from "@osdk/react/experimental";
|
|
24
|
+
function TestComponent() {
|
|
25
|
+
const {
|
|
26
|
+
data: ridsData
|
|
27
|
+
} = useOsdkObjects(Employee, {
|
|
28
|
+
rids: ["ri.foo.123"]
|
|
29
|
+
});
|
|
30
|
+
ridsData?.[0];
|
|
31
|
+
const {
|
|
32
|
+
data: noRidsData
|
|
33
|
+
} = useOsdkObjects(Employee);
|
|
34
|
+
noRidsData?.[0];
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
//# sourceMappingURL=useOsdkObjectsWithRids.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useOsdkObjectsWithRids.js","names":["Employee","useOsdkObjects","TestComponent","data","ridsData","rids","noRidsData"],"sources":["useOsdkObjectsWithRids.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\n// WARNING!\n// WARNING!\n// This file is used for tests that check intellisense. Editing this file by hand will likely\n// break tests that have hard coded line numbers and line offsets.\n\nimport { Employee } from \"@osdk/client.test.ontology\";\nimport { useOsdkObjects } from \"@osdk/react/experimental\";\n\nfunction TestComponent() {\n const { data: ridsData } = useOsdkObjects(Employee, {\n rids: [\"ri.foo.123\"],\n });\n\n const ridsItem = ridsData?.[0];\n\n const { data: noRidsData } = useOsdkObjects(Employee);\n\n const noRidsItem = noRidsData?.[0];\n\n return null;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,SAASA,QAAQ,QAAQ,4BAA4B;AACrD,SAASC,cAAc,QAAQ,0BAA0B;AAEzD,SAASC,aAAaA,CAAA,EAAG;EACvB,MAAM;IAAEC,IAAI,EAAEC;EAAS,CAAC,GAAGH,cAAc,CAACD,QAAQ,EAAE;IAClDK,IAAI,EAAE,CAAC,YAAY;EACrB,CAAC,CAAC;EAEeD,QAAQ,GAAG,CAAC,CAAC;EAE9B,MAAM;IAAED,IAAI,EAAEG;EAAW,CAAC,GAAGL,cAAc,CAACD,QAAQ,CAAC;EAElCM,UAAU,GAAG,CAAC,CAAC;EAElC,OAAO,IAAI;AACb","ignoreList":[]}
|
|
@@ -121,6 +121,30 @@ describe("intellisense", () => {
|
|
|
121
121
|
expect(typeResp.body?.displayString).toBeDefined();
|
|
122
122
|
expect(typeResp.body?.displayString).toContain("Employee");
|
|
123
123
|
});
|
|
124
|
+
it("useOsdkObjectsWithRids", {
|
|
125
|
+
timeout: 40_000
|
|
126
|
+
}, async () => {
|
|
127
|
+
expect(ts.sys.fileExists(intellisenseFilePath)).toBeTruthy();
|
|
128
|
+
!tsServer ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
|
|
129
|
+
const {
|
|
130
|
+
resp: ridsResp
|
|
131
|
+
} = await tsServer.sendQuickInfoRequest({
|
|
132
|
+
file: intellisenseFilePath,
|
|
133
|
+
line: 30,
|
|
134
|
+
offset: 9
|
|
135
|
+
});
|
|
136
|
+
expect(ridsResp.body?.displayString).toBeDefined();
|
|
137
|
+
expect(ridsResp.body?.displayString).toContain("$rid");
|
|
138
|
+
const {
|
|
139
|
+
resp: noRidsResp
|
|
140
|
+
} = await tsServer.sendQuickInfoRequest({
|
|
141
|
+
file: intellisenseFilePath,
|
|
142
|
+
line: 34,
|
|
143
|
+
offset: 9
|
|
144
|
+
});
|
|
145
|
+
expect(noRidsResp.body?.displayString).toBeDefined();
|
|
146
|
+
expect(noRidsResp.body?.displayString).not.toContain("$rid");
|
|
147
|
+
});
|
|
124
148
|
it("useOsdkObjectsWithProperties", {
|
|
125
149
|
timeout: 40_000
|
|
126
150
|
}, async () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intellisense.test.js","names":["startTsServer","findUpSync","path","invariant","ts","afterEach","beforeAll","beforeEach","describe","expect","it","vi","rootLogger","hoisted","pino","pinoPretty","EventEmitter","Promise","resolve","level","build","sync","timestampKey","undefined","errorLikeObjectKeys","errorProps","ignore","destination","write","a","at","slice","console","log","packagesDir","reactPackagePath","reactPackageJson","cwd","import","meta","dirname","process","env","NODE_ENV","join","tsServer","intellisenseFilePath","task","name","sys","fileExists","toBeTruthy","sendOpenRequest","file","error","stop","timeout","resp","sendCompletionsRequest","line","offset","triggerKind","CompletionTriggerKind","Invoked","completions","body","entries","map","e","toContain","typeResp","sendQuickInfoRequest","displayString","toBeDefined","dataResp"],"sources":["intellisense.test.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 { Logger } from \"@osdk/api\";\nimport type { TsServer } from \"@osdk/client/internal-node\";\nimport { startTsServer } from \"@osdk/client/internal-node\";\nimport { findUpSync } from \"find-up\";\nimport * as path from \"node:path\";\nimport invariant from \"tiny-invariant\";\nimport * as ts from \"typescript\";\nimport {\n afterEach,\n beforeAll,\n beforeEach,\n describe,\n expect,\n it,\n vi,\n} from \"vitest\";\n\n// it needs to be hoisted because its referenced from our mocked WebSocket\n// which must be hoisted to work\nconst rootLogger = await vi.hoisted(async (): Promise<Logger> => {\n const pino = (await import(\"pino\")).pino;\n const pinoPretty = await import(\"pino-pretty\");\n const { EventEmitter } = await import(\"node:events\");\n class PinoConsoleLogDestination extends EventEmitter {\n write(a: string) {\n // remove trailing newline since console.log adds one\n if (a.at(-1) === \"\\n\") a = a.slice(0, -1);\n\n // This lets the test framework aggregate the logs per test, whereas direct to stdout does not\n console.log(a);\n }\n }\n return Promise.resolve(pino(\n { level: \"info\" },\n (pinoPretty.build)({\n sync: true,\n timestampKey: undefined,\n errorLikeObjectKeys: [\"error\", \"err\", \"exception\"],\n errorProps: \"stack,cause,properties\",\n ignore: \"time,hostname,pid\",\n destination: new PinoConsoleLogDestination(),\n }),\n ));\n});\n\n/**\n * @vitest-environment node\n * @vitest-pool forks\n */\ndescribe(\"intellisense\", () => {\n let packagesDir: string;\n let reactPackagePath: string;\n\n beforeAll(() => {\n const reactPackageJson = findUpSync(\"package.json\", {\n cwd: import.meta.dirname,\n });\n console.log({ reactPackageJson });\n invariant(reactPackageJson != null);\n packagesDir = path.join(\n path.dirname(reactPackageJson),\n \"..\",\n );\n\n reactPackagePath = path.join(packagesDir, \"react\");\n });\n\n let tsServer: TsServer | undefined;\n let intellisenseFilePath: string;\n\n beforeEach(async (a) => {\n intellisenseFilePath = path.join(\n reactPackagePath,\n \"src\",\n \"intellisense.test.helpers\",\n `${a.task.name}.ts`,\n );\n\n console.log(intellisenseFilePath);\n\n expect(ts.sys.fileExists(intellisenseFilePath)).toBeTruthy();\n\n try {\n tsServer = await startTsServer(rootLogger);\n await tsServer.sendOpenRequest({ file: intellisenseFilePath });\n } catch (error) {\n if (tsServer) {\n try {\n tsServer.stop();\n } catch {\n // Ignore cleanup errors\n }\n tsServer = undefined;\n }\n throw error;\n }\n });\n\n afterEach(() => {\n if (tsServer) {\n tsServer.stop();\n tsServer = undefined;\n }\n });\n\n it(\"useOsdkObjectsWithPivot\", { timeout: 40_000 }, async () => {\n expect(ts.sys.fileExists(intellisenseFilePath)).toBeTruthy();\n invariant(tsServer);\n\n const { resp } = await tsServer.sendCompletionsRequest({\n file: intellisenseFilePath,\n line: 29,\n offset: 15,\n triggerKind: ts.CompletionTriggerKind.Invoked,\n });\n\n const completions = resp.body?.entries.map(e => e.name) ?? [];\n expect(completions).toContain(\"lead\");\n\n const { resp: typeResp } = await tsServer.sendQuickInfoRequest({\n file: intellisenseFilePath,\n line: 33,\n offset: 10,\n });\n\n expect(typeResp.body?.displayString).toBeDefined();\n expect(typeResp.body?.displayString).toContain(\"Employee\");\n });\n\n it(\"useOsdkObjectsWithProperties\", { timeout: 40_000 }, async () => {\n expect(ts.sys.fileExists(intellisenseFilePath)).toBeTruthy();\n invariant(tsServer);\n\n const { resp } = await tsServer.sendQuickInfoRequest({\n file: intellisenseFilePath,\n line: 27,\n offset: 10,\n });\n\n expect(resp.body?.displayString).toContain(\"DerivedProperty.Clause\");\n\n const { resp: dataResp } = await tsServer.sendQuickInfoRequest({\n file: intellisenseFilePath,\n line: 31,\n offset: 11,\n });\n\n expect(dataResp.body?.displayString).toBeDefined();\n expect(dataResp.body?.displayString).toContain(\"Osdk.Instance<Employee\");\n });\n});\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA,SAASA,aAAa,QAAQ,4BAA4B;AAC1D,SAASC,UAAU,QAAQ,SAAS;AACpC,OAAO,KAAKC,IAAI,MAAM,WAAW;AACjC,OAAOC,SAAS,MAAM,gBAAgB;AACtC,OAAO,KAAKC,EAAE,MAAM,YAAY;AAChC,SACEC,SAAS,EACTC,SAAS,EACTC,UAAU,EACVC,QAAQ,EACRC,MAAM,EACNC,EAAE,EACFC,EAAE,QACG,QAAQ;;AAEf;AACA;AACA,MAAMC,UAAU,GAAG,MAAMD,EAAE,CAACE,OAAO,CAAC,YAA6B;EAC/D,MAAMC,IAAI,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,EAAEA,IAAI;EACxC,MAAMC,UAAU,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC;EAC9C,MAAM;IAAEC;EAAa,CAAC,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC;EAUpD,OAAOC,OAAO,CAACC,OAAO,CAACJ,IAAI,CACzB;IAAEK,KAAK,EAAE;EAAO,CAAC,EAChBJ,UAAU,CAACK,KAAK,CAAE;IACjBC,IA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,oBAAoB,CAAC;MAC7DlB,IAAI,EAAEP,oBAAoB;MAC1Ba,IAAI,EAAE,EAAE;MACRC,MAAM,EAAE;IACV,CAAC,CAAC;IAEFnD,MAAM,CAACiE,QAAQ,CAACT,IAAI,EAAEO,aAAa,CAAC,CAACC,WAAW,CAAC,CAAC;IAClDhE,MAAM,CAACiE,QAAQ,CAACT,IAAI,EAAEO,aAAa,CAAC,CAACH,SAAS,CAAC,wBAAwB,CAAC;EAC1E,CAAC,CAAC;AACJ,CAAC,CAAC","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"intellisense.test.js","names":["startTsServer","findUpSync","path","invariant","ts","afterEach","beforeAll","beforeEach","describe","expect","it","vi","rootLogger","hoisted","pino","pinoPretty","EventEmitter","Promise","resolve","level","build","sync","timestampKey","undefined","errorLikeObjectKeys","errorProps","ignore","destination","write","a","at","slice","console","log","packagesDir","reactPackagePath","reactPackageJson","cwd","import","meta","dirname","process","env","NODE_ENV","join","tsServer","intellisenseFilePath","task","name","sys","fileExists","toBeTruthy","sendOpenRequest","file","error","stop","timeout","resp","sendCompletionsRequest","line","offset","triggerKind","CompletionTriggerKind","Invoked","completions","body","entries","map","e","toContain","typeResp","sendQuickInfoRequest","displayString","toBeDefined","ridsResp","noRidsResp","not","dataResp"],"sources":["intellisense.test.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 { Logger } from \"@osdk/api\";\nimport type { TsServer } from \"@osdk/client/internal-node\";\nimport { startTsServer } from \"@osdk/client/internal-node\";\nimport { findUpSync } from \"find-up\";\nimport * as path from \"node:path\";\nimport invariant from \"tiny-invariant\";\nimport * as ts from \"typescript\";\nimport {\n afterEach,\n beforeAll,\n beforeEach,\n describe,\n expect,\n it,\n vi,\n} from \"vitest\";\n\n// it needs to be hoisted because its referenced from our mocked WebSocket\n// which must be hoisted to work\nconst rootLogger = await vi.hoisted(async (): Promise<Logger> => {\n const pino = (await import(\"pino\")).pino;\n const pinoPretty = await import(\"pino-pretty\");\n const { EventEmitter } = await import(\"node:events\");\n class PinoConsoleLogDestination extends EventEmitter {\n write(a: string) {\n // remove trailing newline since console.log adds one\n if (a.at(-1) === \"\\n\") a = a.slice(0, -1);\n\n // This lets the test framework aggregate the logs per test, whereas direct to stdout does not\n console.log(a);\n }\n }\n return Promise.resolve(pino(\n { level: \"info\" },\n (pinoPretty.build)({\n sync: true,\n timestampKey: undefined,\n errorLikeObjectKeys: [\"error\", \"err\", \"exception\"],\n errorProps: \"stack,cause,properties\",\n ignore: \"time,hostname,pid\",\n destination: new PinoConsoleLogDestination(),\n }),\n ));\n});\n\n/**\n * @vitest-environment node\n * @vitest-pool forks\n */\ndescribe(\"intellisense\", () => {\n let packagesDir: string;\n let reactPackagePath: string;\n\n beforeAll(() => {\n const reactPackageJson = findUpSync(\"package.json\", {\n cwd: import.meta.dirname,\n });\n console.log({ reactPackageJson });\n invariant(reactPackageJson != null);\n packagesDir = path.join(\n path.dirname(reactPackageJson),\n \"..\",\n );\n\n reactPackagePath = path.join(packagesDir, \"react\");\n });\n\n let tsServer: TsServer | undefined;\n let intellisenseFilePath: string;\n\n beforeEach(async (a) => {\n intellisenseFilePath = path.join(\n reactPackagePath,\n \"src\",\n \"intellisense.test.helpers\",\n `${a.task.name}.ts`,\n );\n\n console.log(intellisenseFilePath);\n\n expect(ts.sys.fileExists(intellisenseFilePath)).toBeTruthy();\n\n try {\n tsServer = await startTsServer(rootLogger);\n await tsServer.sendOpenRequest({ file: intellisenseFilePath });\n } catch (error) {\n if (tsServer) {\n try {\n tsServer.stop();\n } catch {\n // Ignore cleanup errors\n }\n tsServer = undefined;\n }\n throw error;\n }\n });\n\n afterEach(() => {\n if (tsServer) {\n tsServer.stop();\n tsServer = undefined;\n }\n });\n\n it(\"useOsdkObjectsWithPivot\", { timeout: 40_000 }, async () => {\n expect(ts.sys.fileExists(intellisenseFilePath)).toBeTruthy();\n invariant(tsServer);\n\n const { resp } = await tsServer.sendCompletionsRequest({\n file: intellisenseFilePath,\n line: 29,\n offset: 15,\n triggerKind: ts.CompletionTriggerKind.Invoked,\n });\n\n const completions = resp.body?.entries.map(e => e.name) ?? [];\n expect(completions).toContain(\"lead\");\n\n const { resp: typeResp } = await tsServer.sendQuickInfoRequest({\n file: intellisenseFilePath,\n line: 33,\n offset: 10,\n });\n\n expect(typeResp.body?.displayString).toBeDefined();\n expect(typeResp.body?.displayString).toContain(\"Employee\");\n });\n\n it(\"useOsdkObjectsWithRids\", { timeout: 40_000 }, async () => {\n expect(ts.sys.fileExists(intellisenseFilePath)).toBeTruthy();\n invariant(tsServer);\n\n const { resp: ridsResp } = await tsServer.sendQuickInfoRequest({\n file: intellisenseFilePath,\n line: 30,\n offset: 9,\n });\n\n expect(ridsResp.body?.displayString).toBeDefined();\n expect(ridsResp.body?.displayString).toContain(\"$rid\");\n\n const { resp: noRidsResp } = await tsServer.sendQuickInfoRequest({\n file: intellisenseFilePath,\n line: 34,\n offset: 9,\n });\n\n expect(noRidsResp.body?.displayString).toBeDefined();\n expect(noRidsResp.body?.displayString).not.toContain(\"$rid\");\n });\n\n it(\"useOsdkObjectsWithProperties\", { timeout: 40_000 }, async () => {\n expect(ts.sys.fileExists(intellisenseFilePath)).toBeTruthy();\n invariant(tsServer);\n\n const { resp } = await tsServer.sendQuickInfoRequest({\n file: intellisenseFilePath,\n line: 27,\n offset: 10,\n });\n\n expect(resp.body?.displayString).toContain(\"DerivedProperty.Clause\");\n\n const { resp: dataResp } = await tsServer.sendQuickInfoRequest({\n file: intellisenseFilePath,\n line: 31,\n offset: 11,\n });\n\n expect(dataResp.body?.displayString).toBeDefined();\n expect(dataResp.body?.displayString).toContain(\"Osdk.Instance<Employee\");\n });\n});\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA,SAASA,aAAa,QAAQ,4BAA4B;AAC1D,SAASC,UAAU,QAAQ,SAAS;AACpC,OAAO,KAAKC,IAAI,MAAM,WAAW;AACjC,OAAOC,SAAS,MAAM,gBAAgB;AACtC,OAAO,KAAKC,EAAE,MAAM,YAAY;AAChC,SACEC,SAAS,EACTC,SAAS,EACTC,UAAU,EACVC,QAAQ,EACRC,MAAM,EACNC,EAAE,EACFC,EAAE,QACG,QAAQ;;AAEf;AACA;AACA,MAAMC,UAAU,GAAG,MAAMD,EAAE,CAACE,OAAO,CAAC,YAA6B;EAC/D,MAAMC,IAAI,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,EAAEA,IAAI;EACxC,MAAMC,UAAU,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC;EAC9C,MAAM;IAAEC;EAAa,CAAC,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC;EAUpD,OAAOC,OAAO,CAACC,OAAO,CAACJ,IAAI,CACzB;IAAEK,KAAK,EAAE;EAAO,CAAC,EAChBJ,UAAU,CAACK,KAAK,CAAE;IACjBC,IAAI,EAAE,IAAI;IACVC,YAAY,EAAEC,SAAS;IACvBC,mBAAmB,EAAE,CAAC,OAAO,EAAE,KAAK,EAAE,WAAW,CAAC;IAClDC,UAAU,EAAE,wBAAwB;IACpCC,MAAM,EAAE,mBAAmB;IAC3BC,WAAW,EAAE,IAjBjB,cAAwCX,YAAY,CAAC;MACnDY,KAAKA,CAACC,CAAS,EAAE;QACf;QACA,IAAIA,CAAC,CAACC,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAAED,CAAC,GAAGA,CAAC,CAACE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAA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M,CAAC;EAC9D,CAAC,CAAC;EAEF3D,EAAE,CAAC,8BAA8B,EAAE;IAAE8C,OAAO,EAAE;EAAO,CAAC,EAAE,YAAY;IAClE/C,MAAM,CAACL,EAAE,CAAC6C,GAAG,CAACC,UAAU,CAACJ,oBAAoB,CAAC,CAAC,CAACK,UAAU,CAAC,CAAC;IAC5D,CAAUN,QAAQ,GAAAJ,OAAA,CAAAC,GAAA,CAAAC,QAAA,oBAAlBxC,SAAS,UAATA,SAAS;IAET,MAAM;MAAEsD;IAAK,CAAC,GAAG,MAAMZ,QAAQ,CAAC0B,oBAAoB,CAAC;MACnDlB,IAAI,EAAEP,oBAAoB;MAC1Ba,IAAI,EAAE,EAAE;MACRC,MAAM,EAAE;IACV,CAAC,CAAC;IAEFnD,MAAM,CAACgD,IAAI,CAACQ,IAAI,EAAEO,aAAa,CAAC,CAACH,SAAS,CAAC,wBAAwB,CAAC;IAEpE,MAAM;MAAEZ,IAAI,EAAEoB;IAAS,CAAC,GAAG,MAAMhC,QAAQ,CAAC0B,oBAAoB,CAAC;MAC7DlB,IAAI,EAAEP,oBAAoB;MAC1Ba,IAAI,EAAE,EAAE;MACRC,MAAM,EAAE;IACV,CAAC,CAAC;IAEFnD,MAAM,CAACoE,QAAQ,CAACZ,IAAI,EAAEO,aAAa,CAAC,CAACC,WAAW,CAAC,CAAC;IAClDhE,MAAM,CAACoE,QAAQ,CAACZ,IAAI,EAAEO,aAAa,CAAC,CAACH,SAAS,CAAC,wBAAwB,CAAC;EAC1E,CAAC,CAAC;AACJ,CAAC,CAAC","ignoreList":[]}
|
|
@@ -42,4 +42,65 @@ export function makeExternalStore(createObservation, _name, initialValue) {
|
|
|
42
42
|
getSnapShot
|
|
43
43
|
};
|
|
44
44
|
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Like makeExternalStore but for async subscription creation.
|
|
48
|
+
*
|
|
49
|
+
* Uses an isActive flag to handle race conditions:
|
|
50
|
+
* If cleanup runs before promise resolves, the stale subscription is
|
|
51
|
+
* immediately unsubscribed when it eventually resolves
|
|
52
|
+
*/
|
|
53
|
+
export function makeExternalStoreAsync(createObservation, _name, initialValue) {
|
|
54
|
+
let lastResult = initialValue;
|
|
55
|
+
function getSnapShot() {
|
|
56
|
+
return lastResult;
|
|
57
|
+
}
|
|
58
|
+
function subscribe(notifyUpdate) {
|
|
59
|
+
let isActive = true;
|
|
60
|
+
let currentSubscription;
|
|
61
|
+
const subscriptionPromise = createObservation({
|
|
62
|
+
next: payload => {
|
|
63
|
+
if (isActive) {
|
|
64
|
+
lastResult = payload;
|
|
65
|
+
notifyUpdate();
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
error: error => {
|
|
69
|
+
if (isActive) {
|
|
70
|
+
lastResult = {
|
|
71
|
+
...(lastResult ?? {}),
|
|
72
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
73
|
+
};
|
|
74
|
+
notifyUpdate();
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
complete: () => {}
|
|
78
|
+
});
|
|
79
|
+
subscriptionPromise.then(sub => {
|
|
80
|
+
if (isActive) {
|
|
81
|
+
currentSubscription = sub;
|
|
82
|
+
} else {
|
|
83
|
+
sub.unsubscribe();
|
|
84
|
+
}
|
|
85
|
+
}).catch(error => {
|
|
86
|
+
if (isActive) {
|
|
87
|
+
lastResult = {
|
|
88
|
+
...(lastResult ?? {}),
|
|
89
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
90
|
+
};
|
|
91
|
+
notifyUpdate();
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
return () => {
|
|
95
|
+
isActive = false;
|
|
96
|
+
if (currentSubscription) {
|
|
97
|
+
currentSubscription.unsubscribe();
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
subscribe,
|
|
103
|
+
getSnapShot
|
|
104
|
+
};
|
|
105
|
+
}
|
|
45
106
|
//# sourceMappingURL=makeExternalStore.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"makeExternalStore.js","names":["makeExternalStore","createObservation","_name","initialValue","lastResult","getSnapShot","subscribe","notifyUpdate","obs","next","payload","error","Error","String","complete","unsubscribe"],"sources":["makeExternalStore.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 Observer,\n Unsubscribable,\n} from \"@osdk/client/unstable-do-not-use\";\n\nexport type Snapshot<X> =\n | X & { error?: Error }\n | (Partial<X> & { error?: Error })\n | undefined;\n\nexport function makeExternalStore<X>(\n createObservation: (callback: Observer<X | undefined>) => Unsubscribable,\n _name?: string,\n initialValue?: Snapshot<X>,\n): {\n subscribe: (notifyUpdate: () => void) => () => void;\n getSnapShot: () => Snapshot<X>;\n} {\n let lastResult: Snapshot<X> = initialValue;\n\n function getSnapShot(): Snapshot<X> {\n return lastResult;\n }\n\n function subscribe(notifyUpdate: () => void) {\n const obs = createObservation({\n next: (payload) => {\n lastResult = payload as Snapshot<X>;\n notifyUpdate();\n },\n error: (error: unknown) => {\n lastResult = {\n ...(lastResult ?? {}),\n error: error instanceof Error ? error : new Error(String(error)),\n } as Snapshot<X>;\n notifyUpdate();\n },\n complete: () => {},\n });\n\n return (): void => {\n obs.unsubscribe();\n };\n }\n\n return {\n subscribe,\n getSnapShot,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAYA,OAAO,SAASA,iBAAiBA,CAC/BC,iBAAwE,EACxEC,KAAc,EACdC,YAA0B,EAI1B;EACA,IAAIC,UAAuB,GAAGD,YAAY;EAE1C,SAASE,WAAWA,CAAA,EAAgB;IAClC,OAAOD,UAAU;EACnB;EAuBA,OAAO;IACLE,SAAS,EAtBX,SAASA,SAASA,CAACC,YAAwB,EAAE;MAC3C,MAAMC,GAAG,GAAGP,iBAAiB,CAAC;QAC5BQ,IAAI,EAAGC,OAAO,IAAK;UACjBN,UAAU,GAAGM,OAAsB;UACnCH,YAAY,CAAC,CAAC;QAChB,CAAC;QACDI,KAAK,EAAGA,KAAc,IAAK;UACzBP,UAAU,GAAG;YACX,IAAIA,UAAU,IAAI,CAAC,CAAC,CAAC;YACrBO,KAAK,EAAEA,KAAK,YAAYC,KAAK,GAAGD,KAAK,GAAG,IAAIC,KAAK,CAACC,MAAM,CAACF,KAAK,CAAC;UACjE,CAAgB;UAChBJ,YAAY,CAAC,CAAC;QAChB,CAAC;QACDO,QAAQ,EAAEA,CAAA,KAAM,CAAC;MACnB,CAAC,CAAC;MAEF,OAAO,MAAY;QACjBN,GAAG,CAACO,WAAW,CAAC,CAAC;MACnB,CAAC;IACH,CAGW;IACTV;EACF,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"makeExternalStore.js","names":["makeExternalStore","createObservation","_name","initialValue","lastResult","getSnapShot","subscribe","notifyUpdate","obs","next","payload","error","Error","String","complete","unsubscribe","makeExternalStoreAsync","isActive","currentSubscription","subscriptionPromise","then","sub","catch"],"sources":["makeExternalStore.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 Observer,\n Unsubscribable,\n} from \"@osdk/client/unstable-do-not-use\";\n\nexport type Snapshot<X> =\n | X & { error?: Error }\n | (Partial<X> & { error?: Error })\n | undefined;\n\nexport function makeExternalStore<X>(\n createObservation: (callback: Observer<X | undefined>) => Unsubscribable,\n _name?: string,\n initialValue?: Snapshot<X>,\n): {\n subscribe: (notifyUpdate: () => void) => () => void;\n getSnapShot: () => Snapshot<X>;\n} {\n let lastResult: Snapshot<X> = initialValue;\n\n function getSnapShot(): Snapshot<X> {\n return lastResult;\n }\n\n function subscribe(notifyUpdate: () => void) {\n const obs = createObservation({\n next: (payload) => {\n lastResult = payload as Snapshot<X>;\n notifyUpdate();\n },\n error: (error: unknown) => {\n lastResult = {\n ...(lastResult ?? {}),\n error: error instanceof Error ? error : new Error(String(error)),\n } as Snapshot<X>;\n notifyUpdate();\n },\n complete: () => {},\n });\n\n return (): void => {\n obs.unsubscribe();\n };\n }\n\n return {\n subscribe,\n getSnapShot,\n };\n}\n\n/**\n * Like makeExternalStore but for async subscription creation.\n *\n * Uses an isActive flag to handle race conditions:\n * If cleanup runs before promise resolves, the stale subscription is\n * immediately unsubscribed when it eventually resolves\n */\nexport function makeExternalStoreAsync<X>(\n createObservation: (\n callback: Observer<X | undefined>,\n ) => Promise<Unsubscribable>,\n _name?: string,\n initialValue?: Snapshot<X>,\n): {\n subscribe: (notifyUpdate: () => void) => () => void;\n getSnapShot: () => Snapshot<X>;\n} {\n let lastResult: Snapshot<X> = initialValue;\n\n function getSnapShot(): Snapshot<X> {\n return lastResult;\n }\n\n function subscribe(notifyUpdate: () => void) {\n let isActive = true;\n let currentSubscription: Unsubscribable | undefined;\n\n const subscriptionPromise = createObservation({\n next: (payload) => {\n if (isActive) {\n lastResult = payload as Snapshot<X>;\n notifyUpdate();\n }\n },\n error: (error: unknown) => {\n if (isActive) {\n lastResult = {\n ...(lastResult ?? {}),\n error: error instanceof Error ? error : new Error(String(error)),\n } as Snapshot<X>;\n notifyUpdate();\n }\n },\n complete: () => {},\n });\n\n subscriptionPromise.then((sub) => {\n if (isActive) {\n currentSubscription = sub;\n } else {\n sub.unsubscribe();\n }\n }).catch((error: unknown) => {\n if (isActive) {\n lastResult = {\n ...(lastResult ?? {}),\n error: error instanceof Error ? error : new Error(String(error)),\n } as Snapshot<X>;\n notifyUpdate();\n }\n });\n\n return (): void => {\n isActive = false;\n if (currentSubscription) {\n currentSubscription.unsubscribe();\n }\n };\n }\n\n return {\n subscribe,\n getSnapShot,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAYA,OAAO,SAASA,iBAAiBA,CAC/BC,iBAAwE,EACxEC,KAAc,EACdC,YAA0B,EAI1B;EACA,IAAIC,UAAuB,GAAGD,YAAY;EAE1C,SAASE,WAAWA,CAAA,EAAgB;IAClC,OAAOD,UAAU;EACnB;EAuBA,OAAO;IACLE,SAAS,EAtBX,SAASA,SAASA,CAACC,YAAwB,EAAE;MAC3C,MAAMC,GAAG,GAAGP,iBAAiB,CAAC;QAC5BQ,IAAI,EAAGC,OAAO,IAAK;UACjBN,UAAU,GAAGM,OAAsB;UACnCH,YAAY,CAAC,CAAC;QAChB,CAAC;QACDI,KAAK,EAAGA,KAAc,IAAK;UACzBP,UAAU,GAAG;YACX,IAAIA,UAAU,IAAI,CAAC,CAAC,CAAC;YACrBO,KAAK,EAAEA,KAAK,YAAYC,KAAK,GAAGD,KAAK,GAAG,IAAIC,KAAK,CAACC,MAAM,CAACF,KAAK,CAAC;UACjE,CAAgB;UAChBJ,YAAY,CAAC,CAAC;QAChB,CAAC;QACDO,QAAQ,EAAEA,CAAA,KAAM,CAAC;MACnB,CAAC,CAAC;MAEF,OAAO,MAAY;QACjBN,GAAG,CAACO,WAAW,CAAC,CAAC;MACnB,CAAC;IACH,CAGW;IACTV;EACF,CAAC;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;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C;IAEF,OAAO,MAAY;MACjBU,QAAQ,GAAG,KAAK;MAChB,IAAIC,mBAAmB,EAAE;QACvBA,mBAAmB,CAACH,WAAW,CAAC,CAAC;MACnC;IACF,CAAC;EACH;EAEA,OAAO;IACLT,SAAS;IACTD;EACF,CAAC;AACH","ignoreList":[]}
|
|
@@ -66,13 +66,13 @@ export function useLinks(objects, linkName, options = {}) {
|
|
|
66
66
|
}, observer), `links ${linkName} for ${objectsKey}`);
|
|
67
67
|
}, [enabled, observableClient, objectsArray, objectsKey, linkName, stableWhere, otherOptions.pageSize, stableOrderBy, otherOptions.mode, otherOptions.dedupeIntervalMs]);
|
|
68
68
|
const payload = React.useSyncExternalStore(subscribe, getSnapShot);
|
|
69
|
-
return {
|
|
69
|
+
return React.useMemo(() => ({
|
|
70
70
|
links: payload?.resolvedList,
|
|
71
71
|
isLoading: enabled ? payload?.status === "loading" || payload?.status === "init" || !payload : false,
|
|
72
72
|
isOptimistic: payload?.isOptimistic ?? false,
|
|
73
73
|
error: payload?.error,
|
|
74
74
|
fetchMore: payload?.hasMore ? payload?.fetchMore : undefined,
|
|
75
75
|
hasMore: payload?.hasMore ?? false
|
|
76
|
-
};
|
|
76
|
+
}), [payload, enabled]);
|
|
77
77
|
}
|
|
78
78
|
//# sourceMappingURL=useLinks.js.map
|
|
@@ -1 +1 @@
|
|
|
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","dedupeInterval","dedupeIntervalMs","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 * The number of milliseconds to wait after the last observed link change.\n *\n * Two uses of `useLinks` with the same parameters will only trigger one\n * network request if the second is within `dedupeIntervalMs`.\n */\n dedupeIntervalMs?: number;\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 dedupeInterval: otherOptions.dedupeIntervalMs ?? 2_000,\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 otherOptions.dedupeIntervalMs,\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;AAiFhD,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,CA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RQ,KAAK,EAAEF,WAAW;MAClBuB,QAAQ,EAAExB,YAAY,CAACwB,QAAQ;MAC/BjB,OAAO,EAAED,aAAa;MACtBmB,IAAI,EAAEzB,YAAY,CAACyB,IAAI;MACvBC,cAAc,EAAE1B,YAAY,CAAC2B,gBAAgB,IAAI;IACnD,CAAC,EACDL,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,EACjBzB,YAAY,CAAC2B,gBAAgB,CAEjC,CAAC;EAED,MAAMC,OAAO,GAAGzC,KAAK,CAAC0C,oBAAoB,CACxCV,SAAS,EACTC,WACF,CAAC;EAED,OAAO;
|
|
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","dedupeInterval","dedupeIntervalMs","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 * The number of milliseconds to wait after the last observed link change.\n *\n * Two uses of `useLinks` with the same parameters will only trigger one\n * network request if the second is within `dedupeIntervalMs`.\n */\n dedupeIntervalMs?: number;\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 dedupeInterval: otherOptions.dedupeIntervalMs ?? 2_000,\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 otherOptions.dedupeIntervalMs,\n ],\n );\n\n const payload = React.useSyncExternalStore(\n subscribe,\n getSnapShot,\n );\n\n return React.useMemo(() => ({\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 }), [payload, enabled]);\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;AAiFhD,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,CAACH,IAAI,CAACC,SAAS,CAACL,YAAY,CAACO,OAAO,CAAC,CACvC,CAAC;EAED,MAAMC,UAAU,GAAGrB,KAAK,CAACe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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,EACjBzB,YAAY,CAAC2B,gBAAgB,CAEjC,CAAC;EAED,MAAMC,OAAO,GAAGzC,KAAK,CAAC0C,oBAAoB,CACxCV,SAAS,EACTC,WACF,CAAC;EAED,OAAOjC,KAAK,CAACe,OAAO,CAAC,OAAO;IAC1B4B,KAAK,EAAEF,OAAO,EAAEG,YAAY;IAC5BC,SAAS,EAAEjC,OAAO,GACb6B,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,GAAG3B,SAAS;IAC5D4B,OAAO,EAAET,OAAO,EAAES,OAAO,IAAI;EAC/B,CAAC,CAAC,EAAE,CAACT,OAAO,EAAE7B,OAAO,CAAC,CAAC;AACzB","ignoreList":[]}
|
|
@@ -18,6 +18,7 @@ import { computeObjectSetCacheKey } from "@osdk/client/unstable-do-not-use";
|
|
|
18
18
|
import React from "react";
|
|
19
19
|
import { makeExternalStore } from "./makeExternalStore.js";
|
|
20
20
|
import { OsdkContext2 } from "./OsdkContext2.js";
|
|
21
|
+
const OBJECT_TYPE_PLACEHOLDER = "$__OBJECT__TYPE__PLACEHOLDER";
|
|
21
22
|
/**
|
|
22
23
|
* React hook for observing and interacting with OSDK object sets.
|
|
23
24
|
*
|
|
@@ -40,7 +41,7 @@ export function useObjectSet(baseObjectSet, options = {}) {
|
|
|
40
41
|
} = options;
|
|
41
42
|
|
|
42
43
|
// Track object type to detect when we switch to a different object type
|
|
43
|
-
const objectTypeKey = baseObjectSet.$objectSetInternals.def.apiName;
|
|
44
|
+
const objectTypeKey = enabled ? baseObjectSet.$objectSetInternals.def.apiName : OBJECT_TYPE_PLACEHOLDER;
|
|
44
45
|
const previousObjectTypeRef = React.useRef(objectTypeKey);
|
|
45
46
|
const previousPayloadRef = React.useRef();
|
|
46
47
|
const objectTypeChanged = previousObjectTypeRef.current !== objectTypeKey;
|
|
@@ -93,13 +94,13 @@ export function useObjectSet(baseObjectSet, options = {}) {
|
|
|
93
94
|
previousPayloadRef.current = payload;
|
|
94
95
|
}
|
|
95
96
|
}, [payload]);
|
|
96
|
-
return {
|
|
97
|
+
return React.useMemo(() => ({
|
|
97
98
|
data: payload?.resolvedList,
|
|
98
99
|
isLoading: payload?.status === "loading" || !payload && true || false,
|
|
99
100
|
error: payload && "error" in payload ? payload.error : undefined,
|
|
100
101
|
fetchMore: payload?.hasMore ? payload.fetchMore : undefined,
|
|
101
102
|
objectSet: payload?.objectSet || baseObjectSet,
|
|
102
103
|
totalCount: payload?.totalCount
|
|
103
|
-
};
|
|
104
|
+
}), [payload, baseObjectSet]);
|
|
104
105
|
}
|
|
105
106
|
//# 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","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<Q, RDPs> || baseObjectSet,\n totalCount: payload?.totalCount,\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;AAwIhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,YAAYA,CAK1BC,aAAqC,EACrCC,OAAqC,GAAG,CAAC,CAAC,EACb;EAC7B,MAAM;IAAEC;EAAiB,CAAC,GAAGN,KAAK,CAACO,UAAU,CAACL,YAAY,CAAC;EAE3D,MAAM;IAAEM,OAAO,GAAG,IAAI;IAAEC,aAAa;IAAE,GAAGC;EAAa,CAAC,GAAGL,OAAO;;EAElE;EACA,MAAMM,aAAa,GAAGP,aAAa,CAACQ,mBAAmB,CAACC,GAAG,CAACC,OAAO;EACnE,MAAMC,qBAAqB,GAAGf,KAAK,CAACgB,MAAM,C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W;EACvB,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useObjectSet.js","names":["computeObjectSetCacheKey","React","makeExternalStore","OsdkContext2","OBJECT_TYPE_PLACEHOLDER","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\nconst OBJECT_TYPE_PLACEHOLDER = \"$__OBJECT__TYPE__PLACEHOLDER\";\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 = enabled\n ? baseObjectSet.$objectSetInternals.def.apiName\n : OBJECT_TYPE_PLACEHOLDER;\n\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 React.useMemo(() => ({\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<Q, RDPs> || baseObjectSet,\n totalCount: payload?.totalCount,\n }), [payload, baseObjectSet]);\n}\n"],"mappings":"AAAA;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EAAEF,gBAAgB,EAAEc,SAAS,EAAEX,aAAa,EAAES,iBAAiB,CACzE,CAAC;EAED,MAAM0B,OAAO,GAAG7C,KAAK,CAAC8C,oBAAoB,CAAChB,SAAS,EAAEC,WAAW,CAAC;EAClE/B,KAAK,CAAC+C,SAAS,CAAC,MAAM;IACpB,IAAIF,OAAO,EAAE;MACX3B,kBAAkB,CAACE,OAAO,GAAGyB,OAAO;IACtC;EACF,CAAC,EAAE,CAACA,OAAO,CAAC,CAAC;EAEb,OAAO7C,KAAK,CAACgC,OAAO,CAAC,OAAO;IAC1BgB,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,CAAC,EAAE,CAACX,OAAO,EAAExC,aAAa,CAAC,CAAC;AAC/B","ignoreList":[]}
|
|
@@ -135,7 +135,7 @@ export function useOsdkAction(actionDef) {
|
|
|
135
135
|
}
|
|
136
136
|
};
|
|
137
137
|
}, []);
|
|
138
|
-
return {
|
|
138
|
+
return React.useMemo(() => ({
|
|
139
139
|
applyAction,
|
|
140
140
|
validateAction,
|
|
141
141
|
error,
|
|
@@ -143,6 +143,6 @@ export function useOsdkAction(actionDef) {
|
|
|
143
143
|
isPending,
|
|
144
144
|
isValidating,
|
|
145
145
|
validationResult
|
|
146
|
-
};
|
|
146
|
+
}), [applyAction, validateAction, error, data, isPending, isValidating, validationResult]);
|
|
147
147
|
}
|
|
148
148
|
//# sourceMappingURL=useOsdkAction.js.map
|
|
@@ -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 {\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,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,CAAiC,CAAC;EACxE,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AmB,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":[]}
|
|
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","useMemo"],"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 React.useMemo(() => ({\n applyAction,\n validateAction,\n error,\n data,\n isPending,\n isValidating,\n validationResult,\n }), [\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,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,CAAiC,CAAC;EACxE,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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AAEF;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,OAAOvB,KAAK,CAACiD,OAAO,CAAC,OAAO;IAC1B9B,WAAW;IACXqB,cAAc;IACdlC,KAAK;IACLG,IAAI;IACJE,SAAS;IACTE,YAAY;IACZE;EACF,CAAC,CAAC,EAAE,CACFI,WAAW,EACXqB,cAAc,EACdlC,KAAK,EACLG,IAAI,EACJE,SAAS,EACTE,YAAY,EACZE,gBAAgB,CACjB,CAAC;AACJ","ignoreList":[]}
|
|
@@ -14,10 +14,12 @@
|
|
|
14
14
|
* limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
+
import { computeObjectSetCacheKey } from "@osdk/client/unstable-do-not-use";
|
|
17
18
|
import React from "react";
|
|
18
|
-
import { makeExternalStore } from "./makeExternalStore.js";
|
|
19
|
+
import { makeExternalStore, makeExternalStoreAsync } from "./makeExternalStore.js";
|
|
19
20
|
import { OsdkContext2 } from "./OsdkContext2.js";
|
|
20
21
|
const EMPTY_WHERE = {};
|
|
22
|
+
|
|
21
23
|
/**
|
|
22
24
|
* React hook for performing aggregations on OSDK object sets.
|
|
23
25
|
*
|
|
@@ -30,6 +32,7 @@ const EMPTY_WHERE = {};
|
|
|
30
32
|
*
|
|
31
33
|
* @example
|
|
32
34
|
* ```tsx
|
|
35
|
+
* // Basic aggregation without ObjectSet
|
|
33
36
|
* const { data, isLoading, error } = useOsdkAggregation(Employee, {
|
|
34
37
|
* where: { department: "Engineering" },
|
|
35
38
|
* aggregate: {
|
|
@@ -40,46 +43,79 @@ const EMPTY_WHERE = {};
|
|
|
40
43
|
* }
|
|
41
44
|
* }
|
|
42
45
|
* });
|
|
46
|
+
*
|
|
47
|
+
* // With a pivoted ObjectSet
|
|
48
|
+
* const pivotedSet = useMemo(() => $(Employee).pivotTo("primaryOffice"), []);
|
|
49
|
+
* const { data } = useOsdkAggregation(Office, {
|
|
50
|
+
* objectSet: pivotedSet,
|
|
51
|
+
* aggregate: { $select: { $count: "unordered" } }
|
|
52
|
+
* });
|
|
43
53
|
* ```
|
|
44
54
|
*/
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
55
|
+
|
|
56
|
+
export function useOsdkAggregation(type, options) {
|
|
57
|
+
const {
|
|
58
|
+
where = EMPTY_WHERE,
|
|
59
|
+
withProperties,
|
|
60
|
+
intersectWith,
|
|
61
|
+
aggregate,
|
|
62
|
+
dedupeIntervalMs
|
|
63
|
+
} = options;
|
|
64
|
+
const objectSet = "objectSet" in options ? options.objectSet : undefined;
|
|
51
65
|
const {
|
|
52
66
|
observableClient
|
|
53
67
|
} = React.useContext(OsdkContext2);
|
|
54
|
-
const canonWhere = observableClient.canonicalizeWhereClause(where
|
|
68
|
+
const canonWhere = observableClient.canonicalizeWhereClause(where);
|
|
55
69
|
const stableCanonWhere = React.useMemo(() => canonWhere, [JSON.stringify(canonWhere)]);
|
|
70
|
+
const objectSetRef = React.useRef(objectSet);
|
|
71
|
+
objectSetRef.current = objectSet;
|
|
72
|
+
const objectSetKeyString = objectSet ? computeObjectSetCacheKey(objectSet) : undefined;
|
|
56
73
|
const stableWithProperties = React.useMemo(() => withProperties, [JSON.stringify(withProperties)]);
|
|
57
74
|
const stableAggregate = React.useMemo(() => aggregate, [JSON.stringify(aggregate)]);
|
|
75
|
+
const stableIntersectWith = React.useMemo(() => intersectWith, [JSON.stringify(intersectWith)]);
|
|
58
76
|
const {
|
|
59
77
|
subscribe,
|
|
60
78
|
getSnapShot
|
|
61
|
-
} = React.useMemo(() =>
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
79
|
+
} = React.useMemo(() => {
|
|
80
|
+
if (objectSetKeyString && objectSetRef.current) {
|
|
81
|
+
return makeExternalStoreAsync(observer => observableClient.observeAggregation({
|
|
82
|
+
type: type,
|
|
83
|
+
objectSet: objectSetRef.current,
|
|
84
|
+
where: stableCanonWhere,
|
|
85
|
+
withProperties: stableWithProperties,
|
|
86
|
+
intersectWith: stableIntersectWith,
|
|
87
|
+
aggregate: stableAggregate,
|
|
88
|
+
dedupeInterval: dedupeIntervalMs ?? 2_000
|
|
89
|
+
}, observer), process.env.NODE_ENV !== "production" ? `aggregation ${type.apiName} ${objectSetKeyString} ${JSON.stringify(stableCanonWhere)}` : void 0);
|
|
90
|
+
}
|
|
91
|
+
return makeExternalStore(observer =>
|
|
92
|
+
// eslint-disable-next-line @typescript-eslint/no-deprecated
|
|
93
|
+
observableClient.observeAggregation({
|
|
94
|
+
type: type,
|
|
95
|
+
where: stableCanonWhere,
|
|
96
|
+
withProperties: stableWithProperties,
|
|
97
|
+
intersectWith: stableIntersectWith,
|
|
98
|
+
aggregate: stableAggregate,
|
|
99
|
+
dedupeInterval: dedupeIntervalMs ?? 2_000
|
|
100
|
+
}, observer), process.env.NODE_ENV !== "production" ? `aggregation ${type.apiName} ${JSON.stringify(stableCanonWhere)}` : void 0);
|
|
101
|
+
}, [observableClient, type.apiName, type.type, objectSetKeyString, stableCanonWhere, stableWithProperties, stableIntersectWith, stableAggregate, dedupeIntervalMs]);
|
|
68
102
|
const payload = React.useSyncExternalStore(subscribe, getSnapShot);
|
|
69
|
-
let error;
|
|
70
|
-
if (payload && "error" in payload && payload.error) {
|
|
71
|
-
error = payload.error;
|
|
72
|
-
} else if (payload?.status === "error") {
|
|
73
|
-
error = new Error("Failed to execute aggregation");
|
|
74
|
-
}
|
|
75
103
|
const refetch = React.useCallback(async () => {
|
|
76
104
|
await observableClient.invalidateObjectType(type.apiName);
|
|
77
105
|
}, [observableClient, type.apiName]);
|
|
78
|
-
return {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
106
|
+
return React.useMemo(() => {
|
|
107
|
+
let error;
|
|
108
|
+
if (payload && "error" in payload && payload.error) {
|
|
109
|
+
error = payload.error;
|
|
110
|
+
} else if (payload?.status === "error") {
|
|
111
|
+
error = new Error("Failed to execute aggregation");
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
data: payload?.result,
|
|
115
|
+
isLoading: payload?.status === "loading" || payload?.status === "init" || !payload,
|
|
116
|
+
error,
|
|
117
|
+
refetch
|
|
118
|
+
};
|
|
119
|
+
}, [payload, refetch]);
|
|
84
120
|
}
|
|
85
121
|
//# sourceMappingURL=useOsdkAggregation.js.map
|