@rise-x/apps-sdk 0.20.1 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,6 +6,7 @@ exports.readWorkBack = readWorkBack;
6
6
  exports.createWorkConnector = createWorkConnector;
7
7
  const _internal_1 = require("../_internal");
8
8
  const errors_1 = require("./errors");
9
+ const project_1 = require("./project");
9
10
  const readPolicy_1 = require("./readPolicy");
10
11
  const search_1 = require("./search");
11
12
  const types_1 = require("./types");
@@ -20,6 +21,8 @@ const PATCH_OPERATION_CODES = {
20
21
  };
21
22
  // Wire code of the platform's ResourceType enum for work items.
22
23
  const RESOURCE_TYPE_WORK = 2;
24
+ // The work's actions submit() would run for `actionName` (the shell's eventName ?? name rule).
25
+ const actionsNamed = (detail, actionName) => (detail?.actions ?? []).filter((a) => (a.eventName ?? a.name) === actionName);
23
26
  const DEFAULT_PAGE_SIZE = 50;
24
27
  // Exported so the query layer's cache keys can resolve a FlowRef the same
25
28
  // way the request body does (see query/work.ts) — an object ref and its bare
@@ -101,6 +104,47 @@ function createWorkConnector(deps = { shell: _internal_1.requireShell }) {
101
104
  return poco ? (0, types_1.mapWorkDetail)(poco) : null;
102
105
  },
103
106
  });
107
+ const getSummary = async (workId, opts = {}) => {
108
+ const fields = opts.fields ?? [];
109
+ const wholeDocument = fields.includes("data");
110
+ const paths = fields
111
+ .filter((f) => f.startsWith("data."))
112
+ .map((f) => f.slice("data.".length));
113
+ const wantsData = wholeDocument || paths.length > 0;
114
+ const [poco, doc] = await Promise.allSettled([
115
+ workApi().get(`/api/v4/work/${workId}`, {
116
+ signal: opts.signal,
117
+ }),
118
+ wantsData
119
+ ? workApi().get(`/api/v4/work/${workId}/data`, {
120
+ signal: opts.signal,
121
+ })
122
+ : Promise.resolve(null),
123
+ ]);
124
+ if (poco.status === "rejected") {
125
+ const failure = (0, errors_1.toConnectorError)(poco.reason);
126
+ if (failure.code === "NOT_FOUND")
127
+ return null;
128
+ throw failure;
129
+ }
130
+ // A work with no data document yet reads as an empty one.
131
+ const dataFailure = doc.status === "rejected" ? (0, errors_1.toConnectorError)(doc.reason) : null;
132
+ if (dataFailure && dataFailure.code !== "NOT_FOUND")
133
+ throw dataFailure;
134
+ const document = doc.status === "fulfilled" ? doc.value?.data ?? null : null;
135
+ const raw = poco.value.data ?? {};
136
+ return (0, types_1.mapWorkSummary)({
137
+ ...raw,
138
+ // The v4 work names these differently to a search row.
139
+ workCode: raw.workCode ?? raw.code,
140
+ flowState: raw.flowState ?? raw.state,
141
+ data: !wantsData
142
+ ? undefined
143
+ : wholeDocument
144
+ ? document ?? {}
145
+ : (0, project_1.projectDataPaths)(document, paths),
146
+ });
147
+ };
104
148
  // `async` so the path guard below rejects rather than throwing synchronously.
105
149
  const getData = async (workId, opts = {}) => {
106
150
  // Rejected before a source is chosen: resolved locally `..` yields an array, the endpoint a scalar.
@@ -153,12 +197,9 @@ function createWorkConnector(deps = { shell: _internal_1.requireShell }) {
153
197
  };
154
198
  // Without the action set's name, `Submit` matches the step's autosubmit event: a 200 that moves
155
199
  // nothing. Any miss sends no name, as before, so a call that worked without one still does.
156
- const resolveStepName = async (args) => {
200
+ const resolveStepName = async (args, detail) => {
157
201
  try {
158
- const detail = await get(args.workId, { signal: args.signal });
159
- const actionSetIds = new Set((detail?.actions ?? [])
160
- .filter((a) => (a.eventName ?? a.name) === args.actionName)
161
- .map((a) => a.actionSetId));
202
+ const actionSetIds = new Set(actionsNamed(detail, args.actionName).map((a) => a.actionSetId));
162
203
  const [actionSetId] = actionSetIds;
163
204
  if (!detail?.flowId || actionSetIds.size !== 1 || !actionSetId) {
164
205
  return undefined;
@@ -179,14 +220,54 @@ function createWorkConnector(deps = { shell: _internal_1.requireShell }) {
179
220
  return undefined;
180
221
  }
181
222
  };
223
+ // The platform merges a destination's to/cc into its own default for the step it names, and
224
+ // into the one at the same position when none matches. An action that lists no destination
225
+ // gets one unnamed entry, which the platform applies to its first.
226
+ const buildInvitation = (args, detail) => {
227
+ if (args.invitation)
228
+ return args.invitation;
229
+ if (!args.to?.length && !args.cc?.length)
230
+ return undefined;
231
+ const targets = actionsNamed(detail, args.actionName).flatMap((a) => a.destinations);
232
+ const steps = targets.length
233
+ ? targets.map((d) => d.targetStep)
234
+ : [undefined];
235
+ return {
236
+ destinations: steps.map((targetStep) => ({
237
+ targetStep,
238
+ targetStepName: targetStep,
239
+ to: args.to ?? [],
240
+ cc: args.cc ?? [],
241
+ })),
242
+ };
243
+ };
182
244
  const submit = async (args) => {
245
+ if (args.invitation && (args.to?.length || args.cc?.length)) {
246
+ throw new errors_1.ConnectorError("INVALID_ARG", "work.submit takes `invitation` or `to`/`cc`, not both.");
247
+ }
183
248
  let submitted;
184
249
  try {
185
- const stepName = args.stepName ?? (await resolveStepName(args));
250
+ const sendsInvitees = !args.invitation && !!(args.to?.length || args.cc?.length);
251
+ const needsWorkRead = !args.stepName || sendsInvitees;
252
+ let detail = null;
253
+ if (needsWorkRead) {
254
+ // A failed read only costs the step-name lookup, but invitees sent without the action's
255
+ // destinations would reach its first destination only: reject instead.
256
+ detail = await get(args.workId, { signal: args.signal }).catch((e) => {
257
+ if (sendsInvitees)
258
+ throw e;
259
+ return null;
260
+ });
261
+ if (!detail && sendsInvitees) {
262
+ throw new errors_1.ConnectorError("NOT_FOUND", `work.submit could not read work ${args.workId} to address its to/cc invitees.`);
263
+ }
264
+ }
265
+ const stepName = args.stepName ?? (await resolveStepName(args, detail));
266
+ const invitation = buildInvitation(args, detail);
186
267
  const { data } = await deps
187
268
  .shell()
188
269
  .getApi()
189
- .post(`/api/v3/flow/submit/${args.workId}`, { stepName }, { params: { eventName: args.actionName }, signal: args.signal });
270
+ .post(`/api/v3/flow/submit/${args.workId}`, invitation ? { stepName, invitation } : { stepName }, { params: { eventName: args.actionName }, signal: args.signal });
190
271
  submitted = (0, types_1.mapWorkDetail)(data ?? {});
191
272
  }
192
273
  catch (e) {
@@ -308,6 +389,7 @@ function createWorkConnector(deps = { shell: _internal_1.requireShell }) {
308
389
  return {
309
390
  start,
310
391
  get,
392
+ getSummary,
311
393
  getData,
312
394
  getMyAccess,
313
395
  patchData,
@@ -0,0 +1,34 @@
1
+ /** What the hook is doing right now. `idle` includes the moment the browser is asking for the microphone. */
2
+ export type DictationState = "idle" | "recording" | "transcribing";
3
+ /**
4
+ * Why the last attempt failed. `denied`: the user or the browser refused microphone access, so
5
+ * only a change to the site's permissions can fix it. `failed`: anything else (no microphone, a
6
+ * busy device, the transcription request failing).
7
+ */
8
+ export type DictationError = "denied" | "failed";
9
+ export interface UseDictationOptions {
10
+ /** ISO-639-1 code such as `"en"`. Omit it and the language is detected from the audio. */
11
+ language?: string;
12
+ /** Called once per clip with the transcript, never with an empty string. */
13
+ onText?: (text: string) => void;
14
+ }
15
+ export interface UseDictationResult {
16
+ /**
17
+ * `false` when the browser cannot record audio, or the host offers no AI. Hide the mic button
18
+ * then: `start()` does nothing.
19
+ */
20
+ supported: boolean;
21
+ state: DictationState;
22
+ /** Set when an attempt fails; cleared by the next `start()` or by `cancel()`. */
23
+ error: DictationError | null;
24
+ /**
25
+ * Asks for the default microphone and starts recording. Resolves once recording has begun or
26
+ * failed (see `error`), and never rejects. Does nothing while recording or transcribing.
27
+ */
28
+ start(): Promise<void>;
29
+ /** Ends the recording and transcribes it. A no-op unless recording. */
30
+ stop(): void;
31
+ /** Ends the recording and discards it, or abandons a transcription in flight. `onText` is not called. */
32
+ cancel(): void;
33
+ }
34
+ export declare function useDictation(options?: UseDictationOptions): UseDictationResult;
@@ -0,0 +1,205 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useDictation = useDictation;
4
+ // @rise-x/apps-sdk/dictation: a mic-button hook that records speech and turns it into text.
5
+ //
6
+ // The hook records the default microphone with `MediaRecorder` and sends the clip to the host's
7
+ // AI through `agents.transcribe`. The transcript arrives in one piece when recording stops, so
8
+ // there are no interim words to show. Nothing is stored: no chat or run is created.
9
+ //
10
+ // Not re-exported from the package root: it reads the agents connector, which the root barrel
11
+ // stays free of.
12
+ const react_1 = require("react");
13
+ const accessors_1 = require("../accessors");
14
+ const agents_1 = require("../connectors/agents");
15
+ // First container the browser will actually record. Chrome and Firefox take webm/opus and Safari
16
+ // only mp4. Left to its own default, MediaRecorder may pick one the gateway does not accept.
17
+ const PREFERRED_TYPES = [
18
+ "audio/webm;codecs=opus",
19
+ "audio/webm",
20
+ "audio/mp4",
21
+ "audio/ogg",
22
+ ];
23
+ // Below this a clip is a mis-tap, not speech. Transcription models make up words for
24
+ // near-silence, so an accidental double-tap would otherwise insert text nobody said.
25
+ const MIN_CLIP_MS = 600;
26
+ function pickMimeType() {
27
+ if (typeof MediaRecorder === "undefined" || !MediaRecorder.isTypeSupported) {
28
+ return undefined;
29
+ }
30
+ return PREFERRED_TYPES.find((type) => MediaRecorder.isTypeSupported(type));
31
+ }
32
+ // Read on every call rather than captured: the host can finish wiring its AI after the first
33
+ // render, and the browser APIs are absent outside a secure context.
34
+ function isSupported() {
35
+ return (typeof window !== "undefined" &&
36
+ typeof MediaRecorder !== "undefined" &&
37
+ typeof navigator !== "undefined" &&
38
+ !!navigator.mediaDevices?.getUserMedia &&
39
+ (0, accessors_1.getShellAi)() !== null);
40
+ }
41
+ function useDictation(options = {}) {
42
+ const [state, setState] = (0, react_1.useState)("idle");
43
+ const [error, setError] = (0, react_1.useState)(null);
44
+ const recorder = (0, react_1.useRef)(null);
45
+ const stream = (0, react_1.useRef)(null);
46
+ // Claimed synchronously: `recorder` is only set after the getUserMedia await, so without this
47
+ // two fast clicks both pass the guard and the second recorder replaces the first while its
48
+ // stream stays open, with the microphone indicator on.
49
+ const starting = (0, react_1.useRef)(false);
50
+ const startedAt = (0, react_1.useRef)(0);
51
+ const upload = (0, react_1.useRef)(null);
52
+ // The user's intent. A stop that is already flushing must not be undone by the `stop` event
53
+ // that follows, and a cancel during the getUserMedia await must still win once the stream arrives.
54
+ const discarded = (0, react_1.useRef)(false);
55
+ // The latest options, so `start` stays stable and a re-render never changes what an in-flight
56
+ // clip reports to.
57
+ const latest = (0, react_1.useRef)(options);
58
+ latest.current = options;
59
+ const releaseStream = (0, react_1.useCallback)(() => {
60
+ stream.current?.getTracks().forEach((track) => track.stop());
61
+ stream.current = null;
62
+ }, []);
63
+ const transcribeClip = (0, react_1.useCallback)(async (clip) => {
64
+ const controller = new AbortController();
65
+ upload.current = controller;
66
+ setState("transcribing");
67
+ try {
68
+ const text = await agents_1.agents.transcribe(clip, {
69
+ language: latest.current.language,
70
+ signal: controller.signal,
71
+ });
72
+ if (!controller.signal.aborted && text.trim()) {
73
+ latest.current.onText?.(text);
74
+ }
75
+ }
76
+ catch {
77
+ // An abort is our own cancel, not a failure worth reporting.
78
+ if (!controller.signal.aborted)
79
+ setError("failed");
80
+ }
81
+ finally {
82
+ // Only the clip that is still current settles the state: after a cancel, a new recording
83
+ // may already own it.
84
+ if (upload.current === controller) {
85
+ upload.current = null;
86
+ setState("idle");
87
+ }
88
+ }
89
+ }, []);
90
+ const start = (0, react_1.useCallback)(async () => {
91
+ if (!isSupported() ||
92
+ recorder.current ||
93
+ starting.current ||
94
+ upload.current) {
95
+ return;
96
+ }
97
+ starting.current = true;
98
+ // Cleared after the guards, so a no-op start cannot undo a pending cancel.
99
+ discarded.current = false;
100
+ setError(null);
101
+ let media;
102
+ try {
103
+ media = await navigator.mediaDevices.getUserMedia({
104
+ audio: {
105
+ echoCancellation: true,
106
+ noiseSuppression: true,
107
+ autoGainControl: true,
108
+ },
109
+ });
110
+ }
111
+ catch (e) {
112
+ starting.current = false;
113
+ if (discarded.current)
114
+ return;
115
+ // Only a permission problem is `denied`: a missing or busy microphone is `failed`,
116
+ // because sending the user to their browser settings cannot fix it.
117
+ const name = e?.name;
118
+ setError(name === "NotAllowedError" || name === "SecurityError"
119
+ ? "denied"
120
+ : "failed");
121
+ return;
122
+ }
123
+ // Cancelled, or unmounted, while the browser was asking: the stream is no longer wanted.
124
+ if (discarded.current) {
125
+ media.getTracks().forEach((track) => track.stop());
126
+ starting.current = false;
127
+ return;
128
+ }
129
+ const mimeType = pickMimeType();
130
+ let instance;
131
+ try {
132
+ instance = new MediaRecorder(media, mimeType ? { mimeType } : undefined);
133
+ }
134
+ catch {
135
+ // Leaving the stream open here would keep the microphone indicator on with nothing recording.
136
+ media.getTracks().forEach((track) => track.stop());
137
+ starting.current = false;
138
+ setError("failed");
139
+ return;
140
+ }
141
+ const chunks = [];
142
+ instance.ondataavailable = (event) => {
143
+ if (event.data.size)
144
+ chunks.push(event.data);
145
+ };
146
+ instance.onstop = () => {
147
+ releaseStream();
148
+ recorder.current = null;
149
+ const clip = new Blob(chunks, { type: instance.mimeType || mimeType });
150
+ if (discarded.current ||
151
+ !clip.size ||
152
+ Date.now() - startedAt.current < MIN_CLIP_MS) {
153
+ setState("idle");
154
+ return;
155
+ }
156
+ void transcribeClip(clip);
157
+ };
158
+ stream.current = media;
159
+ recorder.current = instance;
160
+ startedAt.current = Date.now();
161
+ try {
162
+ instance.start();
163
+ }
164
+ catch {
165
+ recorder.current = null;
166
+ releaseStream();
167
+ starting.current = false;
168
+ setError("failed");
169
+ return;
170
+ }
171
+ starting.current = false;
172
+ setState("recording");
173
+ }, [releaseStream, transcribeClip]);
174
+ // The state guard matters: `stop()` flips the recorder to `inactive` at once but fires its
175
+ // events a tick later, so a second call in that window would throw InvalidStateError. A
176
+ // double-clicked button, a key repeat, or the unmount cleanup on top of either all land here.
177
+ const stop = (0, react_1.useCallback)(() => {
178
+ const instance = recorder.current;
179
+ if (instance && instance.state !== "inactive")
180
+ instance.stop();
181
+ }, []);
182
+ const cancel = (0, react_1.useCallback)(() => {
183
+ discarded.current = true;
184
+ upload.current?.abort();
185
+ upload.current = null;
186
+ // A recorder that is already flushing releases the stream from its own `stop` event.
187
+ if (recorder.current)
188
+ stop();
189
+ else
190
+ releaseStream();
191
+ setError(null);
192
+ setState("idle");
193
+ }, [releaseStream, stop]);
194
+ (0, react_1.useEffect)(() => {
195
+ return () => {
196
+ // Unmount: the microphone indicator must go out even mid-clip.
197
+ discarded.current = true;
198
+ upload.current?.abort();
199
+ upload.current = null;
200
+ stop();
201
+ releaseStream();
202
+ };
203
+ }, [releaseStream, stop]);
204
+ return { supported: isSupported(), state, error, start, stop, cancel };
205
+ }
@@ -125,29 +125,33 @@ function useRelatedAssets(args, options) {
125
125
  // Returns the draft work item — fill it with usePatchWorkData and save it
126
126
  // with useSubmitWork (which also refreshes the asset listings).
127
127
  function useCreateAsset(options) {
128
- return (0, shared_1.useSdkMutation)((vars) => assets_1.assets.create(vars), (client) => {
128
+ return (0, shared_1.useSdkMutation)((vars) => assets_1.assets.create(vars), (client, _data, _vars, searches) => {
129
129
  const envId = (0, shared_1.getLiveEnvId)();
130
130
  // CROSS-DOMAIN: the draft shows up as a WORK item, and the platform
131
131
  // saves the asset as a draft at once, so asset listings go stale too.
132
132
  void client.invalidateQueries({
133
133
  queryKey: keys_1.queryKeys.work.allRows(envId),
134
134
  });
135
- void client.invalidateQueries({
136
- queryKey: keys_1.queryKeys.work.searchAll(envId),
137
- });
138
- void client.invalidateQueries({ queryKey: keys_1.queryKeys.assets.all(envId) });
135
+ if (searches) {
136
+ void client.invalidateQueries({
137
+ queryKey: keys_1.queryKeys.work.searchAll(envId),
138
+ });
139
+ }
140
+ void (0, shared_1.invalidateScope)(client, keys_1.queryKeys.assets.all(envId), searches);
139
141
  }, options);
140
142
  }
141
143
  function useStartEditAsset(options) {
142
- return (0, shared_1.useSdkMutation)((vars) => assets_1.assets.startEdit(vars), (client, _data, vars) => {
144
+ return (0, shared_1.useSdkMutation)((vars) => assets_1.assets.startEdit(vars), (client, _data, vars, searches) => {
143
145
  const envId = (0, shared_1.getLiveEnvId)();
144
146
  // CROSS-DOMAIN: same draft-as-work-item model as useCreateAsset.
145
147
  void client.invalidateQueries({
146
148
  queryKey: keys_1.queryKeys.work.allRows(envId),
147
149
  });
148
- void client.invalidateQueries({
149
- queryKey: keys_1.queryKeys.work.searchAll(envId),
150
- });
150
+ if (searches) {
151
+ void client.invalidateQueries({
152
+ queryKey: keys_1.queryKeys.work.searchAll(envId),
153
+ });
154
+ }
151
155
  // The asset's draftWorkId now names this draft.
152
156
  void client.invalidateQueries({
153
157
  queryKey: keys_1.queryKeys.assets.detail(envId, vars.assetId),
@@ -155,21 +159,23 @@ function useStartEditAsset(options) {
155
159
  }, options);
156
160
  }
157
161
  function useCloneAsset(options) {
158
- return (0, shared_1.useSdkMutation)((vars) => assets_1.assets.clone(vars.assetId), (client) => {
162
+ return (0, shared_1.useSdkMutation)((vars) => assets_1.assets.clone(vars.assetId), (client, _data, _vars, searches) => {
159
163
  const envId = (0, shared_1.getLiveEnvId)();
160
164
  void client.invalidateQueries({
161
165
  queryKey: keys_1.queryKeys.assets.allRows(envId),
162
166
  });
163
- void client.invalidateQueries({
164
- queryKey: keys_1.queryKeys.assets.searchAll(envId),
165
- });
167
+ if (searches) {
168
+ void client.invalidateQueries({
169
+ queryKey: keys_1.queryKeys.assets.searchAll(envId),
170
+ });
171
+ }
166
172
  void client.invalidateQueries({
167
173
  queryKey: keys_1.queryKeys.assets.quickSearchAll(envId),
168
174
  });
169
175
  }, options);
170
176
  }
171
177
  function useDeleteAsset(options) {
172
- return (0, shared_1.useSdkMutation)((vars) => assets_1.assets.delete(vars.assetId), (client, _data, vars) => {
178
+ return (0, shared_1.useSdkMutation)((vars) => assets_1.assets.delete(vars.assetId), (client, _data, vars, searches) => {
173
179
  const envId = (0, shared_1.getLiveEnvId)();
174
180
  client.removeQueries({
175
181
  queryKey: keys_1.queryKeys.assets.detail(envId, vars.assetId),
@@ -177,9 +183,11 @@ function useDeleteAsset(options) {
177
183
  void client.invalidateQueries({
178
184
  queryKey: keys_1.queryKeys.assets.allRows(envId),
179
185
  });
180
- void client.invalidateQueries({
181
- queryKey: keys_1.queryKeys.assets.searchAll(envId),
182
- });
186
+ if (searches) {
187
+ void client.invalidateQueries({
188
+ queryKey: keys_1.queryKeys.assets.searchAll(envId),
189
+ });
190
+ }
183
191
  void client.invalidateQueries({
184
192
  queryKey: keys_1.queryKeys.assets.quickSearchAll(envId),
185
193
  });
@@ -11,11 +11,26 @@ export interface SdkQueryOptions {
11
11
  retry?: boolean | number;
12
12
  }
13
13
  export interface SdkMutationOptions<TData, TVariables> {
14
+ /**
15
+ * Whether the hook's built-in invalidation of cached searches (`useWorkSearch`,
16
+ * `useAssetSearch`) runs after the write. Default `true`.
17
+ *
18
+ * A search is cached on the server for a couple of minutes, so reading it again right after
19
+ * a write can return the rows as they were before it, and overwrite a list the app has already
20
+ * brought up to date from live events. An app that does that (see `@rise-x/apps-sdk/live`)
21
+ * passes `"unlessLive"`: the searches are left alone while the host's live connection is
22
+ * `connected`, and invalidated as before when it is not. `false` never invalidates them.
23
+ * Everything else the hook invalidates (the work's detail and data, the audit trail, row
24
+ * listings, other scopes) is unaffected.
25
+ */
26
+ invalidateSearches?: boolean | "unlessLive";
14
27
  onSuccess?: (data: TData, variables: TVariables) => unknown;
15
28
  onError?: (error: ConnectorError, variables: TVariables) => unknown;
16
29
  onSettled?: (data: TData | undefined, error: ConnectorError | null, variables: TVariables) => unknown;
17
30
  }
18
31
  export declare function getLiveEnvId(): QueryEnvId;
32
+ export declare function shouldInvalidateSearches(option: SdkMutationOptions<unknown, unknown>["invalidateSearches"]): boolean;
33
+ export declare function invalidateScope(client: QueryClient, queryKey: readonly unknown[], searches: boolean): Promise<void>;
19
34
  export interface RowsPage {
20
35
  items: {
21
36
  id: string;
@@ -39,5 +54,5 @@ interface BuiltInfiniteQuery<TPage> {
39
54
  enabled?: unknown;
40
55
  }
41
56
  export declare function useSdkInfiniteQuery<TPage>(built: BuiltInfiniteQuery<TPage>, options?: SdkQueryOptions): UseInfiniteQueryResult<InfiniteData<TPage>, ConnectorError>;
42
- export declare function useSdkMutation<TData, TVariables>(mutationFn: (variables: TVariables) => Promise<TData>, effects: (client: QueryClient, data: TData, variables: TVariables) => void, options?: SdkMutationOptions<TData, TVariables>): import("@tanstack/react-query").UseMutationResult<TData, ConnectorError, TVariables, unknown>;
57
+ export declare function useSdkMutation<TData, TVariables>(mutationFn: (variables: TVariables) => Promise<TData>, effects: (client: QueryClient, data: TData, variables: TVariables, searches: boolean) => void, options?: SdkMutationOptions<TData, TVariables>): import("@tanstack/react-query").UseMutationResult<TData, ConnectorError, TVariables, unknown>;
43
58
  export {};
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getLiveEnvId = getLiveEnvId;
4
+ exports.shouldInvalidateSearches = shouldInvalidateSearches;
5
+ exports.invalidateScope = invalidateScope;
4
6
  exports.getNextRowsPageParam = getNextRowsPageParam;
5
7
  exports.invalidateAppSdkQueries = invalidateAppSdkQueries;
6
8
  exports.useEnvSubscription = useEnvSubscription;
@@ -28,6 +30,20 @@ const context_1 = require("./context");
28
30
  function getLiveEnvId() {
29
31
  return (0, accessors_1.getShellEnvironment)()?.id ?? null;
30
32
  }
33
+ // Resolved when the write succeeds, so "unlessLive" reflects the connection at that moment.
34
+ function shouldInvalidateSearches(option) {
35
+ if (option === "unlessLive")
36
+ return (0, accessors_1.getShellLive)()?.getStatus() !== "connected";
37
+ return option !== false;
38
+ }
39
+ // Invalidates a scope of the cache, leaving out its v4 search listings when `searches` is false.
40
+ // Every key is [root, envId, domain, kind, ...], so a search is `kind === "search"`.
41
+ function invalidateScope(client, queryKey, searches) {
42
+ return client.invalidateQueries({
43
+ queryKey,
44
+ predicate: searches ? undefined : (query) => query.queryKey[3] !== "search",
45
+ });
46
+ }
31
47
  // Shared getNextPageParam for the domains' skip-paged infinite rows queries.
32
48
  // Mirrors the connectors' iterate() bail/advance rule exactly: stop when the
33
49
  // server reports no more rows, or when a "full" page turned out to be
@@ -112,12 +128,14 @@ function useSdkInfiniteQuery(built, options) {
112
128
  };
113
129
  return (0, react_query_1.useInfiniteQuery)(merged, client);
114
130
  }
115
- function useSdkMutation(mutationFn, effects, options) {
131
+ function useSdkMutation(mutationFn,
132
+ // `searches` is whether the caller's `invalidateSearches` allows invalidating the v4 searches.
133
+ effects, options) {
116
134
  const client = (0, context_1.useAppQueryClient)();
117
135
  return (0, react_query_1.useMutation)({
118
136
  mutationFn,
119
137
  onSuccess: (data, variables) => {
120
- effects(client, data, variables);
138
+ effects(client, data, variables, shouldInvalidateSearches(options?.invalidateSearches));
121
139
  return options?.onSuccess?.(data, variables);
122
140
  },
123
141
  onError: (error, variables) => options?.onError?.(error, variables),
@@ -125,18 +125,20 @@ function useWorkAudit(workId, options) {
125
125
  return (0, shared_1.useSdkQuery)(exports.workQueries.audit(workId), options);
126
126
  }
127
127
  function useStartWork(options) {
128
- return (0, shared_1.useSdkMutation)((vars) => work_1.work.start(vars), (client) => {
128
+ return (0, shared_1.useSdkMutation)((vars) => work_1.work.start(vars), (client, _data, _vars, searches) => {
129
129
  const envId = (0, shared_1.getLiveEnvId)();
130
130
  void client.invalidateQueries({
131
131
  queryKey: keys_1.queryKeys.work.allRows(envId),
132
132
  });
133
- void client.invalidateQueries({
134
- queryKey: keys_1.queryKeys.work.searchAll(envId),
135
- });
133
+ if (searches) {
134
+ void client.invalidateQueries({
135
+ queryKey: keys_1.queryKeys.work.searchAll(envId),
136
+ });
137
+ }
136
138
  }, options);
137
139
  }
138
140
  function usePatchWorkData(options) {
139
- return (0, shared_1.useSdkMutation)(({ workId, ...patch }) => work_1.work.patchData(workId, patch), (client, _data, vars) => {
141
+ return (0, shared_1.useSdkMutation)(({ workId, ...patch }) => work_1.work.patchData(workId, patch), (client, _data, vars, searches) => {
140
142
  const envId = (0, shared_1.getLiveEnvId)();
141
143
  void client.invalidateQueries({
142
144
  queryKey: keys_1.queryKeys.work.dataAll(envId, vars.workId),
@@ -148,13 +150,15 @@ function usePatchWorkData(options) {
148
150
  void client.invalidateQueries({
149
151
  queryKey: keys_1.queryKeys.work.allRows(envId),
150
152
  });
151
- void client.invalidateQueries({
152
- queryKey: keys_1.queryKeys.work.searchAll(envId),
153
- });
153
+ if (searches) {
154
+ void client.invalidateQueries({
155
+ queryKey: keys_1.queryKeys.work.searchAll(envId),
156
+ });
157
+ }
154
158
  }, options);
155
159
  }
156
160
  function useSubmitWork(options) {
157
- return (0, shared_1.useSdkMutation)((vars) => work_1.work.submit(vars), (client, data, vars) => {
161
+ return (0, shared_1.useSdkMutation)((vars) => work_1.work.submit(vars), (client, data, vars, searches) => {
158
162
  const envId = (0, shared_1.getLiveEnvId)();
159
163
  client.setQueryData(keys_1.queryKeys.work.detail(envId, vars.workId), data);
160
164
  void client.invalidateQueries({
@@ -169,17 +173,19 @@ function useSubmitWork(options) {
169
173
  void client.invalidateQueries({
170
174
  queryKey: keys_1.queryKeys.work.allRows(envId),
171
175
  });
172
- void client.invalidateQueries({
173
- queryKey: keys_1.queryKeys.work.searchAll(envId),
174
- });
176
+ if (searches) {
177
+ void client.invalidateQueries({
178
+ queryKey: keys_1.queryKeys.work.searchAll(envId),
179
+ });
180
+ }
175
181
  // CROSS-DOMAIN: asset create/edit drafts materialize via work.submit —
176
182
  // the whole assets scope goes stale. Over-broad but correct; only
177
183
  // active asset queries actually refetch.
178
- void client.invalidateQueries({ queryKey: keys_1.queryKeys.assets.all(envId) });
184
+ void (0, shared_1.invalidateScope)(client, keys_1.queryKeys.assets.all(envId), searches);
179
185
  }, options);
180
186
  }
181
187
  function useDeleteWork(options) {
182
- return (0, shared_1.useSdkMutation)((vars) => work_1.work.delete(vars.workId), (client, _data, vars) => {
188
+ return (0, shared_1.useSdkMutation)((vars) => work_1.work.delete(vars.workId), (client, _data, vars, searches) => {
183
189
  const envId = (0, shared_1.getLiveEnvId)();
184
190
  client.removeQueries({
185
191
  queryKey: keys_1.queryKeys.work.detail(envId, vars.workId),
@@ -193,9 +199,11 @@ function useDeleteWork(options) {
193
199
  void client.invalidateQueries({
194
200
  queryKey: keys_1.queryKeys.work.allRows(envId),
195
201
  });
196
- void client.invalidateQueries({
197
- queryKey: keys_1.queryKeys.work.searchAll(envId),
198
- });
202
+ if (searches) {
203
+ void client.invalidateQueries({
204
+ queryKey: keys_1.queryKeys.work.searchAll(envId),
205
+ });
206
+ }
199
207
  void client.invalidateQueries({
200
208
  queryKey: keys_1.queryKeys.work.relatedAll(envId),
201
209
  });